qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
28,869,932
This is my code: ``` <?php $value = 'something from somewhere'; setcookie("TestCookie", $value); ?> ``` I am getting the error message as follows: > > Warning: Cannot modify header information - headers already sent by > (output started at /home/nairsoft/public\_html/page1.php:2) in > /home/nairsoft/public\_html/page1.php on line 4 > > > I am using a free webhosting server.
2015/03/05
[ "https://Stackoverflow.com/questions/28869932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4422446/" ]
The headers are sent at the beginning of a request before the body of the server's response. It looks like your code already sent the headers so you can't modify them. As Afaan suggested, make sure you don't ouput anything before the opening php tag. In general, it is a good idea to process everything you need at the beginning of the request before sending any of the response.
Cookie is a part of headers and headers must be sent ***before*** any actual output to the browser. Make sure that you set your cookies and other headers before you output *anything*. It has nothing whatsoever to do with what type of hosting package you have.
414,055
I'm (really) newbie to functional programming (in fact only had contact with it using python) but seems to be a good approach for some list-intensive tasks in a shell environment. I'd love to do something like this: ``` $ [ git clone $host/$repo for repo in repo1 repo2 repo3 ] ``` Is there any Unix shell with these kind of feature? Or maybe some feature to allow easy shell access (commands, env/vars, readline, etc...) from within python (the idea is to use python's interactive interpreter as a replacement to bash). **EDIT:** Maybe a comparative example would clarify. Let's say I have a list composed of *dir/file*: `$ FILES=( build/project.rpm build/project.src.rpm )` And I want to do a really simple task: copy all files to *dist/* AND install it in the system (it's part of a build process): Using bash: ``` $ cp ${files[*]} dist/ $ cd dist && rpm -Uvh $(for f in ${files[*]}; do basename $f; done)) ``` Using a "pythonic shell" approach (caution: this is imaginary code): ``` $ cp [ os.path.join('dist', os.path.basename(file)) for file in FILES ] 'dist' ``` Can you see the difference ? THAT is what i'm talking about. How can not exits a shell with these kind of stuff build-in yet? It's a real pain to handle lists in shell, even its being a so common task: list of files, list of PIDs, list of everything. And a really, really, important point: using syntax/tools/features everybody already knows: sh and python. IPython seams to be on a good direction, but it's bloated: if var name starts with '$', it does this, if '$$' it does that. It's syntax is not "natural", so many rules and "workarounds" (`[ ln.upper() for ln in !ls ]` --> syntax error)
2012/04/18
[ "https://superuser.com/questions/414055", "https://superuser.com", "https://superuser.com/users/-1/" ]
Scheme Shell, scsh, is really good. As Keith Thompson notes, it's not useful as an interactive shell (though Commander S looks like an interesting experiment). Instead, it's an excellent programming language for contexts where having all the POSIX bindings is useful -- that includes cases where you want to call other unix applications. A shell script of more than a few dozen lines will *always* feel like a hack, no matter how neatly you write `sh`; in contrast there's nothing stopping you writing significant programs using scsh. scsh isn't very compact (brevity is both the strength and the weakness of sh-family languages), but it's powerful. Because it's useful and practical for small and large tasks, scsh is incidentally a good way of getting to grips with a Scheme (although, if that happened to be your goal, you might as well go straight to Racket, these days). The advantages of functional languages aren't just for list-intensive tasks (though because of their history, they tend to favour lists as a data structure) -- it's a really robust way to get programs written, once you drink the right kool-aid. There is no meaningful sense in which the sh-style shells are functional, and Python is only functional in the marginal sense that it has a lambda function.
Don't know about it being "functional", but there is also [rc](http://en.wikipedia.org/wiki/Rc), which the [scsh paper](ftp://ftp.cs.indiana.edu/pub/scheme-repository/imp/scsh-paper.ps) mentions. It's a predecesor to es. On Linux Mint (and probably Debian, Ubuntu...) you can try it with ``` sudo apt-get install rc man rc rc ```
281,620
I am kind of confused.... Are the two sentences below the same? > > 1. Let’s pretend that none of this had ever/never happened. > 2. Let’s pretend that none of this have ever/never happened. > > > If it’s different, can you please be specific on how they are different from each other?
2021/04/16
[ "https://ell.stackexchange.com/questions/281620", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/134450/" ]
I think your claim is that the statement "either there is a professor of linguistics or there isn't" is a [tautology](https://en.wikipedia.org/wiki/Tautology_(logic)) and therefore not a supposition at all. And I think you're right. Unless we want to dive into [the philosophy of existence](https://en.wikipedia.org/wiki/Metaphysics), "X exists" is a true or false statement. If we call that statement P, then from a standpoint of formal logic, "P or not P" is a tautology since it is always true: so P is meaningless and not a supposition. I think the real presupposition in your sentence is "MIT exists." But this is not what the Wikipedia page presents.
I didn't see any indication on the linked page that that presupposition has anything wrong with it. The page simply points out that a presupposition is implied by the question, and will be recognized by the hearer of the question. It is a yes/no question.
7,571,509
1. This code executes primes upto a given number. It works correctly as far as the prime generation is concerned but the output is painfully repetitive. 2. The code is: ``` numP = 1 x = 3 y = int(input('Enter number of primes to be found: ')) while numP<=y: for n in range(2, x): for b in range(2, n): if n % b == 0: break else: # loop fell through without finding a factor print (n) x += 2 numP += 1 ``` 3. The output is like (e.g. for y=4): ``` 2 2 3 2 3 5 2 3 5 7 ``` 4. I want to avoid repetition and obtain output like: ``` 2 3 5 7 ``` 5. How should the code be modified?
2011/09/27
[ "https://Stackoverflow.com/questions/7571509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/952616/" ]
Remove one of the `slf4j-log4j12-1.5.8.jar` or `slf4j-log4j12-1.6.0.jar` from the classpath. Your project should not depend on different versions of SLF4J. I suggest you to use just the 1.6.0. If you're using Maven, you can [exclude transitive dependencies](http://maven.apache.org/pom.html#Exclusions). Here is an example: ``` <dependency> <groupId>com.sun.xml.stream</groupId> <artifactId>sjsxp</artifactId> <version>1.0.1</version> <exclusions> <exclusion> <groupId>javax.xml.stream</groupId> <artifactId>stax-api</artifactId> </exclusion> </exclusions> </dependency> ``` With the [current slf4j-api implementation](http://search.maven.org/#artifactdetails|org.slf4j|slf4j-api|1.6.2|jar) it is not possible to remove these warnings. The `org.slf4j.LoggerFactory` class prints the messages: ``` ... if (implementationSet.size() > 1) { Util.report("Class path contains multiple SLF4J bindings."); Iterator iterator = implementationSet.iterator(); while(iterator.hasNext()) { URL path = (URL) iterator.next(); Util.report("Found binding in [" + path + "]"); } Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation."); } ... ``` The `Util` class is the following: ``` public class Util { static final public void report(String msg, Throwable t) { System.err.println(msg); System.err.println("Reported exception:"); t.printStackTrace(); } ... ``` The `report` method writes directly to `System.err`. A workaround could be to replace the `System.err` with [`System.setErr()`](http://download.oracle.com/javase/6/docs/api/java/lang/System.html#setErr%28java.io.PrintStream%29) *before* the first `LoggerFactory.getLogger()` call but you could lose other important messages if you do that. Of course you can download the source and remove these `Util.report` calls and use your modified slf4j-api in your project.
Have you read the URL referenced by the warning? ``` SLF4J: See [http://www.slf4j.org/codes.html#multiple_bindings][1] for an explanation. ``` Here is what the link states: > > SLF4J API is desinged to bind with one and only one underlying logging > framework at a time. If more than one binding is present on the class > path, SLF4J will emit a warning, listing the location of those > bindings. When this happens, select the one and only one binding you > wish to use, and remove the other bindings. > > > For example, if you have both slf4j-simple-1.6.2.jar and > slf4j-nop-1.6.2.jar on the class path and you wish to use the nop > (no-operation) binding, then remove slf4j-simple-1.6.2.jar from the > class path. > > > Note that the warning emitted by SLF4J is just that, a warning. SLF4J > will still bind with the first framework it finds on the class path. > > >
33,159,911
Why doesn't this return a value when the function is called? I've tried it with callbacks, and I can't seem to get it to work either. It lets me console.log, but it just won't return it to the `tmp` variable. ``` var URL = "https://api.instagram.com/v1/media/popular?client_id=642176ece1e7445e99244cec26f4de1f"; function getData(){ var tmp; $.ajax({ type: "GET", url: URL, dataType: "jsonp", success: function(result){ if(result.meta.code == 200){ tmp = result.data; //console.log(result.data); }else{ alert('fail'); alert(result.meta.error_message); } } }); return tmp; } console.log(getData()); // undefined? ``` thanks in advance!
2015/10/15
[ "https://Stackoverflow.com/questions/33159911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3224271/" ]
The problem is that your site does not contain anchors with the class `page-link` when it is loaded with `urllib`. However you see it in your browser. This is because JavaScript creates the page links to the next sites. If you use a browser with good developer tools (I use Chrome) you can disable JavaScript execution on sites. If you do this and load the site again you will see the pagination vanish. But to solve your problem you can extract the job result count and create the URL list based on this value: each site displays 20 job postings. You can divide the result count through 20 and see how many pages you have to crawl. Naturally this works only for searches where the result is under 1000. Over 1000 results you get only "1000+ results" displayed so you cannot really calculate the amount of pages. However if you look carefully through the source code of the page which is loaded you can locate a JavaScript tag which creates the pagination. This includes the total number of pages which you can use to create your URL list to scrape. Naturally this would include some text parsing but if you invest some time you can find a way how to do it. And if you have the amount of pages you can create a loop (or generator) and use your commented line for the next url: ``` for p in range(2,page_count+1): url = "http://jobs.monster.com/search/?q=data%20science&page="+str(p) ``` or ``` urls = ["http://jobs.monster.com/search/?q=data%20science&page="+str(p) for p in range(2, page_count+1)] ``` The loop starts from 2 because the first site you already have so there is no need to load it again.
Thanks GHajba for the detailed explanation! That's more or less what I ended up doing: ``` try: for i in range(2, 100): page = urlparse.urljoin(mainUrl, "?q=data%20science&page=" + str(i)) readPage = urllib.urlopen(page).read() soup = BeautifulSoup(readPage) except: pass ``` Thanks everyone!
34,140,559
I have connected temperature sensor to BeagleBone Black [BBB] board, after interval of 1 sec it sense the temperature and pass to BBB and beaglebone dumps it into mysql database on another computer. I want to show temperature data in graphical format. Graph should be updated after each second. I tried various libraries like c3, canvasJS but i was unable to implement with realtime updates. Sample Temperature Data: 1 : 32 2 : 33 . . . . so on.. Following is the canvasJS code which I tried ```js window.onload = function() { var dps = []; // dataPoints var chart = new CanvasJS.Chart("chartContainer", { title: { text: "Tempreture Input From XBee" }, data: [{ type: "line", dataPoints: dps }] }); var xVal = 0; var updateInterval = 1000; var dataLength = 10; // number of dataPoints visible at any point var updateChart = function(count) { $.getJSON("http://localhost/smartfarm/admin/getGraphJson", function(result) { $.each(result, function(key, value) { dps.push({ x: xVal, y: value }); xVal++; }); }); dps.shift(); chart.render(); }; // generates first set of dataPoints updateChart(dataLength); // update chart after specified time. setInterval(function() { updateChart() }, updateInterval); } ``` ```html <div id="chartContainer" style="height: 300px; width:100%;"></div> ``` Problem is that this code wont shift,It only adds new datapoints to graph because of this graph becomes too complicated to see.
2015/12/07
[ "https://Stackoverflow.com/questions/34140559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4436739/" ]
``` import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ClassRoom { private List<Student> studentList = new ArrayList<>(); public void addStudents(Student... students) { studentList.addAll(Arrays.asList(students)); } } ``` Sample student class ``` class Student { } ```
It is possible to have variable parameter length with the following code: ``` public void addStudents(Student... students) {...} ``` `students` will be an array of `Student`.
33,546
Specifically, I was wondering if a core of magnitite or some such other magnetic metal could be a planet's core. This is in relation to my other question, found here: [Can airborne floating/flying islands be scientifically possible?](https://worldbuilding.stackexchange.com/questions/33513/can-airborne-floating-flying-islands-be-scientifically-possible)
2016/01/17
[ "https://worldbuilding.stackexchange.com/questions/33546", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/17137/" ]
The answer depends on what your question really is. **Could you theoretically construct a magnetic planet using a core materially different than iron? Yes** Nickel and cobalt have are similar to iron in terms of their electrical, magnetic, and physical properties and both are a little denser than iron. **Could such terrestrial planets form naturally? No** Based on the standard models of stellar nuclear synthesis and planetary formation, neither cobalt nor nickel exist in sufficient quantity to become the dominant material in a planetary core. Although nickel is formed in considerable abundance in supergiant stars, the nickel is unstable and decays into iron. Not all of the nickel in stellar syntheses decays to iron, though much if not most nickel is thought to be derived from supernova debris. Supernovas are the accepted source for essentially all of the heavy elements past iron. But the mass fractions are all relatively small. Note that Earth's core is considered to consist of iron primarily, but with a significant fraction of nickel (perhaps 5%). --- I know that at normal temperature an electromagnet typically uses a ferromagnetic core to intensify the magnetic field. I also know that the temperature of the Earth's core is expected too far exceed the Curie temperature of iron, nickel and cobalt so this is not a conventional option. But it is also reported that Curie temperature is pressure dependent, and that it increases with pressure - but I was not able to find Curie temperature for material under core pressures. Given that the Earth's magnetic field is thought to derive from the flow of liquid iron outside the inner core, I would expect the inner core to still be well above the Curie temperature in any configuration able to generate a magnetic field, but I could not actually confirm this. I don't assume the terrestrial planet must have core temperatures that match Earth's (it could have less radioactives, etc.) but I would expect that pressure would be similar given a similar planet size. It should also be observed that the details of the Earth's magnetic field are poorly understood as should not be surprising considering that we cannot actually observe the conditions at the core. We only know of three types of planets, rocky, gas giant, and ice planets. Earth has the strongest magnetic field of the rocky planets. The gas giants all have much stronger fields in terms of total field strength, whereas icy Pluto (former planet) has no magnetic field. The question referenced a previous question that clearly restricts the interest to earth-like planets as it is inhabited by humans. But Jupiter is thought to have a magnetic core due to the flow of liquid metallic hydrogen. But for earth-like planets, the only reasonable natural magnetic core is iron; it has the abundance and density requirements. Magnesium (mostly as oxides) is thought to the second most abundant metal on earth - mostly in the mantle - but it is largely excluded in the core by the considerably more dense iron. The also relatively common metals aluminum and calcium are also too light to exist in abundance in the core.
The problem with having magnetite as the core of an Earth-like planet is the pressure and associated temperature that the core would reach. Magnetite ($\text{Fe}\_{3}\text{O}\_{4}$) breaks down at very high pressures and temperatures (800°C and 10-11GPa) to a different phase, $\text{Fe}\_{4}\text{O}\_{5}$, which is similarly magnetic to magnetite. However, the pressure in the core of the Earth is more than 300GPa and temperatures can reach as high as 5000°C. I haven't seen any proper research on magnetite in these conditions, but it could be safe to assume that pushing it to those temperatures would cause either completely new phases with differing magnetic properties to form, or it would simply cause the oxide to melt. The reason that the core of the Earth is iron (and nickel, gold, and platinum group elements) is that these elements are among the heaviest elements present in the formation of the planet, and preferentially dissolve into molten iron (siderophile elements). As such, when the planet was freshly accreting from the disc of dust around the Sun, these elements sunk into the core because they were denser than the surrounding material. So to answer your first question, whatever the core of your planet is has to be the densest thing that was there when it formed, assuming your planet formed in the same way as Earth did.
15,464
In the page <http://www.teslamotors.com/models> if we scroll down we see the several flavors Tesla sells its Model S. It puzzles me why the 85 version has a shorter range than the 85D. The first can run 265 miles, the second 270. Given that in the former the battery has to feed only one motor and in latter it has to feed two, why the first has a more limited ride distance?
2015/02/16
[ "https://mechanics.stackexchange.com/questions/15464", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/9367/" ]
It says right on the webpage: > > Conventional all-wheel drive cars employ complex mechanical linkages to distribute power from a single engine to all four wheels. This sacrifices efficiency in favor of all weather traction. In contrast, **each Model S motor is lighter, smaller and more efficient than its rear wheel drive counterpart, providing both improved range and faster acceleration**. > > >
This is pieced together from articles about this and the talk we had from a Tesla rep at the car leasing company I work for. The improved range of the dual motor setup arises from the front and rear gearboxes (one per motor, nothing interlinking them) having different ratios. Electric motors have a rpm range in which they operate most efficiently, having the motors geared differently means that the car has 2 road speed ranges (1 for each motor) in which the motors are at peak efficiency, covering much more of the car's total speed range. Also, each motor can be smaller which may be more efficient than a larger motor as a lot of the time only 1 motor will be propelling the car, though that will be offset to some degree by the increased frictional losses from having double the number of drivetrain components. On a side note, I don't have any info but my guess is that the shorter geared motor has a 1-way clutch of some sort to prevent it from over speeding when the car is travelling at high speed.
30,725,682
I am trying to create a login screen. I have used ScrollView to hold input fields. I have following xml: ``` <RelativeLayout ... > <RelativeLayout android:id="@+id/top_menu" ... > <ImageButton ... /> <com.neopixl.pixlui.components.textview.TextView... /> </RelativeLayout> <ScrollView android:id="@+id/scroll_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/top_menu" android:overScrollMode="always"> <LinearLayout android:id="@+id/login_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:orientation="vertical"> <com.neopixl.pixlui.components.edittext.EditText android:id="@+id/user_name_email" android:layout_width="match_parent" android:layout_height="@dimen/input_height_size" android:layout_marginEnd="20dp" android:layout_marginStart="20dp" android:background="@drawable/edit_text_strock" android:hint="@string/user_Name_Email_EditText" android:maxLines="1" android:paddingLeft="10dp" android:paddingStart="10dp" android:textColor="@color/White" android:textColorHint="@color/White" android:textSize="@dimen/register_input_text_size" pixlui:typeface="MuseoSans.otf"/> <com.neopixl.pixlui.components.edittext.EditText.... /> <com.neopixl.pixlui.components.button.Button... /> <com.neopixl.pixlui.components.textview.TextView... /> <com.neopixl.pixlui.components.textview.TextView... /> <com.neopixl.pixlui.components.textview.TextView... /> <com.neopixl.pixlui.components.button.Button... /> </LinearLayout> </ScrollView> </RelativeLayout> ``` You can see full xml [here](http://pastebin.com/WcLS7EwR). When I click on EditText user\_name\_email, it goes off the screen. Before click: ![Before click](https://i.stack.imgur.com/YH0Sk.png) After click: ![After click](https://i.stack.imgur.com/S6SdX.png) I have tried `scrollTo(x, y)` and `smootScrollTo(x, y)` bu they didn't work. How can I fix it? **UPDATE:** `adjustPan` works but I want it to work with `adjustResize`. Is it possible?
2015/06/09
[ "https://Stackoverflow.com/questions/30725682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614065/" ]
this is my code ```js window.onload = function () { var chart = new CanvasJS.Chart("chartContainer", { title: { text: "Top Categoires of New Year's Resolution" }, exportFileName: "Pie Chart", exportEnabled: true, animationEnabled: true, legend: { verticalAlign: "bottom", horizontalAlign: "center", fontFamily: "tahoma" }, data: [ { type: "pie", showInLegend: true, toolTipContent: "{legendText}: <strong>{y}%</strong>", indexLabel: "{label} {y}%", dataPoints: [ { y: 35, legendText: "Mahan Company for Mines & Industries Developmentشركت گسترش صنايع و معادن ماهان(سهامي خاص) ", exploded: true, label: "Mahan Company for Mines & Industries Developmentشركت گسترش صنايع و معادن ماهان(سهامي خاص)" }, { y: 20, legendText: "OILMICOشركت بين المللي طراحي و مهندسي ساخت صنايع نفت (سهامي خاص)", label: "OILMICOشركت بين المللي طراحي و مهندسي ساخت صنايع نفت (سهامي خاص)" }, { y: 18, legendText: "شركت مهندسي ايساتيس پوياي ايرانيان(اركان رويان كوير)", label: "شركت مهندسي ايساتيس پوياي ايرانيان(اركان رويان كوير)" }, { y: 15, legendText: "شركت صنايع لمينت و بسته بندي نفيس كار افرين", label: "شركت صنايع لمينت و بسته بندي نفيس كار افرين" }, { y: 5, legendText: "سازمان صنايع دريايي-گروه شناورهاي زير سطحي", label: "سازمان صنايع دريايي-گروه شناورهاي زير سطحي" }, { y: 7, legendText: "ايسيكو(شركت مهندسي خدمات صنعتي ايران خودرو", label: "ايسيكو(شركت مهندسي خدمات صنعتي ايران خودرو" } ] } ] }); chart.render(); } ``` ```html <script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body dir="rtl"> <div id="chartContainer" style="height: 300px; width: 100%;"></div> </body> </html> ```
change `<div id="chartContainer" style="height: 300px; width: 100%;"></div>` with `<div id="chartContainer" style="height: 300px; width: 100%;direction: ltr;"></div>` its work very good
214,648
A lot of more realistic depictions of dragons have their fire breath coming from some sort of flammable substance like a gas or liquid that their body produces and stores before they spew it that they then light to create the illusion or at least an approximation of 'breathing fire'... somehow. My question is this. Could/Is-it-possible-for a creature evolve to grow steel teeth, or at least steel somewhere in their mouth, and have their tongue be tipped with some sort of flint-like stone or object that they could scrape against the steel in their mouth to create the spark that would light the flammable substance?
2021/10/02
[ "https://worldbuilding.stackexchange.com/questions/214648", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/90499/" ]
**The Flint** Flint is a mineral; it is a sedimentary cryptocrystalline form of the mineral quartz. Biomineralization is a naturally occurring trait of living organisms, and this is process is how seashells get formed, for example. So, yes, your dragon is some biological manner have a “tongue of flint.” Maybe its tongue has surface that scales flint and regenerates dead tongue skin cells. Maybe your dragon’s mouth is a nice environment for the bacteria similar to the sea floor and it’s that bacteria which produces the mineralization process, which catalyzes on your dragon’s tongue. **The Steel** Biological production of steel is a bit tougher nut to crack. It doesn’t occur. But it doesn’t need to occur. I get that you’re going after a literal “flint and steel” fire starting mechanism. But the purpose of the steel in a flint and steel kit is merely to serve as a (relatively softer) material for striking the harder flint against. It is but one, relatively later, materials used to manufacture a class of tools generally called a fire striker within the class of fire starting generally termed “percussion fire making.” Percussion fire making involve the striking of one material against the other to cleave a small, hot, oxidizing metal particle that can ignite tinder. This contrasts other fire making methods such as volcanic ignition, meteorite strike, lightening, or friction (hand bow, etc.) Early fire strikers, and fire making, predate the Iron Age and therefore steel. Early fire strikers were manufactured from a variety of iron pyrite. Also marcasite was used with flint and other stones to produce a high-temperature spark that could be used to create fire. For example, anthropologists believe that the "Iceman" called Ötzi may have used iron pyrite to make fire. Marcasite, sometimes called “white iron pyrite”, is iron sulfide with orthorhombic crystal structure. It is physically and crystallographically distinct from pyrite, which is iron sulfide with cubic crystal structure. It is a mineral, and that gets us back to mineralization. Or perhaps naturally produced teeth. However, I would be apt to swap the two: the teeth should be the harder of the flint-and-steel mechanism, perhaps wearing somewhat over time. The tongue should be the sacrificial element, flaking off dead skin cells in the form of sparks that simply get regenerated over night. Well, that’s how I see it anyway.
Use Ferrocerium Instead ======================= Ferrocerium is an alloy that is used to start fires, like a flint-and-steel. However, ferroceriums are far better. Namely, their sparks burn far hotter (making it easier to light the fire), and can be sparked on many types of edge There is one problem: Cerium (a major part of ferrocerium) is not biologically active, at least not in animals. However, there is a solution: There are a few methanotrophic bacteria that do use cerium, and it's not completely implausible that bacteria like these could help pass these metals into the dragon's bloodstream. There is also the problem of getting the cerium, but if these dragons are the subterranean type, then they could easily get it from eating the right minerals On the specific placement of the ferrocerium, it'd be best to have regular teeth, with the metal at the sides of the tongue, like the 'teeth' of a goose. This should allow the dragon to eat and move its mouth without causing sparks and wearing down its metal-parts. The teeth should also have a rough edge on the inner face, for quick and consisent sparking The secretion of metallic parts seems quite plausible, as many species (including every basis for a dragon) already deposit minerals into their tissues. While metals are a little different, the principle should be the same
15,970,246
I am using Proguard in my application, After exporting build i have performed reverse engineering on it with help of dex2jar, but some java class names are still in readable format but method names are obfuscated. e.g. If i having class named as TestClass.java before obfuscation after obfuscation it expect something like a.java or b.java... But it appears as TestClass.java for Activity classes in my project. Do anybody having any idea where i am wrong that Activity classes names are in readable format ? Thanks in Advance!
2013/04/12
[ "https://Stackoverflow.com/questions/15970246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1787795/" ]
Years later, there is now [Paws](https://metacpan.org/pod/Paws), a Perl AWS interface. It's on CPAN.
<http://www.timkay.com/aws/> I have found Tim Kay's "aws" and "s3" tools quite useful. They are written in Perl. It has the added advantage of --exec, so you can append commands directly to the output, in their original state from AWS. It has been a terror for me to have international characters and other junk floating about as sad excuse for file names. With Tim's toolset, I was able to workaround the problem by using the --exec to call for the prefix of the filename (also unique) and then act upon it directly, instead of mucking about with metacharacters and other nonsense. For example: ``` /123/456/789/You can't be serious that this is really a filename.txt /123/456/901/Oh!Yes I can! *LOL* Honest!.txt ``` To nuke the first one: ``` aws ls --no-vhost mybucketname/123/456/789/ --exec='system "aws", "rm", "--no-vhost", "$bucket/$key"' ``` Simply put, the tool performs an equivalent "ls" on the S3 bucket, for that prefix, and returns ALL file names in that prefix, which are passed into the exec function. From there, you can see I am blindly deleting whatever files are held within. (note: --no-vhost helps resolve bucketnames with periods in them and you don't need to use long URLs to get from point a to point b.)
48,419,094
I am new to Angular js and I want to try the following. I have an Object Array that come from Database. This is the url(example): <http://localhost:3000/items/showAll> I have yet implemented the Add, Edit, Update, Delete (Crud operation in backend with nodejs and express js and frontend with angularjs) but my problem is with the checkbox. I have in a table in my database a field "state", typ boolean default 0 (1 or 0 value). I have a list of items(for example 100) and want to select with a checkbox in ng-repeat one or more items and send the value(1) to my filed state in the database. My logic is: I need to bind a single item id with the checkbox, then add a value to the checkbox and if is checked send it to the database. ``` <input type="checkbox" ng-model="state" parse-int ng-true-value="'1'" ng-false-value="'0'" class="form-check-input" > [{"id":1,"name":"item1","state":0}] ``` What can I in my controller do? **Updated:** Code: Controller ``` $scope.createState = function() { var postItem = { id : $scope.id, state : $scope.state }; itemsService .createItem(postItem) .then( function successCallback(response, data) { $scope.clearForm(); }, function errorCallback(error, data, status, haders, config) { console.log("Error getting: " + data); } ); }; ``` Service: ``` var pathItems = "/items/add"; this.createItem = function(postItem) { return $http.post(pathItems, postItem) }; ``` html ng-repeat: ``` <input type="checkbox" ng-true-value="1" ng-false-value="0" ng-model="item.state" ng-click="createState(item.id)"> ``` Update the database, api ``` addItem: function(item, id, callback) { return database.query("Update items SET state=? WHERE id=?", [item.state, id], callback); }, router.post('/update/', function(req, res, next) { items.addItem(req.body, function(error, count) { if (error) { res.json(error); } else { res.json(req.body); } }); }); ``` This can update the database and I can do this from a bootstrap modal. I wanted to do this with a list of one checkbox per user, but I don't now what to do in AngularJS.
2018/01/24
[ "https://Stackoverflow.com/questions/48419094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8587628/" ]
The following will match 6 numbers, with any amount of space characters between them. ``` (?:\d\s*){5}\d ``` `?:` at the beginning there makes the group non-capturing. It's not necessary if all you wish to do is a simple match. A live example: <https://regex101.com/r/PZJ8DO/2>
You can try to use ``` (?<=).*6.* ``` This will match any line that contains '6' even if there are some white spaces or other characters in the line. The (?<=) Positive Look Behind. The . matches any character except line breaks. The \* matches 0 or more of the preceding token. And 6 matches a "6" Character. You can test Regular Expression here: [RegExr](https://regexr.com/) Note that the positive look behind feature is not supported in all flavors of RegEx.
7,853,914
> > **Possible Duplicate:** > > [python str.strip strange behavior](https://stackoverflow.com/questions/2990973/python-str-strip-strange-behavior) > > > I have following piece of code: ``` st = '55000.0' st = st.strip('.0') print st ``` When i execute, it print only `55` but i expect it to print `55000`. I thought that the `dot` in `strip` causing this as we usually `escape` it in `Regular Expression` so i also tried `st = st.strip('\.0')` but still is giving same results. Any ideas why it is not just striping `.0` and why all zeros striped??
2011/10/21
[ "https://Stackoverflow.com/questions/7853914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/860103/" ]
You've misunderstood strip() - it removes **any** of the specified characters from both ends; there is no regex support here. You're asking it to strip both `.` and `0` off both ends, so it does - and gets left with `55`. See the [official String class docs](http://docs.python.org/library/string.html#string.strip) for details.
Because [that's what `strip` does](http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip): > > The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped > > >
13,580,848
Capturing a repetition group is always returning the last element but that is not quite helpfull. For example: ``` var regex = new RegEx("^(?<somea>a)+$"); var match = regex.Match("aaa"); match.Group["somea"]; // return "a" ``` I would like to have a collection of match element instead of the last match item. Is that possible?
2012/11/27
[ "https://Stackoverflow.com/questions/13580848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343957/" ]
Take a look in the `Captures` collection: ``` match.Groups["somea"].Captures ```
You can also try something like this : ``` var regex = new RegEx("^(?<somea>a)+$"); var matches = regex.Matches("aaa"); foreach(Match _match in matches){ match.Group["somea"]; // return "a" } ``` This is just a sample but it should give a good start. I did not check the validity of your regular expression though
20,678,664
How can I export a table to `.csv` in Postgres, when I'm not superuser and can't use the `copy` command? I can still import the data to postgres with "import" button on the right click, but no export option.
2013/12/19
[ "https://Stackoverflow.com/questions/20678664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3118674/" ]
Use psql and redirect stream to file: ``` psql -U <USER> -d <DB_NAME> -c "COPY <YOUR_TABLE> TO stdout DELIMITER ',' CSV HEADER;" > file.csv ```
I was having trouble with superuser and running psql, I took the simple stupid way using PGAdmin III. 1) SELECT \* FROM ; Before running select Query in the menu bar and select 'Query to File' This will save it to a folder of your choice. May have to play with the settings on how to export, it likes quoting and ;. 2) SELECT \* FROM ; run normally and then save the output by selecting export in the File menu. This will save as a .csv This is not a good approach for large tables. Tables I have done this for are a few 100,000 rows and 10-30 columns. Large tables may have problems.
92,305
Comedian/podcaster/QI elf [Dan Schreiber asked on Twitter](https://twitter.com/Schreiberland/status/1505611873735086085?s=20&t=vaW2BggycytqzVhVYbCeUg), as proxy for his 4-year old > > if it would ever be possible to hook a plane (like a 737) onto the back of another plane, like a train carriage, and then have both take off? I know the answer is no, but just wanted to double check with you, Twitter > > > and [continued](https://twitter.com/Schreiberland/status/1505613338285334534) > > I knew about gliders...Just wondering about the Boeings...in case some one comes in with an XKCD-style answer > > > For the purposes of focusing our question, I'd like to ask: **can a jet airliner TOW (not piggyback / eat) another airliner from takeoff to landing?** It is pre-noted that this is not a good idea, voids the warranty, etc. However, laying out considerations / difficulties / show stoppers, with particular attention to modern flavors of the 737, or noting which if any airliners would be preferable tow-ers or tow-ees, will be appreciated.
2022/03/21
[ "https://aviation.stackexchange.com/questions/92305", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/3146/" ]
[![enter image description here](https://i.stack.imgur.com/knASl.png)](https://i.stack.imgur.com/knASl.png)[Pic source](https://militaryhistorynow.com/2014/09/29/soar-winners-the-glider-troopers-of-ww2-2/) Yes it should be possible for an airliner to tow another airliner. In WW2 gliders with paratroopers on board were towed to their drop zones, the technology has been around for a while. Another interesting story can be found in [this link](https://theaviationgeekclub.com/this-f-86-pilot-pushed-his-wingmans-crippled-sabre-for-60-miles-to-keep-him-out-of-enemy-hands/), about capt. Robbie Risner using his F-86 Sabre to push his wing mate's F-86 into friendly airspace during the Korean war. A fighter jet pushing another fighter jet. > > Risner told Logan to shut down his engine, now almost out of fuel. Then he gently inserted the upper lip of his air intake into the tailpipe of Logan’s F-86....Miraculously, Risner nudged Joe Logan’s F-86 all the way to Cho Do, maintaining an airspeed of 190 knots and enough altitude to stay out of range of automatic weapons. > > > One airliner pulling another one would indeed take structural preparation. The wing/body intersection is the strong point of the plane, dimensioned to absorb the forces from the jet engines which will now be provided by the tow ropes. If the tow ropes are attached at this point pitch moments will be produced into both the towed (nose up) and the towing (nose down) aeroplane, which receives an automatic trim correction for the engine thrust. Issues to tackle: 1. **Stability of the towee.** The towed plane will need to deal with interference and stability issues, and will need to have its flight controls powered. The B737 does have (very heavy) manual backup modes for the elevators & ailerons, the secondary flight controls require electrical/hydraulic powering. From the APU or from a RAT (which the [B737 does not have](https://aviation.stackexchange.com/a/42566/21091)). The batteries provide 60 mins of backup power, but powered flight controls are essential. Longitudinal stability should be OK, since the plane is built to deal with the thrust of the turbofan engines. Directional stability must be improved by leading the tow rope through a support fixed at the node wheel structure. The rope won't always pull straight ahead like the engines do, and this degree of freedom needs to be eliminated as much as possible. [![From FAA site linked below](https://i.stack.imgur.com/5Gae3.png)](https://i.stack.imgur.com/5Gae3.png) 2. **Wake turbulence**. The towed plane will need to evade wake turbulence from the towing plane, as [depicted above](https://www.faa.gov/air_traffic/publications/atpubs/aim_html/chap7_section_4.html). So the towed aeroplane can take off first, and remain above the vortex field - or fly below the wake field as in [this video](https://www.f-106deltadart.com/eclipse.htm). As @Neil\_UK mentions in a comment: > > Wake turbulence is not so much a problem, as a feature, for sail-plane towing. Once reasonably competent at straightforward tow-launches, the next exercise is to 'box the tug', that is, flying in, under, over, left and right of the tug plane's wake turbulence. – > Neil\_UK > > > And on the strength of the wake field, from the [FAA site](https://www.faa.gov/air_traffic/publications/atpubs/aim_html/chap7_section_4.html) > > Weight, speed, wingspan, and shape of the generating aircraft's wing all govern the strength of the vortex. The vortex characteristics of any given aircraft can also be changed by extension of flaps or other wing configuring devices. However, the vortex strength from an aircraft increases proportionately to an increase in operating weight or a decrease in aircraft speed. Since the turbulence from a “dirty” aircraft configuration hastens wake decay, the greatest vortex strength occurs when the generating aircraft is HEAVY, CLEAN, and SLOW. > > > So the towing plane can reduce the wake vortex by eliminating the payload, extending its flaps, and speed up to max climb speed (point 3. below) 3. **Optimum range**. The towing plane needs to provide thrust to overcome drag of two planes. The towed plane has its own wings and provides its own lift, so we'll only need to consider increased drag on the towing plane. In the [Breguet range equation](https://ocw.mit.edu/courses/aeronautics-and-astronautics/16-100-aerodynamics-fall-2005/lecture-notes/16100lecture9_cg.pdf) $\frac{V}{sfc} \cdot \frac{L}{D} \cdot log \frac{W\_i}{W\_f}$ the towed/towing plane combination has twice drag D, and the corresponding speed for maximum range will be lower than for a single plane. [![enter image description here](https://i.stack.imgur.com/aggcs.png)](https://i.stack.imgur.com/aggcs.png) One thing is clear: it can be done, because it has been demonstrated already: the Eclipse project mentioned in @ErinAnne's comment, a Starlifter towing a Delta Dart on a 1000 ft rope. [This report](https://www.f-106deltadart.com/pdf-files/Eclipse-Project-by-Tom-Tucker.pdf) mentions how the attachment point on the Dart was constructed at the nose, how the towing took place successfully (the Dart pilot took his hands off of the controls), and how the wake turbulence introduced some shakiness so stay either below or above the wake field.
It is surely possible in theory, but not that much in practice - at least not without some serious custom engineering. One big problem is going to be find a point strong enough to attach the towing cable on both planes. Planes that are made to tow / be towed have special strong points. Also do not forget that when towing, the towed plane usually releases and it lands on his own. This means that you will also need a cable release system and the towed plane will have to have everything required for autonomous flight and landing. And as someone remarked in the comments, the wake turbulence is going to be extremely, probably prohibitively bad. It is already a problem for much smaller towing aircraft when launching gliders. However if the cable is long enough it should be possible to fly slightly above or slightly below the worst turbulence while keeping the tow angle close to zero. Towing is very widely used for launching sail-planes and some heavier hang-gliding wings.
219,329
For $t\in [ 0, 1 )$ is $$ \frac{xe^{tx}}{e^{x}-1}$$ integrable over $x\in (0 , \infty )$? I.e., $$ \int\_{0}^{\infty} \frac{xe^{tx}}{e^{x}-1} dx < \infty?$$ How do I show this?
2012/10/23
[ "https://math.stackexchange.com/questions/219329", "https://math.stackexchange.com", "https://math.stackexchange.com/users/41872/" ]
As $x\to0$, $x/(e^x-1)$ approaches a finite limit. As $x\to\infty$, do a limit-comparison of the integrand to $xe^{tx}/e^x$.
As $\frac x{e^x-1}$ as a limit when $x\to 0$ (namely $1$), the only problem is when $x\to\infty$. We have $e^x-1\sim e^x$ at $+\infty$, so $\dfrac{xe^{tx}}{e^x-1}\sim xe^{(t-1)x}$. Using Taylor's series, $$e^{(t-1)x}\leq \frac 1{1+(1-t)x+x^2(1-t)^2/2+x^3(1-t)^3/6},$$ the integral is convergent for $t\in[0,1)$.
17,070,281
I know that for targeting IE8+ you should use: ``` <!--[if gte IE 8]> According to the conditional comment this is IE 8 or higher<br /> <![endif]--> ``` For targeting non IE browsers you can use: ``` <!--[if !IE]> --> According to the conditional comment this is not IE<br /> <!-- <![endif]--> ``` You can also combine conditions like this: ``` [if (IE 6)|(IE 7)] ``` But my problem, now that I want to target IE8+ or non IE browsers, I try to target them like this: ``` <!--[if (!IE)|(gte IE 8)]> --> This should be non IE or IE8+ browsers <!-- <![endif]--> ``` This seems to work for non ie browsers but add `-->` to IE. I'm guessing it has something to do with the types of comments *downlevel revealed*, and *downlevel hidden*, but I'm not sure how to handle them.
2013/06/12
[ "https://Stackoverflow.com/questions/17070281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463065/" ]
From: [link](http://www.mediacollege.com/internet/html/detect/detect-ie.html) > > The next example is the opposite: "Only show this content if the > browser is NOT Internet Explorer". > > > ``` <![if !IE]> Place content here to target all users not using Internet Explorer. <![endif]> ``` Conditional comments are only recognized by Internet Explorer — other browsers treat them as normal comments and ignore them. Note that in the second example above (the one that targets "other" browsers), the content is not actually inside a comment — that's why other browsers display it. So I think that you can not combine two different types of conditional comments
This is what works for me. I ended up having to include the non-IE-8 css twice: ``` <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="/css/ie8.css"/> <![endif]--> <!--[if gte IE 9]> <link rel="stylesheet" type="text/css" href="/css/non_ie8.css"/> <![endif]--> <!--[if !IE]><!--> <link rel="stylesheet" type="text/css" href="/css/non_ie8.css"/> <!--<![endif]--> ``` See: <http://msdn.microsoft.com/en-us/library/ms537512.ASPX> <http://css-tricks.com/how-to-create-an-ie-only-stylesheet/> <http://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/> Of course, this causes a performance hit, and makes the code harder to maintain. It does, however, work (at least on the browsers I've tried). You might consider a good css library, if you can find one that meets your needs.
44,642,412
I'm building out a simple user role management UI that has multiple permissions based on RBAC rules. So I have lets say a group called users and inside of that group you get "add user", "edit users", "delete users" and "view users". What I want to do is be able to select the entire "users" group checkbox and it should select the children checkboxes that belong to it, and so on. I have around 20 of these permissions groups. I have looked around in stack overflow but am unable to find the solution or come up with something that works. I'm looking for some help with either Javascript or Jquery. I have included a screenshot to show you guys what I mean. I don't have any JS code to show because I'm not even sure where to start. I'm building the HTML view with `Blade` which is Laravel's templating engine. Here is my HTML so far. ``` @foreach($permissions as $name => $permission) <div class="col-sm-3"> <h4> <label> <input type="checkbox"> {{ $name }} </label> </h4> @foreach($permission as $item) <div class="checkbox small"> <label> <input name="permissions[]" value="{{ $item }}" type="checkbox"> {{ $item }} </label> </div> @endforeach </div> @endforeach ``` [![permissions](https://i.stack.imgur.com/LPQnT.png)](https://i.stack.imgur.com/LPQnT.png)
2017/06/20
[ "https://Stackoverflow.com/questions/44642412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2923236/" ]
Add appropriate classes to your parent elements and to your child elements so your code could be altered like in the below example. ``` @foreach($permissions as $name => $permission) <div class="col-sm-3"> <h4> <label> <input type="checkbox" class="{{ $name }}"> {{ $name }} </label> </h4> @foreach($permission as $item) <div class="checkbox small"> <label> <input name="permissions[]" class="{{ $name }}-child" value="{{ $item }}" type="checkbox"> {{ $item }} </label> </div> @endforeach </div> @endforeach ``` Your HTML will become like this regarding class names. ``` users<input class="users" type="checkbox" /> <br><br> <input class="users-child" type="checkbox" /> <input class="users-child" type="checkbox" /> <input class="users-child" type="checkbox" /> <input class="users-child" type="checkbox" /> <input class="users-child" type="checkbox" /> <input class="users-child" type="checkbox" /> ``` Finally your jQuery part ``` $(".users").on("click",function(){ // use the same code for user-roles var parentClassName = $(this).get(0).className; if($(this).is(":checked")) { $("."+parentClassName+"-child").each(function(key,value){ if($(value).get(0).checked==false) { $(value).get(0).checked = true; } }); } else { $("."+parentClassName+"-child").each(function(key,value){ $(value).get(0).checked = false; }); } }); ``` A small example of the above you can check in [jsFiddle](https://jsfiddle.net/pdwvoqtw/1/)
Your code is just fine but to make the answer even smaller I would like you to assign `class` attribute to your main div and checkbox so out jquery will depend on our own classes/selector instead of bootstrap classes. ``` <div class="col-sm-3 permission-block"> <h4> <label> <input type="checkbox" class="something"> {{ $name }} </label> </h4> ``` and then your can add jQuery something like this. ``` $(document).ready(function(){ $(".something").on("click", function() { var checked = $(this).is(":checked"); $(this).parent(".permission-block").children(".checkbox").find("input[type='checkbox']").props("checked", checked); }) }) ```
5,502,213
I have limited access to libraries so although using boost::multi\_index would solve my issue it is something that I cannot use. My current map setup is: The structure contains a fair amount of information in it such as an INT that I will also need to search by. What I was hoping was a structure such as so that I can search by int or string and return the structure values. I am assuming that I am going to have to write the key but, was coming here for other suggestions. Ideas?
2011/03/31
[ "https://Stackoverflow.com/questions/5502213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68046/" ]
I'm a little confused. You seem to be saying that you have a construct like this: (psudocode) ``` struct Gizmo { Gizmo(int foo, string bar) : foo_(foo), bar_(bar) {}; int foo_; string bar_; }; Gizmo make_gizmo(int foo, string bar) { return Gizmo(foo,bar); } std::map<string, Gizmo> my_gizmos; my_gizmos["aaa"] = make_gizmo(1,"hello"); my_gizmos["bbb"] = make_gizmo(2,"there"); ``` ...and you want to be able to search for `Gizmo`s by the value of `foo_`? In that case, you have 2 main options. 1) Just write a custom functor yourself (again psudocude): ``` struct match_foo : public std::unary_function<...> { match_foo(int foo) : foo_(foo) {}; bool operator()(map<string,Gizmo>::const_iterator it) const { return it->second.foo_ == foo_; } private: int foo_; }; map<string,Gizmo>::const_iterator that = find_if(my_gizmos.begin(), my_gizmos.end(), match_foo(2)); }; ``` 2) Create an index of the `foo_` values, mapping back to the `Gizmo` in the main `map`. This map might look something like this ... a ``` map<int,map<string,Gizmo>::const_iterator> foo_index; ``` ...which you would maintain any time you update the main map, `my_gizmos`.
If your searches actually are windowing queries(meaning you must return values in [param0\_0, peram0\_1]x[param1\_0, param1\_2]x...) or so, then you can use range tree structure for efficiency.
13,502,996
I have used `preventDefault` on an element event like this: ``` $('#element').click(function (e) { do stuff... }); ``` Now, I have a function that takes an argument already in which I would like to use `preventDefault` but I'm not sure how: ``` <a href="#services" id="services_link" class="services" onclick="sectionScroll('services')">Services</a> function sectionScroll(id) { history.pushState(null, null, '#' + id); $('html, body').animate({ scrollTop: $("#" + id).offset().top }, 1000); } ``` I tried using return false instead but this caused some flickering when the link was clicked. How can I add `preventDefault` to the above function? **EDIT** My original question was around using preventDefault in a function that has other arguments. I didn't need to use inline javascript in the end (it was looking like there was no way to avoid it), so this is what I used. I think it's quite tidy: ``` <a href="#services" class="menu-link">Services</a> $('.menu-link').click(function (e) { e.preventDefault(); var location = $(this).attr('href'); history.pushState(null, null, location) $('html, body').animate({ scrollTop: $(location).offset().top }, 1000); }); ```
2012/11/21
[ "https://Stackoverflow.com/questions/13502996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595279/" ]
You can use jQuery, like you are with the other example, to handle the click event: ``` <a href="#services" id="services_link" class="services">Services</a> $('#services_link').click(function (e) { var id = "services"; history.pushState(null, null, '#' + id); $('html, body').animate({ scrollTop: $("#" + id).offset().top }, 1000); e.preventDefault(); } ``` This will then allow you to call `preventDefault` on the event. This is also much better since you will no longer be using inline Javascript and your event logic can all be handled using one method (i.e. jQuery) rather than some of it being in jQuery and some inline. I would suggest reading "[Why Should I Avoid Inline Scripting?](https://softwareengineering.stackexchange.com/questions/86589/why-should-i-avoid-inline-scripting)" to get an idea of why you should try to avoid inline scripting.
If .on("click") adds "overflow:hidden" to the body or html, the page scrolls anyway to the top, even if you use e.preventDefalt() inside the callback.
4,649,953
Let's say that I have this query: ``` SELECT * FROM students_results WHERE full_name LIKE '".trim($_POST['full_name'])."' AND mother_name LIKE '".$database->escape_value(trim($_POST['mother_name']))."' AND birthday = '".$database->escape_value($_POST['year2'])."'" ``` I need to display a message for the vistor to tell him that he entered a wrong name or wrong mother name or wrong year. Now, I display a message for the user that he entered wrong values, I want to display detailed information about what wrong values he entered. Thanks in advance.
2011/01/10
[ "https://Stackoverflow.com/questions/4649953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/308745/" ]
> > How to get wrong values when executing > MySQL query? > > > **You can't.** Take the example of two `John Smith`s, one born 1/1/70 with a mother named Ann, and one born 1/1/80 with a mother named Alice. When the older John Smith enters 1/1/70 and Alice, how will you know it's not the younger John Smith entering the wrong birthdate? You couldn't be certain.
If `Students_results` table holds the students name, mothers name, the birthdate then I think the database isn't normalized enough. Normalizing could solve your problems too. You can use a student\_id to identify the correct row instead of a composite combination of name + mother name + bdate.
73,149,937
I'm writing a Java program that calculates the frequencies of words in an input. The initial integer indicates how many words will follow. Here is my code so far: ``` import java.util.Scanner; public class LabProgram { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int numberWords = scnr.nextInt(); String[] wordsList = new String[numberWords]; int i; int j; int[] frequency = new int[numberWords]; for (i = 0; i < numberWords; ++i) { wordsList[i] = scnr.next(); frequency[i] = 0; for (j = 0; j < numberWords; ++j) { if (wordsList[i].equals(wordsList[j])) { frequency[i] = frequency[i] + 1; } } } for (i = 0; i < numberWords; ++i) { System.out.print(wordsList[i] + " - " + frequency[i]); System.out.print("\n"); } } } ``` When I input the following: ```none 6 pickle test rick Pickle test pickle ``` This is the output: ```none pickle - 1 test - 1 rick - 1 Pickle - 1 test - 2 pickle - 2 ``` However, this is the expected output: ```none pickle - 2 test - 2 rick - 1 Pickle - 1 test - 2 pickle - 2 ``` It looks like it's picking up the correct frequencies for later occurrences, but not for the initial occurrences.
2022/07/28
[ "https://Stackoverflow.com/questions/73149937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19638813/" ]
Creating a `HashMap` containing frequencies of each word is the most performant approach. One of the ways to do it is by using method [`merge()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Map.html#merge(K,V,java.util.function.BiFunction)), that was introduced in the `Map` interface with Java 8. It expects three arguments: a *key*, a *value* to be associated with that *key* (if it was not present in the map) and a *function* that would be evaluated if the already exists, and we need to merge the previous value and a new one. ``` public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numberWords = scanner.nextInt(); Map<String, Integer> frequencies = new HashMap<>(); for (int i = 0; i < numberWords; i++) { frequencies.merge(scanner.next(), 1, Integer::sum); } frequencies.forEach((k, v) -> System.out.println(k + " -> " + v)); } ``` *Output:* ``` Pickle -> 1 test -> 2 rick -> 1 pickle -> 2 ``` In case if you're comfortable with Stream API, you can approach this problem using built-in *collector* [`toMap()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/Collectors.html#toMap(java.util.function.Function,java.util.function.Function,java.util.function.BinaryOperator)) (***note*** that we can read the input directly from the stream): ``` public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Map<String, Integer> frequencies = IntStream.range(0,scanner.nextInt()) .mapToObj(i -> scanner.next()) .collect(Collectors.toMap( Function.identity(), i -> 1, Integer::sum )); frequencies.forEach((k, v) -> System.out.println(k + " -> " + v)); } ``` *Output:* ``` Pickle -> 1 test -> 2 rick -> 1 pickle -> 2 ```
I used another string variable I named currWord to hold the values in wordsList[i] and then compared currWord to wordsList[j]. Here is the code: ``` import java.util.Scanner; public class LabProgram { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String [] userString = new String[20]; int [] wordFreq = new int[20]; String currWord; int stringLength; int i; int j; stringLength = scnr.nextInt(); userString = new String[stringLength]; wordFreq = new int[stringLength]; for (i = 0; i < stringLength; ++i) { userString[i] = scnr.next(); wordFreq[i] = 0; } for (i = 0; i < stringLength; ++i) { currWord = userString[i]; for (j = 0; j < stringLength; ++j) { if (userString[j].compareTo(currWord) == 0) { wordFreq[i] = wordFreq[i] + 1; } } } for (i = 0; i < stringLength; ++i) { System.out.println(userString[i] + " - " + wordFreq[i]); } } } ```
53,231
I have a long stretch of yard where I want to allow some of it to grow into a forested backstop / wind-block / nature promotion (birds, squirrels...whatever) It has been just grass for a long time, but I just started letting this section go a few weeks ago, in hopes it will eventually grow some trees, bushes...etc. Would eventually love tall trees, big oaks, maples, pines...etc, but that's probably a LONG way away. I did start by planting some small trees, but I'm wondering if this is the best path toward the end goal. As opposed to burning off the grass and weeds, or... I don't know. Anything else. Will the small 3ft saplings get overtaken by the weeds before they get a chance to grow? Is my only hope for big trees to plant them all myself, or might I get lucky had have some "dropped" in by birds? [![birdseye view](https://i.stack.imgur.com/hQAO1.jpg)](https://i.stack.imgur.com/hQAO1.jpg) [![yard](https://i.stack.imgur.com/UbhqF.jpg)](https://i.stack.imgur.com/UbhqF.jpg)
2020/07/17
[ "https://gardening.stackexchange.com/questions/53231", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/17234/" ]
Depends on how much money and work you want to put into it. I once helped a friend who wanted trees in a 60 acre former corn field he bought. He welded up a couple things to poke a 12" deep holes in the ground and we put in about a zillion cuttings of various trees. I never saw it again but he did occasionally speak of his "woods". Same fellow ,another technique; he buried many pounds of black walnuts in a moderately wooded area ( southern IN.).I prefer to put in trees, you can buy a variety of bare root trees from catalogs or internet- this must be done in early spring or maybe late fall when dormant. Or you can dig your own in some locations but a lot of work. Or you can buy trees in plastic buckets ,can be expensive. Also check with your state department of agriculture ,they offer low cost or free trees ( probably bare root) from time to time. Conifers need to be bought in buckets, although I got a bunch in bushel baskets from a Christmas tree farm in early spring. I have never found grass or weeds to be any problem. I would avoid foreign invasives like chinese tallow and alanthus altisimus, -they grow great and are snuck into package deals
After 10 loads of wood chips I've found that having an arborist dump off loads of late season tree trimmings with seeds in them will have plenty of viable seeds in them that you will want to spread in the area to about 1' in depth, but if you want specific trees you should plant the seeds in the wood chip mulch.
184,129
In Civil War we see Black Panther scratches Cap's shield with his claws, even though both are made of vibranium. How is this possible, especially given that Cap's shield is made of a vibranium alloy which is even stronger than simply using Vibranium? [![enter image description here](https://i.stack.imgur.com/F15fg.jpg)](https://i.stack.imgur.com/F15fg.jpg) My Question is different from [How were bullets able to dent Captain America's Shield?](https://scifi.stackexchange.com/questions/43043/how-were-bullets-able-to-dent-captain-americas-shield) because the conclusion to that question was that the bullets **don't** dent the shield, whereas in this case the claws **do** scratch the shield.
2018/03/23
[ "https://scifi.stackexchange.com/questions/184129", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/89070/" ]
Simple answer. In the MCU, [Cap's shield](http://marvelcinematicuniverse.wikia.com/wiki/Captain_America%27s_Shield) is only made out of Vibranium, not an alloy, as in the comics. > > "No, no, that's just a prototype." > > "What's it made of?" > > "Vibranium. It's stronger than steel and a third of the weight. It's completely vibration absorbent." > > "How come it's not standard issue?" > > "That's the rarest metal on Earth. What you're holding there, that's all we've got." > > ―Howard Stark and Steve Rogers > > > Thus, we have two items that are likely made of metals of the same toughness and hardness (there's no information on what other processing might be done with Vibranium). And that's assuming that Wakanda hasn't made any improvements on the process in the last several decades.
Though it wasn't explicitly stated, Black Panther's claws are made of Antarctic Vibranium or "Anti-metal", which is the opposite of Wakandan Vibranium. While Vibranium from Wakanda strengthens vibrations, Antarctic Vibranium weakens them.
112,443
I am currently doing my master’s in German and need to start writing my thesis. Although I am already comfortable speaking the language, writing (especially academic papers) is not something I feel great about. Also, my thesis is a big deal. Legally speaking, could I write it in English and have it translated? It would still be my work.
2018/07/10
[ "https://academia.stackexchange.com/questions/112443", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/94846/" ]
When I had to do my project in French - I wrote in French directly trying to minimise my errors - as it was engineering based the vocabulary is more difficult... But as I completed each chapter / section I got my French colleagues (also students) to read and correct / improve / comment on what I was writing. I bribed them with food and wine :) :) But we also had an exchange where I would look at the the English they had to write and help them with that... We helped each other...
First of all you need to weigh in pros and cons of having the final version of your thesis in German vs in English. Think of your future career plans in Germany or elsewhere, language the defense committee is comfortable with, etc. If you decide to write it in English and translate into German, do the following: 1. Make sure the thesis is complete, nice, and shiny in English 2. Translate it roughly by yourself into German with the help of fine free tools such as Google Translate and text editor spell checker, etc. Read it and see if you can correct some translation by yourself. 3. Buy a translation service to edit and proofread your translation. You will supply the translators with your German version and well as the English version. That way everything is perfectly legal, ethical, moral, transparent, and makes total sense on your side. Now, whether the translators will edit your German translation or completely discard it and translate it on their own isn't really of your concern, in fact it is their own business.
11,669,461
While instrumenting a class for its different methods In order to make a method do a write operation in a text file. I first stored the string in a local variable 3160 explicitly defined. How to choose these variables to prevent conflicts with already existing variables. Like in this snippet The code does the work of writing the class name to a text file every time it enters any method. In order to do so the string s had to be loaded on stack using variable 3160 ( value kept large so that the already defined variable names do not conflict with variable s (3160). My Question is how to define a local variables in a method during instrumentation with ASM Library. This question may seem kind of premature to many but that is because I am a beginner. ``` String s= className; mv.visitLdcInsn(s); mv.visitVarInsn(Opcodes.ASTORE, 3160); mv.visitTypeInsn(Opcodes.NEW, "java/lang/StringBuilder"); mv.visitInsn(Opcodes.DUP); mv.visitVarInsn(Opcodes.ALOAD, 3160); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;"); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "(Ljava/lang/String;)V"); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "com/me/database/dataCollectionFile/Info", "callMeAnyTime", "()Ljava/lang/String;"); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;"); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;"); ```
2012/07/26
[ "https://Stackoverflow.com/questions/11669461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1303506/" ]
You should use [LocalVariablesSorter](http://asm.ow2.org/asm40/javadoc/user/org/objectweb/asm/commons/LocalVariablesSorter.html) adapter (either extend your own visitor from it, or add it to the visitors chain before MethodWriter). Then when you'll need a new variable you can call [LocalVariablesSorter.newLocal()](http://asm.ow2.org/asm40/javadoc/user/org/objectweb/asm/commons/LocalVariablesSorter.html#newLocal%28org.objectweb.asm.Type%29) method to get new variable slot allocated. Also see [ASM guide](http://download.forge.objectweb.org/asm/asm4-guide.pdf) for more details.
I would look at the local variables debug table and I would use the next available id which is more likely to be 2 or 10 rather than 3160. If you don't have debugging information, you may need to scan the code more than once, first to see how many ids have been used. Note: `double` and `long` require two ids for historical reasons.
3,132,053
The following is a failing unittest explaining a bug I found today: ``` [TestMethod] public void WFT() { string configDebug = "false"; bool configDebugEnabled = bool.TryParse(configDebug, out configDebugEnabled); Assert.AreEqual(false, configDebugEnabled); } ``` This is how to make the test go from red to green: ``` [TestMethod] public void WFT() { string configDebug = "false"; bool configDebugEnabled; bool.TryParse(configDebug, out configDebugEnabled); Assert.AreEqual(true, configDebugEnabled); } ``` I haven't been able to find the paragraph explaining this in the C# specification but there's most likely a decent explanation to this behaviour. Can anybody explain to me why the first test is failing?
2010/06/28
[ "https://Stackoverflow.com/questions/3132053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11850/" ]
The reason it's failing is that you are using the same variable to store the *success or failure* of the `TryParse` itself. As the parsing succeeds (the string does translate to a boolean value) you are overwriting the returned value of `false` with `true`.
bool.TryParse returns a bool to specify whether the parse was successful. You are assigning that result to the same bool variable that you are putting in the out parameter. You need a separate variable to test for the success of the function.
4,374,476
I just began learning group theory and this question came across my mind. Suppose $f :G \to H$ is a group homomorphism, where $G$ and $H$ are groups. Is $\ker f $ unique? Based on my understanding, since homomorphism preserves identity from $G$ to $H$, and that identity in groups $G$ and $H$ is unique, there is only a unique element in $\ker f $.
2022/02/05
[ "https://math.stackexchange.com/questions/4374476", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1022273/" ]
Your argument only shows that the identity element of $G$ is contained in the kernel of $f$. There might be more elements depending on $f$ though. To give an extreme example: Let $G$ and $H$ be arbitrary groups and consider the homomorphism $1 \colon G \rightarrow H$ of groups that sends each element of $G$ to the identity element of $H$. Then the kernel of $1$ coincides with the group $G$.
Kernel of a homomorphism $f:G \to H$ is a set and the set is uniquely defined. If $0$ is the identity in $H$, then the $\ker(f) = \{g\in G \ | \ f(g) = 0\}$. However, the kernel need not have a unique element. Look at the following example: Let $G$ be the group of integers $\mathbb{Z}$ under addition. Consider the set $\{0,1\}$ and check that the set along with the operation defined as $0+0 = 0 = 1 + 1$ and $0+1 = 1 = 1+0$ forms a group. Call this group $H$. Further check that the operation $f: G \to H$ defined as $f(z) = 0$ if $z$ is even and $f(z) = 1$ if $z$ is odd is a homomorphism. Finally check that the kernel of $f$ is the set of even integers.
4,077,059
I want to find every url in text and wrap them with a tag (`<a href="...">...</a>`). ``` var src = "bla blaaa blaaaaaa 1 http://yahoo.com text something about and. http://www.google.com"; var match = /http:\/\/([a-z0-9.-]+)/.exec(src); //this only can one matched // result: ["http://yahoo.com", "yahoo.com"] ``` But i need to wrap every links.
2010/11/02
[ "https://Stackoverflow.com/questions/4077059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104085/" ]
You can use `/g` (global) to match all occurences and the backreference like this: ``` var src = "bla blaaa blaaaaaa 1 http://yahoo.com text something about and. http://www.google.com"; var match = src.replace(/http:\/\/([a-z0-9.-]+)/g, '<a href="$1">$1</a>'); ``` [You can test it out here](http://www.jsfiddle.net/nick_craver/GjHU5/1/).
``` var res = src.replace(/(http:\/\/([a-z0-9.-]+))/g, '<a href="$1">$2</a>'); ``` Outputs: `bla blaaa blaaaaaa 1 <a href="http://yahoo.com">yahoo.com</a> text something about and. <a href="http://www.google.com">www.google.com</a>` Not sure that was the intention, but what I could think of. Use `<a href="$1">$1</a>` as replacement if you want to preserve the `http://` prefix in the link text, too. (In the meantime Nick Craver provided the answer *and* introduced the `g` modifier.)
15,042,989
During some projects I have needed to validate some data and be as certain as possible that it is javascript numerical value that can be used in mathematical operations. jQuery, and some other javascript libraries already include such a function, usually called isNumeric. There is also a [post on stackoverflow](https://stackoverflow.com/a/1830844/592253) that has been widely accepted as the answer, the same general routine that the fore mentioned libraries are using. ``` function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } ``` Being my first post, I was unable to reply in that thread. The issue that I had with the accepted post was that there appear to be some corner cases that affected some work that I was doing, and so I made some changes to try and cover the issue I was having. First, the code above would return true if the argument was an array of length 1, and that single element was of a type deemed as numeric by the above logic. In my opinion, if it's an array then its not numeric. To alleviate this problem, I added a check to discount arrays from the logic ``` function isNumber(n) { return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n); } ``` Of course, you could also use `Array.isArray` instead of `Object.prototype.toString.call(n) !== '[object Array]'` **EDIT:** I've changed the code to reflect a generic test for array, or you could use jquery `$.isArray` or prototypes `Object.isArray` My second issue was that Negative Hexadecimal integer literal strings ("-0xA" -> -10) were not being counted as numeric. However, Positive Hexadecimal integer literal strings ("0xA" -> 10) wrere treated as numeric. I needed both to be valid numeric. I then modified the logic to take this into account. ``` function isNumber(n) { return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, '')); } ``` If you are worried about the creation of the regex each time the function is called then you could rewrite it within a closure, something like this ``` isNumber = (function () { var rx = /^-/; return function (n) { return Object.prototype.toString.call(n) !== '[object Array]' && !isNaN(parseFloat(n)) && isFinite(n.toString().replace(rx, '')); }; }()); ``` I then took CMSs [+30 test cases](http://dl.getdropbox.com/u/35146/js/tests/isNumber.html) and cloned the [testing on jsfiddle](http://jsfiddle.net/Xotic750/2q8pp/embedded/result/) added my extra test cases and my above described solution. Everything appears to be working as expected and I haven't experienced any issues. Are there any issues, code or theoretical, that you can see? It may not replace the widely accepted/used answer but if this is what you are expecting as results from your isNumeric function then hopefully this will be of some help. **EDIT**: As pointed out by [Bergi](https://stackoverflow.com/a/15230431/592253), there are other possible objects that could be considered numeric and it would be better to whitelist than blacklist. With this in mind I would add to the criteria. I want my isNumeric function to consider only Numbers or Strings With this in mind, it would be better to use ``` function isNumber(n) { return (Object.prototype.toString.call(n) === '[object Number]' || Object.prototype.toString.call(n) === '[object String]') &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, '')); } ``` This has been added as test 22
2013/02/23
[ "https://Stackoverflow.com/questions/15042989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592253/" ]
> > In my opinion, if it's an array then its not numeric. To alleviate this problem, I added a check to discount arrays from the logic > > > You can have that problem with any other object as well, for example `{toString:function(){return "1.2";}}`. Which objects would you think were numeric? `Number` objects? None? Instead of trying to blacklist some things that fail your test, you should explicitly whitelist the things you want to be numeric. What is your function supposed to get, primitive strings and numbers? Then test exactly for them: ``` (typeof n == "string" || typeof n == "number") ```
How about: ``` function isNumber(value) { value = Number(value); return typeof value === 'number' && !isNaN(value) && isFinite(value); } ```
197,625
So, my friend and I were chatting the other day. I, being a new father, sent him a picture of my clothesline completely full of my daughter's diapers. Then this dialogue happened: > > My friend: Woah, babies are really poop factories. > > Me: No shit. > > > Now, at that point, the chat spiraled out to a discussion on how wrong I was on using *no shit* on *poop factory*. Words such as *"complete opposite"* and *"idioms, idiot"* were uttered. I pointed my friend at the definition at [thefreedictionary.com definition](http://idioms.thefreedictionary.com/no+shit): > > *no shit* (rude) > > > 1. something is very surprising and hard to believe *He's coming here tonight? No shit!* > 2. the truth *This is no shit - we're going to have the money for you tomorrow.* > > > He wouldn't have it. So, I turn to ELU as final arbiter. Was my response above correct or not? Edit: After accepting the answer below, I notice that this question could use a better title. If you have a better idea on what should this question be titled, please edit it and remove this paragraph.
2014/09/22
[ "https://english.stackexchange.com/questions/197625", "https://english.stackexchange.com", "https://english.stackexchange.com/users/88539/" ]
Correct and appropriate. Additionally *No shit Sherlock* ==> "You are stating the obvious" which according to [Wiktionary](http://en.wiktionary.org/wiki/no_shit,_Sherlock) breaks down into > > **no shit** (“an expression of amazement”) + **Sherlock** (“a fictional detective who makes ingenious deductions”) > > >
Mplungjan has explained one sense in which your response was appropriate. There is another too, though it does involve inserting a comma into your original formulation: > > *"No, shit".* > > > Or perhaps (even more appropriately, given the topic) a colon: > > *"No: shit".* > > > You would say this if you felt that *shit* was a more suitable word than *poop* to describe your child's excreta (for instance, because you are the type of person who believes in calling a spade a spade rather than a 'digging implement'). It also puns rather pleasingly on the idiom that Mplungjan described.
14,612,444
I'm a newbie to shell scripting. I have written a shell script to do incremental backup of MySQL database.The script is in executable format and runs successfully when executed manually but fails when executed through crontab. Crontab entry is like this : ``` */1 * * * * /home/db-backup/mysqlbackup.sh ``` Below is the shell script code - ``` #!/bin/sh MyUSER="root" # USERNAME MyPASS="password" # PASSWORD MyHOST="localhost" # Hostname Password="" #Linux Password MYSQL="$(which mysql)" if [ -z "$MYSQL" ]; then echo "Error: MYSQL not found" exit 1 fi MYSQLADMIN="$(which mysqladmin)" if [ -z "$MYSQLADMIN" ]; then echo "Error: MYSQLADMIN not found" exit 1 fi CHOWN="$(which chown)" if [ -z "$CHOWN" ]; then echo "Error: CHOWN not found" exit 1 fi CHMOD="$(which chmod)" if [ -z "$CHMOD" ]; then echo "Error: CHMOD not found" exit 1 fi GZIP="$(which gzip)" if [ -z "$GZIP" ]; then echo "Error: GZIP not found" exit 1 fi CP="$(which cp)" if [ -z "$CP" ]; then echo "Error: CP not found" exit 1 fi MV="$(which mv)" if [ -z "$MV" ]; then echo "Error: MV not found" exit 1 fi RM="$(which rm)" if [ -z "$RM" ]; then echo "Error: RM not found" exit 1 fi RSYNC="$(which rsync)" if [ -z "$RSYNC" ]; then echo "Error: RSYNC not found" exit 1 fi MYSQLBINLOG="$(which mysqlbinlog)" if [ -z "$MYSQLBINLOG" ]; then echo "Error: MYSQLBINLOG not found" exit 1 fi # Get data in dd-mm-yyyy format NOW="$(date +"%d-%m-%Y-%T")" DEST="/home/db-backup" mkdir $DEST/Increment_backup.$NOW LATEST=$DEST/Increment_backup.$NOW $MYSQLADMIN -u$MyUSER -p$MyPASS flush-logs newestlog=`ls -d /usr/local/mysql/data/mysql-bin.?????? | sed 's/^.*\.//' | sort -g | tail -n 1` echo $newestlog for file in `ls /usr/local/mysql/data/mysql-bin.??????` do if [ "/usr/local/mysql/data/mysql-bin.$newestlog" != "$file" ]; then echo $file $CP "$file" $LATEST fi done for file1 in `ls $LATEST/mysql-bin.??????` do $MYSQLBINLOG $file1>$file1.$NOW.sql $GZIP -9 "$file1.$NOW.sql" $RM "$file1" done $RSYNC -avz $LATEST /home/rsync-back ``` * First of all, when scheduled on crontab it is not showing any errors. How can I get to know whether the script is running or not? * Secondly, what is the correct way to execute the shell script in a crontab. Some blogs suggest for change in environment variables. What would be the best solution When I did $echo PATH, I got this ``` /usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/mysql/bin:/opt/android-sdk-linux/tools:/opt/android-sdk-linux/platform-tools:~/usr/lib/jvm/jdk-6/bin ```
2013/01/30
[ "https://Stackoverflow.com/questions/14612444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1809252/" ]
The problem is probably that your $PATH is different in the manual environment from that under which crontab runs. Hence, `which` can't find your executables. To fix this, first print your path in the manual environment (`echo $PATH`), and then manually set up PATH at the top of the script you run in crontab. Or just refer to the programs by their full path. Edit: Add this near the top of your script, before all the `which` calls: ``` export PATH="/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/mysql/bin:/opt/android-sdk-linux/tools:/opt/android-sdk-linux/platform-tools:~/usr/lib/jvm/jdk-6/bin" ```
My Issue was that I set the cron job in /etc/cron.d (Centos 7). It seems that when doing so I need to specify the user who executes the script, unlike when a cronjob is entered at a user level. All I had to do was ``` */1 * * * * root perl /path/to/my/script.sh */5 * * * * root php /path/to/my/script.php ``` Where "root" states that I am running the script as root. Also need to make sure the following are defined at the top of the file. Your paths might be different. If you are not sure try the command "which perl", "which php". ``` SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin ```
46,421,677
I'm using the following code to agregate students per year. The purpose is to know the total number of student for each year. ``` from pyspark.sql.functions import col import pyspark.sql.functions as fn gr = Df2.groupby(['Year']) df_grouped = gr.agg(fn.count(col('Student_ID')).alias('total_student_by_year')) ``` The problem that I discovered that so many ID's are repeated, so the result is wrong and huge. I want to agregate the students by year, count the total number of student by year and avoid the repetition of ID's.
2017/09/26
[ "https://Stackoverflow.com/questions/46421677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8674940/" ]
If you are working with an older Spark version and don't have the `countDistinct` function, you can replicate it using the combination of `size` and `collect_set` functions like so: ``` gr = gr.groupBy("year").agg(fn.size(fn.collect_set("id")).alias("distinct_count")) ``` In case you have to count distinct over multiple columns, simply concatenate the columns into a new one using `concat` and perform the same as above.
By using Spark/PySpark SQL ``` y.createOrReplaceTempView("STUDENT") spark.sql("SELECT year, count(DISTINCT id) as count" + \ "FROM STUDENT group by year").show() ```
19,764,216
Assume I have some controller "Controller" and public method in it: ``` public ActionResult GetICal(int? param1, int? param2) { string cal = ""; //some logic goes here return File(Encoding.UTF8.GetBytes(cal), "text/calendar", "calendar.ics"); } ``` Then I'm trying to export it to Google Calendar via url: <https://my.site.com/controller/getIcal?param1=0&param2=1> And then nothing happens. Once i've got message like "Can't fetch url" (or simething like that). I don't know, what I'm doing wrong. This url is 100% accessible without authorization. And if I'm adding this calendar via file, everything is going ok (so calendar has correct format).
2013/11/04
[ "https://Stackoverflow.com/questions/19764216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2169077/" ]
It's unfortunate that this bug has been around for so long, and that most answers here thought the question was about horizontal alignment rather than vertical spacing. [The bug](https://github.com/matplotlib/matplotlib/issues/6323) is known, and there is a patch to fix it, but it hasn't been merged, and simply been listed as needing review for the last year and a half. Interestingly, it's a bug that is rather confusing. The problem initially arises in that, for some reason, TeX gives a minus sign (and several other math symbols) a descender value, suggesting that it extends goes below the baseline. dvipng, used to create the labels in raster backends, just crops to the visible, so this wouldn't matter. But to keep things aligned that actually do have descenders, matplotlib has a separate system, dviread, that reads values from the dvi file itself. This picks up the odd descender value. Then matplotlib's alignment system, thinking that part of the png is *supposed* to be below the baseline, moves it down. The fix in the bug report is very simple, but I'm not entirely sure how it works. I've tried it, however, and it does work. Of course, this question was asked in 2013, so it doesn't seem like the patch is going to be applied any time soon. So what are the alternatives? One easy option is to just ignore the alignment issue when working, but, when doing presentation output, use the pdf backend. If you want images, you can always use other software to convert. The pdf backend does not suffer from the same problem, as it handles TeX portions completely differently. The other option is to just tweak the position of negative xticks. In theory, you could pull the exact tweak out from \_get\_layout, which will give you the descender value, but I'm not sure how to convert the values. So here's an example of just eyeing the alignment: ``` import numpy as np import matplotlib.pyplot as plt t = np.linspace(-10.0, 10.0, 100) s = np.cos(t) i = [-10,-5,0,5,10] plt.rc('text', usetex=True) plt.rc('font', family='serif', size=30) plt.plot(t, s) for n,l in zip(*plt.xticks()): if n<0: l.set_position((0,0.014)) ```
The way I fix minor problems like this is to save the plot as an SVG and then edit it in my favourite Vector Graphics program (such as [InkScape](http://www.inkscape.org/en/)). This will allow you to select the individual parts of the plot and move them while preserving the good quality vector graphics.
2,836,042
When I look up for properties of the natural Logarithm I found in particular this property > > $$ \ln(x^r)=r \ln(x) $$ > > with $$x\in \Bbb R^{+\*} $$ > and$$ r\in\Bbb Q$$ > > > My Question is : Why $r$ should be $ \in\Bbb Q$ why not $r\in\Bbb R$ because i can't figure out any problem with being $ r\in\Bbb R$
2018/06/29
[ "https://math.stackexchange.com/questions/2836042", "https://math.stackexchange.com", "https://math.stackexchange.com/users/473273/" ]
It should be for all real $r$. The only reason I can see to restrict to $\Bbb Q$ is if you haven't defined $x^r$ for irrational $r$. You can define it for rational $r$ based on the definition for integers and the laws of exponents. Wherever you saw this may not have made the definition for irrational $r$ yet. That usually goes through defining the exponential function or the natural logarithm, with the natural log defined as the integral of $\frac 1x$
In the terms you put it, there is really no problem: that identity holds for all $r\in\Bbb R$.
7,087,861
I have a set of file names. ``` Eg: name=apple_class=1A_regis=1.txt name=apple_class=1A_regis=2.txt name=pear_class=1A_regis=1.txt ``` I want to be able to save all the file names that have the same 'name=apple\_class=1A' into an array. That would save the first two file names into an array. I have tried using for loop but I am still unable to get this as I have no idea how to check the filenames. Please help. Thanks!
2011/08/17
[ "https://Stackoverflow.com/questions/7087861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/897920/" ]
Alternative for those wanting method/action or class/controller wide `no-cache` ``` [OutputCache(Location = OutputCacheLocation.None)] public class HomeController : Controller { ... } ``` As explained here: [OutputCacheLocation Enumeration](http://msdn.microsoft.com/en-us/library/system.web.ui.outputcachelocation%28v=vs.100%29.aspx) > > None : The output cache is disabled for the requested page. This value > corresponds to the HttpCacheability.NoCache enumeration value. > > > [HttpCacheability Enumeration](http://msdn.microsoft.com/en-us/library/system.web.httpcacheability%28v=vs.100%29.aspx) > > NoCache - Sets the Cache-Control: no-cache header.... > > >
I recommend that these calls be limited to non-GET requests, to avoid losing the benefit of cache on GETs. The following ensures that even aggressive caching browsers like iOS 6 Safari will not cache anything that is not a GET request. I use a Controller base class that all of my controllers inherit from for a number of reasons, and this served well in that my Initialize override can handle setting my caching headers conditionally. ``` public class SmartController : Controller { ... public HttpContextBase Context { get; set; } protected override void Initialize(System.Web.Routing.RequestContext requestContext) { Context = requestContext.HttpContext; if (Context.Request.RequestType != "GET") { Context.Response.Cache.SetCacheability(HttpCacheability.NoCache); } base.Initialize(requestContext); ... } ... } ```
16,771,958
I have created a .NET Windows Service and installed the debug release from the bin/debug folder (yes I know this isn't a good approach, but I just want to be able to test it and attach debugger). The service basically runs in an endless loop checking an FTP directory for files, processing them, sleeping for a minute and then looping. When I attempt to start the service I get the following error ``` Error 1053: The service did not respond to the start or control request in a timely fashion ``` On further inspection the service is completing the first loop and then timing out during the first thread sleep. As such I'm somewhat confused as to how I should start the service. Is it my (lack of) understanding of threading that is causing this? My start code is ``` protected override void OnStart(string[] args) { eventLog.WriteEntry("Service started"); ThreadStart ts = new ThreadStart(ProcessFiles); workerThread = new Thread(ts); workerThread.Start(); } ``` In the ProcessFiles function, once a loop has been completed I simply have ``` eventLog.WriteEntry("ProcessFiles Loop complete"); Thread.Sleep(new TimeSpan(0,1,0)); ``` When I check the event logs the 'ProcessFiles Loop complete' log is there, but that is the last event before the service timesout and fails to start. Can someone explain what I am doing wrong? EDIT ==== The way I am handling the loop in my ProcessFiles function is as below ``` while (!this.serviceStopped) { // Do Stuff eventLog.WriteEntry("ProcessFiles Loop complete"); Thread.Sleep(new TimeSpan(0,1,0)); } ``` Cheers Stewart
2013/05/27
[ "https://Stackoverflow.com/questions/16771958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821210/" ]
As hinted in the comments, you need to reduce the number of queries by catenating as many inserts as possible together. In PHP, it is easy to achieve that: ``` $query = "insert into scoretable values"; for($a = 0; $a < 1000000; $a++) { $id = rand(1,75000); $score = rand(1,100000); $time = rand(1367038800 ,1369630800); $query .= "($id, $score, $time),"; } $query[strlen($query)-1]= ' '; ``` There is a limit on the maximum size of queries you can execute, which is directly related to the `max_allowed_packet` server setting ([This page](http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html) of the mysql documentation describes how to tune that setting to your advantage). Therfore, you will have to reduce the loop count above to reach an appropriate query size, and repeat the process to reach the total number you want to insert, by wrapping that code with another loop. Another practice is to disable check constraints on the table you wish to do bulk insert: ``` ALTER TABLE yourtablename DISABLE KEYS; SET FOREIGN_KEY_CHECKS=0; -- bulk insert comes here SET FOREIGN_KEY_CHECKS=1; ALTER TABLE yourtablename ENABLE KEYS; ``` This practice however must be done carefully, especially in your case since you generate the values randomly. If you have any unique key within the columns you generate, you cannot use that technique with your query as it is, as it may generate a duplicate key insert. You probably want to add a `IGNORE` clause to it: ``` $query = "insert INGORE into scoretable values"; ``` This will cause the server to silently ignore duplicate entries on unique keys. To reach the total number of requiered inserts, just loop as many time as needed to fill up the remaining missing lines. I suppose that the only place where you could have a unique key constraint is on the `id` column. In that case, you will never be able to reach the number of lines you wish to have, since it is way above the range of random values you generate for that field. Consider raising that limit, or better yet, generate your ids differently (perhaps simply by using a counter, which will make sure every record is using a different key).
You are doing several things wrong. First thing you have to take into account is what MySQL engine you're using. The default one is InnoDB, previously the default engine is MyISAM. I'll write this answer under assumption you're using InnoDB, which you should be using for plethora of reasons. InnoDB operates in something called autocommit mode. That means that every query you make is wrapped in a transaction. To translate that to a language that us mere mortals can understand - every query you do *without* specifying `BEGIN WORK;` block is a transaction - ergo, MySQL will wait until hard drive confirms data has been written. Knowing that hard drives are slow (mechanical ones are still the ones most widely used), that means your inserts will be as fast as the hard drive is. Usually, mechanical hard drives can perform about 300 input output operations per second, ergo assuming you can do 300 inserts a second - yes, you'll wait quite a bit to insert 1 million records. So, knowing how things work - you can use them to your advantage. The amount of data that the HDD will write per transaction will be generally very small (4KB or even less), and knowing today's HDDs can write over 100MB/sec - that indicates that we should wrap several queries into a single transaction. That way MySQL will send quite a bit of data and wait for the HDD to confirm it wrote everything and that the whole world is fine and dandy. So, assuming you have 1M rows you want to populate - you'll execute 1M queries. If your transactions commit 1000 queries at a time, you should perform only about 1000 write operations. That way, your code becomes *something* like this: (I am not familiar with mysqli interface so function names might be wrong, and seeing I'm typing without actually running the code - the example might not work so use it at your own risk) ``` function generateRandomData() { $db = new mysqli('localhost','XXX','XXX','scores'); if(mysqli_connect_errno()) { echo 'Failed to connect to database. Please try again later.'; exit; } $query = "insert into scoretable values(?,?,?)"; // We prepare ONCE, that's the point of prepared statements $stmt = $db->prepare($query); $start = 0; $top = 1000000; for($a = $start; $a < $top; $a++) { // If this is the very first iteration, start the transaction if($a == 0) { $db->begin_transaction(); } $id = rand(1,75000); $score = rand(1,100000); $time = rand(1367038800 ,1369630800); $stmt->bind_param("iii",$id,$score,$time); $stmt->execute(); // Commit on every thousandth query if( ($a % 1000) == 0 && $a != ($top - 1) ) { $db->commit(); $db->begin_transaction(); } // If this is the very last query, then we just need to commit and end if($a == ($top - 1) ) { $db->commit(); } } } ```
17,751,377
Sorry if the title is a little confusing. I have a form for an `Item` with the field `name`. There's a text field where the user can input a name and submit it. But if the user doesn't type in anything and hits submit, Rails gives me a `param not found: item` error, and I'm not sure who to get around this. items\_controller.rb ``` def new @item = Item.new() respond_to do |format| format.html format.json { render json: @item } end end def create @item = Item.new(item_params) respond_to do |format| if @item.save format.html { redirect_to items_path } format.json { render json: @item, status: :created, location: @item } else format.html { render action: 'new', :notice => "Input a name." } format.json { render json: @item.errors, status: :unprocessable_entity } end end end private def item_params params.require(:item).permit(:name) end ``` app/views/items/new.html.haml ``` = form_for @item do |f| = f.label :name = f.text_field :name = f.submit "Submit" ``` The params.require(:item) part is what is causing the error. What the convention for handling the error when params[:item] isn't present?
2013/07/19
[ "https://Stackoverflow.com/questions/17751377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1839623/" ]
**Update:** Scaffolded rails4 app: <https://github.com/szines/item_17751377> It works if a user keep name field empty when create a new item... Looks, it works without problem... Development.log shows that parameters would be the following if user keep a field empty: ``` "item"=>{"name"=>""} ``` There is always something in the hash... As Mike Li already mentioned in a comment, something wrong... because shouldn't be empty this params[:item]... You can check if something nil, with `.nil?` , in this case `params[:item].nil?` will be `true` if it is `nil`. Or you can use .present? as sytycs already wrote. **Previous answer:** If you have situation when :item is empty, you should just use params[:item] without require. ``` def item_params params[:item].permit(:name) end ``` More information about require in strong\_parameters.rb source code: ``` # Ensures that a parameter is present. If it's present, returns # the parameter at the given +key+, otherwise raises an # <tt>ActionController::ParameterMissing</tt> error. # # ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person) # # => {"name"=>"Francesco"} # # ActionController::Parameters.new(person: nil).require(:person) # # => ActionController::ParameterMissing: param not found: person # # ActionController::Parameters.new(person: {}).require(:person) # # => ActionController::ParameterMissing: param not found: person def require(key) self[key].presence || raise(ParameterMissing.new(key)) end ```
I personally have not switched to strong parameters so I'm not sure how one should handle something like: ``` params.require(:item).permit(:name) ``` but you can always check for item presence with something like: ``` if params[:item].present? … end ```
1,492,297
In MySQL, how can I retrieve ALL rows in a table, starting from row X? For example, starting from row 6: ``` LIMIT 5,0 ``` This returns nothing, so I tried this: ``` LIMIT 5,ALL ``` Still no results (sql error). I'm not looking for pagination functionality, just retrieving all rows starting from a particular row. `LIMIT 5,2000` seems like overkill to me. Somehow Google doesn't seem to get me some answers. Hope you can help. Thanks
2009/09/29
[ "https://Stackoverflow.com/questions/1492297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37630/" ]
If you're looking to get the last x number of rows, the easiest thing to do is `SORT DESC` and LIMIT to the *first* x rows. Granted, the `SORT` will slow your query down. But if you're opposed to setting an arbitrarily large number as the second `LIMIT` arg, then that's the way to do it.
The only solution I am aware of currently is to do as you say and give a ridiculously high number as the second argument to LIMIT. I do not believe there is any difference in performance to specifying a low number or a high number, mysql will simply stop returning rows at the end of the result set, or when it hits your limit.
43,723
I think it would be interesting to show some type of recognition on the main page for the "developer of the week", i.e. the developer who received the most votes (not reputation since there's a 200 per day cap) for a week. While no mortal man can possibly catch up with Jon Skeet's reputation; they may be able to top him over the period of a week. Could make the game a bit more interesting. Just thinking... --- **Update (Aug 23 '11)** *I can't believe this idea got picked up (<https://stackoverflow.com/users>) after everyone gave me crap for it :P Now there's a week, month, year and all-time reputation tab. The idea is the same just the location is different.*
2010/03/23
[ "https://meta.stackexchange.com/questions/43723", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/134817/" ]
I'd be for this if the basis for the "Developer of the Week" title wouldn't be just reputation, but, say, the fact that somebody has gone the "extra mile" (providing support in comments beyond the mere collection of reputation for a good answer) extraordinarily often, or provided a truly brilliant, unheard-of answer. Things like that would have to be picked (or nominated) manually by users in the different tags. Otherwise, we'll just have even more of a rat-race of people trying to collect as much reputation as possible.
This is for reputation, not upvotes, but the [reputation leagues](https://stackexchange.com/leagues/1/week/stackoverflow) show this.
111,487
We have a big problem that's just started happening. One of our network apps (may it rot in hell) requires a mapped network drive to function. Therefore, we map a drive to the network share in question for the users. This usually shows up of course in Explorer as: ``` Sharename on 'Servername' (Q:) ``` Problem is, it now shows up as ``` Disconnected Network Drive (Q:) ``` And I can't remove it in any way * **Right-click and select disconnect**: "The network connection could not be found" * **CMD: net use q: /delete** - "The network connection could not be found." * **CMD: net use \servername\sharename /delete** - "The network connection could not be found." * **CMD: net use Q: \servername\sharename** - "The device is already in use" * **Delete the user profile** - no change * **Log in as new, never-logged-in-before user** - same problem * **REG: delete HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2##servername#sharename** - no change Other items of note: * Client machine is Windows Server 2003 R2 x86 * Server is Windows Server 2003 x86
2010/02/10
[ "https://serverfault.com/questions/111487", "https://serverfault.com", "https://serverfault.com/users/14556/" ]
It almost sounds like you're after a P2P kind of deployment. I've never seen something like that, but it could be an interesting idea. We use ESET NOD32, which can run just fine without connection to a central server. Of course, then you miss out on centralized monitoring and alerting, as well as automated deployment. I believe it uses HTTP as the update method, so with a bit of hacking you could get all of the clients to update from a local HTTP server.
I think it may be worth you while to grab eval copies of some likely looking AV products and install them on a test (virtual?) machine. Then have a look to see if they can be configured to grab the updates from a specific source. If they can, it should be easy enough to determine where their default downloads come from, along with whatever connection strings are sent to the source. Once you've found one you can work with, set one machine up to download the updates and configure the rest to get them from that machine. In all likelihood the download source settings will be stored in the registry, making it simply to use GPO or a script to propagate that information. It's a fair bit of fiddling about but the end result may be worth it.
33,438,858
I am adding a folder module to a Moodle course using the API: ``` folder_add_instance($data, null); ``` I am getting the error below when running the script using CMD: ``` !!! Invalid course module ID !!! ``` I looked into the folder\_add\_instance() function in the library, the error is occurring when trying to get the context: ``` $context = context_module::instance($cmid)//$cmid = 8 ``` i looked into the mdl\_context table in Moodle database but couldn't understand the values and their relation to the error i am getting. Will deleting the mdl\_context values from the database will help? or i am missing something here? Note that the script was working fine, until i deleted all the courses i had on Moodle using the web interface.(i deleted the category containing all the courses).
2015/10/30
[ "https://Stackoverflow.com/questions/33438858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1934229/" ]
Here's complete code using `forEach`. The steps are same as [Quentin](https://stackoverflow.com/users/19068/quentin) has stated in his [answer](https://stackoverflow.com/a/33438900/2025923) 1. Copy the value 2. Remove the key-value from the object 3. Add new item with new value in the object ```js var arr = [{ "FIRST NAME": "Philip", "LAST NAME": "Rivers", "NUMBER": "17", "GPA": "1.0", "OLD_FACTOR": "8", "NICENESS": "1" }, { "FIRST NAME": "Peyton", "LAST NAME": "Manning", "NUMBER": "18", "GPA": "4.0", "OLD_FACTOR": "5000", "NICENESS": "5000" }]; // Iterate over array arr.forEach(function(e, i) { // Iterate over the keys of object Object.keys(e).forEach(function(key) { // Copy the value var val = e[key], newKey = key.replace(/\s+/g, '_'); // Remove key-value from object delete arr[i][key]; // Add value with new key arr[i][newKey] = val; }); }); console.log(arr); document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4); ``` ```html <pre id="result"></pre> ``` --- **Strictly if the JSON is get in the form of String from server:** Replace the spaces by `_` from the keys. ``` JSON.parse(jsonString.replace(/"([\w\s]+)":/g, function (m) { return m.replace(/\s+/g, '_'); })); ```
You need to: * Copy the **value** * Delete the old property * Modify the correct object. (`data[i][obj]` will convert `obj` to a string and try to use it as a property name). Such: ``` for (var original_property in obj) { var new_property = original_property.split(' ').join('_'); obj[new_property] = obj[original_property]; delete obj[original_property] } ```
9,198,362
``` <html> <head> </head> <body onload=> <button></button> <script> function give_show(value) { return function() { console.log(value); } } var button_element =document.getElementsByTagName('button')[0]; button_element.addEventListener('load',give_show('bong!'),false) </script> </body> </html> ``` The above code works. in console I got: ``` bong! ``` However, if I change this part: ``` function give_show(value) { return function() { console.log(value); } ``` to ``` function give_show(value) { return function(value) { console.log(value); } ``` I got something like ``` mouse.event ``` What's causing that to happen? FYI: I use Safari console to get the result.
2012/02/08
[ "https://Stackoverflow.com/questions/9198362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
Nested functions have access to everything defined in the scope in which they are created. So: ``` function give_show(value){ return function(){ console.log(value); } } ``` when you reference `value` in the nested function the variable defined in `give_show` is in scope and is used. However, when you do this: ``` function give_show(value){ return function(value){ console.log(value); } } ``` you are returning a function that takes an argument `value`, so that variable name hides the one defined by `give_show`. --- To make what's happening in the second case more obvious, this code does exactly the same thing, without hiding the `value` variable from the outer scope: ``` function give_show(value){ return function(event){ console.log(event); } } ``` The `console.log` method is using the argument passed to your returned function, and is completely ignoring the value passed to `give_show`. This is why you're getting 'mouse.event' and not 'bong!' in your second case - event handlers are passed the event as their argument.
I change `load` for `click` on listners and add `console.log` before return internal function: ``` <html> <head> </head> <body> <button></button> <script> function give_show(value) { console.log(value); return function(value) { console.log(value); } } var button_element =document.getElementsByTagName('button')[0]; button_element.addEventListener('click',give_show("bong!"),false); </script> </body> </html> ``` confusion is when `give_show` is passed to `addEventListner`. In example `give_show` run before you click in button and `Bong!` is write on console. The `addEventListner` only recognizes function: ``` function(value) { console.log(value); } ``` and event(click) pass to `value` the position of clicked by mouse. This is same to make this: ``` button_element.addEventListener('click',function(value) { console.log(value); }, false); ``` If you suppress `value` parameter `value` used is from passed to `give_show` function.
4,585,439
I have tried searching almost all the blog sites. I need to send an MMS programatically. As far as my research on this I came to know that its not possible for IOS < 3. Is there any way i can use the messageUI kit fot sending MMS for IOS 4. Please let me know the possible ways. Thanks in advance!!!
2011/01/03
[ "https://Stackoverflow.com/questions/4585439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/561365/" ]
You cannot send MMS right now. `MFMessageComposeViewController` only allow SMS messages on iOS 4 only.
iOS prevents SMS or MMS messages from being sent programmatically. You can compose the message, providing the "To" and the body of the message (in iOS 4+) and display a dialog that allows the user to tap a button and send it, but user intervention is always required.
44,437,784
trying to parse multiple sql variables from one file to another using session arrays but i cant. Whats the part iam missing here? Thanks in advance. file1.php ``` session_start(); while($row=mysql_fetch_array($result,MYSQL_BOTH)) { echo "<tr>"; $id=$row['id']; $array[] = $id; } $_SESSION['id'] = $array; ``` file2.php ``` session_start(); foreach( $array as $id ) { echo $id; } ```
2017/06/08
[ "https://Stackoverflow.com/questions/44437784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5687851/" ]
You can simply use this: ``` 'request_input' => exists:table,col,alternative_col_1,alternative_val_1,alternative_col_2,alternative_val_2, ...' ``` The SQL query is like below: ``` select count(*) as aggregate from `table` where `id` = [request_input] and `alternative_col1` = "alternative_val1" and `alternative_col2` = "alternative_val2" ```
``` if (is_numeric($request->get('emailOrphone'))){ $request->validate([ 'emailOrphone'=>'exists:users,phone', ], [ 'emailOrphone.exists'=>'phone is invalid.' ]); }else{ $request->validate([ 'emailOrphone'=>'exists:users,email', ], [ 'emailOrphone.exists'=>'email is invalid.'' ]); } ```
51,256,570
I want to be able to move an img around within its container once the image is zoomed in, because as you can see once you click the image it becomes too big and you can't see the whole image. Also how can I make the image goes back to normal once it's not being hovered? thanks in advance. ```js // Zoom in/out clothing img $('.image').click(function() { $(this).toggleClass('normal-zoom zoom-in'); }); ``` ```css .container { width: 800px; margin: 0 auto; border: 2px solid black; display: flex; } .img-wrapper { margin: 10px; overflow: hidden; } .image { width: 100%; height: 100%; } .text { width: 40%; padding: 20px; } .normal-zoom { transform: scale(1); cursor: zoom-in; transition: all 250ms; } .zoom-in { transform: scale(1.6); cursor: zoom-out; transition: all 250ms; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="img-wrapper"> <img src="https://static1.squarespace.com/static/560c458be4b0af26f729d191/560c5de0e4b083d9c365515f/560d53d4e4b03b1013fd40de/1443714010032/lauren-winter-wide-pant-natural_0178.jpg?format=750w" class="image normal-zoom"> </div> <p class="text">Kept in sent gave feel will oh it we. Has pleasure procured men laughing shutters nay. Old insipidity motionless continuing law shy partiality. Depending acuteness dependent eat use dejection. Unpleasing astonished discovered not nor shy. Morning hearted now met yet beloved evening. Has and upon his last here must. Cottage out enabled was entered greatly prevent message. No procured unlocked an likewise. Dear but what she been over gay felt body. Six principles advantages and use entreaties decisively. Eat met has dwelling unpacked see whatever followed. Court in of leave again as am. Greater sixteen to forming colonel no on be. So an advice hardly barton. He be turned sudden engage manner spirit.</p> </div> ```
2018/07/10
[ "https://Stackoverflow.com/questions/51256570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9840977/" ]
Since you're using `transform: scale()` for the zoom effect it's faster and more correct to modify `transform-origin` to change the center point of the zoom effect on mousemove: ```js // Zoom in/out clothing img $('.image').click(function() { $(this).toggleClass('normal-zoom zoom-in'); }); $('.image').on('mousemove', function(event) { // This gives you the position of the image on the page var bbox = event.target.getBoundingClientRect(); // Then we measure how far into the image the mouse is in both x and y directions var mouseX = event.clientX - bbox.left; var mouseY = event.clientY - bbox.top; // Then work out how far through the image as a percentage the mouse is var xPercent = (mouseX / bbox.width) * 100; var yPercent = (mouseY / bbox.height) * 100; // Then we change the `transform-origin` css property on the image to center the zoom effect on the mouse position //event.target.style.transformOrigin = xPercent + '% ' + yPercent + '%'; // It's a bit clearer in jQuery: $(this).css('transform-origin', (xPercent+'% ' + yPercent+ '%') ); // We add the '%' units to make sure the string looks exactly like the css declaration it becomes. }); // If you want it to automatically trigger on hover $('.image').on('mouseenter', function() { $(this).addClass('zoom-in'); $(this).removeClass('normal-zoom'); }); // and stop when not hovering $('.image').on('mouseleave', function() { $(this).addClass('normal-zoom'); $(this).removeClass('zoom-in'); }); ``` ```css .container { width: 800px; margin: 0 auto; border: 2px solid black; display: flex; } .img-wrapper { margin: 10px; overflow: hidden; } .image { width: 100%; height: 100%; } .text { width: 40%; padding: 20px; } .normal-zoom { transform: scale(1); cursor: zoom-in; transition: transform 250ms; } .zoom-in { transform: scale(1.6); cursor: zoom-out; transition: transform 250ms; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="img-wrapper"> <img src="https://static1.squarespace.com/static/560c458be4b0af26f729d191/560c5de0e4b083d9c365515f/560d53d4e4b03b1013fd40de/1443714010032/lauren-winter-wide-pant-natural_0178.jpg?format=750w" class="image normal-zoom"> </div> <p class="text">Kept in sent gave feel will oh it we. Has pleasure procured men laughing shutters nay. Old insipidity motionless continuing law shy partiality. Depending acuteness dependent eat use dejection. Unpleasing astonished discovered not nor shy. Morning hearted now met yet beloved evening. Has and upon his last here must. Cottage out enabled was entered greatly prevent message. No procured unlocked an likewise. Dear but what she been over gay felt body. Six principles advantages and use entreaties decisively. Eat met has dwelling unpacked see whatever followed. Court in of leave again as am. Greater sixteen to forming colonel no on be. So an advice hardly barton. He be turned sudden engage manner spirit.</p> </div> ```
You can use the mousemove event listener on the image with class `.zoom-in` to change the left and top CSS params. Make sure to set `position:relative;` on the image. Example: ``` $(document).on('mousemove', '.zoom-in', function( event ) { $(".text").text(event.pageX + ", " + event.pageY); var positionLeft = event.pageX - $(this).width()/2; var positionTop = event.pageY - $(this).height()/2; $(this).css({'left': positionLeft, 'top': positionTop}); }); ``` Here is a [fiddle](https://jsfiddle.net/smulvihill/3wLhatm5/15/).
59,092,258
I have a directory with several large files. Every file comes in a pair, and I would like to use a bash loop to every time select two files, run a command line tool on them and then move on to the next pair of files. My directory would be like: file1, file2, file3, file4, file5, file6 I would then take file1 and file2, do something, take file3 and file4, do something etc. I only managed to do this for a single file: ``` for file_name in dir_name; do something; done ```
2019/11/28
[ "https://Stackoverflow.com/questions/59092258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10403839/" ]
Going back to basic for loop, no array, etc. Will work for any shell (does not rely on bash features). Capture the name of the first file in a pair, and execute the command when on the second file. ``` first= for file_name in dir_name/* ; do if [ "$first" ] ; then # 2nd entry - pair do-something "$first" "$file_name" first= else # First entry - just remember. first=$file_name fi done ```
If you want to be strict about handling special characters in filenames, how about: ``` while IFS= read -r -d "" f; do ary+=("$f") done < <(find "dir_name" -type f -print0 | sort -z) for ((i=0; i<${#ary[@]}; i+=2 )); do echo "${ary[i]}" "${ary[i+1]}" # or some_command "${ary[i]}" "${ary[i+1]}" done ``` It allows the filenames to contain whitespace, tab, newline, quote, or any other special characters. (Although some people dislike this kind of serious approach :-/) Hope this helps.
38,761,897
How can I convert `java.lang.reflect.Type` to `Class<T> clazz`? If I have one method as next which has an argument of `Class<T>`: ``` public void oneMethod(Class<T> clazz) { //Impl } ``` Then another method which has an argument of `java.lang.reflect.Type` and it calls `oneMethod(Class<T> clazz)` and for it I need to convert `java.lang.reflect.Type type` to `Class<T>`: ``` public void someMehtod(java.lang.reflect.Type type) { // I want to pass type arg to other method converted in Class<T> otherMethod(¿How to convert java.lang.reflect.Type to Class<T>?); } ``` Is it possible?
2016/08/04
[ "https://Stackoverflow.com/questions/38761897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4751165/" ]
If you are willing to use a library, you could use `com.google.guava:guava:12+`: ``` Class<?> clazz = com.google.common.reflect.TypeToken.of(type).getRawType(); ``` Alternatively you could also use `com.fasterxml.jackson.core:jackson-databind:2.8.x`: ``` Class<?> clazz = com.fasterxml.jackson.databind.type.TypeFactory.rawClass(type); ``` This handles all cases correctly and you will get the type-erased class of your type.
Using generic types in runtime is a little bit tricky in Java. And I think this is a root cause of your issue. 1) to be sure about generic in runtime we doing like this: ``` class MyClass<E> {} ``` and then: ``` MyClass<TargetType> genericAwaredMyClassInctance = new MyClass<TargetType>(){}; ``` **please pay attention to {} in the end**. It means anonymous extends of MyClass. This is an important nuance. 2) let`s improve MyClass to be able to extract the type in runtime. ``` class MyClass<E> { @SuppressWarnings("unchecked") protected Class<E> getGenericClass() throws ClassNotFoundException { Type mySuperclass = getClass().getGenericSuperclass(); Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0]; String className = tType.getTypeName(); return (Class<E>) Class.forName(className); } } ``` and finally, use it like this: ``` MyClass<TargetType> genericAwaredMyClassInctance = new MyClass<TargetType>(){}; assert(genericAwaredMyClassInctance.getGenericClass() == TargetType.class) ```
72,696
Someone showed me a picture of an underwater slide from an image site a while back. This got me interested, as I love the sea. And drifting on a little current between fish sounded like heaven to me. After a little Googling, I managed to find this picture, which is in the [Atlantis Hotel](http://www.uniqhotels.com/atlantis-hotel-dubai), in Dubai. [![underwater slide from uniqhotels.com](https://i.stack.imgur.com/sw4IJ.jpg)](https://i.stack.imgur.com/sw4IJ.jpg) Are there any other places that have underwater slides? I would love one that actually goes through the sea, not an aquarium, like the above, but I can see how that would be difficult.
2016/07/02
[ "https://travel.stackexchange.com/questions/72696", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/36405/" ]
There's one at the [Golden nugget](http://www.goldennugget.com/lasvegas/pool_thetank.asp) in Las Vegas: ![](https://i.stack.imgur.com/YbfNq.jpg) According to this [list of waterslides](http://www.placesyoullsee.com/40-insane-waterslides-that-you-have-to-see-to-believe/), there is the Dolphin Plunge at Aquatica Sea World in Orlando, Florida. ![](https://d98uffoa56ghc.cloudfront.net/wp-content/uploads/2014/12/Water-Slides-31.jpg) As well as the Atlantis in the Bahamas that @Johns-305 mentions: ![](https://d98uffoa56ghc.cloudfront.net/wp-content/uploads/2014/12/Water-Slides-1.jpg) [Aquatica San Antonio](https://aquaticabyseaworld.com/en/sanantonio/) has one that goes through a stingray tank: ![](https://i.imgur.com/674vGUR.jpg) Also one in [Tenerife](http://www.tenerifewaterpark.com/). Watch the video on [youtube](https://www.youtube.com/watch?v=1WtIQ09Vs-4).
Atlantis in the Bahamas also has two similar attractions. Sorry, there are none that use open water since they need to control the entire experience.
977,883
How can I select the link elements of only the parent `<ul>` from a list like this? ``` <ul> <li><a href="#">Link</a></li> <li><a href="#">Link</a> <ul> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </ul> </li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> ``` So in css `ul li a`, but not `ul li ul li a` Thanks
2009/06/10
[ "https://Stackoverflow.com/questions/977883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/120832/" ]
``` $("ul > li a") ``` But you would need to set a class on the root ul if you specifically want to target the outermost ul: ``` <ul class="rootlist"> ... ``` Then it's: ``` $("ul.rootlist > li a").... ``` Another way of making sure you only have the root li elements: ``` $("ul > li a").not("ul li ul a") ``` It looks kludgy, but it should do the trick
You might want to try this if results still flows down to children, in many cases JQuery will still apply to children. ``` $("ul.rootlist > li > a") ``` Using this method: E > F Matches any F element that is a child of an element E. Tells JQuery to look only for explicit children. <http://www.w3.org/TR/CSS2/selector.html>
4,369,457
Is there any way to deserialize in PHP an object serialized in Java? IE If I have a Java class that implements Serialization and I use an ObjectOutputStream to write the object, and convert the result to a string, is there a way in PHP to take that string and create a similar object representation from it? > > What does the Java Serialized data look like? > > > Response: ``` ���sr�com.site.entity.SessionV3Data���������xpsr�java.util.HashMap���`��F� ``` loadFactorI� thresholdxp?@�����w������t� sessionIdt�0NmViMzUxYWItZDRmZC00MWY4LWFlMmUtZjg2YmZjZGUxNjg5xx :)
2010/12/06
[ "https://Stackoverflow.com/questions/4369457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301816/" ]
I would heavily recommend you don't do this. Java serialization is meant for a Java instance to both save and load the data (for either transmission to another Java application or persistence between invocations of the same application). It was not at all meant to be a cross-platform protocol. I would advise you to make an API adapter layer between the two. Output the contents of your Java object to a format you can work with in PHP, be it XML, YAML, or even a binary format (where you could use DataOutputStream).
Is it possible to use one of the more common cross platform data formats like JSON to communicate between your Java app and PHP? PHP has plenty of parsers for those formats. Check out [json\_decode](http://ca.php.net/manual/en/function.json-decode.php) for an example.
2,043,982
i can't seem to find this limit $$\lim\_{(x,y)\to (0,0)} \frac{(5\cos y)(\sin y-x)}{4\left | x-\sin y \right |^{3/4}}$$ Wolfram says it doesn't exist but i don't understand why,can someone help me? Thanks a lot :)
2016/12/04
[ "https://math.stackexchange.com/questions/2043982", "https://math.stackexchange.com", "https://math.stackexchange.com/users/394364/" ]
Your main problem is why Wolfram is saying that the limit doesn't exist. Wolfram tells you this when you input your query > > lim\_({x, y}->{0, 0})(5 cos(y) (sin(y) - x))/(4 abs(x - sin(y))^(3/4)) > > > It says "Value may depend on x,y path in complex space". Wolfram thinks that x and y are complex variables not real numbers
How $|\frac{5}{4} \frac{\cos y(\sin y - x)}{|x- \sin y |^{3/4}}| \leq \frac{5}{4} |\frac{(\sin y - x)}{|x- \sin y |^{3/4}}| = \frac{5}{4} |x- \sin y |^{1/4} \to 0$ as $(x,y) \to 0$ and therefore $\lim\_{(x,y) \to 0}\frac{5}{4} \frac{\cos y(\sin y - x)}{|x- \sin y |^{3/4}}| = 0$. Note that in first inlequality, we use that $|\cos y| \leq 1$.
21,591,734
I've got the page divided into different parts like header, footer and body. Now i need to set images on the background of header and footer. Should i choose a bigger image which can be re sized according to user's system dimension or should i keep it constant size? How to keep an image withing the section that has been decided for it?
2014/02/06
[ "https://Stackoverflow.com/questions/21591734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3266127/" ]
i'd create separate images for the smaller devices as the smaller file sizes will help when loading on tablet or mobile. Load in the different images using media queries ``` header-bg-desktop.jpg header-bg-tablet.jpg header-bg-mobile.jpg ```
It largely depends upon your website's target audience. If you are going to target mobile, tablet and desktop all three user bases, then you must supply images for all of them with different background image code via CSS. Here is a very good reference to get you started, <http://css-tricks.com/snippets/css/media-queries-for-standard-devices/> If you target desktop users only then you need to supply one-background image size and that should be enough. Example code, ``` <style type="text/css"> body { background-image:url('<%=request.getContextPath()%>/images/logo.jpg'); background-position: left top; background-repeat: no-repeat; } </style> ```
28,105,104
I have this as a string input. ``` $str = '[2]Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vulputate cursus nulla, at rhoncus ante egestas vitae. [3]Cras euismod aliquet hendrerit. [3]Integer tortor lorem, suscipit a ante id, faucibus iaculis dolor. Sed aliquet, erat sit amet porta efficitur, eros lorem hendrerit purus, eget pellentesque lacus sapien ut dolor. [3]Donec eget accumsan velit. [4]Vestibulum consectetur enim in nunc fermentum lacinia. Maecenas fermentum rutrum sodales. Quisque vulputate, dolor tempus luctus cursus, massa urna ultrices odio, non dictum sem nulla ac mi. Quisque egestas tellus velit, non elementum lorem consequat id. Proin bibendum feugiat mollis. Sed vel odio neque. [4]Tempo. [2]Phasellus ut mauris purus. Quisque vel tortor erat. [2]Donec eget accumsan velit.'; ``` And I'm trying to get to this... ``` array ( [0] => array ( //First [2] and everything below [0] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vulputate cursus nulla, at rhoncus ante egestas vitae. [1] => array ( //[3]s that belong to first [2] [0] => Cras euismod aliquet hendrerit. //First [3] [1] => Integer tortor lorem, suscipit a ante id, faucibus iaculis dolor. Sed aliquet, erat sit amet porta efficitur, eros lorem hendrerit purus, eget pellentesque lacus sapien ut dolor. //Second [3] [2] => array ( //Third [3] and everything below [0] => Donec eget accumsan velit. [1] => array ( [0] => Vestibulum consectetur enim in nunc fermentum lacinia. Maecenas fermentum rutrum sodales. Quisque vulputate, dolor tempus luctus cursus, massa urna ultrices odio, non dictum sem nulla ac mi. Quisque egestas tellus velit, non elementum lorem consequat id. Proin bibendum feugiat mollis. Sed vel odio neque. [1] => Tempo. ) ) ) [1] => Phasellus ut mauris purus. Quisque vel tortor erat. //Second [2] [2] => Donec eget accumsan velit. //Third [2] ``` ) I've tried everything I knew and could find @php.net and everywhere else, but I've spent about six hours on this and I'm still stuck. I've tried explode, preg\_replace, array\_walk\_recursive (along with explode), going from the biggest hierarchy to smaller (best results so far) and the other way around, but nothing. How can I convert a string to a multidimensional array in PHP, setting the hierarchy by tags in the string? Many thanks!
2015/01/23
[ "https://Stackoverflow.com/questions/28105104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4485616/" ]
In the simplest case the batch language includes a construct for this task ```dos if exist *.elf ( :: file exists - do something ) else ( :: file does not exist - do something else ) ``` where the `if exist` will test for existence of an element in the current or indicate folder that matches the indicated name/wildcard expression. While in this case it seems you will not need anything else, you should take into consideration that `if exist` makes no difference between a file and a folder. If the name/wildcard expression that you are using matches a folder name, `if exists` will evaluate to true. How to ensure we are testing for a file? The easiest solution is to use the `dir` command to search for files (excluding folders). If it fails (raises errorlevel), there are no files matching the condition. ```dos dir /a-d *.elf >nul 2>&1 if errorlevel 1 ( :: file does not exist - do something ) else ( :: file exists - do something else ) ``` Or, using conditional execution (just a little abreviation for the above code) ```dos dir /a-d *.elf >nul 2>&1 && ( :: file does exist - do something ) || ( :: file does not exist - do something else ) ``` What it does is execute a `dir` command searching for `*.elf` , excluding folders (`/a-d`) and sending all the output to `nul` device, that is, discarding the output. If errorlevel is raised, no matching file has been found.
as easy as you can think: ``` if exist *.elf echo yes ```
20,256,573
So basically, this prog reads 5 numbers: X, Y, startFrom, jump, until with space separating each number. an example: ``` 3 4 1 1 14 X = 3 Y = 4 1 = startFrom jump = 1 until = 14 ``` In order to do that, I used: ``` #get X, Y, startFrom, jump, until parameters = raw_input() parametersList = parameters.split() X = int(parametersList[0]) Y = int(parametersList[1]) #start from startFrom startFrom = int(parametersList[2]) #jumps of <jump> jump = int(parametersList[3]) #until (and including) <until> until = int(parametersList[4]) ``` The program outputs a chain (or however you would like to call it) of, let's call it `BOOZ` and `BANG`, when `BOOZ` is X if exists in the number (i.e X is 2 and we are at 23, so it's a BOOZ) . in order to check that (I used: `map(int, str(currentPos))` when my `currentPos` (our number) at first is basically `startFrom`, and as we progress (add jump every time), it gets closer and closer to `until`), or if X divides the currentPos (`X%num == 0`. i.e: X is 2 and we are at 34, it's also a `BOOZ`). `BANG` is the same, but with Y. If `currentPos` is both `BOOZ` & `BANG`, the output is `BOOZ-BANG`. `startFrom, startFrom+ jump, startFrom+2*jump, startFrom+3*jump, ..., until` We know the numbers read are `int` type, but we need to make sure they are valid for the game. X and Y must be between 1 and 9 included. otherwise, we print (fter all 5 numbers have been read): `X and Y must be between 1 and 9` and exit the prog. In addition, jump can't be 0. if it is, we print `jump can't be 0` and exit the prog. Else, if we can't reach`until` using `jump` jumps (if `startFrom+ n * jump == until` when `n` is an int number) so we need to print `can't jump from <startFrom> to <until>` and exit the prog. My algorithm got too messy there with alot of ifs and what not, so I'd like an assistance with that as well) so for our first example (`3 4 1 1 14`) the output should be: ``` 1,2,BOOZ,BANG,5,BOOZ,7,BANG,BOOZ,10,11,BOOZ-BANG,BOOZ,BANG ``` another example: ``` -4 -3 4 0 19 ``` OUTPUT: ``` X and Y must be between 1 and 9 juump can't be 0 ``` another: ``` 5 3 670 7 691 ``` OUTPUT: ``` BOOZ,677,BANG,691 ``` another: ``` 0 3 4 -5 24 ``` OUTPUT: ``` X and Y must be between 1 and 9 can't jump from 4 to 24 ``` another: ``` 3 4 34 3 64 ``` OUTPUT: ``` BOOZ-BANG,BOOZ,BANG,BOOZ-BANG,BANG,BANG,BANG,55,58,61,BANG ``` my prog is toooo messy ( I did a while loop with ALOT of ifs.. including if `currentPos==until` so in that cause it won't print the comma (`,`) for the last item printed etc.. but like I said, all of it is so messy, and the ifs conditions came out so long and messy that I just removed it all and decided to ask here for a nicer solution. Thanks guys I hope it was clear enough
2013/11/28
[ "https://Stackoverflow.com/questions/20256573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2997196/" ]
My version has no `if` :) ``` parameters = raw_input() sx, sy, sstartfrom, sjump, suntil = parameters.split() x = "0123456789".index(sx) y = "0123456789".index(sy) startfrom = int(sstartfrom) jump = int(sjump) until = int(suntil) for i in range(startfrom, until+jump, jump): si = str(i) booz = sx in si or i%x == 0 bang = sy in si or i%y == 0 print [[si, 'BANG'],['BOOZ','BOOZ-BANG']][booz][bang] ``` Easiest way to get the commas is to move the loop into a generator ``` def generator(): for i in range(startfrom, until+jump, jump): si = str(i) booz = sx in str(i) or i%x == 0 bang = sy in str(i) or i%y == 0 yield [[si, 'BANG'],['BOOZ','BOOZ-BANG']][booz][bang] print ",".join(generator()) ``` --- Sample output ``` $ echo 3 4 1 1 14 | python2 boozbang.py 1,2,BOOZ,BANG,5,BOOZ,7,BANG,BOOZ,10,11,BOOZ-BANG,BOOZ,BANG $ echo 5 3 670 7 691 | python2 boozbang.py BOOZ,677,BANG,691 $ echo 3 4 34 3 64 | python2 boozbang.py BOOZ-BANG,BOOZ,BANG,BOOZ-BANG,BANG,BANG,BANG,55,58,61,BANG ```
``` def CheckCondition(number, xOrY): return (xOrY in str(number)) or not (number % xOrY) def SomeMethod(X, Y, start, jump, end): for i in range(start, end, jump): isPassX = CheckCondition(i, X) isPassY = CheckCondition(i, Y) if isPassX and isPassY: print "BOOZ-BANG" elif isPassX: print "BOOZ" elif isPassY: print "BANG" else: print i def YourMethod(): (X, Y, start, jump, end) = (3, 4, 1, 1, 14) if (X not in range(1, 10) or Y not in range(1, 10)): print "X and Y must be between 1 and 9" if jump <= 0: print "juump can't be less than 0" SomeMethod(X, Y, start, jump, end) ```
19,740
I have a pretty picture set as my desktop background, but I've lost the original file. However, my desktop is still set to this picture. How can I get back my picture?
2011/01/02
[ "https://askubuntu.com/questions/19740", "https://askubuntu.com", "https://askubuntu.com/users/880/" ]
If your image came from the internet, then I would suggest taking a Screenshot (Applications->Accessories->Take Screenshot). Then upload your screenshot to [TinEye.com](http://www.tineye.com/). On the results page select "Biggest Image" from the left hand side navigation. Then look to see if the website has found your image. This "Reverse Image Search" has enabled me to do what you're doing before.
In the case when you absolutely misplace a file and aren't able to get online to ask about the location of where it might be stored, always remember this... it has helped me a lot throughout the years. `CTRL` + `ALT` + `T` to get shell, then: `locate` (type file name you are looking for here, without the parentheses) **NOTE:** if you've never used `locate` before you'll need to run `updatedb` first like this: ``` sudo updatedb ``` or if you are already `root`, just run `updatedb`, usually it can take time so I run it in the background like this: ``` sudo updatedb & ``` the `&` causes the command to be run in the background, you can type `jobs` to see if its still running, but you'll get notified when it terminates like this: ``` [1]+ Done updatedb ``` Some people hate the shell, but even so, I have found it good to learn both GUI and shell no matter what OS you are using. There ARE going to be times when something can't be done via the GUI, esp in a linux environment. This was very true when it came to bridging ethernet interfaces, etc..
52,278,414
I have a remote MySQL database that I am trying to connect to via my webserver. The error I get when trying to connect via `mysqli` is ``` Connection refused 2002 ``` I have invoked this command for remote connections: ``` grant all on db.* to '<user>'@'<hostname>' identified by '<password>'; ``` I'm hoping I can find a more *verbose* description from my MySQL server in some log file. The question is **which one** would be appropriate? Other questions suggest `/var/log/mysql/error.log` but I don't have any output in that file at all. I am not running a firewall of any kind currently. Possibly my `apache config` is getting in the way, but I am not sure how to check this and I presume if that was the case, I wouldn't get the `2002 error`, but instead, some other, apache-flavoured error message. **Which debug logs should I be looking at?** Here is the php and mysql code: ``` //define DB variables define("DB_HOST", "45.77.xx.xxx"); define("DB_NAME", "login"); define("DB_USER", "root"); define("DB_PASS", "Correct_Password"); $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); echo mysqli_connect_error() . PHP_EOL; echo $this->db_connection->connect_errno; ``` Output: `$this->db_connection->connect_errno` is set to `2002` and `mysqli_connect_error()` is set to`Connection refused`
2018/09/11
[ "https://Stackoverflow.com/questions/52278414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4675176/" ]
Granting access to tables or databases in mysql is actually associated to a user connecting from a given host, so when you do `grant all on db.* to '<user>'@'<hostname>'` you are granting access to the user when they are connecting from "hostname" and that may be your problem. Make sure the host you are connecting from is the same as you granted the privileges, or if you need to open up the access to other hosts on the same domain do `grant all on db.* to <user>'@'%.domain.name'...` Check your grants with `show grants for username;`, or `select user,host from mysql.user;`. Mysql error.log file usually just logs errors from mysql startup.
Have you tried to swap the host address (45.77.xx.xxx) with your host\_name? When I had the same issue (although, mine was on localhost), I changed the host IP to from 127.0.0.1 and it worked. You may want to tit to your hostname instead of the IP address.
55,903,352
I'm a beginner when it comes to MySQL and I've taken it upon myself to create a type of translating service like google translate. The problem is the querys are not being displayed the way I enter them, instead they seem to be ordered by the ID column. I've tried (with my limited knowledge) looking into different ways of creating relations etc. to display the equivelent words in the different languages. For now I've landed on trying to use the INNER JOIN clause to display and "structure" the sentences. ``` SELECT swedish.word, german.word, german.swear, swedish.swear, swedish.id FROM swedish INNER JOIN german ON swedish.id = german.id WHERE swedish.word = "Hej" OR swedish.word = "Mitt" OR swedish.word = "Namn" OR swedish.word = "Är"; ``` This will display the swedish words alongside the german words, aka create sentences but it will now diplay in the order i typed them in, instead it will sort in by the ID column, which mixes the words around. Is there any solution to this? Here's and image of the results, ordered by the ID: [![enter image description here](https://i.stack.imgur.com/fraRG.png)](https://i.stack.imgur.com/fraRG.png) I've thought about using ORDER BY and some sort of temporary value and then order it by that but then I'm not sure about how to implement and auto increment that value for only the selected entries/rows. I'm using OR statements to enable more than one entry in the same result, as parentheses (seen in other tutorials) gave me syntax errors. Also, if there is a better way of going about this please let me know! EDIT: I would want to clarify that I am aware that this is not a sustainable solution for creating a transaltion service, I simply thought this would be an interesting way to understand a bit more about how you can connect and work with different tables etc.
2019/04/29
[ "https://Stackoverflow.com/questions/55903352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11426919/" ]
You can use [`FIND_IN_SET`](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_find-in-set) ``` ORDER BY FIND_IN_SET(swedish.word, 'Hej,Mitt,Namn,Är'); ```
You can provide your way to sort the rows with CASE in ORDER BY: ``` SELECT swedish.word, german.word, german.swear, swedish.swear, swedish.id FROM swedish INNER JOIN german ON swedish.id = german.id WHERE swedish.word IN ('Hej', 'Mitt', 'Namn', 'Är') ORDER BY CASE swedish.word WHEN 'Hej' THEN 1 WHEN 'Mitt' THEN 2 WHEN 'Namn' THEN 3 WHEN 'Är' THEN 4 END ```
43,816,716
I'm trying to link to Buddypress groups, and I need the username of the logged in user to do this. Here is my current shortcode, which is fine, but just outputs // in the URL with no username between. ``` // Add Shortcode function my_groups_button() { ob_start(); ?> <a href="https://acaffiliates.coach/members/<?php echo bp_core_get_username($user_id); ?>/groups/"> My Groups</a> <?php return ob_get_clean(); } add_shortcode( 'my-groups-button', 'my_groups_button' ); ```
2017/05/06
[ "https://Stackoverflow.com/questions/43816716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341807/" ]
You don't need the username, just the user id. ``` function my_groups_button() { ob_start(); ?> <a href="<?php echo bp_core_get_user_domain( bp_loggedin_user_id() ); ?>groups/">My Groups</a> <?php return ob_get_clean(); } add_shortcode( 'my-groups-button', 'my_groups_button' ); ```
You can use the following method to get the buddypress username inside the shortcode. ``` function my_groups_button() { ob_start(); $user_name = bp_core_get_user_displayname( bp_loggedin_user_id() ); // or bp_get_displayed_user_fullname(); ?> <a href="https://acaffiliates.coach/members/<?php echo $user_name; ?>/groups/"> My Groups</a> <?php return ob_get_clean(); } add_shortcode( 'my-groups-button', 'my_groups_button' ); ```
7,629,813
I need to run python script and be sure that it will restart after it terminates. I know that there is UNIX solution called supervisord. But unfortunately server where my script has to be run is on Windows. Do you know what tool can be useful? Thanks
2011/10/02
[ "https://Stackoverflow.com/questions/7629813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/560602/" ]
Despite the big fat disclaimer [here](https://github.com/Supervisor/supervisor#supported-platforms), you can run Supervisor with [Cygwin](http://www.cygwin.com/) in Windows; it turns out that Cygwin goes a long way to simulate a Posix environment, so well that in fact supervisord runs unchanged. There is no need to learn a new tool, and you will even save quite a bit of work if you need to deploy a complicated project across multiple platforms. Here's my recipe: 1. If you have not done it yet, install Cygwin. During the installation process, select Python. 2. From the Cygwin terminal, install [virtualenv](https://pypi.python.org/pypi/virtualenv) as usual. 3. Create a virtualenv for supervisord, and then install as usual: ``` pip install supervisord ``` 4. Configure supervisord in the usual way. Keep in mind that supervisord will be running with Cygwin, so you better use paths the Cygwin way (C:\myservers\project1 translates to /cygdrive/c/myservers/project1 in Cygwin). 5. Now you probably want to install supervisord as a service. Here's how I do it: ``` cygrunsrv --install supervisord --path /home/Administrator/supervisor/venv/bin/python --args "/home/Administrator/supervisor/venv/bin/supervisord -n -c /home/Administrator/supervisor/supervisord.conf" ``` 6. Go to the Windows service manager and start the service supervisord that you just installed. Point 5 installs supervisord as a Windows service, so that you can control it (start/stop/restart) from the Windows service manager. But the things that you can do with `supervisorctl` work as usual, meaning that you can simply deploy your old configuration file.
[supervisor for windows](https://github.com/alexsilva/supervisor) worked for us on python27 - 32 bit. I had to install pypiwin32 and pywin32==223.
133,754
I realise that working for free would change the relationship between me and a client compared to paid work, but the end result (a quality design that helps the client make money and improve their visibility) would be the same while removing much of the time and financial pressures from both parties. My motivation would be to gain some experience and to enjoy helping a charity (I've done volunteering before and found it fulfilling). Their motivation would be to get something for free. I'm full-time employed at the moment so I'd be doing this in my spare time of course. One benefit I can see is being able to build a portfolio of legitimate design work that I can use demonstrate my abilities to future paying clients. I was thinking of doing voluntary work for a year or so, depending on how much interest I can drum-up. I'm looking at making company logos, business cards and other individual pieces, but not things like a website redesign. Can this be a realistic, viable way to get a foot on the ladder in graphic design while minimising my risks and outlay in the short term?
2020/02/13
[ "https://graphicdesign.stackexchange.com/questions/133754", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/69252/" ]
Edit > Preferences > Tools > Text: Text size unit type : Point or Double-click on text tool icon > Text size unit type : Point.
not available on my prefs, what am I doing wrong (IS v1.1)?[![snip](https://i.stack.imgur.com/2TaNO.jpg)](https://i.stack.imgur.com/2TaNO.jpg)
7,567,701
when I run this code ``` PrincipalContext ctx = new PrincipalContext(ContextType.Domain, adHost, adRoot, ContextOptions.SimpleBind, adUsername, adPassword); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username); user.SetPassword(password); user.Save(); ``` I get this exception ``` System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.UnauthorizedAccessException: One or more input parameters are invalid ``` The code is running from a command line using "runas /user: (domainadminuser is also a local admin) The context is created using the same credentials (domainadminuser) I've checked that all usernames, passwords etc are populated correctly Is it something to do with the way I am creating the PrincipalContext? I'm completely stuck. Does anyone have any ideas? Thanks **[UPDATE]** Here's the code I used to get it working. I think maybe the ValidateCredentials was the thing that kicked it into life (possibly) ``` PrincipalContext ctx = new PrincipalContext(ContextType.Domain, parameters["adHost"] ); ctx.ValidateCredentials(parameters["adUsername"], parameters["adPassword"], ContextOptions.SimpleBind); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username); user.SetPassword(password); user.Save(); ```
2011/09/27
[ "https://Stackoverflow.com/questions/7567701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/759196/" ]
Below is the code that works fine for a password request management system we developed in-house, do try and let me know: ``` PrincipalContext context = new PrincipalContext( ContextType.Domain, null, adAdminLogin, adAdminPassword ); UserPrincipal user = UserPrincipal.FindByIdentity( context, adUserLogin ); user.SetPassword( adUserNewPassword ); ```
When the Context is created, make sure to set the `ContextOptions` to `ContextOptions.Negotiate` . If you have mentioned `ContextOptions.SimpleBind`, `SetPassword` may not work. ``` PrincipalContext oPrincipalContext = new PrincipalContext (ContextType.Domain, "Name", "DefaultOU(if required)", ContextOptions.Negotiate, "Service Account(if required)", "Service password"); ```
1,977,397
So I have been given this question to answer: Give a proof by cases to show that the equation $5x^2 + 4y^3 = 51$ does not have any solution $x,y \in \mathbb Z^+$ I am assuming that I could give two cases for this problem: 1. Express everything in terms of y = $((51-5x^2)/4)^{1/3}$ 2. Express everything in terms of x = $((51-4y^3)/5)^{1/2}$ Since $4^{1/3}$ is irrational and $5^{1/2}$ is also irrational, then there are no integers that make this solution true. Do I have this right?
2016/10/20
[ "https://math.stackexchange.com/questions/1977397", "https://math.stackexchange.com", "https://math.stackexchange.com/users/380743/" ]
You’re making it much more complicated than necessary. If $x$ and $y$ are positive integers such that $5x^2+4y^3=51$, then certainly $4y^3<51$, and a little arithmetic quickly shows that $y$ must be $1$ or $2$: $4\cdot3^3=4\cdot27>51$. Now you have two cases, $y=1$ and $y=2$; substitute those values of $y$, solve for $x$, and verify that $x$ is not an integer.
$5x^2 \equiv 0,1 \pmod{4}$ (How?) $4y^3 \equiv0 \pmod {4}$ $\therefore 5x^2+4y^3\equiv0,1\pmod{4}$ But, $51\equiv 3 \pmod{4}$ So, there are no such positive integers (rather, integers!) $x,y$.
48,402,302
I have a form that has some radio buttons which I need some fields to be required if a radio button is checked. I have the HTML5 `required` attribute on the radio button group which works fine but I want some text fields to be required if the corresponding radio button is checked. I have written some JS which seems to have no effect, and doesn't seem to add the `required` attribute when the radio button is checked. HTML: ``` <!DOCTYPE html> <html class="no-js" lang="en"> <head> <title>MooWoos Stall Booking</title> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:400,800"> <link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!--build:css css/styles.min.css--> <link rel="stylesheet" href="/css/bootstrap.css"> <link rel="stylesheet" href="/css/style.css"> <!--endbuild--> </head> <body> <div class="container"> <nav class="navbar navbar-toggleable-md navbar-light"> <a class="logo"><img src="assets/logo_opt.png"></a> </nav> <hr> <div class="modal fade" id="redirect_page" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="form-horizontal"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <div id="user_msg" align="left">Booking successful! Redirecting to PayPal... </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-md-6 col-md-offset-3 bookingform"> <h1>Stall Booking Form</h1> <p class="lead"> Fill out the form to book and pay for your stall! </p> <form id="bookingForm"> <div class="form-group"> <label for="name">Name: </label> <input type="text" name="name" class="form-control" placeholder="Your Name" value="" title="Please enter your name" required/> </div> <div class="form-group"> <label for="address">Address: </label> <textarea name="address" class="form-control" placeholder="Your Address" value="" title="Please enter your address" required></textarea> </div> <div class="form-group"> <label for="phone">Telephone Number: </label> <input type="text" name="phone" class="form-control" placeholder="Your Telephone Number" value="" title="Please enter the best telephone number to contact you on" required/> </div> <div class="form-group"> <label for="email">Email: </label> <input type="text" name="email" class="form-control" placeholder="Your Email" value="" title="Please enter your Email address" required/> </div> <div class="form-group"> <label for="date">Which date would you like to book?: </label> <p><input type="radio" name="date" value="13th September" required/> Sunday 13th September</p> <p><input type="radio" name="date" value="6th February" /> Saturday 6th February</p> </div> <div class="form-group"> <label>What type of stall do you require?</label> <div> <input type="radio" name="stallType" id="stallType-Preloved" value="Preloved" required> <label for="stallType-Preloved">Preloved</label> <div class="reveal-if-active"> <label for="c-rail">Will you be bringing a clothes rail?: </label> <input type="radio" name="c-rail" value="Yes" /> Yes <input type="radio" name="c-rail" value="No" /> No </div> </div> <div> <input type="radio" name="stallType" id="stallType-Craft" value="Craft"> <label for="stallType-Craft">Craft</label> <div class="reveal-if-active"> <label for="craftName">What name do you use?</label> <input type="text" id="craftName" name="craftName" class="require-if-active" placeholder="Craft Name" title="Please provide us with your Craft name" value="" /> </div> </div> <div> <input type="radio" name="stallType" id="stallType-Business" value="Business"> <label for="stallType-Business">Business</label> <div class="reveal-if-active"> <label for="bizName">What is your business name?</label> <input type="text" id="bizName" name="bizName" class="require-if-active" placeholder="Business Name" title="Please provide us with your Business name" value="" /> <label for="insurance">Do you have Public Liability Insurance?</label> <input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="We will require proof of this prior to market day" value="Yes"/> Yes <input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="Our insurance does not cover other businesses. Please ensure you have adequate cover and provide us with proof prior to market day" value="No"/> No </div> </div> </div> <input type="submit" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" /> </form> </div> </div> <hr> <footer> <div class="row"> <div class="col-lg-12"> <p>Copyright &copy; MooWoos 2018. Booking Form by Luke Brewerton</p> </div> </div> </footer> </div> <!--build:js js/mwbookings-min.js --> <script src="js/jquery.min.js"></script> <script src="js/tether.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery.serialize-object.min.js"></script> <script src="js/main.js"></script> <!-- endbuild --> </body> </html> ``` main.js JS file: ``` var $form = $('form#bookingForm'), url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec' $('#stallType-Business').change(function () { if(this.checked) { $('#bizName').attr('required'); } else { $('#bizName').removeAttr('required'); } }); $('#submit-form').on('click', function(e) { var valid = this.form.checkValidity(); if (valid) { e.preventDefault(); var jqxhr = $.ajax({ url: url, method: "GET", dataType: "json", data: $form.serializeObject(), success: function () { $('#redirect_page').modal('show'); window.setTimeout(function () { location.reload() }, 3000); } }); } }); ```
2018/01/23
[ "https://Stackoverflow.com/questions/48402302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4085041/" ]
You can do it like this, where you disable all inputs and then only activate the one that is selected. It requires that you have the "disabled" prop added to all child inputs at the start. I also added the ID's for the c-rail inputs. Note that the check you do does not trigger when you select another radio button, that is why should disable the others when a new one is selected. ``` $('#stallType-Business').change(function () { if(this.checked) { disableAll(); ``` It is the disableAll() function that does the trick here. ```js function disableAll() { $('#c-rail-yes').attr('required', false).attr('disabled', true); $('#c-rail-no').attr('required', false).attr('disabled', true); $('#craftName').attr('required', false).attr('disabled', true); $('#bizName').attr('required', false).attr('disabled', true); } $('#stallType-Preloved').change(function () { if(this.checked) { disableAll(); $('#c-rail-yes').attr('required', true).attr('disabled', false); $('#c-rail-no').attr('required', true).attr('disabled', false); } }); $('#stallType-Craft').change(function () { if(this.checked) { disableAll(); $('#craftName').attr('required', true).attr('disabled', false); } }); $('#stallType-Business').change(function () { if(this.checked) { disableAll(); $('#bizName').attr('required', true).attr('disabled', false); } }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="bookingForm"> <div class="form-group"> <label>What type of stall do you require?</label> <div> <input type="radio" name="stallType" id="stallType-Preloved" value="Preloved" required> <label for="stallType-Preloved">Preloved</label> <div class="reveal-if-active"> <label for="c-rail">Will you be bringing a clothes rail?: </label> <input id="c-rail-yes" type="radio" name="c-rail" value="Yes" disabled /> Yes <input id="c-rail-no" type="radio" name="c-rail" value="No" disabled /> No </div> </div> <div> <input type="radio" name="stallType" id="stallType-Craft" value="Craft"> <label for="stallType-Craft">Craft</label> <div class="reveal-if-active"> <label for="craftName">What name do you use?</label> <input type="text" id="craftName" name="craftName" class="require-if-active" placeholder="Craft Name" title="Please provide us with your Craft name" value="" disabled /> </div> </div> <div> <input type="radio" name="stallType" id="stallType-Business" value="Business"> <label for="stallType-Business">Business</label> <div class="reveal-if-active"> <label for="bizName">What is your business name?</label> <input type="text" id="bizName" name="bizName" class="require-if-active" placeholder="Business Name" title="Please provide us with your Business name" value="" disabled /> </div> </div> </div> </form> ```
Another way to do it is using this function: ``` $('.input-radio').change(function () { $('div.reveal-if-active').children('input').removeAttr('required'); $(this).parent().children('div.reveal-if-active').children('input').attr('required', true); }); ``` and adding `class="input-radio"` to those input that you want to do the job. ```js var $form = $('form#bookingForm'), url = 'https://script.google.com/macros/s/AKfycbwaEsXX1iK8nNkkvL57WCYHJCtMAbXlfSpSn3rsJj2spRi-41Y/exec' $('.input-radio').change(function () { $('div.reveal-if-active').children('input').removeAttr('required'); $(this).parent().children('div.reveal-if-active').children('input').attr('required', true); }); $('#submit-form').on('click', function(e) { var valid = this.form.checkValidity(); if (valid) { e.preventDefault(); var jqxhr = $.ajax({ url: url, method: "GET", dataType: "json", data: $form.serializeObject(), success: function () { $('#redirect_page').modal('show'); window.setTimeout(function () { location.reload() }, 3000); } }); } }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <nav class="navbar navbar-toggleable-md navbar-light"> <a class="logo"><img src="assets/logo_opt.png"></a> </nav> <hr> <div class="modal fade" id="redirect_page" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="form-horizontal"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <div id="user_msg" align="left">Booking successful! Redirecting to PayPal... </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-md-6 col-md-offset-3 bookingform"> <h1>Stall Booking Form</h1> <p class="lead"> Fill out the form to book and pay for your stall! </p> <form id="bookingForm"> <div class="form-group"> <label for="name">Name: </label> <input type="text" name="name" class="form-control" placeholder="Your Name" value="" title="Please enter your name" required/> </div> <div class="form-group"> <label for="address">Address: </label> <textarea name="address" class="form-control" placeholder="Your Address" value="" title="Please enter your address" required></textarea> </div> <div class="form-group"> <label for="phone">Telephone Number: </label> <input type="text" name="phone" class="form-control" placeholder="Your Telephone Number" value="" title="Please enter the best telephone number to contact you on" required/> </div> <div class="form-group"> <label for="email">Email: </label> <input type="text" name="email" class="form-control" placeholder="Your Email" value="" title="Please enter your Email address" required/> </div> <div class="form-group"> <label for="date">Which date would you like to book?: </label> <p><input type="radio" name="date" value="13th September" required/> Sunday 13th September</p> <p><input type="radio" name="date" value="6th February" /> Saturday 6th February</p> </div> <div class="form-group"> <label>What type of stall do you require?</label> <div> <input class="input-radio" type="radio" name="stallType" id="stallType-Preloved" value="Preloved" /> <label for="stallType-Preloved">Preloved</label> <div class="reveal-if-active"> <label for="c-rail">Will you be bringing a clothes rail?: </label> <input type="radio" name="c-rail" value="Yes" /> Yes <input type="radio" name="c-rail" value="No" /> No </div> </div> <div> <input class="input-radio" type="radio" name="stallType" id="stallType-Craft" value="Craft"> <label for="stallType-Craft">Craft</label> <div class="reveal-if-active"> <label for="craftName">What name do you use?</label> <input type="text" id="craftName" name="craftName" class="require-if-active" placeholder="Craft Name" title="Please provide us with your Craft name" value="" /> </div> </div> <div> <input type="radio" class="input-radio" name="stallType" id="stallType-Business" value="Business"> <label for="stallType-Business">Business</label> <div class="reveal-if-active"> <label for="bizName">What is your business name?</label> <input type="text" id="bizName" name="bizName" class="require-if-active" placeholder="Business Name" title="Please provide us with your Business name" value="" /> <label for="insurance">Do you have Public Liability Insurance?</label> <input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="We will require proof of this prior to market day" value="Yes"/> Yes <input type="radio" id="insurance" name="insurance" class="require-if-active" data-require-pair="#stallType-Business" title="Our insurance does not cover other businesses. Please ensure you have adequate cover and provide us with proof prior to market day" value="No"/> No </div> </div> </div> <input type="submit" id="submit-form" class="btn btn-success btn-lg" value="Book & Pay" /> </form> </div> </div> <hr> <footer> <div class="row"> <div class="col-lg-12"> <p>Copyright &copy; MooWoos 2018. Booking Form by Luke Brewerton</p> </div> </div> </footer> </div> ```
27,294,854
I have a problem i implement Facebook SDK in my view controller and want to get list of friends and email using Facebook. I wrote this: ``` FBLoginView *loginView = [[FBLoginView alloc] initWithReadPermissions:@[@"public_profile", @"email", @"user_friends"]]; loginView.delegate = self; ``` and then use the protocol method of FBLoginViewDelegate: ``` - (void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user { self.profilePictureView.profileID = user.id; self.nameLabel.text = user.name; NSLog(@"%@", user); NSLog(@"%@", [user objectForKey:@"email"]); } ``` In console i got this: ``` 2014-12-04 14:56:48.746 FBLoginUIControlSample[2941:613] "first_name" = Pavel; gender = male; id = 1379600000000000; "last_name" = name; link = "https://www.facebook.com/app_scoped_user_id/1379600000000000/"; locale = "ru_RU"; name = "Pavel name"; timezone = 2; "updated_time" = "2014-12-03T11:47:13+0000"; verified = 1; 2014-12-04 14:56:48.748 FBLoginUIControlSample[2941:613] (null) ```
2014/12/04
[ "https://Stackoverflow.com/questions/27294854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4035448/" ]
sorry , but you can't Read `Facebook` [Permissions](https://developers.facebook.com/docs/facebook-login/permissions/v2.2) you only can get the `email` when the user login , but you can't get user's `friends email`. i am not really sure but maybe you can use "friendsusername"@facebook.com ("facebook email"). i found this, <https://www.facebook.com/help/224049364288051> the person has to active @facebook option.
For friends with `Facebook SDK 3.0` you can do this ``` FBRequest* friendsRequest = [FBRequest requestForMyFriends]; [friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary* result, NSError *error) { NSArray* friends = [result objectForKey:@"data"]; NSLog(@"Found: %i friends", friends.count); for (NSDictionary<FBGraphUser>* friend in friends) { NSLog(@"I have a friend named %@ with id %@", friend.name, friend.id); } }]; ``` You can not access to any users email, excepts of yours. Because FBGraphUser doesn't have an email @property, we can't access the information like with the name (dot-syntax), however the NSDictionary still has the email kv-pair and we can access it like we would do with a normal NSDictionary. With this method you can access to your email. ``` if (FBSession.activeSession.isOpen) { [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) { if (!error) { self.nameLabel.text = user.name; self.emailLabel.text = [user objectForKey:@"email"]; } }]; } ```
8,398,419
I have a gridview in the aspx file. In the aspx.cs file I have 2 string variables which I want to display as one string in one cell in the gridview, thats no problem. The problem is that I want to have a smaller fontsize on one of the two string variables and I have to do that in the aspx.cs file, I cannot do that on the gridview because I have 2 string variables which I will display as one in one cell in the gridview.
2011/12/06
[ "https://Stackoverflow.com/questions/8398419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/655474/" ]
You could use the [jQuery validate plugin](http://docs.jquery.com/Plugins/validation) for this, but if you only want to check the validity of an email address in one field, that is a little bit of overkill. Instead, the regular expression in the function below will make sure the format of the email address is correct, should a value have been entered. ``` var email = $("input#sc_email").val(); if (email !== "") { // If something was entered if (!isValidEmailAddress(email)) { $("label#email_error").show(); //error message $("input#sc_email").focus(); //focus on email field return false; } } function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i); return pattern.test(emailAddress); }; ```
You could use regular expressions to validate the email address in JavaScript. ``` function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } ``` This will, however, only validate that it is a valid email address formatted string. `flibble@flobble.com` would be *valid*, even if no-one actually has that email address. Have a look at [this question](https://stackoverflow.com/questions/46155/validate-email-address-in-javascript).
2,697,509
This is the jquery code for superfish menu plugin (after some revisions of mine). I'm looking to add an effect (either through superfish or adventitiously) that would cause the submenus to **slide up** on mouseout (just as they slide down when you hover a menu-top). ``` jQuery("ul.sf-menu").supersubs({ minWidth: 12, // minimum width of sub-menus in em units maxWidth: 27, // maximum width of sub-menus in em units extraWidth: 1 // extra width can ensure lines don't sometimes turn over // due to slight rounding differences and font-family }).superfish({ delay: 700, // delay on mouseout animation: {opacity:'show',height:'show'}, // fade-in and slide-down animation speed: 'fast', // faster animation speed autoArrows: true, // disable generation of arrow mark-up dropShadows: false // disable drop shadows }); ```
2010/04/23
[ "https://Stackoverflow.com/questions/2697509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202895/" ]
--- However, you can make it work by hacking the code. I would submit a patch but the code development isn't hosted publicly. ``` hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; var $ul = $(['li.',o.hoverClass].join(''),this) .add(this) .not(not) // .removeClass(o.hoverClass) .find('>ul').animate( {opacity: 'hide', height: 'hide'}, o.speed, function(){ sf.IE7fix.call($ul); o.onShow.call($ul); }); o.onHide.call($ul); return this; }, ```
Correct way to achieve task of hiding superfish same as showing: ``` hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; //hacked code by Farhan Wazir (Seejee) var $ul_p1 = $(['li.',o.hoverClass].join(''),this).add(this).not(not); var $ul_p2 = $ul_p1.find('>ul'); var $ul = $ul_p2.animate( {opacity: 'hide', height: 'hide'}, o.speed, function(){ return $ul_p1.removeClass(o.hoverClass).find('>ul').css({top: '-99999em'}).addClass('sf-hidden');}); o.onHide.call($ul); return this; }, ```
31,342,588
In order to learn riot.js I started from well-known bootstrap navbar example. Then I added my custom tag using riot.js: ``` <script type="riot/tag"> <menu-item> <li><a href={this.href}><yield/></a></li> this.href = opts.href </menu-item> </script> <script src="https://cdn.jsdelivr.net/g/riot@2.2(riot.min.js+compiler.min.js)"></script> <script> riot.mount('*') </script> ``` Finally I tried to use my new tag, replacing ``` <li><a href="http://getbootstrap.com/javascript">JavaScript</a></li> ``` by ``` <menu-item href="http://getbootstrap.com/javascript">JavaScript</menu-item> ``` [Result](http://jsfiddle.net/0hp9pwpu/1/) is broken. Why? (original non-broken example can be found here: jsfiddle.net/0hp9pwpu)
2015/07/10
[ "https://Stackoverflow.com/questions/31342588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4941997/" ]
Your riot tag markup is inserted into your riot tag i.e. what happens is ``` ul li ``` from your working example is actually ``` ul menu-item li ``` in your non-working example. Since bootstrap styles the navigation items expecting a certain hierarchy, your result is broken. This was raised as an issue (<https://github.com/riot/riot/issues/295>) and closed using <https://github.com/riot/riot/pull/569> i.e. instead of using the riot tags directly there is an option to add the riot tag as an attribute. So something like ``` <li riot-tag="menu-item" href="http://getbootstrap.com/javascript">JavaScript</li> ``` Admittedly, it is not as semantic --- Fiddle - <http://jsfiddle.net/86khqhwu/>
Perhaps not so elegant, but in riot 2.3.13 I'm using something like this in a .tag file: ``` <menu-bar> <ul list="<yield/>"> <li each={ item in items }> <a href="http://localhost/pages/{ item }.html">{ titles[item] }</a> </li> </ul> <script> this.titles = { inventario: 'Inventario', resguardos: 'Resguardos', catalogos: 'Catálogos', reportes: 'Reportes', configurar: 'Configurar', utilidades: 'Utilidades' } this.items = null this.on('mount', function () { var el = this.root.querySelector('ul') this.items = el.getAttribute('list').trim().split(/,\s?/) el.removeAttribute('list') this.update() }) </script> </menu-bar> ``` Now, in the HTML page: ``` <menu-bar> inventario,resguardos,catalogos,reportes </menu-bar> ``` Works.
116,076
I'm in the process to move the development on Ubuntu 14.04. At the beginning everything seemed to work fine but quickly I discovered it was not. Installing new modules, by UI, Drupal stops without (displaying) any error and shows a blank page. After that, the site works undisturbed. You can go back and continue on other tasks. After many attempts to log the error without success, I run few test with [NetBeans](https://netbeans.org/) discovering that the code stops, with no reason, in `system.tar.inc`, when preparing to `untar` the package. Really weird. Tried with fresh install of Drupal 7.28: the same. Now I don't know how to go on. Main suspect is PHP 5.5.9, but before starting a new adventure with PHP versions, I'd like to hear you. What should I try first? --- No way. Reinstalled starting from a new VirtualBox, Ubuntu 14.04 and Ubuntu 7.28. Same story, all is working but stops when I try to install a new module (without errors). I took note of every piece i installed and can't find a reason why. apache ------ ``` apt-get install apache2 ``` * in global section of /etc/apache2/apache2.confd: ``` ServerName localhost ``` * replace run user in /etc/apache2/envvars ``` export APACHE_RUN_USER=joe export APACHE_RUN_GROUP=joe ``` * rewrite mode ``` sudo a2enmod rewrite ``` MYSQL ----- ``` apt-get install mysql-server apt-get install mysql-client apt-get install mysql-workbench mysql_secure_installation ``` PHP5 ---- ``` apt-get install php5 apt-cache search php apt-get install php5-curl php-pear php5-imagick php5-imap apt-get install php5-mcrypt libssh2-php php5-dev php5-gd php5-mcrypt ``` * changed values in php.ini ``` realpath_cache_ttl = 36000 max_execution_time = 300 max_input_time = 60 memory_limit = 256M post_max_size = 128M upload_max_filesize = 256M default_socket_timeout = 60 ``` * ``` apt-get install phpmyadmin ``` * complete manually some missing conf in: /etc/apache2/apache2.conf ``` include /etc/phpmyadmin/apache.conf ``` * virtual host test-me ``` <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName test.me ServerAlias *.test.me DocumentRoot /home/joe/Workarea/test-me <Directory "/home/joe/Workarea/test-me"> Options All AllowOverride All Require all granted </Directory> </VirtualHost> ``` * in /etc/hosts ``` 127.0.0.1 test.me ``` **DRUPAL** * created a db test-me with collation `utf8_unicode_ci` * in: /home/joe/Workarea ``` wget http://ftp.drupal.org/files/projects/drupal-7.28.tar.gz tar xzvf drupal-7.28 mv drupal-7.28 test-me ``` * in settings.php file: ``` $databases['default']['default'] = array( 'driver' => 'mysql', 'database' => 'test-me', 'username' => 'root', 'password' => '', 'host' => 'localhost', 'prefix' => 'main_', 'collation' => 'utf8_unicode_ci', ); ``` * Permissions: ``` chmod 644 settings.php chmod a+w sites/default ```
2014/06/02
[ "https://drupal.stackexchange.com/questions/116076", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/27180/" ]
This could be a bug, see: * <https://bugs.launchpad.net/ubuntu/+source/php5/+bug/1315888> * <https://bugs.php.net/bug.php?id=53829> As I had the same error and after deep diving I reached to `modules/system/system.tar.inc at line 716` which calls `gzopen()`. Here the errors are suppressed using `@`. Actually its giving following error on ubuntu 14.04: ``` Fatal error: Call to undefined function gzopen() in /var/www/html/drupcom/modules/system/system.tar.inc on line 718 ``` So this is issue with Zlib. I've tried to solve it using [these instructions](http://www.namhuy.net/2430/install-enable-zlib-linux-server.html), but no luck. Then I found that it is known bug.
Try enabling error reporting of PHP on your application adding temporally on the index.php: ``` error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); ``` You could do the same by editing the same values on the php.ini. Enable error reporting on Drupal adding on the settings.php: ``` $conf['error_level'] = 2; ``` I had a similar problem with Drupal 6 and PHP 5.4, here is one of the reported issues related to [that problem](https://www.drupal.org/node/1954296).
61,193,815
I am trying to do some basic group management using Azure Automation, but I'm having a heck of a time getting the script to authenticate correctly. I have added the Azure.Account modules to the runbook, and the connection seems to get established (at least, it doesn't throw an exception, and the returned object is not null). When using "Get-AzAdGroup", I am getting: ``` Get-AzADGroup : Insufficient privileges to complete the operation. ``` The app account created is a "Contributor" in AAD, so as far as I understand, has full rights to the directory. I have tried the solution listed at [How to connect-azaccount in Azure DevOps release pipeline](https://stackoverflow.com/questions/56350960/how-to-connect-azaccount-in-azure-devops-release-pipeline), to the same effect (Insufficient privileges). I have also applied "Group.Read.All", "Group.ReadWrite.All", "GroupMember.Read.All", "GroupMember.ReadWrite.All" based on what I can read from <https://learn.microsoft.com/en-us/graph/permissions-reference#group-permissions> - but I'm not 100% clear if the Az\* cmdlets use the Microsoft Graph, or if that's separate altogether. Code is as follows: ``` $connectionName = "AzureRunAsConnection" try { # Get the connection "AzureRunAsConnection " $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName "Logging in to Azure..." <# # Original, technically legacy. Add-AzureRmAccount ` -ServicePrincipal ` -TenantId $servicePrincipalConnection.TenantId ` -ApplicationId $servicePrincipalConnection.ApplicationId ` -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint #> $connectState = Connect-AzAccount ` -ServicePrincipal ` -TenantId $servicePrincipalConnection.TenantId ` -ApplicationId $servicePrincipalConnection.ApplicationId ` -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint <# # From https://stackoverflow.com/questions/56350960/how-to-connect-azaccount-in-azure-devops-release-pipeline, same result. $AzurePassword = ConvertTo-SecureString "*****" -AsPlainText -force $psCred = New-Object System.Management.Automation.PSCredential($servicePrincipalConnection.ApplicationId , $AzurePassword) $connectState = Connect-AzAccount -Credential $psCred -TenantId $servicePrincipalConnection.TenantId -ServicePrincipal #> if ($connectState) { "Connected." } else { "Doesn't seem to be connected." } } catch { if (!$servicePrincipalConnection) { $ErrorMessage = "Connection $connectionName not found." throw $ErrorMessage } else{ Write-Error -Message $_.Exception throw $_.Exception } } # Get groups Get-AzADGroup ``` My gut tells me that since both connect-azaccount methods yield the same result (connected, but no access) my issue isn't necessarily in the script, but short of creating a service account (which presents challenges with MFA), I don't know how to fix this.
2020/04/13
[ "https://Stackoverflow.com/questions/61193815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/328161/" ]
I have faced a very similar issue. You have a problem with the API permissions Azure APP has. In my case, my **azure App was working as a Service Principal**, and not only modifying some stuff in the **Azure AD**, but also some **Azure resources**, therefore, these were the api permissions that I had to grant: [![enter image description here](https://i.stack.imgur.com/kzLel.png)](https://i.stack.imgur.com/kzLel.png) > > Remember that you also need to grant admin consent from the Azure tenant for these permissions update. > > >
**Go to Azure portal --> Azure AD --> roles and Administrator-->Directory Readers role --> assign this role to the runbook account name**
16,187,902
Since Firefox 19, there is an internal default PDF reader "pdf.js". How can I detect whether this is the reader by default?
2013/04/24
[ "https://Stackoverflow.com/questions/16187902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097647/" ]
This might be what you are looking for... <http://www.pinlady.net/PluginDetect/PDFjs/>
This will test for it. I can't get to the other link due to corporate firewall. Dunno what it says. Maybe its the same. [FIDDLE HERE](http://jsfiddle.net/bWstc/) ``` <iframe src="some.pdf" id="iframe" name="iframe"></iframe> ``` . ``` // FireFox test for PDFJS to display PDFs. Works in 20 & 21. // If you don't test for the browser ... // IE says PDFJS is there. It isn't. // Chrome hangs on the fiddle // Safari for Windows says PDFJS isn't there $(window).load(function() { var userAgent = navigator ? navigator.userAgent.toLowerCase() : "other"; if(userAgent.indexOf("firefox") > -1) { var $iframe = $("#iframe"); var $innerDiv; try { $innerDiv = $iframe.contents().find('div'); alert("PDFJS not loaded"); } catch (e) { alert("PDFJS loaded"); } } else { alert("Not running in FireFox - no PDFJS available"); } }); ```
4,229,602
I'm building a site that needs to work with browsers that support JavaScript and browsers that don't (or that have it disable). What are some good resources that explain good approaches in doing this? Any specific technologies or frameworks that handle this well?
2010/11/19
[ "https://Stackoverflow.com/questions/4229602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53183/" ]
The technique is called Progressive Enhancement, [Christian Heilmann wrote a good introduction to the subject.](http://icant.co.uk/articles/pragmatic-progressive-enhancement/)
There is a [great video presentation](http://jsconfeu.blip.tv/file/4336317/) from JSConf.eu 2010 on exactly this topic.
291,974
I took a look at my old accounting system, and it seems that performance is taking a role in the daily labor of the employees using it. So, I discovered that using a subquery was the problem, I've been reading, testing and, it seems that using a JOIN is like 100x faster as the data that we have in our Databases is huge now. How do I can convert this subquery into a JOIN? > > I'm seeking for help because I'm trying, but I'm being unable to do it, and I'm starting to think that this is not possible. > > > ``` $sql = "SELECT orders.order_id, orders.order_time, orders.order_user, orders.payment_state, orders.order_state, orders.area_name, ( SELECT COUNT(*) FROM order_item WHERE order_item.order_id = orders.order_id ) AS items_number FROM orders WHERE orders.order_state = 1 AND order_time BETWEEN DATE_SUB(NOW(), INTERVAL 365 DAY) AND NOW()"; ``` Being specific, the data we are retrieving here is all the rows created in the last year from the orders table **AND** the number of items purchased in each order, which is called from the subquery as items\_number from order\_item table **WHERE** order\_id is equal in each table.
2021/05/21
[ "https://dba.stackexchange.com/questions/291974", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/228193/" ]
I would not do what another Answer suggests -- it involves the "explode-implode", which is even slower. I would start by seeing if this helped much: ``` orders: INDEX(order_state, order_time) ``` Your correlated subquery is not necessarily inefficient *in this case*. (That 100X quote is based on too few examples to be trustworthy.) This avoids the explode-implode and turns the subquery into a "derived table" (which is similar) but it needs to be executed only once. ``` SELECT o.order_id, o.order_time, o.order_user, o.payment_state, o.order_state, o.area_name, i.items_number FROM ( SELECT order_id, COUNT(*) AS items_number FROM order_item GROUP BY order_id ) AS i JOIN orders AS o ON o.order_id = i.order_id WHERE order_state = 1 AND order_time >= NOW() - INTERVAL 365 DAY ``` If you need "zero" values for orders without items, a minor change can achieve that; let me know. The index above is needed here. Also, if you don't already have `order_id` indexed in `order\_item, add that.
A simple way to do this would be like so: ``` SELECT ord.order_id, ord.orden_time, ord.orden_user, ord.payment_state, ord.order_state, ord.area_name, COUNT(itm.item_id) AS items_number FROM orders ord INNER JOIN order_item itm ON ord.order_id = itm.order_id WHERE ord.order_state = 1 and ord.order_time BETWEEN DATE_SUB(NOW(), INTERVAL 365 DAY) AND NOW() GROUP BY ord.order_id, ord.orden_time, ord.orden_user, ord.payment_state, ord.order_state, ord.area_name ``` This query assumes that every `orders` record will contain a minimum of one `order_item` record, which makes sense. Be sure to change `item_id` to whatever the primary key is for the `order_item` table. As an aside, if you would like your `BETWEEN` statement to be a little more fixed in time, you might want to use `DATE_FORMAT()` to ensure the start time is always `00:00:00` rather than the time of day when the query was run: ``` and ord.order_time BETWEEN DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 365 DAY), '%Y-%m-%d 00:00:00') AND NOW() ```
85,780
It has 46 chromosomes by default when healthy(Differences almost always are pathological) and has almost every biological functions, processes a Newborn or and Adult person has. It even invades fertile ground(womb) to survive.
2019/07/26
[ "https://biology.stackexchange.com/questions/85780", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/52803/" ]
That looks like the cast off outer layer of a dragon fly nymph§: [![Dragon fly larvae from: https://butterfliesandgardens.wordpress.com/tag/dragonfly-larvae/](https://i.stack.imgur.com/kuHxb.jpg)](https://i.stack.imgur.com/kuHxb.jpg) The following resources may be helpful to get a more precise identification: <https://www.fba.org.uk/sites/default/files/EA_specid/ea_specid_mod_8.pdf> <https://british-dragonflies.org.uk/odonata/species-and-identification/> --- §Note: As pointed out by [Arthur J. Frost](https://biology.stackexchange.com/users/32396/arthur-j-frost) this is actually the exoskeleton left behind when a dragonfly nymph molted and became an adult.
indeed -Exuvieae of a Anisopera dragonfly. <https://en.wikipedia.org/wiki/Exuviae>
29,554,041
I'm trying to setup a vagrant system for rails development. My vagrant version is Vagrant 1.4.2 and I have installed both the plugins vagrant-librarian-chef (0.1.4) and vagrant-vbguest (0.10.0). But when I do `vagrant up` I get the following error. > > The plugin "vagrant-vbguest" could not be found. Please make sure that it is > properly installed via `vagrant plugin`. Note that plugins made for > Vagrant 1.0.x are not compatible with 1.1+ and this error will likely > continue to show when you use `plugin install` with a 1.0.x plugin. > Bringing machine 'default' up with 'virtualbox' provider... > There are errors in the configuration of this machine. Please fix > the following errors and try again: > > > vm: > > \* The box 'base' could not be found. > > >
2015/04/10
[ "https://Stackoverflow.com/questions/29554041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4772231/" ]
If you don't read from the pipe, the subprocess is fairly likely to **never** terminate. The buffer between the ends of the pipe is fairly small. So, as the subprocess writes output, the buffer will fill and the subprocess will block in the `write()` call. Then you'll have deadlock. The parent process is waiting for the subprocess to terminate before reading from the pipe, the subprocess is blocked until the parent process reads from the pipe and so can't terminate.
This won't work (at least not on Linux system). The file descriptor (as given by [fileno(3)](http://man7.org/linux/man-pages/man3/fileno.3.html)) of a [popen(3)](http://man7.org/linux/man-pages/man3/popen.3.html)-ed command is a [pipe(7)](http://man7.org/linux/man-pages/man7/pipe.7.html). So it is not seekable, and [fstat(2)](http://man7.org/linux/man-pages/man2/fstat.2.html) won't give any significant size on it. If you need such fine grained information, don't use `popen` but call the underlying syscalls [pipe(2)](http://man7.org/linux/man-pages/man2/pipe.2.html), [fork(2)](http://man7.org/linux/man-pages/man2/fork.2.html), [execve(2)](http://man7.org/linux/man-pages/man2/execve.2.html), [waitpid(2)](http://man7.org/linux/man-pages/man2/waitpid.2.html) then you can use [poll(2)](http://man7.org/linux/man-pages/man2/poll.2.html). If you insist on using `popen` you could still `poll` its `fileno`; however there is no standard way to get its pid (to use `waitpid`) this is why you should use the [syscalls(2)](http://man7.org/linux/man-pages/man2/syscalls.2.html) directly. I guess that `fstat`-ing a pipe should not give a plain file but a [fifo(7)](http://man7.org/linux/man-pages/man7/fifo.7/html) if it succeeds, so special-case on `st.st_mode & S_IFMT == S_IFIFO` to detect that case.
1,172,826
I need to export data from a SQL server 2005 DB to an Access 97 .mdb file. The client that needs it, needs it to be Access 97 because the system that they're importing it into requires Access 97 file format (don't get me started). Any suggestions how to write an old-timey Access file from SQL or .Net (or VB6 or Ruby or Python..)? Thanks in advance, Lee
2009/07/23
[ "https://Stackoverflow.com/questions/1172826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385504/" ]
What you need to do is export into an Access file for whatever Access version you have installed (as long as it's 2000...2003; Access 2007 can't write to Access 97 files). I assume you already know how to do this. Then you can create an Access object via COM and ask it to convert your new .mdb file into a new Access 97 database. In VBScript, the code looks like this (adjust as necessary if you're using VBA, VB.Net, or another language): ``` const acFileFormatAccess97 = 8 dim app set app = CreateObject("Access.Application") app.ConvertAccessProject "y:\mydatabase.mdb", "y:\mydatabase97.mdb", acFileFormatAccess97 ``` If you have Access 97 installed, the above command won't work, because Access didn't have the ConvertAccessProject function in that version. Of course, you don't need to convert the file in that case anyway.
I think it's crazy to do it from SQL Server. Just create an ODBC DSN for your SQL Server and import the tables into your Access 97 MDB and be done with it. The only reason you might want to do it otherwise is if you want to automate it and do it repeatedly, but that can be automated in Access, too (TransferDatabase can do ODBC imports), and will take only as many lines of code as there are tables to import.
20,094,193
I would like to filter the papers sold within a particular range of time but i still don't know how can i insert the Date when the papers were ordered. Please see current codes ``` SELECT p.PaperID, p.PaperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders LEFT JOIN Papers as p ON Orders.PaperID=p.PaperID GROUP BY PaperName, p.PaperID ``` Cuurent output: ``` PaperID PaperName No. of Orders 1 Paper1 2 2 Paper2 1 ``` Database table Sales ``` SaleID OrderID Amount Date 1 1 10 2013-11-10 2 2 10 2013-11-20 3 3 30 2013-11-30 ``` Orders ``` OrderID PaperID 1 1 2 1 3 2 ```
2013/11/20
[ "https://Stackoverflow.com/questions/20094193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1473914/" ]
First of all you need to sum the arrays: ``` raw_data.sum ``` This will return sth like: ``` [ {"created_at"=>"2013-11-17","number"=>0,"s_number"=>0,"l_number"=>0}, {"created_at"=>"2013-11-18","number"=>6,"s_number"=>1,"l_number"=>4}, {"created_at"=>"2013-11-19","number"=>1,"s_number"=>1,"l_number"=>1}, {"created_at"=>"2013-11-20","number"=>0,"s_number"=>0,"l_number"=>0} {"created_at"=>"2013-11-17","number"=>2,"s_number"=>3,"l_number"=>4}, {"created_at"=>"2013-11-18","number"=>1,"s_number"=>41,"l_number"=>1}, {"created_at"=>"2013-11-19","number"=>5,"s_number"=>45,"l_number"=>7}, {"created_at"=>"2013-11-20","number"=>7,"s_number"=>8,"l_number"=>2} ] ``` Now, we need to group elements by 'created\_at' key: ``` raw_data.sum.group_by{|element| element['created_at']} ``` This will result in: ``` { "2013-11-17" => [ {"created_at"=>"2013-11-17","number"=>0,"s_number"=>0,"l_number"=>0}, {"created_at"=>"2013-11-17","number"=>2,"s_number"=>3,"l_number"=>4}, ], "2013-11-18" => [ {"created_at"=>"2013-11-18","number"=>6,"s_number"=>1,"l_number"=>4}, {"created_at"=>"2013-11-18","number"=>1,"s_number"=>41,"l_number"=>1} ], ... } ``` We only need values of this hash: ``` raw_data.sum.group_by{|element| element['created_at']}.values # => [ [ {"created_at"=>"2013-11-17","number"=>0,"s_number"=>0,"l_number"=>0}, {"created_at"=>"2013-11-17","number"=>2,"s_number"=>3,"l_number"=>4}, ], [ {"created_at"=>"2013-11-18","number"=>6,"s_number"=>1,"l_number"=>4}, {"created_at"=>"2013-11-18","number"=>1,"s_number"=>41,"l_number"=>1} ], ... } ``` And now we need to map each array of hashes to one hash. For this we'll use inject and merge function with a block: ``` raw_data.sum.group_by{|element| element[:created_at]}.values.map{|a| a.inject({}) {|result, hash| result.merge(hash) {|key, old_value, new_value| key == :created_at ? old_value : old_value + new_value}}} # => [ {"created_at"=>"2013-11-17","number"=>2,"s_number"=>3,"l_number"=>4}, {"created_at"=>"2013-11-18","number"=>7,"s_number"=>42,"l_number"=>5}, {"created_at"=>"2013-11-19","number"=>6,"s_number"=>46"l_number"=>8}, {"created_at"=>"2013-11-20","number"=>7,"s_number"=>8,"l_number"=>2} ] ```
``` output = [] raw_data.flatten.group_by {|x| x[:created_at].to_s}.each do |key, values| temp_hash = { :created_at => key.to_date } [:number, :s_number, :l_number].each do |attr| temp_hash[attr] = values.collect{|w| w[attr]}.sum end output << temp_hash end # output will contain your result ```
4,897,737
I need to change the td background to grey and text in another td when the user's mouse goes over the first mentioned td. I have done this so far: ``` <td onMouseOver="this.style.background='#f1f1f1'" onMouseOut="this.style.background='white'"> ``` but this only changes the background of the first td and does not change the text in the second td. Any ideas please?
2011/02/04
[ "https://Stackoverflow.com/questions/4897737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272756/" ]
Have a look at this: ``` function highlightNext(element, color) { var next = element; do { // find next td node next = next.nextSibling; } while (next && !('nodeName' in next && next.nodeName === 'TD')); if (next) { next.style.color = color; } } function highlightBG(element, color) { element.style.backgroundColor = color; } ``` HTML: ``` <td onMouseOver="highlightBG(this, 'red');highlightNext(this, 'red')" onMouseOut="highlightBG(this, 'white');highlightNext(this, 'black')" > ``` [**DEMO**](http://jsfiddle.net/jEekg/2/) Note that adding the event handler in the HTML is not considered to be good practice. --- [Depending on which browser you want to support](http://www.quirksmode.org/css/contents.html#t12) (it definitely won't work in IE6), you really should consider the CSS approach which will work even if JS is turned off. Is much less code and it will be easier to add this behaviour to multiple elements: ``` td:hover { background-color: red; } td:hover + td { color: red; } ``` [**DEMO**](http://jsfiddle.net/bC3qj/)
You should give that other td an id and access it from your onmouseover event handler. Maybe you should put that onmouseover code into its own function and call it from the onmouseover.
8,892,360
I am using this code to convert a `Set` to a `List`: ``` Map<String, List<String>> mainMap = new HashMap<>(); for (int i=0; i < something.size(); i++) { Set<String> set = getSet(...); //returns different result each time List<String> listOfNames = new ArrayList<>(set); mainMap.put(differentKeyName, listOfNames); } ``` I want to avoid creating a new list in each iteration of the loop. Is that possible?
2012/01/17
[ "https://Stackoverflow.com/questions/8892360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420613/" ]
You could use this one line change: `Arrays.asList(set.toArray(new Object[set.size()]))` ``` Map<String, List> mainMap = new HashMap<String, List>(); for(int i=0; i<something.size(); i++){ Set set = getSet(...); mainMap.put(differentKeyName, Arrays.asList(set.toArray(new Object[set.size()]))); } ```
I create simple `static` method: ``` public static <U> List<U> convertSetToList(Set<U> set) { return new ArrayList<U>(set); } ``` ... or if you want to set type of List you can use: ``` public static <U, L extends List<U>> List<U> convertSetToList(Set<U> set, Class<L> clazz) throws InstantiationException, IllegalAccessException { L list = clazz.newInstance(); list.addAll(set); return list; } ```
46,435,376
It is true that each object has its own copy of instance variables. But is it true that like static members, there is only one copy of instance methods? If yes, then where it resides in memory?
2017/09/26
[ "https://Stackoverflow.com/questions/46435376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8465183/" ]
There only needs to be one copy of instance methods in memory. When an instance method is called there will be a "this" variable implicitly included in the stack. The "this" variable allows the instance method to access the instance variables for the object instance that called it. Classes, including their methods, would typically end up in the long lived heap as it is uncommon for them to be garbage collected.
Yes. Logically, a method in every instance of one class, shares one algorithm. Memory behaves in a similar way. Each object calls one method algorithm and required values are pushed to the stack temporary during the method call. Method is a set of instructions to follow, not a data structure. It should not specifically allocate memory. Method call instructions are stored in RAM separately, as same as other application instructions. This is not a part of Java memory allocation process.
237,733
I've been a bad programmer because I am doing a copy and paste. An example is that everytime i connect to a database and retrieve a recordset, I will copy the previous code and edit, copy the code that sets the datagridview and edit. I am aware of the phrase code reuse, but I have not actually used it. How can i utilize code reuse so that I don't have to copy and paste the database code and the datagridview code.,
2008/10/26
[ "https://Stackoverflow.com/questions/237733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26087/" ]
Put the code into a routine and call the routine whenever you want that code to be executed.
Easy: whenever you catch yourself copy-pasting code, take it out *immediately* (i.e., don't do it after you've already CP'd code several times) into a new function.
467,482
Any pointers on how I can programmatically get exactly the identical stored procedure source from SQL Server 2005, as when I right-click on that stored procedure in SQL Server Management Studio and select modify? I'm trying using SMO, but there are some textual differences. The procedure always has CREATE, not ALTER, and there are some differences in the header, such as missing GOs in the version I'm getting programmatically. I can fix these up, but perhaps there is a better way? Again, I'm in SQL Server 2005, using SMSE. Using SMO via Visual Studio 8 2008. **Update**: Gotten some answers that tell the basics of how to retrieve the stored procedure. What I'm looking for is retrieving the text identical (or nearly identical) to what the GUI generates. Example: for sp\_mysp, right-click in Management Studio, select modify. This generates: ``` USE [MY_DB] GO /****** Object: StoredProcedure [dbo].[sp_mysp] Script Date: 01/21/2009 17:43:18 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= ALTER PROCEDURE [dbo].[sp_mysp] ``` I'd like to programmatically get the same thing (notice the GOs in the header, and the fact that it's an ALTER PROCEDURE. Ideally, I'd like to get this with minimal programmatic fixing up of the source retrieved. I'd be happy to only get something that differed in the Script Date details . . .
2009/01/21
[ "https://Stackoverflow.com/questions/467482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49251/" ]
``` EXEC sp_helptext 'your procedure name'; ``` This avoids the problem with INFORMATION\_SCHEMA approach wherein the stored procedure gets cut off if it is too long. Update: David writes that this isn't identical to his sproc...perhaps because it returns the lines as 'records' to preserve formatting? If you want to see the results in a more 'natural' format, you can use Ctrl-T first (output as text) and it should print it out exactly as you've entered it. If you are doing this in code, it is trivial to do a foreach to put together your results in exactly the same way. Update 2: This will provide the source with a "CREATE PROCEDURE" rather than an "ALTER PROCEDURE" but I know of no way to make it use "ALTER" instead. Kind of a trivial thing, though, isn't it? Update 3: See the comments for some more insight on how to maintain your SQL DDL (database structure) in a source control system. That is really the key to this question.
You said programmatically, right? I hope C# is ok. I know you said that you tried SMO and it didn't quite do what you wanted, so this probably won't be perfect for your request, but it will programmatically read out legit SQL statements that you could run to recreate the stored procedure. If it doesn't have the `GO` statements that you want, you can probably assume that each of the strings in the `StringCollection` could have a `GO` after it. You may not get that comment with the date and time in it, but in my similar sounding project (big-ass deployment tool that has to back up everything individually), this has done rather nicely. If you have a prior base that you wanted to work from, and you still have the original database to run this on, I'd consider tossing the initial effort and restandardizing on this output. ``` using System.Data.SqlClient; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo; … string connectionString = … /* some connection string */; ServerConnection sc = new ServerConnection(connectionString); Server s = new Server(connection); Database db = new Database(s, … /* database name */); StoredProcedure sp = new StoredProcedure(db, … /* stored procedure name */); StringCollection statements = sp.Script; ```
14,279
If you purchase a movie bundle including multiple formats, is it legal to distribute one or more of those formats—at no cost—to varying family members and/or friends? When I say "distribute" I mean to give away the original without making copies. The verbiage from one Blu-Ray + DVD + Digital HD combo reads "Unless expressly authorized in writing by the copyright owner, any copying, exhibition, export, *distribution* or other use of this product or any part of it is strictly prohibited." I realize the above's intent is to prevent piracy and resale, but the way it's worded suggests that it's even illegal to give away the entire set, perhaps as a gift. That seems ridiculous and raises more questions than it addresses. Spirit of the law aside, I'm trying to understand my rights with each original copy found in a bundle.
2016/09/29
[ "https://law.stackexchange.com/questions/14279", "https://law.stackexchange.com", "https://law.stackexchange.com/users/9269/" ]
There *was* a lawsuit Disney v Redbox in 2018 and 2019 about exactly that. [It settled.](https://www.youtube.com/watch?v=dKvdD_A8iGo) [Lawfull masses has 6 videos about the topic](https://www.youtube.com/results?search_query=lawful+masses+disney+v+redbox). In part, it did lead to Disney altering the ToS of the digital download/streaming site they use to include that you need to own the DVD to be not in violation and to not break the combo pack.
Video stores sell previously viewed titles without the digital download s all the time, some are even selling them separately as a unique product. In litigation, it is likely to be established that the spirit of the contractual language is intended specifically to prevent unauthorized copies of an intellectual property from being sold / marketed and not parts or portions of the product that was lawfully purchased and re-sold in whole or part. Consider you purchased the "combo" pack, used the digital download (which could not be used again), then later sold the physical disc(s). This is the same scenario, but in reverse.
78,869
I have a coworker that primarily develops programs for internal use in the company. They design their programs in such a way that they progressively consolidate their position within the company so that they are gradually more difficult to replace. Some examples: * Don't check their code into company version control, only distribute compiled binaries. * Design their programs using client-server architecture so that the programs they distribute are thin clients that send requests to a server they run on their machine; nobody knows how this server works or what it's doing (other than a high level description). * Whenever anything related to their programs breaks, the only person who can fix it is themselves, everyone else doesn't have access to his code and lacks required knowledge to replicate the functionality of his server. * Nobody has the time to write a parallel set of programs or reverse engineer the secret server, so we're stuck with what we get from that person. Since they have developed a huge chunk of programs we use internally, they cannot be replaced, and since they won't be replaced, we can't get out of this situation. And we're becoming more dependent on that person, since they keep designing their code to strengthen their position in the company. How to break out of this vicious cycle? How to approach management about this?
2016/11/01
[ "https://workplace.stackexchange.com/questions/78869", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/59396/" ]
**You need to compile a report for management.** Write a short document outlining *exactly* why the current approach is leading the company down a dangerous path (getting hit by a bus scenario, for example). Outline security risks, maybe even cite cautionary tales from within your industry, with references to articles, etc. Also include a list of ways in which this guy's approach is impairing your own work, as well as the work of your coworkers. Last but not least, make sure to list of recommendations to be implemented immediately, such as adding the code to version control for all to see, and running the server on a VM which everyone has access to. Outline how these measures should in no way impact this person's work, and will simply add security and transparency to the whole process - ***make it clear that there are no reasonable objections to these measures.*** Perhaps sit down with your boss when you hand him this report, and verbally deliver the exact fears you've written here: that this guy is building himself an empire in the company's infrastructure, and that, ultimately, he is [potentially dangerous](https://workplace.stackexchange.com/questions/63016/how-to-benefit-from-being-able-to-save-my-company-from-a-disaster-while-being-la/63019#63019). If your bosses feel that this person may become unreasonable, then you may wish to follow @BillLeeper 's advice and seize control of his machine so that he will be unable to harm your organization. This will, of course, be for them to decide.
It seems there are some good remedies here to prevent this in the future, but not what to do about it now. 1. Secure the computer. Either have management and an IT expert go over when it's unlocked and un-attended, or go and demand that he unlock the machine and grant access. Then get this monster off the network. Make an immediate image of the HD in case he has a dead mans switch. 2. Fire this individual immediately. Walk him out the door. Don't worry about cause, there will be plenty of evidence on that computer of his. If the company is worried, have their lawyer work his magic, that's what they get paid for. 3. Get the team together. Explain what went down. This individual was acting in a reckless and un-professional manner. He put the company at risk and was terminated for that. It is going to take all the resources we have to get this mess sorted out. 4. Use the team to re-build and re-deploy this work in a proper manner on secured machines etc. The team is going to have to go through app by app and get a handle on things. Don't worry right away about rewriting, just make sure there are no back doors etc., then get the services up on fresh, controlled hardware. 5. Get a security expert in. This guy will probably not go quietly and will try and 'hack' back in to sabotage or otherwise get access to his system. He may also have global passwords to systems he interacted with or obtained individuals passwords over time. IT should trigger a forced password reset on all users and block any outside access for a time (like VPN).
5,326,763
I have the following two Python functions: ``` @classmethod def serialize_dict(cls, d): values = [] for column_name in cls().distinguishing_column_names(): value = str(d[column_name]) if value == 'None': value = '' values.append(value) return ' '.join(values) @classmethod def serialize_row(cls, row): values = [] for column_name in cls().distinguishing_column_names(): value = str(row.value(cls()._meta.db_table, column_name)) if value == 'None': value = '' values.append(value) return ' '.join(values) ``` As you can see, the two functions are identical except for the first line of the `for` loop. Not very DRY. How could I refactor this code to take out all the repetitions, given that `row` and `d` are of different types (`dict` and a custom type of mine, respectively)?
2011/03/16
[ "https://Stackoverflow.com/questions/5326763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199712/" ]
Add an `if isinstance(arg, dict)` to determine whether to treat it as a row or dict, then merge the two methods together.
You could implement the function that serialise the bit into two different lambda functions that can then used as parameters of a single serialisation method: ``` ds = lambda d , cls , column_name : str(d[column_name]) rs = lambda d , cls , column_name : str(d.value(cls()._meta.db_table, column_name)) def __serialize(cls, d, ser): values = [] for column_name in cls().distinguishing_column_names(): value = ser(d,cls,column_name) if value == 'None': value = '' values.append(value) return ' '.join(values) @classmethod def serialize_dict(cls, d): return __serialize(cls, d, ds) @classmethod def serialize_row(cls, row): return __serialize(cls, d, rs) ```
31,542,454
I have been using an Arduino Uno to connect to IoT Foundation on Bluemix. I've used both the Quickstart and the Registered devices. So far I've found that connecting to either service is intermittent. Currently I cannot connect my device (using IBM internal IP) to the quickstart. I've set this up and tested in the past but lately it doesn't work (from 2 IBM sites). I'm using the recipe verbatim except for the device ID/MAC address. Pinging quickstart.messaging.internetofthings.ibmcloud.com returns a timeout.
2015/07/21
[ "https://Stackoverflow.com/questions/31542454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2252757/" ]
Quickstart will not respond to ping, which is why you get a timeout when pinging that hostname. Using mosquitto (<http://mosquitto.org/>) I use the following as a simple test when debugging issues like this -- are you sure your arduino isn't having networking issues as all seems fine when I connect? Make a subscription: ``` mosquitto_sub -h quickstart.messaging.internetofthings.ibmcloud.com -p 1883 -i a:quickstart:flobble_app -t iot-2/type/+/id/flobble/evt/+/fmt/+ ``` Send an event: ``` mosquitto_pub -h quickstart.messaging.internetofthings.ibmcloud.com -p 1883 -i d:quickstart:flibble:flobble -t iot-2/evt/status/fmt/json -m "{\"d\": {\"hi\": 100, \"name\":\"flibble\", \"foo\": 80}}" ```
We have also had issues with connections and outages when working with Bluemix. Another issue we faced was with the length of messages in the suggested [MQTT library](https://github.com/256dpi/arduino-mqtt/pull/5). We ended up using ATSD instead of Bluemix for our IOT use cases with Arduino Uno devices and DHT sensors. [Here](https://github.com/axibase/arduino/tree/master/dataTransmission) you can find an in-depth guide on setting up a temperature/humidity sensor paired with an Arduino device. Using the guide you will be able to stream the sensor data into ATSD using MQTT or TCP protocol. Open-source sketches are included.
48,386,443
Let's say I have a file named `m1.txt`, whose contents (`- . ... - / -. --- / .----`) I want to decode from Morse to text. Here's what I have written: ``` sed -i 's/.- /A/g' m1.txt sed -i 's/-... /B/g' m1.txt sed -i 's/-.-. /C/g' m1.txt ``` and so on, including numbers, and later on: ``` sed -i 's:/ : :g' m1.txt cat m1.txt ``` in order to clear the separating slash and output the message. The expected output is `TEST NO 1`, however the program outputs `D...AE-ED.--A` instead, ignoring any whitespaces and returning a wrong message. What have I done wrong?
2018/01/22
[ "https://Stackoverflow.com/questions/48386443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5976239/" ]
Two things: 1. You need to escape `.`, since it will match any character 2. You need to consider interactions, since `.` (E) will match a single dot, it will also match the end of (N) `-.` unless you consider them in the right order or preserve the separators (on both the left and right). (1) is obvious to solve, simply escape the `.`. For (2), we can first map the beginning and end of the line to spaces (so that we have separators consistently on the left and right, and then we preserve the separators on output (to avoid interactions). Then, in the second to last line, clean up the spaces. Then, in the final line, map your slashes to the word break spaces which are the only spaces you want in your output. I didn't do the whole alphabet for you, just enough for you to see the idea. Here's a working solution: ``` $ cat m1.txt - . ... - / -. --- / .---- $ cat morse.sed s/^/ / s/$/ / s/ - / T /g s/ \. / E /g s/ \.\.\. / S /g s/ -\.\ / N /g s/ --- / O /g s/ \.---- / 1 /g s/[ ]\+//g s:/: :g $ cat m1.txt | sed -f morse.sed TEST NO 1 ``` Note: this answer was revised because I didn't at first realize that the `(` and `)` were not part of the input. Also, @Bach Lien's idea to map the anchors to spaces in the first lines is a great one, it makes things a lot cleaner, so I've incorporated that idea.
Morse table (morse-to-char mapping): ``` $ cat morse-table.txt ## this is table of char-to-morse-code mapping ## taken from https://en.wikipedia.org/wiki/Morse_code ## dated: 2018 01 23 ## characters A .- B -... C -.-. D -.. E . F ..-. G --. H .... I .. J .--- K -.- L .-.. M -- N -. O --- P .--. Q --.- R .-. S ... T - U ..- V ...- W .-- X -..- Y -.-- Z --.. ## numbers 1 .---- 2 ..--- 3 ...-- 4 ....- 5 ..... 6 -.... 7 --... 8 ---.. 9 ----. 0 ----- ## special symbols ## in fact, there is no ## such symbols in traditional morse codes ## this part is fake, just for testing . ....... \ ------- / -.-.-.- ? --.--.- [ .--.--. ] --..--. ``` Program to convert Morse table to `sed` script: ``` $ cat make-m2t.sh #!/bin/bash t=morse-table.txt # morse table s=m2t # sed script s1=' # s1 = pre-processing s:\s+: :g # space-gap to TWO space-chars s:^: : # add a space at line beginning s:$: : # add a space at line end s:/: \n :g # change all slash to " \n " ' s2=' # s2 = morse-table to sed-script s:\s+: :g # space-gap to space-char s:##.*$:: # remove all comments s:^ *:: # remove all leading spaces s: *$:: # remove all trailing spaces /^[^ ] [\.-]+$/!d # ignore all invalid lines s:\.:\\.:g # add back-slash for dot (escape for dot) s:^\\\. :\. : # but not for the char-dot s:^\\ :\\\\ : # add b-slash for b-slash (escape for b-slash) s:^\/ :\\\/ : # add b-slash for slash (escape for slash) s:^([^ ]+) +([^ ]+).*$:s/ \2 / \1 /g: # morse-map to sed-subsitution ' s3=' # s3 = post-processing s: ::g # remove all spaces s:\n: :g # convert \n to space ' # now, make the sed script echo '#!/usr/bin/sed -Ef' >"$s" # shebang sed -E 's:\s*#.*$::' <<<"$s1" >>"$s" # remove comments from s1 sed -E "$s2" "$t" >>"$s" # convert morse to chars sed -E 's:\s*#.*$::' <<<"$s3" >>"$s" # remove comments from s3 sed -i -E '/^\s*$/d' "$s" # remove all blank lines chmod +x "$s" # make it executable ``` Test: ``` $ ./make-m2t.sh $ echo '- . ... -/-. ---/.----' | ./m2t TEST NO 1 $ echo '.--.--. .... . .-.. .-.. --- --..--./....... --.--.-' | ./m2t [HELLO] .? $ cat m1.txt - . ... - / -. --- / .---- $ ./m2t m1.txt TEST NO 1 $ cat m2t #!/usr/bin/sed -Ef s:\s+: :g s:^: : s:$: : s:/: \n :g s/ \.- / A /g s/ -\.\.\. / B /g s/ -\.-\. / C /g s/ -\.\. / D /g s/ \. / E /g s/ \.\.-\. / F /g s/ --\. / G /g s/ \.\.\.\. / H /g s/ \.\. / I /g s/ \.--- / J /g s/ -\.- / K /g s/ \.-\.\. / L /g s/ -- / M /g s/ -\. / N /g s/ --- / O /g s/ \.--\. / P /g s/ --\.- / Q /g s/ \.-\. / R /g s/ \.\.\. / S /g s/ - / T /g s/ \.\.- / U /g s/ \.\.\.- / V /g s/ \.-- / W /g s/ -\.\.- / X /g s/ -\.-- / Y /g s/ --\.\. / Z /g s/ \.---- / 1 /g s/ \.\.--- / 2 /g s/ \.\.\.-- / 3 /g s/ \.\.\.\.- / 4 /g s/ \.\.\.\.\. / 5 /g s/ -\.\.\.\. / 6 /g s/ --\.\.\. / 7 /g s/ ---\.\. / 8 /g s/ ----\. / 9 /g s/ ----- / 0 /g s/ \.\.\.\.\.\.\. / . /g s/ ------- / \\ /g s/ -\.-\.-\.- / \/ /g s/ --\.--\.- / ? /g s/ \.--\.--\. / [ /g s/ --\.\.--\. / ] /g s: ::g s:\n: :g ``` --- **Note:** 1. User only need to define the morse-table.txt, to map morse codes to characters 2. Based on morse-table, `bash` program would generate `sed` script to convert morse codes to text 3. The `sed` script is based on the solution of @JawguyChooser. 4. Because we use space `' '` as "delimiter" of Morse block, so, when pre-processing we must convert all space gap to TWO space-characters; otherwise error will occur for words like `'HELLO'` (double `L`)
42,137,020
I tried to write raspbian operating system to my sdcard. I put my sdcard into sdcard reader and then tried to format it to fat32. I can not do that with microsoft windows, so I downloaded [sdformatter](https://www.sdcard.org/downloads/formatter_4/eula_windows/) and my sdcard formatted successfully. After that , I tried to write raspbian dd image into my sdcard, but I get an error and in logs I had: ``` Rufus version: 2.2.668 Windows version: Windows 10 64-bit Syslinux versions: 4.07/2013-07-25, 6.03/2014-10-06 Grub versions: 0.4.6a, 2.02~beta2 Locale ID: 0x0409 Found USB 2.0 device 'Generic- Multi-Card USB Device' (0BDA:0158) 1 device found Disk type: Removable, Sector Size: 512 bytes Cylinders: 979, TracksPerCylinder: 255, SectorsPerTrack: 63 Partition type: MBR, NB Partitions: 1 Disk ID: 0x00000000 Drive has a Zeroed Master Boot Record Partition 1: Type: FAT32 (0x0b) Size: 7.5 GB (8048869376 bytes) Start Sector: 8192, Boot: No, Recognized: Yes Scanning image... 'G:\2017-01-11-raspbian-jessie.img' doesn't look like an ISO image Image has a Zeroed Master Boot Record 'G:\2017-01-11-raspbian-jessie.img' is a bootable disk image Using image: 2017-01-11-raspbian-jessie.img Format operation started Requesting disk access... Opened drive \\.\PHYSICALDRIVE1 for write access Will use 'F:' as volume mountpoint I/O boundary checks disabled Analyzing existing boot records... Drive has a Zeroed Master Boot Record Volume has an unknown Partition Boot Record Deleting partitions... Clearing MBR/PBR/GPT structures... Erasing 128 sectors Writing Image... write error: [0x00000002] The system cannot find the file specified. RETRYING... write error: [0x00000002] The system cannot find the file specified. RETRYING... write error: [0x00000037] The specified network resource or device is no longer available. 0 devices found Found USB 2.0 device 'Generic- Multi-Card USB Device' (0BDA:0158) 1 device found No volume information for drive 0x81 Disk type: Removable, Sector Size: 512 bytes Cylinders: 979, TracksPerCylinder: 255, SectorsPerTrack: 63 Partition type: MBR, NB Partitions: 1 Disk ID: 0x00000001 Drive does not have an x86 Master Boot Record Partition 1: Type: Small FAT16 (0x04) Size: 7.5 GB (8053063680 bytes) Start Sector: 0, Boot: No, Recognized: Yes Found USB 2.0 device 'Generic- Multi-Card USB Device' (0BDA:0158) 1 device found No volume information for drive 0x81 Disk type: Removable, Sector Size: 512 bytes Cylinders: 979, TracksPerCylinder: 255, SectorsPerTrack: 63 Partition type: MBR, NB Partitions: 1 Disk ID: 0x00000001 Drive does not have an x86 Master Boot Record Partition 1: Type: Small FAT16 (0x04) Size: 7.5 GB (8053063680 bytes) Start Sector: 0, Boot: No, Recognized: Yes Found USB 2.0 device 'Generic- Multi-Card USB Device' (0BDA:0158) 1 device found Disk type: Removable, Sector Size: 512 bytes Cylinders: 979, TracksPerCylinder: 255, SectorsPerTrack: 63 Partition type: MBR, NB Partitions: 2 Disk ID: 0x623FDBF4 Drive has a Zeroed Master Boot Record Partition 1: Type: FAT32 LBA (0x0c) Size: 63 MB (66060288 bytes) Start Sector: 8192, Boot: No, Recognized: Yes Partition 2: Type: GNU/Linux (0x83) Size: 4 GB (4301258752 bytes) Start Sector: 137216, Boot: No, Recognized: Yes Found USB 2.0 device 'Generic- Multi-Card USB Device' (0BDA:0158) 1 device found Disk type: Removable, Sector Size: 512 bytes Cylinders: 979, TracksPerCylinder: 255, SectorsPerTrack: 63 Partition type: MBR, NB Partitions: 2 Disk ID: 0x623FDBF4 Drive has a Zeroed Master Boot Record Partition 1: Type: FAT32 LBA (0x0c) Size: 63 MB (66060288 bytes) Start Sector: 8192, Boot: No, Recognized: Yes Partition 2: Type: GNU/Linux (0x83) Size: 4 GB (4301258752 bytes) Start Sector: 137216, Boot: No, Recognized: Yes ```
2017/02/09
[ "https://Stackoverflow.com/questions/42137020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4284233/" ]
Given the string has the above stated format, you could use regex substitution with *backrefs*: ``` import re a = '(a,1.0),(b,6.0),(c,10.0)' a_fix = re.sub(r'\((\w+),', r"('\1',",a) ``` So you look for a pattern `(x,` (with `x` a sequence of `\w`s and you substitute it into `('x',`. The result is then: ``` # result a_fix == "('a',1.0),('b',6.0),('c',10.0)" ``` and then parse `a_fix` and convert it to a `dict`: ``` result = dict(ast.literal_eval(a_fix)) ``` The result in then: ``` >>> dict(ast.literal_eval(a_fix)) {'b': 6.0, 'c': 10.0, 'a': 1.0} ```
No need for regexes, if your string is in this format. ``` >>> a = '(a,1.0),(b,6.0),(c,10.0)' >>> d = dict([x.split(',') for x in a[1:-1].split('),(')]) >>> print(d) {'c': '10.0', 'a': '1.0', 'b': '6.0'} ``` We remove the first opening parantheses and last closing parantheses to get the key-value pairs by splitting on `),(`. The pairs can then be split on the comma. To cast to float, the list comprehension gets a little longer: ``` d = dict([(a, float(b)) for (a, b) in [x.split(',') for x in a[1:-1].split('),(')]]) ```
179,188
For an irreducible finite depth finite index subfactor $(N \subset M)$, there is a structure of fusion category given by the even part of its principal graph. The simple objects $(X\_i)\_{i \in I}$ of depth $0$ or $2$ correspond to the projections $p\_i = I\_{H\_i}$ on the $2$-boxes space $\mathcal{P}\_2(N \subset M) = \bigoplus\_{i \in I} End(H\_i) $ as an algebra. *Warning*: $I$ is the index set for the simple objects of depth $0$ or $2$, but there can have others. On a $2$-boxes space, there is a structure of coproduct $a∗b$ (defined for example [here][1] p4). **Question**: How compute the coproduct $p\_j \* p\_j$ from the fusion $X\_i \boxtimes X\_j$? My guess is that $p\_i \* p\_j \sim \sum\_{k \in K} p\_k$ with $K=\{ k \in I \ \vert \ X\_k \le X\_i \boxtimes X\_j \}$ (*truncated fusion*). Is it true? What's the exact formula? How prove it? Else, if there is a minimal projection $u \preceq p\_i∗p\_j$ such that its central support $Z(u)=p\_k$, but $p\_k \not \preceq p\_i∗p\_j$, is it still true that $X\_k$ appears as a summand of $X\_i ⊠ X\_j$? In other words, is it true that $Z(p\_i \* p\_j) \le \sum\_{k \in K} p\_k$? Is it an equality? (*weak truncated fusion*)
2014/08/23
[ "https://mathoverflow.net/questions/179188", "https://mathoverflow.net", "https://mathoverflow.net/users/34538/" ]
In the formula, $tr(b)$ should be replaced by $tr(|b|)$, i.e., $\|b\|\_1$. $$b\_\alpha\*b\_\beta=\sum\_\gamma\frac{\|b\_\alpha\|\_1\|b\_\beta\|\_1\bar{c}\_{\alpha\beta}^\gamma}{\sqrt{n}\|b\_\gamma\|\_1}b\_\gamma.$$ Unfortunately the proof needs the irreducibility. I do not know how to generalize it to weak Kac algebras. As Dave mentioned, one direction is clear. It is hard to determine when $(p\_i\*p\_j)p\_k=0$. If $P\_{2,\pm}$ are abelian, then I have a criterion for the extremal case: $(p\_i\*p\_j)p\_k \neq 0$ for all permitted fusion rule if and only if $P$ has a Yang-Baxter relation (see [this paper](http://arxiv.org/abs/1507.06030)).
**Depth $2$ case:** Let $(N \subset M)$ be a depth $2$ irreducible subfactor of finite index $[M:N]=: \delta^{2}$. Let $\mathbb{A}:=P\_{2,+}(N \subset M)$ the finite dimensional Kac algebra. Let the inner product $(a,b) = tr(a^\*b)$ on $\mathbb{A}$ with $tr()$ the *normalized* trace. Let $(b\_i)\_i$ be an orthonormal basis of $\mathbb{A}$, i.e. $(b\_i, b\_j) = \delta\_{i,j}$. Consider the comultiplication $\Delta(a)$, the coproduct multiplication $a \* b$, and their constant structure: $$\Delta(b\_i) = \sum\_{j,k} c\_{jk}^i \cdot(b\_j \otimes b\_k)$$ $$ b\_j \* b\_k = \sum\_{i} d\_{jk}^i \cdot b\_i$$ *Proposition*: $d\_{jk}^i = \delta \cdot \overline{c\_{jk}^i}$ *Proof*: by computing the inner product $(b\_i,b\_j∗b\_k)$ in two different manners: the first using the constant structure of $b\_j∗b\_k$ and the second by computing $tr(b\_i^\*.(b\_j∗b\_k))$ diagrammatically. We use the irreducibility, the planar algebraic formulation of the comultiplucation by splitting, and the orthonormality of the basis $(b\_i)\_i$. $\square$ *Corollary*: $b\_j \* b\_k = \delta \sum\_{i} \overline{c\_{jk}^i} \cdot b\_i $ $\mathbb{A} = \bigoplus\_{i \in I} End(H\_i)$ with $(H\_i)\_i$ the sequence of irreducible complex representations of $\mathbb{A}$. If $H\_i \otimes H\_j = \bigoplus\_{ij} M\_{ij}^k \otimes H\_k$ (exactly the fusion rules for the depth $2$ case) and $n\_{ij}^k = \dim(M\_{ij}^k)$ then it's proved [here](https://math.stackexchange.com/a/494385/84284) that the inclusion matrix of $(\Delta(\mathbb{A}) \subset \mathbb{A} \otimes \mathbb{A})$ is $\Lambda = (\Lambda\_{(ij)}^{k})$ with $\Lambda\_{(ij)}^{k} = n\_{ij}^{k}$. > > So $p\_i \* p\_j \sim \sum\_k n\_{ij}^{k}.p\_k$, and my guess for the depth > $2$ case follows ( $\sim$ means "same support"). > > > --- **General case:** *Remark*: An irreducible depth $d$ finite index subfactor $(N \subset M)$ is an intermediate of the depth 2 subfactor $(N \subset M\_{d-2})$, which is non nec. irreducible (see [here](http://arxiv.org/abs/math/0006057v2) prop. 9.1.1 p 37). So the result *could* follow by generalizing the argument on Kac algebras above to an argument on *weak* Kac algebras. The coproduct is not a (central) "truncated fusion", because the coproduct does not keep the centralness. The dual $(S\_2 \subset S\_4)$ subfactor planar algebra is a counter-example (see [here](https://mathoverflow.net/a/191556/34538)). Anyway, the coproduct could be a *non-central* truncation of the fusion.
213,940
Previous owner decided to recess the hinge plate below the previous (larger) hinge plate. While the door closes, you have to pull it closes otherwise it will "spring" back open. The door makes contact with the jamb (on the hinge side), which I believe is caused by this. I am going to go buy some new hinges, but how to I make the jamb look decent, while still having it functional to put on new hinges? I read [this post](https://diy.stackexchange.com/questions/29303/how-to-adjust-when-hinge-mortises-are-cut-too-deep) for some inspiration. I was thinking of filling the entire recessed portion with body filler and starting from scratch. Is there a simpler method I can do? I read about cardboard etc, but I imagine that looks terrible and is not a long term solution. [![enter image description here](https://i.stack.imgur.com/26MZo.png)](https://i.stack.imgur.com/26MZo.png)
2021/01/15
[ "https://diy.stackexchange.com/questions/213940", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/64979/" ]
Shims. Go to the local home center and get some of the (*free?*) laminate counter top samples in the kitchen cabinet section, they are about 3x5 inches. I then cut them to the same size as the hinge plate. Remove the hinge, place it on the sample and trace around it, it does not need to perfect but it should not be bigger then the hinge. I cut them with tin snips. They are about 1/6 inch thick so sometimes you need to stack several of them behind the hinge. Place enough of them behind the hinge to bring the hinge flush with the jam, hold the hinge over them and pre-drill, or mark them so you can pre-drill them, then install the hinge over them. An alternative is to use a [Dutchman](https://en.wikipedia.org/wiki/Dutchman_(repair)). There are many [YouTube videos](https://www.youtube.com/results?search_query=how%20to%20make%20a%20dutchman%20patch) on this. I like Tom Silva's tutorial from Ask This Old House.
Cut a plug of wood to the height and width of the two mortises. Use pine and cut the depth so the plug stands slightly proud when set in the mortises. You want the mortises to be a single mortise so chisel out any partition. Cut the mortise to fit the plug. With a utility knife define the shape of the plug on the jamb. Cut away any parts that obstruct it's placement. Wood glue the plug in place. Once dry plane down the plug to be flush with the jamb. Trace the new hinges outline on the jamb and cut the new mortise.
1,876,606
I can do SELECT TOP (200) ... but why not BOTTOM (200)? Well not to get into philosophy what I mean is, how can I do the equivalent of TOP (200) but in reverse (from the bottom, like you'd expect BOTTOM to do...)?
2009/12/09
[ "https://Stackoverflow.com/questions/1876606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
Logically, ``` BOTTOM (x) is all the records except TOP (n - x), where n is the count; x <= n ``` E.g. Select Bottom 1000 from Employee: In T-SQL, ``` DECLARE @bottom int, @count int SET @bottom = 1000 SET @count = (select COUNT(*) from Employee) select * from Employee emp where emp.EmployeeID not in ( SELECT TOP (@count-@bottom) Employee.EmployeeID FROM Employee ) ```
All you need to do is reverse your `ORDER BY`. Add or remove `DESC` to it.
895,789
* CentOS 7 I have a simple Nginx proxy Docker container listening on port 80. Here is the Dockerfile: ``` FROM centos:7 MAINTAINER Brian Ogden # Not currently being used but may come in handy ARG ENVIRONMENT RUN yum -y update && \ yum clean all && \ yum -y install http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm \ yum -y makecache && \ yum -y install nginx-1.12.0 wget # Cleanup some default NGINX configuration files we don’t need RUN rm -f /etc/nginx/conf.d/default.conf COPY /conf/proxy.conf /etc/nginx/conf.d/proxy.conf COPY /conf/nginx.conf /etc/nginx/nginx.conf CMD ["nginx"] ``` And for this Nginx Proxy here is my nginx.conf: ``` daemon off; user nginx; worker_processes 2; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; use epoll; accept_mutex off; } http { include /etc/nginx/mime.types; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; client_max_body_size 300m; client_body_buffer_size 300k; large_client_header_buffers 8 64k; gzip on; gzip_http_version 1.0; gzip_comp_level 6; gzip_min_length 0; gzip_buffers 16 8k; gzip_proxied any; gzip_types text/plain text/css text/xml text/javascript application/xml application/xml+rss application/javascript application/json; gzip_disable "MSIE [1-6]\."; gzip_vary on; include /etc/nginx/conf.d/*.conf; } ``` And here is my proxy configuration: ``` upstream accountstaging { server 127.0.0.1:5023; } server { listen 80; server_name account.staging.mysite.com; location / { proxy_pass http://accountstaging; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } ``` My proxy configuration is listening on port 80 and trying to request requests from account.staging.mysite.com to a Docker container running on the same Docker host as the Ngnix proxy listening on port 5023. Here is my docker-compose.yml for my Nginx proxy: ``` version: '3' services: reverseproxy: build: context: ./ dockerfile: docker/Dockerfile image: tsl.devops.reverseproxy.image container_name: tsl.devops.reverseproxy.container ports: - "80:80" ``` Here is the docker-compose.yml for this Docker container listening on port 5023: version: '3' ``` services: apistaging: build: context: ./ dockerfile: docker/staging/Dockerfile image: tsl.api.example.image container_name: tsl.api.example.container ports: - "127.0.0.1:5023:80" ``` The Dockerfile does not really matter much to my question but here it is anyways: ``` FROM tsl.devops.dotnetcore.base.image:2 MAINTAINER Brian Ogden WORKDIR /app COPY ./src/Tsl.Example/bin/Release/netcoreapp2.0/publish . ENTRYPOINT ["dotnet", "Tsl.Example.dll"] ``` I followed [this example](https://www.digitalocean.com/community/questions/how-to-bind-multiple-domains-ports-80-and-443-to-docker-contained-applications) to setup my proxy. I have previously asked a related question on Stackexchange forums [here](https://serverfault.com/questions/895273/adding-reverse-proxy-listeners-nginx-stops-all-traffic-to-port-80) and [here](https://devops.stackexchange.com/questions/3253/nginx-reverse-proxy-setup-issues-with-docker-containers). This question I have refined and simplified the scenario to a simply proxy forwarding a request to one Docker container listening on port 5023. Since my base image is CentOS I have followed [this here](https://stackoverflow.com/a/46486315/1258525) to make sure SELinux is allowing forward to port 5023
2018/02/05
[ "https://serverfault.com/questions/895789", "https://serverfault.com", "https://serverfault.com/users/176115/" ]
Thanks to this [question and answer here](https://stackoverflow.com/questions/46264954/connection-refused-while-connecting-to-upstream-when-using-nginx-as-reverse-prox), I was able realize that I had two issues going on: 1. the containers have different default Docker networks because I am using two different docker-compose.yml files, I had envisioned my Ngnix proxy working independently from any of my API containers entirely, including the docker-compose, more on that issue below 2. the second issue is simply when I tried to proxy to 127.0.0.1:5023 that is localhost inside the Ngnix container, not the network outside of the Nginx proxy container So the different default networks being created by docker-compose for my Nginx proxy docker container and my api docker container are because I amusing two different docker-compose.yml files. This is because I have Jenkins builds for many API microservices so the have independant docker-compose files and I needed a Nginx proxy to forward requests on port 80 to each microservice. To test this out, created a docker-compose.yml for both containers, the API and the Nginx proxy: ``` version: '3' services: reverseproxy: build: context: ./ dockerfile: docker/nginxproxy/docker/Dockerfile image: tsl.devops.reverseproxy.image container_name: tsl.devops.reverseproxy.container ports: - "80:80" apistaging: build: context: ./ dockerfile: docker/staging/Dockerfile image: tsl.api.example.image container_name: tsl.api.example.container ports: - "5023:5023" environment: ASPNETCORE_URLS: http://+:5023 ``` Yes there was still an issue, the proxy pass to http//:127.0.0.1:5023, that forward remains in the Nginx Docker container and never finds the API running on the Docker host, I simply needed to use the docker-compose.yml service name to get to it: ``` upstream accountstaging { server apistaging:5023; } server { listen 80; server_name account.staging.mysite.com; location / { proxy_pass http://accountstaging; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } ```
I had this problem but my issue was that I had two folders that both had docker-compose.yml files which both had a service named 'web'. I changed the name of one of the services. **The full picture to help someone struggling with docker networks as much I was (am?):** Docker-compose projects often use nginx as reverse-proxy to route http traffic to the other docker services. nginx was a service in my `projectfolder/docker-compose.yml` which was connected to two docker networks. One was the default network created when I used docker-compose up on `projectfolder/docker-compose.yml` (It is named `projectfolder_default` and services connect to it by default UNLESS you have a `networks` property for your service with another network, then make sure you add `- default` to the list). When I ran `docker network ls` I saw `projectfolder_default` in the list and when I ran `docker network inspect projectfolder_default` I saw the nginx container, so everything was good. The other was a network called `my_custom_network` that I set up myself. I had a startup script that created it if it did not exist using <https://stackoverflow.com/a/53052379/13815107> I needed it in order to talk to the `web` service in `otherproject/docker-compose.yml`. I had correctly added `my_custom_network` to: * `nginx` service's networks list of `projectfolder/docker-compose.yml` * bottom of `projectfolder/docker-compose.yml` * `web` service's networks in `otherproject/docker-compose.yml` * bottom of `otherproject/docker-compose.yml` The network showed up and had the right containers using `docker network ls` and `docker network inspect my_custom_network` However, I assumed that calling http://web would map to the docker service `web.projectfolder_default`. I was mistaken. I opened shell on the nginx container (`docker exec -it nginx sh`). When I used `ping web` (may need to `apt-get update`, `apt-get install iputils-ping`) it succeeded, but it printed a url with `my_custom_network` which is how I figured out the mistake. projectfolder/docker-compose.yml ``` services: # http://web did NOT map to this service!! Use http://web.main_default or change the names web: ... nginx: ... links: - web networks: - default - my_custom_network ... networks: - my_custom_network external: true ``` otherproject/docker-compose.yml ``` services: # http://web connected to this service instead. You could use http://web.my_custom_network to call it out instead web: ... networks: - default - my_custom_network ... networks: - my_custom_network external: true ``` projectfolder/.../nginx/server.conf.template (next to Dockerfile) ... ``` server { ... location /auth { internal; # This routed to wrong 'web' proxy_pass http://web:9001; proxy_pass_request_body off; proxy_set_header Content-Length ""; } location / { alias /data/dist/; } location /robots.txt { alias /robots.txt; } # Project Folder backend location ~ ^/(api|login|logout)/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 300s; proxy_read_timeout 300s; # This routed to wrong 'web' proxy_pass http://web:9001; } # Other project UI location /other-project { alias /data/other-project-client/dist/; } # Other project Django server location ~ ^/other-project/(rest)/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 300s; proxy_read_timeout 300s; # This should work proxy_pass http://web.my_custom_network:8000; } } ```
3,147,905
I would like to convert a Java Object to a String containing the marshaled XML data. One of the ways I could find was to first marshal to a File and then read the file using BufferedReader to convert into a String. I feel this may not be the most efficient way, because the IO operations are performed twice (Once during marshaling and the second time during the conversion of file content into String) Could anyone please suggest any better approach?
2010/06/30
[ "https://Stackoverflow.com/questions/3147905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/333125/" ]
Pass a StringWriter object as argument to [marshal method](http://java.sun.com/webservices/docs/1.6/api/javax/xml/bind/Marshaller.html#marshal%28java.lang.Object,%20java.io.Writer%29) of Marshaller
Here is the simple code by [AbacusUtil](https://github.com/landawn/AbacusUtil) ``` Account account = N.fill(Account.class); String xml = N.toXML(account); N.println(xml); // <account><id>6264304841028291043</id><gui>33acdcbe-fd5b-49</gui><emailAddress>19c1400a-97ae-43</emailAddress><firstName>67922557-8bb4-47</firstName><middleName>7ef242c9-8ddf-48</middleName><lastName>1ec6c731-a3fd-42</lastName><birthDate>1480444055841</birthDate><status>1444930636</status><lastUpdateTime>1480444055841</lastUpdateTime><createTime>1480444055841</createTime></account> Account account2 = N.fromXML(Account.class, xml); assertEquals(account, account2); ``` Declaration: I'm the developer of AbacusUtil.
20,674,662
In eclipse, if you change a variable name, eclipse will automatically change this variable's name in whole project. Can vim do that too?
2013/12/19
[ "https://Stackoverflow.com/questions/20674662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2038901/" ]
Sort of. Because it is not an IDE and thus doesn't understand *anything* about your code, Vim only sees text where you see a variable name. It can't infer anything from the scope or whatever. Without the use of some external program, renaming a variable in Vim is usually done with a buffer-wide or project-wide search/replace. Since you didn't tell us what language you are working with we can't tell you if there is a language-specific solution for your needs.
try this plugin -> [Clighter](https://github.com/bbchung/clighter), for c-family rename-refactoring. It's based on clang, but there are limitations. Still in development
5,075,893
I want to disable a screen saver to another user. How it can be done? I have administrative privileges. I have an application that can't be interrupted by the screen saver.
2011/02/22
[ "https://Stackoverflow.com/questions/5075893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/627977/" ]
If you're writing the application yourself, look into calling the unmanaged API SetThreadExecutionState ([PInvoke reference](http://www.pinvoke.net/default.aspx/kernel32/SetThreadExecutionState)). Copying from my answer to [how do i prevent screen-savers and sleeps during my program execution?](https://stackoverflow.com/questions/3665332/how-do-i-prevent-screen-savers-and-sleeps-during-my-program-execution): Don't mess with the screensaver settings, use [SetThreadExecutionState](http://msdn.microsoft.com/en-us/library/aa373208(VS.85).aspx). This is the API for informing windows on the fact that your application is active: > > Enables an application to inform the > system that it is in use, thereby > preventing the system from entering > sleep or turning off the display while > the application is running. > > > , and > > Multimedia applications, such as video > players and presentation applications, > must use ES\_DISPLAY\_REQUIRED when they > display video for long periods of time > without user input > > > If you *don't* have control over the application, but the screen saver kicking in causes problems, then push this information back to the developers. Disabling the screensaver is *almost always* the wrong solution to the problem, since it affects the users whole experience, not just when the application is running.
[Controlling The Screen Saver With C#](http://www.codeproject.com/KB/cs/ScreenSaverControl.aspx) ``` public static class ScreenSaver { // Signatures for unmanaged calls [DllImport( "user32.dll", CharSet = CharSet.Auto )] private static extern bool SystemParametersInfo( int uAction, int uParam, ref int lpvParam, int flags ); [DllImport( "user32.dll", CharSet = CharSet.Auto )] private static extern bool SystemParametersInfo( int uAction, int uParam, ref bool lpvParam, int flags ); [DllImport( "user32.dll", CharSet = CharSet.Auto )] private static extern int PostMessage( IntPtr hWnd, int wMsg, int wParam, int lParam ); [DllImport( "user32.dll", CharSet = CharSet.Auto )] private static extern IntPtr OpenDesktop( string hDesktop, int Flags, bool Inherit, uint DesiredAccess ); [DllImport( "user32.dll", CharSet = CharSet.Auto )] private static extern bool CloseDesktop( IntPtr hDesktop ); [DllImport( "user32.dll", CharSet = CharSet.Auto )] private static extern bool EnumDesktopWindows( IntPtr hDesktop, EnumDesktopWindowsProc callback, IntPtr lParam ); [DllImport( "user32.dll", CharSet = CharSet.Auto )] private static extern bool IsWindowVisible( IntPtr hWnd ); [DllImport( "user32.dll", CharSet = CharSet.Auto )] public static extern IntPtr GetForegroundWindow( ); // Callbacks private delegate bool EnumDesktopWindowsProc( IntPtr hDesktop, IntPtr lParam ); // Constants private const int SPI_GETSCREENSAVERACTIVE = 16; private const int SPI_SETSCREENSAVERACTIVE = 17; private const int SPI_GETSCREENSAVERTIMEOUT = 14; private const int SPI_SETSCREENSAVERTIMEOUT = 15; private const int SPI_GETSCREENSAVERRUNNING = 114; private const int SPIF_SENDWININICHANGE = 2; private const uint DESKTOP_WRITEOBJECTS = 0x0080; private const uint DESKTOP_READOBJECTS = 0x0001; private const int WM_CLOSE = 16; // Returns TRUE if the screen saver is active // (enabled, but not necessarily running). public static bool GetScreenSaverActive( ) { bool isActive = false; SystemParametersInfo( SPI_GETSCREENSAVERACTIVE, 0, ref isActive, 0 ); return isActive; } // Pass in TRUE(1) to activate or FALSE(0) to deactivate // the screen saver. public static void SetScreenSaverActive( int Active ) { int nullVar = 0; SystemParametersInfo( SPI_SETSCREENSAVERACTIVE, Active, ref nullVar, SPIF_SENDWININICHANGE ); } // Returns the screen saver timeout setting, in seconds public static Int32 GetScreenSaverTimeout( ) { Int32 value = 0; SystemParametersInfo( SPI_GETSCREENSAVERTIMEOUT, 0, ref value, 0 ); return value; } // Pass in the number of seconds to set the screen saver // timeout value. public static void SetScreenSaverTimeout( Int32 Value ) { int nullVar = 0; SystemParametersInfo( SPI_SETSCREENSAVERTIMEOUT, Value, ref nullVar, SPIF_SENDWININICHANGE ); } // Returns TRUE if the screen saver is actually running public static bool GetScreenSaverRunning( ) { bool isRunning = false; SystemParametersInfo( SPI_GETSCREENSAVERRUNNING, 0, ref isRunning, 0 ); return isRunning; } // From Microsoft's Knowledge Base article #140723: // http://support.microsoft.com/kb/140723 // "How to force a screen saver to close once started // in Windows NT, Windows 2000, and Windows Server 2003" public static void KillScreenSaver( ) { IntPtr hDesktop = OpenDesktop( "Screen-saver", 0, false,DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS); if( hDesktop != IntPtr.Zero ) { EnumDesktopWindows( hDesktop, new EnumDesktopWindowsProc( KillScreenSaverFunc ), IntPtr.Zero ); CloseDesktop( hDesktop ); } else { PostMessage( GetForegroundWindow( ), WM_CLOSE, 0, 0 ); } } private static bool KillScreenSaverFunc( IntPtr hWnd, IntPtr lParam ) { if( IsWindowVisible( hWnd ) ) PostMessage( hWnd, WM_CLOSE, 0, 0 ); return true; } } ``` **KillScreenSaver( )** ``` private void KillTimer_Elapsed( object state ) { // Toggle kill state to indicate activity killState = ( killState == 1 ) ? 0 : 1; this.SetText( killState.ToString( ) ); // Stop the screen saver if it's active and running, // otherwise reset the screen saver timer. // Apparently it's possible for GetScreenSaverRunning() // to return TRUE before the screen saver has time to // actually become the foreground application. So... // Make sure we're not the foreground window to avoid // killing ourself. if( ScreenSaver.GetScreenSaverActive( ) ) { if( ScreenSaver.GetScreenSaverRunning( ) ) { if( ScreenSaver.GetForegroundWindow() != hThisWnd) ScreenSaver.KillScreenSaver( ); } else { // Reset the screen saver timer, so the screen // saver doesn't turn on until after a full // timeout period. If killPeriod is less than // ssTimeout the screen saver should never // activate. ScreenSaver.SetScreenSaverActive( TRUE ); } } } ```
55,695,866
I'm trying to set the logo to the left and the rest of the list to the right. I tried removing it from the and adding it on it's own. it ends up behind the text even with a z-index= 2. I tried a and floated it to the left i found in another thread. still didn't work ```css * { font-family: arial, sans-serif; box-sizing: border-box;} html, body { margin: 0; padding: 0; } a { text-decoration: none; color: black; } .nav { position: fixed; top: 0; left: 0; background-color: rgba(255,255,255,.8); border-radius: 0px; border: none; width: 100%; margin: 0; padding: 25px 0; flex-direction: row; display: flex; align-items: center; justify-content: flex-end; } .item { color: black; font-weight: bold; text-transform: uppercase; font-size: 15px; margin-left: 30px; margin-right: 30px; } ``` ```html <nav> <ul class="nav"> <li class="item"> <a href="index.html"> <img src="../Images/Navigation/Intak Logo 25px High.png" alt="Home" align="left"/> </a> </li> <li class="item has-children" style="color:#4D4D4D;">Printing </li> <li class="item has-children"><a href="Graphic Design.html">Graphic Design</a> </li> <li class="item has-children">Chinese Calendars <ul class="submenu"> <li><a href="Calendars/Cane Wallscroll Calendars.html">Cane Wallscroll Calendars</a></li> <li><a href="Calendars/Wall Calendars.html">Wall Calendars</a></li> <li><a href="Calendars/Mini Calendars.html">Mini Calendars</a></li> <li><a href="Calendars/Desk Calendars.html">Desk Calendars</a></li> <li><a href="Calendars/Special Desk Calendars.html">Special Desk Calendars</a></li> <li><a href="Calendars/Red Packet.html">Red Packet</a></li> <li><a href="Calendars/More.html">More Calendars</a></li> </ul> </li> <li class="item"><a href="FAQS.html">FAQS</a></li> <li class="item"><a href="Contact Us.html">Contact Us</a></li> </ul> </nav> ``` Need to some how split the logo from the nav and have it floated or positioned to the left
2019/04/15
[ "https://Stackoverflow.com/questions/55695866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9255004/" ]
I found a solution, also thanks to the one who took the trouble to read the question Code: ``` $data = 'foobar'; return datatables() ->of($query) ->addColumn('Action', function() use ($data){ return view('Actions.something', compact('data')); }) ->rawColumns(['Action']) ->toJson(); ``` View (something.blade.php): ``` @if (isset($data)) @if($data == 'foobar') <span>true</span> @else <span>false</span> @endif @endif ```
This question is the only one that shows up, when I try to google this problem. I can see that @lewis4u's problem isn't solved yet. If anyone else experience this, the following code snippet will allow you to access the model variables. ``` return datatables() ->of($query) ->addColumn('Action', function($row){ return view('Actions.something', compact('row')); }) ->rawColumns(['Action']) ->toJson(); ``` The key is passing the `$row` parameter to the function. Then you can access `$row` in your `something.blade.php` view.
31,850,824
My `angular` application is constantly changing these days because our team runs rapid updates right now. Because of cache our clients does not always have the newest version of our code. So is there a way in `angular` to force the browser to clear cache?
2015/08/06
[ "https://Stackoverflow.com/questions/31850824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1647457/" ]
You can use a very simple solution that consist in append a hash to your scripts files. Each time your App is deployed you serve your files with a different hash automatically via a gulp/grunt task. As an example you can use [gulp-rev](https://github.com/sindresorhus/gulp-rev). I use this technique in all my projects and works just fine, this automatized in your build/deploy process can be a solution for all your projects. Yeoman generator for AngularJS [generator-gulp-angular](https://github.com/Swiip/generator-gulp-angular) *(this was my generator of choice)* use this solution to ensure that the browser load the new optimazed file and not the old one in cache. Please create a demo project and play with it and you will see it in action.
If you are looking for a really simple solution and your IDE is visual studio under C# you can get app build Id and concatenate on your js file url. First you should activate incrementation for minor versions like that: ![enter image description here](https://i.stack.imgur.com/VGeNC.png) Go to your project properties, under Application on the new window, click Assembly Information and add a "\*" to Assembly version (last digit as described on image above). After that, add a new property to your codebehind aspx, or web service or webapi, etc... for this piece of code I'm using aspx: ``` public string GetVersionApp => System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); ``` Then, call the property through your html and concatenate the value as param on your url file, like this: ``` <script type="text/javascript" src="App/RequestsList/directives/comment-directive.js?<%=GetVersionApp%>"></script> ``` With this solution, your files only be reloaded if a new build occurs.
8,321,230
I'm trying to get a simple AS3 app up and running, and for some reason, I cannot get a sprite to show. At this point, all I want to do is get a red sprite to fill the stage. ``` public class Main extends Sprite { public function Main():void { super(); stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; var square:Sprite = new Sprite(); square.width = stage.stageWidth; square.height = stage.stageHeight; square.x = square.width / 2; square.y = square.height / 2; square.graphics.clear(); square.graphics.lineStyle(3, 0xFF0000); square.graphics.beginFill(0xFF0000); square.graphics.drawRect(0, 0, width, height); square.graphics.endFill(); square.addEventListener(Event.ADDED_TO_STAGE, addedToStage); square.addEventListener(MouseEvent.CLICK, onClick); addChild(square); } private function addedToStage(e:Event):void { trace("Added sprite to stage"); } private function onClick(e:Event):void { trace("Got click on sprite"); } } ``` The trace shows that the sprite was added to the stage, but nothing is displayed, and if I click on it, the onClick function never gets called. If I use a TextField instead of a Sprite, it displays just fine. There must be something weird about Sprites. What am I doing wrong? Thanks!
2011/11/30
[ "https://Stackoverflow.com/questions/8321230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119283/" ]
You need to pass `RequestContext` in render\_to\_response for `csrf_token` For this : (**views.py**) ``` from django.template import RequestContext ... return render_to_response('fileupload/upload.html', {'form': c['UploadFileForm']}, RequestContext(request)) # Added RequestContext ``` This passes the token for csrf to the template.
For my case, I use AJAX to post data to my views function, then the same error happens, so the easy method to solve it is to change the data from ``` data:{ 'k':'v' } ``` To ``` data:{ 'k':'v' ,addcsrfmiddlewaretoken:'{{ csrf_token }}',} ``` because we manually add a csrf-token, so it is not missing or incorrect.
1,146,785
Consider the series $$\lim \limits\_{n \to \infty}\sum\_{i=1}^n \frac{n}{n^2+i}$$ Considering individual terms, we get $$\lim \limits\_{n \to \infty}\frac{n}{n^2+i}=\lim \limits\_{n \to \infty}\frac{1}{n+\frac{i}{n}}=0.$$ Hence the sum would be $0$. However, considering an alternative approach, we observe that $\frac{n}{n^2+n}<\frac{n}{n^2+i}<\frac{n}{n^2+1}$. Therefore $$\sum\_{i=1}^n \frac{n}{n^2+n}<\sum\_{i=1}^n \frac{n}{n^2+i}<\sum\_{i=1}^n \frac{n}{n^2+1} \implies \frac{n^2}{n^2+n}<\sum\_{i=1}^n \frac{n}{n^2+i}<\frac{n^2}{n^2+1}$$ Taking limit $\lim \limits\_{n \to \infty}$ on the three expressions, we find that $\lim \limits\_{n \to \infty}\frac{n^2}{n^2+n}=\lim \limits\_{n \to \infty}\frac{n^2}{n^2+1}=1.$ Therefore by the sandwich theorem, $\lim \limits\_{n \to \infty}\sum\_{i=1}^n \frac{n}{n^2+i}=1$ Since there exists a unique limit, there must be only one solution. Which approach is the correct one? There was one suggested reason that each of the individual limits that was calculated in the 1st approach had to be summed up to infinite terms. Since each of the limits were infintesimally small, we cannot predict the way they will behave when summed to infinity and therefore the approach is incorrect. However, my counter was that the limits are exact and are not infinitesimals. Therefore 0 can be summed up infinitely many times and the answer will still be zero. Is this reasoning correct/wrong? What must be the answer to the problem?
2015/02/13
[ "https://math.stackexchange.com/questions/1146785", "https://math.stackexchange.com", "https://math.stackexchange.com/users/117913/" ]
The second solution you have is correct (although in the last step, the expression on the right side of the inequality should just be $n^2/(n^2 + 1)$). The first method is incorrect; since the number of terms of the sum varies with $n$, you cannot simply use the addition rule for limits.
Just an addition: you can get some nice asymptotics out of this sum (set $t=n^2$): $$ n \sum\_{k=0}^{n} \frac{1}{t+k} = n \bigg(\frac{1}{t} + \ldots + \frac{1}{t+n} \bigg) \\ =n \bigg(1 + \frac{1}{2} + \ldots \frac{1}{t+n} -(1+\frac{1}{2} +\ldots \frac{1}{t-1} \bigg)\\ \sim n (\log (t+n) - \log t) = n \log (1+\frac{1}{n}) $$ which, for large $n$ converges to 1.