text
stringlengths
64
89.7k
meta
dict
Q: Scroll to div with a sticky navigation bar The page has a sticky navbar that stay on screen all the time. When I am scrolling to the next section(div) of the page, it will scroll so the div starts at the top of the screen , so the navigation bar cover it a little bit. How to minus from y scrolling position the navigation bar height ? $('html, body').animate({ scrollTop: $("#section2").offset().top // minus the nav height }, 1000); Also - how to make this navbar height available to my javascript (from the css) using a good practice ? (global var?) A: You can select your navigation bar (here I gave my navigation bar the id nav) and get its height by doing: $("#nav").height(); You can then subtract this from the scrollTop property. However, do note, if your nav bar has padding and/or a margin, to correctly calculate the height you will need to use a different method from .height. See this answer if you're having difficulties. See working example below: $('html, body').animate({ scrollTop: $("#section2").offset().top - $("#nav").height() // minus the nav height }, 1000); body { margin: 0; } nav { background: black; height: 10vh; width: 100%; position: fixed; } section { height: 100vh; } #section1 { background: red; } #section2 { background: lime; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav id="nav"></nav> <section id="section1">Top</section> <section id="section2">Top</section>
{ "pile_set_name": "StackExchange" }
Q: How to sync 2 async fetches in Parse? So I have a PFobject A that contains 2 other PFobjects B C as value. When I construct my local object a, I would need both of the objects B C. So first I fetch a by doing a query: let query = PFQuery(className: "A") query.getObjectInBackgroundWithId("1", block: { (a, error) -> Void in Then I get b and c from a var b = a!["B"] as! PFObject var c = a!["C"] as! PFObject Then I will need to fetch b and c objects individually b.fetchInBackgroundWithBlock({ (fetchedB, error) -> Void in The problem is, the fetching methods is async and if I put them in the same thread I won't be guaranteed to have both of them fetched in the end. One solution is to have the fetching nested in call-backs so that once one fetch is done it will start the other. b.fetchInBackgroundWithBlock({ (fetchedB, error) -> Void in c.fetchInBackgroundWithBlock({ (fetchedC, error) -> Void in println(fetchedB) println(fetchedC) // Now they have values var myA = A(validB: fetchedB, validC: fetchedC) // Construction can continue But if more objects are needed, it will become nesting in nesting. Like: b.fetchInBackgroundWithBlock({ (fetchedB, error) -> Void in c.fetchInBackgroundWithBlock({ (fetchedC, error) -> Void in d.fetchInBackgroundWithBlock({ (fetchedD, error) -> Void in e.fetchInBackgroundWithBlock({ (fetchedE, error) -> Void in However b,c,d and e are not dependent on each other - it should be perfect to fetch them on separate threads! So is there a way to make the call-backs wait for each other at some point in the main thread to make sure all objects are fetched? Thanks! A: Use the includeKey() method on the first PFQuery to tell parse to fetch both class B and C when performing the query. Relevant documentation for includeKey
{ "pile_set_name": "StackExchange" }
Q: Mongoose avg function by request field I want to return the average of a Number field by another field(the document ID field): Comments.aggregate([ {$group: { _id: ($nid: req.adID), // here is the field I want to set to req.adID adAvg:{$avg:"$stars"} } } ], function(err, resulat){ if(err) { res.send(String(err)); } res.send(resulat); } ) The ID field is in the request object, req.adID, I didnt find an example for grouping by a query (_id : 'req.adID'). My schema looks like: var CommentSchema = new Schema( { _id: Schema.Types.ObjectId, //scheme nid:Number, // ad ID posted: Date, // Date uid: Number, // user ID title: String, //String text: String, // String stars: Number //String } ); Also if someone can write the return data for this query it will be great! A: From your follow-up comments on the question, looks like your aggregation needs the $match pipeline to query the documents that match the req.adID on the nid field, your $group pipeline's _id field should have the $nid field expression so that it becomes your distinct group by key. The following pipeline should yield the needed result: var pipeline = [ { "$match": { "nid": req.adID } }, { "$group": { "_id": "$nid", "adAvg": { "$avg": "$stars" } } } ] Comments.aggregate(pipeline, function(err, result){ if(err) { res.send(String(err)); } res.send(result); })
{ "pile_set_name": "StackExchange" }
Q: Git: How to find commits with given Change-Id? Gerrit automatically adds a Change-Id: I.... line in commit message for every new commits. When a commit is cherry-picked into multiple branches this line is preserved in its message. Is there any way to: find all commits with given Change-Id find the commit on a specific branch with given Change-Id specify the commit with given Change-Id (on a specific branch) as revision parameter(e.g. git cherry-pick {[dev-branch::]Change-Id: Ixxxx}..master) A: EDIT: After I posted this answer, @lz96 suggested this: git --no-pager log --format=format:%H -1 --grep "Change-Id: $1" It's definitely the cleanest way! Here's my original answer: I can't think of a clean way of how to do it in one step, so here's two: git log --grep "Change-Id: <id>" This will show you all commits that have this Change-Id parameter. Step 1b: Pray it is only one. Step 2: git cherry-pick <sha>. Here's my ugly one-stepper: git cherry-pick $(git log --grep "Change-Id: <id>" | head -n 1 | cut -d ' ' -f 2) You could probably make this into a function to hide all that complexity away: function changepick() { git cherry-pick $(git log --grep "Change-Id: $1" | head -n 1 | cut -d ' ' -f 2) } That also gives you the benefit of not having to insert the Change-Id halfway along a line.
{ "pile_set_name": "StackExchange" }
Q: Large file support not working in C programming I'm trying to compile a shared object (that is eventually used in Python with ctypes). The command-line used to build the object is: gcc -Wall -O3 -shared -Wl,-soname,borg_stream -lm -m128bit-long-double -fPIC \ -D_FILE_OFFSET_BITS=64 -o borg_stream.so data_stream.c data_types.c \ file_operations.c float_half.c channels.c statistics.c index_stream.c helpers.c The library builds properly on a 32-bit OS and it does what it needs to for small files. However, it fails the unit tests for files larger than 4GB. In addition, it sets errno to EOVERFLOW when doing an fseek/ftell. However, if I printf sizeof(off_t), it returns 8. If I remove -D_FILE_OFFSET_BITS=64, then it prints 4. So it seems like -D_FILE_OFFSET_BITS is properly doing its job. Why does large file support still not work? What am I doing wrong? A: Add the option -D_LARGE_FILE_SOURCE=1 to gcc compilation. fseek64() is a C function. To make it available you'll have to define _FILE_OFFSET_BITS=64 before including the system headers. That will more or less define fseek to behave as actually fseek64. Or you could do it in the compiler arguments e.g. gcc -D_FILE_OFFSET_BITS=64, that you are already doing. http://www.suse.de/~aj/linux_lfs.html has a good information for large file support on linux: Compile your programs with gcc -D_FILE_OFFSET_BITS=64. This forces all file access calls to use the 64 bit variants. Several types change also, e.g. off_t becomes off64_t. It's therefore important to always use the correct types and to not use e.g. int instead of off_t in your C code. For portability with other platforms you should use getconf LFS_CFLAGS which will return -D_FILE_OFFSET_BITS=64 on Linux platforms but might return something else on for e.g. on Solaris. For linking, you should use the link flags that are reported via getconf LFS_LDFLAGS. On Linux systems, you do not need special link flags. Define _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE. With these defines you can use the LFS functions like open64 directly. Use the O_LARGEFILE flag with open to operate on large files. Hope this helps. A: Use fseeko and ftello. Not fseek and ftell. And certainly not any function with 64 in its name.
{ "pile_set_name": "StackExchange" }
Q: Effect of number of data segments in Periodogram-based PSD In Welch or Bartlett method, original signal is divided into L segments, of D overlapping (D=0 in Bartlett method). Then FFT is done for each segment, and the result is the average of all segments' FFTs. Averaging reduces the variance. But apart from this effect, is there anything else to take into account when choosing the number of segments for a given signal? A: If you increase the number of segments for a fixed total signal length, each segment becomes shorter. This means that you'll have a trade-off between the estimate's variance and the frequency resolution. Averaging many segments will reduce the variance but by using shorter windows, the ability to resolve closely spaced narrow band components is decreased. Shorter windows also decrease the peak amplitudes of any narrow band component. Shorter windows basically average out any details in the spectrum.
{ "pile_set_name": "StackExchange" }
Q: NSRangeException: Call Stack Not Showing Line Number I am getting the following index out of bounds error: *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' *** First throw call stack: (0x2263052 0x24c7d0a 0x224fdb8 0x2f4a7 0x2264ec9 0x81e299 0x81e306 0x75aa30 0x75ac56 0x741384 0x734aa9 0x39a9fa9 0x22371c5 0x219c022 0x219a90a 0x2199db4 0x2199ccb 0x39a8879 0x39a893e 0x732a9b 0x1e5b 0x1dc5 0x1) I know exactly what the error means, but I find these errors very difficult to fix because for some reason the call stack isn't telling me the line of code where the array was being called. Here is the call stack from thread 1: #0 0x9706d9c6 in __pthread_kill () #1 0x93e2cf78 in pthread_kill () #2 0x93e1dbdd in abort () #3 0x02859e78 in dyld_stub__Unwind_DeleteException () #4 0x0285789e in default_terminate() () #5 0x024c7f4b in _objc_terminate () #6 0x028578de in safe_handler_caller(void (*)()) () #7 0x02857946 in __cxa_bad_typeid () #8 0x02858b3e in __cxa_current_exception_type () #9 0x024c7e49 in objc_exception_rethrow () #10 0x02199e10 in CFRunLoopRunSpecific () #11 0x02199ccb in CFRunLoopRunInMode () #12 0x039a8879 in GSEventRunModal () #13 0x039a893e in GSEventRun () #14 0x00732a9b in UIApplicationMain () #15 0x00001e5b in main As you can see this call stack is not very helpful because it doesn't show any methods from my code. Also, the call stack shown in the error has 22 memory addresses, while the stack from thread 1 only has 15, and the addresses don't match at all. No other threads seem to contain any useful information. How is it possible to see the thread of the "First throw call stack" from the error (the one with 22 addresses), so I can find the line causing this error? Perhaps I have something set incorrectly in my Build Settings that is causing the relevant stack to not be retrievable? If someone could point me in the right direction on this I'd be very grateful. Trying to locate the offending line manually is quite tedious. Thanks! A: turn on the debugger and set a breakpoint on whenever an exception is thrown, this way you exactly know which line of code is being a jerk. objc_exception_throw Alternatively, [NSException raise]; Have a look at the following question: Add breakpoint to objc-exception-throw
{ "pile_set_name": "StackExchange" }
Q: Laravel Testing - How to validate each fields in JSON response I want to test my endpoint with valid format. For example, I have /api/token (POST) which will return api token. In my case, this endpoint will return "token" string and "message" fields. Thus, I want to check if this two fields are exist with valid format. Currently I am using Laravel Validator. Example json output: { "message": "login successful", "token": "d4zmendnd69u6h..." } Test class (ApiTokenTest.php). class ApiTokenTest extends TestCase { protected $validFormBody = [ 'os_type' => 'android', 'device_id' => '0000-AAAA-CCCC-XXXX', 'os_version' => '5.1', 'apps_version' => '1.0', ]; public function testSucessResponseFormat() { $response = $this->json('post', '/api/token', $this->validFormBody); $validator = Validator::make(json_decode($response->getContent(), true), [ 'token' => 'required|size:100', // token length should be 100 chars 'message' => 'required', ]); if ($validator->fails()) { $this->assertTrue(false); } else { $this->assertTrue(true); } } } The issue here is the failure message is not really helps, especially if I have more than 1 fields that are not in valid format, should i assert one-by-one?. (see below phpunit output on failure case). What should I use in order to validate format for each fields? Thanks in advance. There was 1 failure: 1) Tests\Feature\ApiTokenTest::testSucessResponseFormat Failed asserting that false is true. A: It looks like you are not displaying anything in the terminal if there is in fact any validation errors, what you can do is a var_dump into the terminal if the validator fails, like so: if ($validator->fails()) { var_dump($validator->errors()->all()); $this->assertTrue(false); } else { $this->assertTrue(true); }
{ "pile_set_name": "StackExchange" }
Q: Codeigniter Subfolder I have a CodeIgniter in my site say abc.com . I have copied full content to a sub folder in same site say abc.com/test . But I can't access the site using abc.com/test . Can anyone help me in this regards Thanks A: Root htaccess RewriteEngine on RewriteBase / RewriteCond $1 !^(index\.php|lib|robots\.txt|test) RewriteRule ^(.*)$ index.php/$1 [L]
{ "pile_set_name": "StackExchange" }
Q: radio buttons in nvd3 charts I am trying to slightly change the behavior of nvd3 horizontal chart. Right now the horizontal chart has a legend with possible option to have multiple legend items selected at the same time. I'm just trying to show only one item at a time so that when one series is selected, others are deselected. var data = [ { "key": "Series1", "color": "#d62728", "values": [ { "label" : "A" , "value" : 1 } , { "label" : "B" , "value" : 8 } , ] }, { "key": "Series2", "color": "#1f77b4", "values": [ { "label" : "C" , "value" : 25 } , { "label" : "D" , "value" : 16 } , ] } ] nv.addGraph(function() { var chart = nv.models.multiBarHorizontalChart() .x(function(d) { return d.label }) .y(function(d) { return d.value }) .margin({top: 30, right: 20, bottom: 50, left: 175}) .showValues(true) .tooltips(false) .showControls(false); chart.yAxis .tickFormat(d3.format(',.2f')); d3.select('#chart svg') .datum(data) .transition().duration(500) .call(chart); nv.utils.windowResize(chart.update); return chart; }); And I also modified the multiBarHorizontalChart portion of nv.d3.js with the following on lines 6264 to 6272: //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ data.map(function(d,i){ d.disabled= true; return d; }); This makes it so that it behaves like radio buttons, however when the chart is first loaded, both Series1 and Series2 are visible. So my question is "how would you make only one series visible?" A: I ended up replacing var barsWrap = g.select('.nv-barsWrap').datum(data.filter(function(d, i) {return !d.disabled })) in the nv.d3.js file with the following: var all_undefined = true; for (var i=0; i < data.length; i++){ if (data[i].disabled === true || data[i].disabled === false){ all_undefined = false; } } if (all_undefined){ var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d, i) { if (i===0){ wrap.selectAll('.nv-series').classed('disabled', true); wrap.select('.nv-series').classed("disabled", false); return !d.disabled } })) } else{ var barsWrap = g.select('.nv-barsWrap') .datum(data.filter(function(d, i) {return !d.disabled })) } Not a very elegant solution, but it works to make radio buttons from the legend in the horizontal bar chart.
{ "pile_set_name": "StackExchange" }
Q: If electrons have less mass than planck mass, do they still exert gravitational force? If electrons have less mass than planck mass do they still exert gravitational force? What about atoms and other subatomic particles with mass? A: We don't know of any reason why they shouldn't. But we don't know for sure, because the gravitational field produced by a Planck-mass object is too small to measure directly. The lightest object I know of whose gravitational field has been directly measured was 706 mg (http://jetp.ac.ru/cgi-bin/dn/e_067_10_1963.pdf), which is still 35,000 times the Planck mass.
{ "pile_set_name": "StackExchange" }
Q: gcc builtin atomic compare and exchange I want to use the gcc builtin function __atomic_compare_exchange() but I need it slightly different than it is specified as and it I am unsure it`s possible to achieve. the function prototype: __atomic_compare_exchange(type *ptr, type *expected, type *desired, bool weak, int success_memmodel, int failure_memmodel) it atomically compares ptr to expected and writes desired into ptr if ptr == expected what I want to achieve is very similiar but my expected is != NULL, basically I want to check if ptr != NULL and if that is true write desired into ptr. can this be done? here is the gcc concerning its usage: https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html A: Sure, but you just have to call it in a loop. On each loop iteration, read the old value. If it's null, break out of the loop and return failure. If it's not null, use that old value as the "expected" for atomic compare-and-exchange. If it succeeds, exit the loop and return success. Otherwise repeat. By the way, this general approach is how you construct arbitrary atomic operations on top of compare-and-exchange.
{ "pile_set_name": "StackExchange" }
Q: Timer not getting repeated My timer not getting repeated please help here is the code timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(doAnimation:) userInfo:nil repeats:YES]; [timer fire]; method -(void)doAnimation:(id)Sender { } A: [timer fire] manually fires the timer only once and is not actually "starting" the timer. From the docs: You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived. You need to add the timer in a run loop before it will start firing and repeating: You must add the new timer to a run loop, using addTimer:forMode:. Then, after seconds seconds have elapsed, the timer fires, sending the message aSelector to target. (If the timer is configured to repeat, there is no need to subsequently re-add the timer to the run loop.) An easier way would be to do something like: timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doAnimation:) userInfo:nil repeats:YES]; and: -(void)doAnimation:(NSTimer*)timer { } This automatically schedules the timer and adds it to the run loop. Just in case you aren't doing it, as you have set the target to be self you have to make sure the method doAnimation is defined within the same class. NSTimer Class Reference A: using timerWithTimeInterval requires you to attach it to a run loop. Try using timer = [NSTimer scheduledTimerWithTimeInterval:1 target self selector:@selector(doAnimation:) userInfo:nil repeats:YES]; change your doAnimation method to the following: -(void)doAnimation:(NSTimer *)timer{ // do Something } p.s why are you telling it to fire immediately? I don't think it is necessary.
{ "pile_set_name": "StackExchange" }
Q: "Type [namespace:type] is not declared" yet is imported correctly, I think Im using Visual Studio 2013 to develop an XSD Schema that imports another schema for use of its "Neck" type. For some reason Visual Studio doesnt like my use of type="wn:Neck", resulting in the error mentioned in the title. Below is my parent schema and after that is the child schema. Visually the schema looks correct but VS2013 disagrees. Does anyone know why this is happening? Ive seen similar questions but haven't found a direct solution to this issue. Parent <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:wn="http://fxb.co/xsd/warmoth/neck.xsd" targetNamespace="http://fxb.co/xsd/warmoth/customitem.xsd"> <xs:import namespace="http://fxb.co/xsd/warmoth/neck.xsd" schemaLocation="./Neck.xsd"/> <xs:element name="CustomItems"> <xs:complexType> <xs:sequence> <xs:element name="CustomItemOption"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="Neck" type="wn:Neck" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Child <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://fxb.co/xsd/warmoth/neck.xsd" > <xs:element id="Neck" name="Neck"> <xs:complexType> <xs:sequence> <xs:element name="Headstock"> <xs:complexType> <xs:attribute name="active" type="xs:boolean" default="true" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> A: In the parent XSD, change <xs:element minOccurs="0" maxOccurs="unbounded" name="Neck" type="wn:Neck" /> to <xs:element minOccurs="0" maxOccurs="unbounded" ref="wn:Neck" /> because you wish to reference the Neck element, not type, from the namespace of the child XSD.
{ "pile_set_name": "StackExchange" }
Q: How to implement inheritance in Screeps objects? I've been toying around with Screeps for a while now and last night I decided to work out some of my behaviors into a class hierarchy by deriving two classes, Miner and Transporter from a Creep main class. However, whenever I do console.log(_.functions(minerInstance)); I get the exact same function list as when I do console.log(_.functions(transporterInstance)); Could someone tell me if I'm doing something wrong OR if I'm actually running into a limitation of the environment my code runs in? This is my code: //////////////////////////// // Creep.js var Creep = function(creep, room) { this.creep = creep; this.room = room; this.name = creep.name; this.id = creep.id; }; module.exports = Creep; Creep.prototype = { tick: function() { console.log("Base class implementation of tick(), should never happen."); }, getRole: function() { return this.creep.memory.role; } }; //////////////////////////// // Miner.js var Creep = require("Creep"); var Miner = function(creep, room) { this.base = Creep; this.base(creep, room); //Creep.call(this, creep, room); }; module.exports = Miner; Miner.prototype = Creep.prototype; Miner.prototype.tick = function() { var creep = this.creep; if (creep.memory.activity === undefined || creep.memory.activity === "") { var target = creep.pos.findNearest(Game.SOURCES_ACTIVE); this.mine(creep, target); } var act = creep.memory.activity; if (act == "mine") { var target = this.getTarget(creep); if (target !== undefined) { if (creep.energy < creep.energyCapacity) { creep.moveTo(target); creep.harvest(target); } else { console.log("Write dump to truck code"); /*var trucks = find.transporterInRange(creep, 1); if (trucks.length) { creep.moveTo(trucks[0]); var amount = trucks[0].energyCapacity - trucks[0].energy; creep.transferEnergy(trucks[0], amount); }*/ } } } }; Miner.prototype.mine = function(creep, target) { creep.memory.target = target.id; creep.memory.activity = "mine"; }; Miner.prototype.getTarget = function(creep) { return Game.getObjectById(creep.memory.target); }; //////////////////////////// // Transporter.js var Creep = require("Creep"); var Transporter = function(creep, room) { Creep.call(this, creep, room); }; module.exports = Transporter; Transporter.prototype = Creep.prototype; Transporter.prototype.tick = function() { var creep = this.creep; if (creep.energy < creep.energyCapacity) { var miner = this.room.findByRole(creep, "miner"); console.log(miner); if (miner !== null) { //console.log(miner[0].name); //creep.moveTo(miner); } else console.log("no miners found"); } else { console.log("moving to drop"); //var drop = find.nearestEnergyDropOff(creep); //creep.moveTo(drop); //creep.transferEnergy(drop); } }; A: With this line... Miner.prototype = Creep.prototype; ... you tell JS that both prototypes are actually the same object. Hence any update for Miner.prototype will affect Creep.prototype too. One possible approach is using Object.create when establishing the link between prototypes. Here goes a simplified example: function Foo(a) { this.a = a; } Foo.prototype.tick = function() { console.log('Foo ticks'); }; Foo.prototype.tock = function() { console.log('Foo tocks'); }; function Bar(a, b) { this.base = Foo; this.base(a); this.b = b; } Bar.prototype = Object.create(Foo.prototype); // as you inherit all the properties, you'll have to reassign a constructor Bar.prototype.constructor = Bar; Bar.prototype.tick = function() { console.log('Bar ticks'); }; var f = new Foo(1); f.tick(); // Foo ticks f.tock(); // Foo tocks console.log(f); // Foo { a=1, ... } var b = new Bar(1, 2); b.tick(); // Bar ticks b.tock(); // Foo tocks console.log(b); // Bar { a=1, b=2, ... }
{ "pile_set_name": "StackExchange" }
Q: Coroutine never calls API after once API is failed In my viewmodel i've a function which uses coroutine to call an API. fun loadPosts(){ GlobalScope.launch(coroutineContext){ changeState(load = true) val list= withContext(Dispatchers.IO) { apiService.getProfile(AUTH) } changeState(false,false,null) showResult(list) } } Everytime i click on a button, this function is fired, API is called and I get valid response. But once my api get Exception like 500 or Http 401 Unauthorized, then again when I hit the button, Coroutine is never called and seems it returns the again error message from cache. For a use case: I clicked on button -> Api is called -> got success response Again I clicked on -> Api is called -> got success response I disconnected my internet from phone I clicked on button -> Api is called -> got exception something like ConnectionError I connected my phone to internet I clicked on button -> Api is not called -> got exception something like ConnectionError Now even my phone has valid internet connection, I press on button, instead of calling api and wait for response, It gives me previous failed response again and again. Earlier I was using Rxjava and I didn't face any such issue in that. I am new to coroutines so if anyone have any suggestion you are most welcome A: Whenever you start a coroutine with a coroutine builder such as launch, you need to start it in a given CoroutineScope - this is enforced by the function being defined as an extension on CoroutineScope. This scope contains a CoroutineContext, which will define how the coroutine is executed. Based on the comment above, I assume you are using roughly this setup: abstract class BaseViewModel : ViewModel(), CoroutineScope { private val job: Job = Job() override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override fun onCleared() { coroutineContext.cancel() } } By using GlobalScope.launch(coroutineContext), you're actually overriding everything provided by GlobalScope with the context parameter. Plus, since your ViewModel itself is a scope already, you don't need to launch in GlobalScope in the first place. You can simply write down launch within the ViewModel with no scope specified (essentially this.launch {}) and no context passed to it, as it will get the one from the scope anyway. The other issue is that you're using a regular Job as a part of your CoroutineContext. This Job becomes a parent for every coroutine you start, and whenever a child coroutine fails, such as on a network error, the parent Job gets cancelled too - meaning that any further children you attempt to start will fail immediately as well, as you can't start a new child under an already failed Job (see the Job documentation for more details). To avoid this, you can use a SupervisorJob instead, which can also group your coroutines together as children, and cancel them when the ViewModel is cleared, but won't get cancelled if one of its children fail. So to sum up the fixes to make at the code level quickly: Use a SupervisorJob in the ViewModel (and while you're there, create this combined CoroutineContext just once, by directly assigning it, and not placing it in a getter): override val coroutineContext: CoroutineContext = Dispatchers.Main + SupervisorJob() Launch your coroutines in the scope defined in the ViewModel instead of in GlobalScope: abstract class BaseViewModel : ViewModel(), CoroutineScope { // ... fun load() { launch { // equivalent to this.launch, because `this` is a CoroutineScope // do loading } } } You may also want to consider having your ViewModel contain a CoroutineScope instead of implementing the interface itself, as described here an discussed here. There's a lot of reading to do on this topic, here are some articles I usually recommend: https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055 https://medium.com/@elizarov/the-reason-to-avoid-globalscope-835337445abc https://proandroiddev.com/demystifying-coroutinecontext-1ce5b68407ad ... and everything else by Roman Elizarov on his blog, really :)
{ "pile_set_name": "StackExchange" }
Q: OutOfRangeExeption в перегрузке оператора Здравтсвуйте, не получается отловить исключение. Когда использую оператор неявного приведения в строку - выбрасывает исключение. Вот код, помогите чем сможете: public class BoolMatrix { private bool[,] matrix; public bool this[int a, int b] { get { return matrix[a, b]; } set { if (value) Count++; matrix[a, b] = value; } } public BoolMatrix(int width, int heigth) { matrix = new bool[width, heigth]; Length = width*heigth; Heigth = heigth; Width = width; Count = 0; } static public implicit operator string(BoolMatrix a) { string s = ""; for (int i = 0; i < a.Width; i++) { for (int j = 0; j < a.Heigth; j++) { s += a[i, j] + " "; } s += '\n'; } return s; } } Это был библиотечный класс, а теперь сам вызов оператора: string s = new BoolMatrix(9, 6); Кстати, если задать одинаковое кол-во строк и столбцов - работает как часы. A: Тут у вас ширина - высота. matrix = new bool[width, heigth]; А в цикле прогоняете сначала по Height, а нужно, как понимаю, по Width вот так: for (int i = 0; i < a.Width; i++) { for (int j = 0; j < a.Heigth; j++) { s += a[i, j] + " "; } s += '\n'; }
{ "pile_set_name": "StackExchange" }
Q: Question on Harmonic maps between Riemannian manifolds In Theory of harmonic maps, main goal is to find minimum of Dirichlet energy function which is defined as follows: $$E(f):=\frac{1}{2}\int_M\|df\|^2dvol_g\qquad f:(M,g)\to(N,h).$$ In many Books such as Calculus of Variations and Harmonic Maps-Hajime Urakawa, used the covariant derivation as a map $\Gamma(f^{-1}TN)\to \Gamma(f^{-1}TN)$ and in another Reference such as Graduate thesise of A.A. joshi the covariant derivation have been considered as a map $\Gamma(TM^*\otimes f^{-1}TN)\to \Gamma(TM^∗ \otimes TM^∗\otimes f^{-1}TN)$. why this two consideration is equivalent? Update: Another application of harmonic maps is the study of the topology of domain manifold. In this purpose how can I get the some topological properties of the domain manifold? Thanks. A: the reason is the directional of derivatives allow us to multiply a tensor field and then we can introduce orthogonal coordinate by the free tensors and use the harmonic maps of covariant derivation (the levi-civita connection type) to study manifolds (in differential geometry)! see: https://en.wikipedia.org/wiki/Covariant_derivative and http://sipi.usc.edu/~ajoshi/mathesis.pdf
{ "pile_set_name": "StackExchange" }
Q: Calculate area between $f$ and $f^{-1}$ Consider $f:[0, 1] \to [0, 1], \: f(x) = x e^{x^2 - 1}$. Calculate $$I=\int_0^1 |f(x) - f^{-1}(x)|dx$$ I know $f(0) = 0$ and $f(1) = 1$. If I had to calculate $$\int_0^1 f^{-1}(x)dx$$ I would put $x = f(y)$ but I don't know how to deal with $I$ because of the absolute value. A: Put $x=f(y)$. $$\int_0^1f^{-1}(x)dx=\int_0^1yf'(y)dy=\left[yf(y)\right]_0^1-\int_0^1f(y)dy=1-\int_0^1f(x)dx$$ Note that for $x\in[0,1]$, $$e^{x^2-1}\le 1$$ $$f(x)\le x$$ Therefore $f^{-1}(x)\ge x\ge f(x)$ and hence $|f(x)-f^{-1}(x)|=f^{-1}(x)-f(x)$ on $[0,1]$. A: $f(x) = xe^{x^2-1}$, so $$ f'(x) = e^{x^2-1} + 2x^2 e^{x^2-1} = e^{x^2-1}(1+2x^2)$$ and $$ f''(x) = 2xe^{x^2-1}(1+2x^2) + e^{x^2-1}(4x) = e^{x^2-1}(4x^3 + 6x). $$ Note that $f'(x) > 0$ on $(0,1)$. Therefore $f(x) = xe^{x^2-1}$ is strictly increasing on $(0,1)$. Therefore $f^{-1}$ actually exists, at least on $[0,1]$, which is all we care about here. Also, $f''(x) > 0$ on $(0,1)$. Therefore $f(x)$ is strictly convex (sometimes also called "strictly concave up" or just "concave up" depending on who you talk to) on $(0,1)$. $f(0) = 0$, $f(1) = 1$, and $f(x)$ is strictly convex on $(0,1)$. Therefore the graph of $y=f(x)$ on $[0,1]$ lies entirely below the segment of the line $y=x$ from $x=0$ to $x=1$, except at $x=0$ and $x=1$, which is where the graphs coincide. Therefore... I'll leave the rest to you, but what does this tell you about the graph of $y=f^{-1}(x)$, and therefore the relationship between $f(x)$ and $f^{-1}(x)$, on the interval $[0,1]$?
{ "pile_set_name": "StackExchange" }
Q: How to move folders if they contain a certain file? I'm writing some (ugly) code in batch to rearrange files between folders. I've created a part of the code that moves file of one type with similar filenames to the same folder, and creates a dummy text file called "serie.txt", if there is more than a file in it. At the end, I have a folder called "E:\videos\catalogar\" with lots of subfolders, and some of them contain the file "series.txt". I need to move these folders to the path "e:\videos\series\", and, for this, I wrote this: for /r "e:\videos\catalogar\" %%F in (serie.txt) do ( set directorio=%%~dpF if not "!directorio!"=="e:\videos\catalogar\" ( del "!directorio!*.txt" move /y "!directorio!." "e:\videos\series\" ) ) delayedexpansion is turned on. The if condition is to avoid moving the entire root folder. The problem is that, for some reason, this code moves all subfolders inside "E:\videos\catalogar\", not only the ones that contain "serie.txt". What's wrong? A: for /r "e:\videos\catalogar\" %%F in (serie.txt) do ( executes a directory-scan, but does not use the filemask. It will only use the filemask if the filemask contains * or ?. Personally, I believe that's a bug (OK if the filemask is '.' but should-match-mask-regardless otherwise) and perhaps asking Microsoft to fix it for W10 here may work. So - maybe add the gate as suggested, or include * or ? in the filemask to force "only directories matching" would solve your problem. Either way, there's little point in assigning a value to directorio as %%~dpF will have exactly the same effect in the sniplet posted.
{ "pile_set_name": "StackExchange" }
Q: Gitlab CI: Docker connect to remote MySQL via SSH Portforwarding before running tests I am trying to integrate my unit tests into Gitlab CI, which is mostly working. The NodeJS application uses MySQL databases hosted on a different server (using: ssh -L 3306:127.0.0.1:3306 username@remoteserver) which we locally port forward to, and as such, all the tests pass locally as we are connected to it. The CI script (included below) seems to work and the tests pass on any function that doesn't require the mysql connection. I need my CI runner to SSH into the remote server and let those remaining functions be tested. However, I am struggling to find a way to have my gitlab-ci.yml script execute the SSH (using a public key) into this remote server and locally port forward it to 127.0.0.1, before the tests are run. I also am unsure as to whether the public/private key pair is to be generated inside Docker, or generally on the machine that the Runner is set up on. Can anyone point me in the right direction? image: node:7.4 before_script: - apt-get update -qy - npm install -g mocha chai assert mysql require moment stages: - test test_job: stage: test tags: ["mySpecificRunner"] script: - npm run test environment: only: - development A: It is not straight forward, but there is a way. GitLab provides documentation and even an example. What you want to do is: Generate a public/private key pair On the server you want to connect to, add the public part of the key to the file listing the authorized ones (usually ~/.ssh/authorized_keys) In Gitlab, create a new variable called SSH_PRIVATE_KEY with the private part of the key as value In your project, modify the file .gitlab-ci.yml so that the Docker container uses the private part of the key: image: debian:latest before_script: # install & run ssh-agent - apt-get -qq update -y - apt-get -qq install openssh-client -y # setup the private key - eval $(ssh-agent -s) - ssh-add <(echo "$SSH_PRIVATE_KEY") - mkdir -p ~/.ssh - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config You script should then be able to connect seamlessly to the server and run commands or scripts there, e.g.($HOST and $USER are also secret variables): deploy-dev: stage: deploy script: - | ssh -t $USER@$HOST << EOF git fetch --all -v git checkout -f dev git reset --hard origin/dev EOF Note that at the time of writing this answer I have been unable to keep the SSH connection active and run commands one by one there. That is the reason behind the use << EOF.
{ "pile_set_name": "StackExchange" }
Q: Calling PHP function on HTML onClick() event? I know there is one answer out on stackoverflow, but that is related to form submission. Mine is different implementation. I need to call a function, which registers a variable in $_SESSION[], and then redirects to another page(html/php). Now I don't want to use AJAX. Please help me with this. A: That is not possible. Php is executed on the server before the html is served. All php functions have been evaluated to HTML at the time onClick occurs. You can do a form and set action="someFile.php" and use $_GET['someVaiable'] or $_POST['someVariable']
{ "pile_set_name": "StackExchange" }
Q: How can a function including a sin operation be linearly transformable for any offset? In the paper "Attention is all you need" the authors have chosen a function to encode the position of a word in a sequence (section 3.5). The following encoding is chosen: $ PE(pos, 2dim) = sin(pos / 10000 ^ {2dim/d_{model}} ) $ For the purposes of this question this function can be simplified to: $ PE(pos) = sin(pos) $ The text states that "for any fixed offset $k$, $PE(pos+k)$ can be represented as a linear function of $PE(pos)$". This did not seem obvious due to me due to the nonlinearity of the sine function. Other resources like Attention is all you need Explained mention this property but do not go deeper into it. I attempted to use linear regression techniques in Python to derive this, but was unable to find a fitting linear transform. As $k$ increases and the sine waves resulting from the $PE(pos)$ function get out of sync, the correlation of the transformation and the truth decreases. Did I misapprehend the statement in the paper, or is my code or understanding of the underlying math here faulty? A: Upon closer inspection, the article defines the function $\operatorname{PE}$ separately for even and odd dimension as \begin{eqnarray*} \operatorname{PE}(\text{pos},2d) &=&\sin(\text{pos}/c^d),\\ \operatorname{PE}(\text{pos},2d+1) &=&\cos(\text{pos}/c^d), \end{eqnarray*} for some constant $c=10000^{\frac{2}{d_{\text{model}}}}$. The trigonometric identity $$\sin(\alpha+\beta)=\sin(\alpha)\cos(\beta)+\cos(\alpha)\sin(\beta),$$ then yields the identity $$\operatorname{PE}(\text{pos}+k,2d)=\operatorname{PE}(\text{pos},2d)\cos(k/c^d)+\operatorname{PE}(\text{pos},2d+1)\sin(k/c^d),$$ which the authers seem to call a linear function of $\operatorname{PE}(\text{pos})$.
{ "pile_set_name": "StackExchange" }
Q: Broken images in "Remove new user restrictions" When my new user restrictions were removed, I saw a privileges page with a short tutorial on how to embed links and pictures in questions. The following example pictures were broken: http://i.stack.imgur.com/lSZui.png ("insert link toolbar button"), and, http://i.stack.imgur.com/C3zkF.png ("insert image toolbar button"). A: Somehow stack was inserted into the existing URLs of images that were uploaded before May 2011: http://i.stack.imgur.com/lSZui.png versus http://i.stack.imgur.com/lSZui.png http://i.stack.imgur.com/C3zkF.png versus http://i.stack.imgur.com/C3zkF.png It seems only https://meta.stackoverflow.com/privileges/new-user still refers to the correct image URLs. Might be a temporary problem though, while images are moved to the new Stack Exchange specific Imgur domain. A: This will be fixed in the next deploy.
{ "pile_set_name": "StackExchange" }
Q: Need example of using fabricjs.d.ts with TypeScript I use fabricjs in a project I'm attempting to convert to use TypeScript but I can't figure out how to use it. Previously I'd create my own custom objects by doing the following: my.namespace.Control = fabric.util.createClass(fabric.Object, { id: "", type: 'Control', color: "#000000", ... }); In my new project, I've installed the TypeDefinition file from here but I can't figure out how I should use it? Looking at the .d.ts file, fabric.Object doesn't appear to be a Function so isn't allowed to be passed to createClass, and createClass itself returns void, so I can't assign the value to a variable. Even if all this worked, how should I format this so it works the TypeScript way? ie, what do I export so that I can import it elsewhere where the Control class is needed? Anyone actually got any examples of doing this? A: The old way of using your fabricjs.d.ts is at the top of your file : /// <reference path="path/to/your/fabricjs.d.ts" /> If you get it with tsd you have to reference your tsd.d.ts bundle file But now with typescript 1.6.2 and vscode you only need to download the reference file via tsd to get the definitions in your code. In the d.ts file you can found the 2 methods signature : createClass(parent: Function, properties?: any): void; createClass(properties?: any): void; So your code seems invalid because fabric.Object as interface IObjectStatict cannot be asignable to type Function. You can cast fabric.Object as a Function doing my.namespace.Control = fabric.util.createClass(<Function>fabric.Object, { id: '', type: 'Control', color: '#000000', ... });
{ "pile_set_name": "StackExchange" }
Q: Accessing double from .txt file I have a .txt file that looks like: (0.781860352, -11.6927013, 7.20992613) (0.364501476, -9.41256046, 6.87873077) (0.394773483, -7.85253429, 6.90275288) I need a code to access each double from each line individually. I am having troubles solving this problem. Any ideas? Thanks! UPDATE: So, like I said, I am accessing each double from each line using the suggestion by Kerrek SB, then I store these values into the components of a vector, then I access each component and perform an operation (say multiply them together), and store the result into an array; finally I add the contents of the array. Anyway, here is the code: int main() { //============================= //Initial Declarations //============================= Vector3 r(0,0,0); int num = 0 , i; string line; char c, d1, d2, d3, d4; double v1, v2, v3 , b[num]; //============================= //Counting Lines in File //============================= ifstream is; is.open ("data.txt"); while (is.good()) { c = is.get(); if (c=='\n')num++; } is.close(); cout<<"Number of lines in file is "<<num<<endl; //============================= //Getting Data //============================= ifstream infile("data.txt"); for (line ,i=0 ; getline(infile, line), i<=num-1;i++ ) { istringstream iss(line); if (!((iss >> d1 >> v1 >> d2 >> v2 >> d3 >> v3 >> d4 >> ws) && iss.get() == EOF && d1 == '(' && d2 == ',' && d3 == ',' && d4 == ')')) { } // Placing data in vector r[0] = v1; r[1] = v2; r[2] = v3; //Placing data from vector into array b[i] = r[0]*r[1]*r[2]; } // Adding contents of array valarray <double> bfinal (b,num); double b_final = bfinal.sum(); cout<< b[0] << "," << b[1] << ", " << b_final << endl; return 0; } The code works (actually it is not adding the contents of the array correctly) , but it seems a little crude. I feel that it could be simplified and/or made more concise. Any ideas? A: The standard C++ idiom: #include <string> #include <fstream> #include <sstream> #include <iostream> std::ifstream infile("data.txt"); for (std::string line; std::getline(infile, line); ) { char d1, d2, d3, d4; double v1, v2, v3; std::istringstream iss(line); if (!((iss >> d1 >> v1 >> d2 >> v2 >> d3 >> v3 >> d4 >> std::ws) && iss.get() == EOF && d1 == '(' && d2 == ',' && d3 == ',' && d4 == ')')) { // error parsing "line" std::cerr << "Sorry, could not parse '" << line << "'. Skipping.\n"; continue; } std::cout << "You said: " << v1 << ", " << v2 << ", and " << v3 << "\n"; }
{ "pile_set_name": "StackExchange" }
Q: How does the Scrum Master participate in Daily Stand-Ups? We have a professional Scrum Master consultant [*] who recently joined our project. Unfortunately, we don't know her name (she never introduced herself to us, she just came in one day and said "we are having a daily stand-up"), and she doesn't seem to do much else except chair a daily stand up meeting - when I half-jokingly asked her to also give daily feedback in the meeting, she was quite affronted, saying it's the Scrum Master's job to "facilitate, not participate". This seems fairly anti-Agile (having worked on other agile projects, where the teams were self directed), which is supposed to be egalitarian, but I am not sure about how it works in the Scrum Methodology. I suspect she doesn't do much all day, and that's the reason for her defensiveness on this issue. Does the Scrum Master take part in the "yesterday, today, impediments" spiel during the stand-up meeting, or is their role to just chair ("facilitate") the meeting? [*] We weren't actually told what her job is, we just assume, since she calls herself the Scrum Master A: Ideally, the scrum master is responsible for facilitating the project activities and to address any sort of impediments faced during that. He/she does not participate in the "yesterday, today, impediments" spiel during the daily stand-up per se, however, is answerable to the team members for any kind of status on the impediments they have reported during the earlier stand-ups. I have worked with 5 scrum teams with a reputed organization, all of them followed the same practice. To get a detailed picture of all the responsibilities of a scrum master, I recommend you have a look at this http://www.scrummasterchecklist.org/pdf/ScrumMaster_Checklist_12_unbranded.pdf
{ "pile_set_name": "StackExchange" }
Q: Colors are not printing accurately I have a brochure which I'm trying to print it has a few shades of purple and grey. At one printing center, Digital Printing, the colors came out completely wrong as blues instead of purples and very dark gray. I tried a different center and the purple came out kinda pinkish but the gray comes out as yellow. Originally the file was CMYK but I changed it to RGB later and saved it as PDF which was later used for printing. Edit: I don't really know the type of the printer but maybe I'll try saving it as CMYK and print it again and see how it turns out A: Call the printer company and ask what Color Profile (ICC colour profile) they use in their printers. If they answer "we don't use any color profile", change to another printing center because this is a copy store, not a printing company. If they are really professionals, you can get two answers: A Standard color profile: in this case go to Menu Edit > Assign Profile and choose the standard profile used in your country. A Custom color profile: ask your printer to send you this profile and save it into your OS's Profiles Folder. For Mac users: HD > Users > Your User > Library > ColorSync > Profiles Maybe be you should restart Illustrator to see it in the list and then assign this profile to your document. Readjust the colors of your document according to the new profile if necessary. Save it and send it to print. Remember if your monitor is not properly calibrated, the colors that you see on your screen may differ and quite a lot of those that will appear in printing. The first step before everything is to well calibrate your monitor according to the type of work you usually do.
{ "pile_set_name": "StackExchange" }
Q: Simple mysql select statement with a string I have an entry in my database that has a name "ABC grocery store" and it has an id too. |_______name________|__id__| |ABC Grocery Store | ?? | | | | In my code I have the name but I need to retrive the id so I make a query: SELECT name, id FROM my_table WHERE name = "ABC Grocery Store" mysql accepts the statement without errors and returns nothing. Im totally new to databases so probably an easy fix. Please help. A: Your row value expected may be case sensitive depending on the collation. Secondly, there might be spaces in the row values. To only select the id, you can use: SELECT id FROM my_table WHERE name = "ABC Grocery Store"; Otherwise, try: SELECT id FROM my_table WHERE TRIM(name) = "ABC Grocery Store"; Or use LIKE: SELECT id FROM my_table WHERE name LIKE "%ABC Grocery Store%";
{ "pile_set_name": "StackExchange" }
Q: Flickering replacement image I have added some jQuery in order to display an .png image with just a blue bar across the bottom with some text, but as you hover over it, it flickers alot, can't seem to control it. This is on the 6 images on the homepage, link provided. I've included the associated html, css, javascript. live url: http://bit.ly/Pjp9Fj html <div class="product-images"> <a href="http://coeval.mangdevelopment.co.uk/Uploads/Product-PDF/1-2.pdf" target="_blank"> <div> <img id="main" src="<?php HTTP_HOST ?>/Images/Index-Products/index-product1.jpg" alt="" title="" /> <img id="overlay" src="<?php HTTP_HOST ?>/Images/thumbnail-overlay.png" alt="" title="" /> <span id="text">Speed Indicator Displays</span> </div></a> </div> css #index-products-gallery .opp-angle .product-images div { position: relative; } #index-products-gallery .opp-angle .product-images #main { width: 222px; height: 160px; } #index-products-gallery .opp-angle .product-images #overlay { position:absolute; width: 222px; height: 160px; top:0; left:0; display:none; margin-left: 0; } #index-products-gallery .opp-angle .product-images #text { position:absolute; bottom: -160px; left: 10px; color: #fff; font-weight: bold; font-family: Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif; font-size: 14px; display:none; z-index: 999; } javascript <script type="text/javascript"> $(document).ready(function() { $("#main").mouseenter(function() { $("#overlay").show(); $("#text").show(); }); $("#main").mouseleave(function() { $("#overlay").hide(); $("#text").hide(); }); }); </script> A: It is due to the fact you are adding a layer on top of the image so that causes the mouseleave event to fire. Apply the mouse enter and leave events to the parent element. Also why are you using tons of ids, use a class HTML: <div class="product-images"> <a href="http://coeval.mangdevelopment.co.uk/Uploads/Product-PDF/1-2.pdf" target="_blank"> <div> <img class="main" src="<?php HTTP_HOST ?>/Images/Index-Products/index-product1.jpg" alt="" title="" /> <img class="overlay" src="<?php HTTP_HOST ?>/Images/thumbnail-overlay.png" alt="" title="" /> <span class="text">Speed Indicator Displays</span> </div></a> </div> JavaScript: $(function() { $(".main").parent().on("mouseenter", function() { $(this).find(".overlay").show(); $(this).find(".text").show(); }).on("mouseleave", function() { $(this).find(".overlay").hide(); $(this).find(".text").hide(); }); });
{ "pile_set_name": "StackExchange" }
Q: R: read and parse Json If R is not suitable for this job then fair enough but I believe it should be. I am calling an API, then dumping the results into Postman json reader. Then I get results like: "results": [ { "personUuid": "***", "synopsis": { "fullName": "***", "headline": "***", "location": "***", "image": "***", "skills": [ "*", "*", "*", "*.", "*" ], "phoneNumbers": [ "***", "***" ], "emailAddresses": [ "***" ], "networks": [ { "name": "linkedin", "url": "***", "type": "canonicalUrl", "lastAccessed": null }, { "name": "***", "url": "***", "type": "cvUrl", "lastAccessed": "*" }, { "name": "*", "url": "***", "type": "cvUrl", "lastAccessed": "*" } ] } }, { Firstly I'm not sure on how to import this into R as I've mainly dealt with csv's. I've seen other questions where people use Json packages to call the URL directly but that's not going to work with what I'm doing so I'd like to know how to read a csv with json in it. I used: x <- fromJSON(file="Z:/json.csv") But perhaps theres a better way. Once this is done the json looks more like: ...$results[[9]]$synopsis$emailAddresses [1] "***" "***" [3] "***" "***" $results[[9]]$synopsis$networks... Then what I would like for each result is to store the headline and then email address into a data table. I tried: str_extract_all(x, 'emailAddresses*$') However I figured * would represent everything between emailAddresses and the $ including new lines etc, however this doesn't work. I also find with extract when you do get * to work, it doesnt extract what * represents. eg: > y <- 'some text. email "[email protected]" other text' > y [1] "some text. email \"[email protected]\" other text" > str_extract_all(y, 'email \"*"') [[1]] [1] "email \"" PART 2: The answers below worked, however if I call the api directly: body ='{"start": 0,"count": 105,...}' x <- POST(url="https://live.*.me/api/v3/person", body=body, add_headers(Accept="application/json", 'Content-Type'="application/json", Authorization = "id=*, apiKey=*")) y <- content(x) Then using fromJSON(y, flatten=TRUE)$results[c("synopsis.headline", "synopsis.emailAddresses")] Does not work. I tried the following: z <- NULL zz <- NULL for(i in 1:y$count){ z=rbind(z,data.table(job = y$results[[i]]$synopsis$headline)) } for(i in 1:y$count){ zz=rbind(zz,data.table(job = y$results[[i]]$synopsis$emailAddresses)) } df <- cbind(z,zz) However when the JSON list is returned, some people have multiple emails. Thus the method above only records the first email for each person, how would I save the multi emails as a vector (rather than having multiple columns)? A: UPDATE 1: to read the json from a URL you can simply use the fromJSON function, passing the string with your json data url: library(jsonlite) url <- 'http://you.url.com/data.json' # in this case we pass an URL to the fromJSON function instead of the actual content we want to parse fromJSON(url, flatten=TRUE)$results[c("synopsis.headline", "synopsis.emailAddresses")] // end UPDATE 1 you could also pass the flatten param to fromJSON and then use the 'results' dataframe. fromJSON(json.data, flatten=TRUE)$results[c("synopsis.headline", "synopsis.emailAddresses")] synopsis.headline synopsis.emailAddresses 1 *** [email protected] 2 *** [email protected] here is how I defined json.data, please note I intentionally added 1 more record to your sample input json. json.data <- '{ "results":[ { "personUuid":"***", "synopsis":{ "fullName":"***", "headline":"***", "location":"***", "image":"***", "skills":[ "*", "*", "*", "*.", "*" ], "phoneNumbers":[ "***", "***" ], "emailAddresses":[ "[email protected]" ], "networks":[ { "name":"linkedin", "url":"***", "type":"canonicalUrl", "lastAccessed":null }, { "name":"***", "url":"***", "type":"cvUrl", "lastAccessed":"*" }, { "name":"*", "url":"***", "type":"cvUrl", "lastAccessed":"*" } ] } }, { "personUuid":"***", "synopsis":{ "fullName":"***", "headline":"***", "location":"***", "image":"***", "skills":[ "*", "*", "*", "*.", "*" ], "phoneNumbers":[ "***", "***" ], "emailAddresses":[ "[email protected]" ], "networks":[ { "name":"linkedin", "url":"***", "type":"canonicalUrl", "lastAccessed":null }, { "name":"***", "url":"***", "type":"cvUrl", "lastAccessed":"*" }, { "name":"*", "url":"***", "type":"cvUrl", "lastAccessed":"*" } ] } } ] }'
{ "pile_set_name": "StackExchange" }
Q: PHP Page redirect problem - Cannot modify header information I have a page that displays various elements even if the id it's calling from the database does not exist or was deleted (which throws up all sorts of ugly errors along with search engines continuing to list non-existent pages). Can you modify the first part of the page code shown below to send a 404 (or at least to projecterror.php which has 404 headers) if $id does not exist? Many thanks! <?php include_once("includes/linkmysql.php"); $adda=$_GET['a']; $cont=$_GET['c']; $select="SELECT * FROM projects where id='$id'"; $qselect = mysql_query($select); while ($row = mysql_fetch_array($qselect)) { The following modification as kindly suggested by Matt Wilson as a result of an original comment by Vivek Goel results in valid entries showing the page correctly but non-existent pages are showing the errors below this modified code: <?php include_once("includes/linkmysql.php"); $adda=$_GET['a']; $cont=$_GET['c']; $select="SELECT * FROM projects where id='$id'"; $qselect = mysql_query($select); if( mysql_num_rows( $qselect ) === 0 ) { header("HTTP/1.1 301 Moved Permanently"); header( 'Location: http://examplesite.domain/errorpage' ) ; exit; } while ($row = mysql_fetch_array($qselect)) { Errors resulting from the above modifications: Warning: Cannot modify header information - headers already sent by (output started at /home/website/public_html/header1.php:14) in /home/website/public_html/header1.php on line 22 Warning: Cannot modify header information - headers already sent by (output started at /home/website/public_html/header1.php:14) in /home/website/public_html/header1.php on line 23 Lines 22 and 23 are the two header lines in your example above Lines 22 and 23 are the two header lines as below: header("HTTP/1.1 301 Moved Permanently"); header( 'Location: http://examplesite.domain/errorpage' ) ; A: I have much easier solution for you - it is simple! Just add this command at the very start of the php source: ob_start(); This will start buffering the output, so that nothing is really output until the PHP script ends (or until you flush the buffer manually) - and also no headers are sent until that time! So you don't need to reorganize your code, just add this line at the very beginning of your code and that's it :-)
{ "pile_set_name": "StackExchange" }
Q: " IN Quires and Places where they sing, here followeth the Anthem " (Book of Common Prayer 1662) I am following the morning and evening prayers as guided in the Anglican Book of Common Prayer. In both the morning and evening services there is a section which states: " IN Quires and Places where they sing, here followeth the Anthem " (Book of Common Prayer 1662). What is the Anthem alluded to here? A: An 'anthem' is a sung piece of church music, often a musical setting of a biblical passage. They differ from a hymn in that they are usually musically complex and sung by a choir rather than by the congregation. Not all services will include a choir, so the anthem is optional. However if one is used, it is sung in the place indicated. 'Quire' is simply an old spelling of 'choir', and the word can be used to mean a place where a choir sings. So the sentence means: If you have a choir or other singers, the anthem will be sung at this point in the service.
{ "pile_set_name": "StackExchange" }
Q: sf::String put into std::map key doesn't work - the vaule is not saved into map as I wrote in the topic - I try to put sf::String into map first argument and it does not work. Here's the code: void Flashcards::add(sf::String sf_string) { std::string text = sf_string.toAnsiString(); std::pair<std::string,std::string> pairr = std::make_pair(text,"<Polish translation>"); std::cout << "Inserting: " << pairr.first << std::endl; all_words.insert(pairr); //std::map<std::string, std::string> variable void Flashcards::show() { std::cout << "Flashcards:\n"; for (std::map<std::string, std::string>::iterator it = all_words.begin(); it != all_words.end(); it++) { std::cout << "English word: " << it->first << " " << "Polish word: " << it->second << std::endl; } The result in console is: Inserting: //a word// Flashcards: Polish word: <Polish translation> Instead of needed: Inserting: hello Flashcards: English word: //a word// Polish word: <Polish translation> Here are the variations I have already tried: 1) I switched the arguments so it looked like this: std::make_pair("<Polish translation>",text); and it works - hardcoded key and the value are both showed in the console (but I don't want hardcoding, what is obvious). 2) Note that this line: std::cout << "Inserting: " << pairr.first << std::endl; shows that the key value is converted into std::string correctly - calling this will show value we have just typed on the keyboard. 3) I tried to send the sf::String value directly to the std::make_pair() method, it works exactly the same as putting std::string there. Can somebody say how to make this work? A: The string you are providing as an argument to the add method obviously ends with a \r (carriage return) character, probably because you are reading it from a Windows text file using a Unix/Linux execution environment. If you capture the output of your program in a file and look at it with a hexdumper (such as hd), you should immediately see what is going on. It certainly has nothing to do with your use of the C++ standard library. However, you don't need to go to all that work to insert an entry into a std::map. Just do this: all_words[key] = value; As long as key has the right type (or there is an automatic conversion), that will do precisely what you want in a single line easily-understood line, and probably more efficiently as well.
{ "pile_set_name": "StackExchange" }
Q: How to ignore English mistakes in Eclipse comments I need to make eclipse stop checking for English mistakes in my comments, it's really annoying to see everything underlined in red, we use tons of "private" names during a project so i really don't see how useful this can be... thank you A: Open the Preferences and search for spell in the search field at the top. There you'll find the option to disable spell checking.
{ "pile_set_name": "StackExchange" }
Q: query MySQL data from multiple tables with multiple entries with PHP I'm working on a database for monitoring sportinjuries. I have 2 tables, one is called injury the other one injury_list. Injury looks like this: ----------------------------------------------------------------------- injury_id | name | body_part | first_mention | last_changed | status ----------------------------------------------------------------------- | 2 | Ben | arm | 2013-06-08 | 2013-06-13 | 0 | | 3 | Rick | knee | 2013-05-10 | 2013-06-12 | 0 | | 4 | Esther| ankle | 2013-05-26 | 2013-06-12 | 1 | ----------------------------------------------------------------------- and then we have injury_list which I use to store the updates from Physiotherapists and coaches ----------------------------------------------------------------------- list_id | injury_id | Comments | trend | comment_added ----------------------------------------------------------------------- | 1 | 2 | Complains a lot wo.... | 1 | 2013-06-01 | | 2 | 2 | Gets a little bit be.. | 3 | 2013-06-08 | | 3 | 2 | no changes so far..... | 2 | 2013-06-13 | | 4 | 4 | aches a lot, send t... | 1 | 2013-06-01 | | 5 | 4 | Got a lot worse ne.... | 1 | 2013-06-08 | | 6 | 4 | no changes so far..... | 2 | 2013-06-13 | ----------------------------------------------------------------------- Trend is used to show if the injury got worse (1), better(2) or no change(3) I have an overview off all injuries where I only use the INJURY table and a detailed page per injury, where I use information from both tables this all works fine. now I want the TREND to show on the main page in the overview, and as you can understand I only want the latest trend (based on comment_added). I tried several several queries but I can't seem to understand how to righteously call the data. I'm not realy good with joins, and I actually don't know if that is the solution here, I hope someone can help me out: $result = mysqli_query($con," SELECT b.injury_id , bl.injury_id b.name , b.body_part , b.first_mention , b.last_changed , b.status FROM injury b JOIN injury_list bl ON bl.injury_id = b.injury_id ORDER BY status ASC , last_changed DESC; "); thanks in advance for thinking with me. A: ...and here's a third way, a simple LEFT JOIN to find the latest row to eliminate the subquery; SELECT i.*,il1.* FROM injury i JOIN injury_list il1 ON i.injury_id = il1.injury_id LEFT JOIN injury_list il2 ON i.injury_id = il2.injury_id AND il1.comment_added < il2.comment_added WHERE il2.injury_id IS NULL An SQLfiddle to test with. EDIT: A quick (and, I realize not entirely easy to follow) explanation; The first join is a totally normal join to get an injury and a corresponding entry in injury_list. I then LEFT JOIN to injury list again to see if there exists a newer entry. If not, the left join will leave all fields in il2 NULL (ie, non existant) and we should show the row we just built. If there exists a newer entry, the fields in il2 will have the data from the newer entry, and in that case the row should not be shown.
{ "pile_set_name": "StackExchange" }
Q: Is it safe to keep all databases on one SQL server? I'm creating a Multi-Tenant application that uses separate databases for each 'client'. Is it safe to keep all the clients databases on one SQL server? Assuming I give each db its own user account? Thanks A: There was an excellent blog post by Brent Ozar last week on this exact subject. How To Design Multi-Client Databases
{ "pile_set_name": "StackExchange" }
Q: Passing data from controller to directive I 'm trying to handle data that is coming from my database in a directive , however these data are being pulled by a controller and being assigned to scope like this: Calendar Controller: 'use strict'; var CalendarController = ['$scope', 'EventModel', function(scope, EventModel) { scope.retrieve = (function() { EventModel.Model.find() .then(function(result) { scope.events = result; }, function() { }); }()); }]; adminApp.controller('CalendarController', CalendarController); Calendar Directive: 'use strict'; var calendarDirective = [function($scope) { var Calendar = { init: function(events) { console.log(events); } }; return { link: function(scope) { Calendar.init(scope.events); } }; }]; adminApp.directive('calendarDirective', calendarDirective); But the data is undefined in the directive, and in the controller the data appears to be ok. Thanks! A: This is a common error for people starting out with AngularJS. This is a load order issue. The events scope variable is not defined when the directive link function is executed. One solution is to use a watch on the variable passed into the directive and load once it is defined. return { link: function(scope) { scope.$watch('events', function() { if(scope.events === undefined) return; Calendar.init(scope.events); }); } };
{ "pile_set_name": "StackExchange" }
Q: Predicting Negative Binomial response when some observations contain no success Problem description: I am attempting to model the number of attempts required in order to make event $Z$ happen. Each day we make $k_i$ attempts with setting $X_i$ (a vector) in an effort to make $Z$ happen for object $i$, for $i$ from 1 to $m$. In other words, we are making multiple attempts with one setting (these settings affect the probability each attempt causes $Z$ to happen), then multiple attempts with another setting, et cetera. However, once we start making attempts with a new setting the previous set of attempts have no effect, because now we've given up on making $Z$ happen (or we've made it happen already) for object $i$ and are attempting to make $Z$ happen for object $j$. Context: The attempts have a cost and the events have a payoff. We are wanting to predict the number of attempts needed so that if a large number of attempts is predicted to be needed we can know not to make any attempts, because it won't be worth it. Issue: My first thought was to just model this with Negative Binomial regression, and the target "count" would be number of attempts required. The problem is that most of the time, event $Z$ doesn't actually happen, so the count for that observation is missing (but known to be greater than $k_i$). A: Let $f(y)$ be pdf and F(y) be CDF of negative binomial distribution. Let $n$ be # of Z happened, and $m$ be the # of Z not happened. Then log-likelihood can be write as: $$\mathrm{LogL} =\sum_{i=1}^n \log f(y_i) +\sum_{j=1}^m\log (1-F(y_j))$$ where $y_i$ means at $y_i$-th trail, Z happened, $y_j$ means Z did not happen till $y_i$-th trail and no more trail.
{ "pile_set_name": "StackExchange" }
Q: LINQ to Object Help I have the following entity structure: public class Party { public Int32 PartyId { get; set; } public List<PartyRelationship> RelationShips { get; set; } } public class PartyRelationship { public Int32 PartyId { get; set; } public Int32 RelatedPartyId { get; set; } } Now if I create a generic list of Party objects, such as List, how can I write a LINQ query against the list that will return all of the PartyRelationship objects that have a relationship to a specific PartyId based on the RelatedPartyId? The LINQ query would need to evaluate the RelatedPartyId of all relationships defined for a Party and compare that against a specific PartyId that I am searching for. When a match is found, I would want that specific PartyRelationship object return in the result. BTW, more than one match can occur. Can anyone provide some insight into how I could do this? Any help would be appreciated. Thanks A: Do you mean: var query = from party in parties // the list where party.RelationShips != null // overkill??? from related in party.RelationShips where related.RelatedPartyId == id select related;
{ "pile_set_name": "StackExchange" }
Q: Using Kile and PdfLaTeX with eps files I'm aware there's a lot of questions regarding using eps files as graphics in pdfLaTeX, and have tried many 'fixes'/'get arounds' based on answers I've read on this forum (amongst others), but still can't get it to work. I'm using Kile 2.1.0 on Ubuntu 12.04 LTS, having recently come from using TeXShop on a Mac. I've read that in order to get Kile to compile my .tex file using PdfLaTeX I need to insert: \usepackage{epstopdf} in the preamble, which I have, but it still doesn't work. For example in a test .tex file I have included \usepackage{epstopdf} in the preamble, and then in the body written: \begin{figure}[h!] \begin{center} \includegraphics[scale = 0.7]{pic1.eps} \caption{\textit{A graphic.}} \label{Label1} \end{center} \end{figure} Upon running PDFLaTeX in Kile I get: ! Package pdftex.def Error: File `pic1-eps-converted-to.pdf' not found. Which would suggest to me that epstopdf is doing SOMETHING, maybe putting the converted eps file somewhere silly? Thanks in advance, Olie A: without the option --shell-escape it can't run external programs. Add it to Kile at `Settings->Configure Kile-> Build: then the following should work: \listfiles \documentclass{article} \usepackage{graphicx} %\usepackage{epstopdf} \begin{document} \includegraphics[width=0.8\linewidth]{/tmp/titel2.eps} \end{document} epstopdf is loaded by default: *File List* article.cls 2007/10/19 v1.4h Standard LaTeX document class size10.clo 2007/10/19 v1.4h Standard LaTeX file (size option) graphicx.sty 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR) keyval.sty 1999/03/16 v1.13 key=value parser (DPC) graphics.sty 2009/02/05 v1.0o Standard LaTeX Graphics (DPC,SPQR) trig.sty 1999/03/16 v1.09 sin cos tan (DPC) graphics.cfg 2010/04/23 v1.9 graphics configuration of TeX Live pdftex.def 2011/05/27 v0.06d Graphics/color for pdfTeX infwarerr.sty 2010/04/08 v1.3 Providing info/warning/error messages (HO) ltxcmds.sty 2011/11/09 v1.22 LaTeX kernel commands for general use (HO) supp-pdf.mkii pdftexcmds.sty 2011/11/29 v0.20 Utility functions of pdfTeX for LuaTeX (HO) ifluatex.sty 2010/03/01 v1.3 Provides the ifluatex switch (HO) ifpdf.sty 2011/01/30 v2.3 Provides the ifpdf switch (HO) epstopdf-base.sty 2010/02/09 v2.5 Base part for package epstopdf grfext.sty 2010/08/19 v1.1 Manage graphics extensions (HO) kvdefinekeys.sty 2011/04/07 v1.3 Define keys (HO) kvoptions.sty 2011/06/30 v3.11 Key value format for package options (HO) kvsetkeys.sty 2012/04/25 v1.16 Key value parser (HO) etexcmds.sty 2011/02/16 v1.5 Avoid name clashes with e-TeX commands (HO) epstopdf-sys.cfg 2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Live /tmp/titel2-eps-converted-to.pdf *********** You can test, if epstopdf.sty is installed. Run in a terminal: kpsewhich epstopdf.sty and it should report the location of the file: voss@shania:~> kpsewhich epstopdf.sty /usr/local/texlive/2013/texmf-dist/tex/latex/oberdiek/epstopdf.sty If it outputs nothing then you have to install that package.
{ "pile_set_name": "StackExchange" }
Q: cannot find symbol -method getvalue (); maybe you meant : intValue import java.util.ArrayList; public class Averager { private ArrayList list; public Averager() { list = new ArrayList(); } public void addGrades(int test, int quiz) { list.add(new Integer(test)); list.add(new Integer(test)); list.add(new Integer(quiz)); } public double getAverage() { int sum = 0; for(int i = 0; i < list.size(); i++) { sum += ((Integer)list.get(i)).getValue(); } return sum / list.size(); } } A: Integer class does not have getValue() method. There is intValue() method. But for arithmetic operations you even don't have to call it - Java will do autoboxing: sum += (Integer)list.get(i);
{ "pile_set_name": "StackExchange" }
Q: What prevents tourists visiting the U.S. from buying firearms? Imagine an ordinary foreigner, arrived with a simple tourist visa into the US. In the U.S., there is no personal identification document. Most of the U.S. people doesn't have a passport. What prevents a simple tourist to go into a weapon shop and buy a rifle? A: 18 USC 922(g) says that it is illegal for various persons to ship or transport in interstate or foreign commerce, or possess in or affecting commerce, any firearm or ammunition; or to receive any firearm or ammunition which has been shipped or transported in interstate or foreign commerce. (5) refers to "being an alien", specifically one who has been admitted to the United States under a nonimmigrant visa (as that term is defined in section 101(a)(26) of the Immigration and Nationality Act (8 U.S.C. 1101(a)(26))) with an exception as provided in subsection (y)(2), The (y)(2) exceptions covers foreign officials and law enforcement (not a typical tourist), and one who is (A) admitted to the United States for lawful hunting or sporting purposes or is in possession of a hunting license or permit lawfully issued in the United States; which pretty much covers simple tourists, if not typical tourists. A: In the U.S., there is no personal identification document. That's not really true. There is no standard personal identification document issued by the national government (if you don't count passports), but state governments do issue such documents. The most common is a state-issued driver license, and people who do not drive can be issued a "non-driver ID" that is otherwise similar. Practically every US citizen or resident has one of these documents, and in practice they are used in a similar way to a national ID card. (You could do an image search to see what they look like.) In fact, there is an identification requirement for buying firearms; see https://www.atf.gov/firearms/qa/what-form-identification-must-licensee-obtain-transferee-firearm. A state driver license or non-driver ID would be sufficient for this purpose, and that's what most people would use. The link mentions that a foreign passport would be acceptable identification; but that doesn't mean a foreign tourist could actually buy a gun. The answer by user6726 cites the relevant law that restricts nonimmigrant aliens from firearm purchases.
{ "pile_set_name": "StackExchange" }
Q: Finding demand functions for an unusual utility function I have a utility function: $U = x + \min\{x,y\}$ I want to draw the indifference curve and find the demand functions. Will it be the case of the usual perfect complements? Also, what preferences could such a utility function represent? Will the optimal solution be at the kink? A: I assume you know how does $\min\{x,y\}$ look like? In order to draw utility function of interest, you need to consider cases: $u(x,y)=x+\min\{x,y\}=\begin{cases}2x, \;\; \mathrm{for} \;\; x \leq y \\ x+y, \;\; \mathrm{for} \;\; x > y\end{cases}$ With $x$ on horizontal and $y$ on vertical axis: Not sure about the "usual" perfect complements. It is more like a combination of substitutes (below $y=x$) and complements (above $y=x$). Also, take a look here: Identifying utility function and Algebraic approach towards convexity where you can see more graphs. EDIT. As for the demand function, Finding demand function given a utility min(x,y) function. A: To provide some real world(ish) interpretation, you could consider the following: Wallace enjoys eating cheese on its own. He doesn't much care for crackers on their own, but he especially loves eating crackers and cheese together, he makes nice little cracker n cheese sandwiches. In this example, we can think of cheese (x) and crackers (y) as perfect complements, but cheese will be a perfect substitute for a cracker and cheese sandwich. If a unit of cheese is cheaper than a unit of crackers he'll skip the sandwiches and spend his whole budget on cheese, but if crackers are cheaper he'll buy cheese and crackers in equal proportions.
{ "pile_set_name": "StackExchange" }
Q: How to send a small amount of data to a large amount of iPhones What kind of protocols can I use to send data from a server (php) to iPhones? I ruled out UDP because on cellular, iPhones don't keep any ports open for outside communication (for obvious reasons). And TCP is too data hungry. I'm trying to find an in between that uses minimal data and doesn't tax infrastructure. I'm first doing an API call to get information - then at this point, I want the iPhones to "listen" for data. Then my server will send data to all the phones that are listening. Any thoughts on how to go about doing this? Or is this kind of connection impossible? A: As discussed in the comments, one solution is to use the Apple Push Notifications Service. More info here: http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/ApplePushService/ApplePushService.html http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html
{ "pile_set_name": "StackExchange" }
Q: Is MapReduce the Right Option When Dealing with Volatile Collections That Need to Be Joined Many times in Realtieme? I need to join 2 collections... so I've tried the map-reduce feature provided by MongoDB. Given the following collections: transactions: { "_id": 1, "userId": 1000, "amount": 0.75, "btcAddress": "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" } { "_id": 2, "userId": 2000, "amount": 0.55, "btcAddress": "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW63i" } users: { "_id": 1000, "username": "joe", "email": "[email protected]" } { "_id": 2000, "username": "tim", "email": "[email protected]" } I need to produce something like this: { "_id": 1, "username": "joe", "email": "[email protected]", "amount": 0.75, "btcAddress": "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" } { "_id": 2, "username": "tim", "email": "[email protected]", "amount": 0.55, "btcAddress": "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW63i" } The documentation is clear, so I just defined the mapping functions like this... transactions_map = function() { ... } users_map = function() { ... } ... and the reduce (merge) function like this: r = function(key, values) { ... } As the final step, I just invoking mapReduce: res = db.transactions.mapReduce(transactions_map, r, {out: {reduce : 'joined'}}); res = db.users.mapReduce(users_map, r, {out: {reduce : 'joined'}}); This works and produces the expected result... but there some considerations. mapReduce generates a temporary collection and in my case this raises a concurrency issue. I guess I need to drop the temporary collection before invoking mapRedudce again... but this process may be triggered many times a hour and by many users simultaneously. mapReduce seems to be designed for statistics, while I need something very similar to a SQL join in real-time since the transactions collection changes very often. Are there alternatives to mapReduce? Or are there at least implementation strategies to deal with use cases like mine? A: If only to make a join as your example, I think mapReduce is unnecessary. I try on this way. var result = []; db.transactions.find().forEach(function(e) { var user = db.users.findOne({_id: e.userId}, {_id:0}); delete e.userId; if (user) { for (var x in user) { e[x] = user[x]; } } result.push(e); }); If the result is very large and you want to save to a temporary collection, you can save the new document into a collection named as new ObjectId().str among the looping to avoid simultaneous impact.
{ "pile_set_name": "StackExchange" }
Q: How to create a shape from string name in Orchard? I would like to create a base ContentPart driver class that can use string values to define a shape. This is not the exact code I am going for, but should show the general idea of what I am hoping to do. Instead of the following: protected override DriverResult Display(ProductPart, string displayType, dynamic shapeHelper) { return this.ContentShape("Parts_Product", () => shapeHelper.Parts_Product()); } I would like to be able to do something like this: protected override DriverResult Display(ProductPart, string displayType, dynamic shapeHelper) { return this.ContentShape("Parts_Product", () => shapeHelper["Parts_Product"]()); } Is there any way to use string names with shapeHelpers to generate shapes? A: Yes, it's perfectly possible. The dynamic shapeHelper object is an instance of IShapeFactory. This interface provides methods for doing exactly what you want. Instead of using the dynamic method call shapeHelper.Parts_Product(), just use one of the provided Create method overloads, eg. shapeHelper.Create("Parts_Product"). In fact, this is exactly what happens under the hood when you call the dynamic method. In the end, your whole example could look like: protected override DriverResult Display( ProductPart part, string displayType, dynamic shapeHelper) { // It's better to cast shapeHelper to IShapeFactory first // to avoid dynamic dispatch return this.ContentShape("Parts_Product", () => ((IShapeFactory)shapeHelper).Create("Parts_Product")); }
{ "pile_set_name": "StackExchange" }
Q: Having trouble with speech to text in Python import speech_recognition as sr rec = sr.Recognizer() with sr.Microphone as source: print('say something') audio = rec.listen(source) voice_data = rec.recognize_google(audio) print(voice_data) This is my code which is shown in plenty of tutorials that I watched online, I installed SpeechRecognizer and pyAudio (using whl file, not with pip, I don't know if it makes a difference). When I try to run it it gives me an error about something in the pydevd.py and at the end gives me: with sr.Microphone as source: AttributeError: enter How can I resolve this? A: I got it to work by moving the statements not related to capturing the audio out of the with statement, this should work for you: import speech_recognition as sr rec = sr.Recognizer() print('say something') with sr.Microphone() as source: audio = rec.listen(source) voice_data = rec.recognize_google(audio) print(voice_data)
{ "pile_set_name": "StackExchange" }
Q: Docker - Celery as a daemon - no pidfiles found I seem to have tried every solution on here but none seem to be working, I'm not sure what I'm missing. Im trying to run celery as a daemon through my docker container. root@bae5de770400:/itapp/itapp# /etc/init.d/celeryd status celery init v10.1. Using config script: /etc/default/celeryd celeryd down: no pidfiles found root@bae5de770400:/itapp/itapp# /etc/init.d/celerybeat status celery init v10.1. Using configuration: /etc/default/celeryd celerybeat is down: no pid file found root@bae5de770400:/itapp/itapp# I've seen lots of posts to do with perms and I've tried them all to no avail. this is my docker file which creates all the perms and folders FROM python:latest ENV PYTHONUNBUFFERED 1 # add source for snmp RUN sed -i "s#jessie main#jessie main contrib non-free#g" /etc/apt/sources.list # install dependancies RUN apt-get update -y \ && apt-get install -y apt-utils python-software-properties libsasl2-dev python3-dev libldap2-dev libssl-dev libsnmp-dev snmp-mibs-downloader git vim # copy and install requirements RUN mkdir /config ADD /config/requirements.txt /config/ RUN pip install -r /config/requirements.txt # create folders RUN mkdir /itapp; RUN mkdir /static; # create celery user RUN useradd -N -M --system -s /bin/false celery RUN echo celery:"*****" | /usr/sbin/chpasswd # celery perms RUN groupadd grp_celery RUN usermod -a -G grp_celery celery RUN mkdir /var/run/celery/ RUN mkdir /var/log/celery/ RUN chown root:root /var/run/celery/ RUN chown root:root /var/log/celery/ # copy celery daemon files ADD /config/celery/init_celeryd /etc/init.d/celeryd RUN chmod +x /etc/init.d/celeryd ADD /config/celery/celerybeat /etc/init.d/celerybeat RUN chmod +x /etc/init.d/celerybeat RUN chmod 755 /etc/init.d/celeryd RUN chown root:root /etc/init.d/celeryd RUN chmod 755 /etc/init.d/celerybeat RUN chown root:root /etc/init.d/celerybeat # copy celery config ADD /config/celery/default_celeryd /etc/default/celeryd # RUN /etc/init.d/celeryd start # set workign DIR for copying code WORKDIR /itapp if I start it manually it works celery -A itapp worker -l info /usr/local/lib/python3.6/site-packages/celery/platforms.py:795: RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended! Please specify a different user using the -u option. ... [2017-09-25 17:29:51,707: INFO/MainProcess] Connected to amqp://it-app:**@rabbitmq:5672/it-app-vhost [2017-09-25 17:29:51,730: INFO/MainProcess] mingle: searching for neighbors [2017-09-25 17:29:52,764: INFO/MainProcess] mingle: all alone the init.d files are copied from the celery repo and this is the contents of my default file if it helps # Names of nodes to start # most people will only start one node: CELERYD_NODES="worker1" # but you can also start multiple and configure settings # for each in CELERYD_OPTS #CELERYD_NODES="worker1 worker2 worker3" # alternatively, you can specify the number of nodes to start: #CELERYD_NODES=10 # Absolute or relative path to the 'celery' command: CELERY_BIN="/usr/local/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="itapp" # or fully qualified: # Where to chdir at start. CELERYD_CHDIR="/itapp/itapp/" # Extra command-line arguments to the worker CELERYD_OPTS="flower --time-limit=300 --concurrency=8" # Configure node-specific settings by appending node name to arguments: #CELERYD_OPTS="--time-limit=300 -c 8 -c:worker2 4 -c:worker3 2 -Ofair:worker1" # Set logging level to DEBUG #CELERYD_LOG_LEVEL="DEBUG" # %n will be replaced with the first part of the nodename. CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" # Workers should run as an unprivileged user. # You need to create this user manually (or you can choose # a user/group combination that already exists (e.g., nobody). CELERYD_USER="celery" CELERYD_GROUP="celery" # If enabled pid and log directories will be created if missing, # and owned by the userid/group configured. CELERY_CREATE_DIRS=1 the only thing in this file which may be wrong I think is the CELERY_BIN value, I'm not sure what to set that too in a docker container Thanks A: So you had few issues in your Dockerfile Celery process shell was set to /bin/false which didn't allow any process to be started. You needed to give permission on /var/run/celery and /var/log/celery to the celery user /etc/default/celeryd should be 640 permission Also too many layers in your Dockerfile So I updated the Dockerfile to below FROM python:latest ENV PYTHONUNBUFFERED 1 # add source for snmp RUN sed -i "s#jessie main#jessie main contrib non-free#g" /etc/apt/sources.list # install dependancies RUN apt-get update -y \ && apt-get install -y apt-utils python-software-properties libsasl2-dev python3-dev libldap2-dev libssl-dev libsnmp-dev git vim # copy and install requirements RUN mkdir /config ADD /config/requirements.txt /config/ RUN pip install -r /config/requirements.txt # create folders RUN mkdir /itapp && mkdir /static; # create celery user RUN useradd -N -M --system -s /bin/bash celery && echo celery:"B1llyB0n3s" | /usr/sbin/chpasswd # celery perms RUN groupadd grp_celery && usermod -a -G grp_celery celery && mkdir -p /var/run/celery/ /var/log/celery/ RUN chown -R celery:grp_celery /var/run/celery/ /var/log/celery/ # copy celery daemon files ADD /config/celery/init_celeryd /etc/init.d/celeryd RUN chmod +x /etc/init.d/celeryd ADD /config/celery/celerybeat /etc/init.d/celerybeat RUN chmod 750 /etc/init.d/celeryd /etc/init.d/celerybeat RUN chown root:root /etc/init.d/celeryd /etc/init.d/celerybeat # copy celery config ADD /config/celery/default_celeryd /etc/default/celeryd RUN chmod 640 /etc/default/celeryd # set workign DIR for copying code ADD /itapp/ /itapp/itapp WORKDIR /itapp And then got into the web service container and all worked fine root@ab658c5d0c67:/itapp/itapp# /etc/init.d/celeryd status celery init v10.1. Using config script: /etc/default/celeryd celeryd down: no pidfiles found root@ab658c5d0c67:/itapp/itapp# /etc/init.d/celeryd start celery init v10.1. Using config script: /etc/default/celeryd celery multi v4.1.0 (latentcall) > Starting nodes... > worker1@ab658c5d0c67: OK > flower@ab658c5d0c67: OK root@ab658c5d0c67:/itapp/itapp# /etc/init.d/celeryd status celery init v10.1. Using config script: /etc/default/celeryd celeryd down: no pidfiles found root@ab658c5d0c67:/itapp/itapp# /etc/init.d/celeryd status celery init v10.1. Using config script: /etc/default/celeryd celeryd (node worker1) (pid 66) is up... root@ab658c5d0c67:/itapp/itapp#
{ "pile_set_name": "StackExchange" }
Q: where can I set that the tree in the explorer in eclipse when opened is expanded exactly as it was before last exit? where can I set that the tree in the explorer in eclipse when opened is expanded exactly as it was before last exit? A: I think it's answered here: How to save the "Package Explorer" in Eclipse
{ "pile_set_name": "StackExchange" }
Q: Dynamic index path helper I have to path helpers: automobile_albums_path and community_albums_path Album model belongs to polymorphic owner and I want to put link to other albums of current album's owner using @album model. So I want to write something like that: link_to @album.owner.albums But this does not works. I want to avoid using case statement to select proper helper. Is there a universal one? A: # app/helpers/application_helper.rb module ApplicationHelper def albums_path(owner) # change the name if it will collide with a route helper Rails.application.routes.url_helpers.send "#{owner.class.name.downcase}_albums_path" # add the owner as a second param to 'send' if needed end end Edited!
{ "pile_set_name": "StackExchange" }
Q: Spacy NLP - Chunking with Regular Expressions Spacy includes the noun_chunks functionality to retrieve set of Noun -Phrases. The function english_noun_chunks (attached below) uses word.pos == NOUN def english_noun_chunks(doc): labels = ['nsubj', 'dobj', 'nsubjpass', 'pcomp', 'pobj', 'attr', 'root'] np_deps = [doc.vocab.strings[label] for label in labels] conj = doc.vocab.strings['conj'] np_label = doc.vocab.strings['NP'] for i in range(len(doc)): word = doc[i] if word.pos == NOUN and word.dep in np_deps: yield word.left_edge.i, word.i+1, np_label elif word.pos == NOUN and word.dep == conj: head = word.head while head.dep == conj and head.head.i < head.i: head = head.head # If the head is an NP, and we're coordinated to it, we're an NP if head.dep in np_deps: yield word.left_edge.i, word.i+1, np_label I would like to get chunks from a sentence that maintain some regular expression. For example, I phrase of zero or more adjectives followed by one or more nouns. {(<JJ>)*(<NN | NNS | NNP>)+} Is it possible w/o overriding the english_noun_chunks function? A: You could rewrite this function without losing any performance, since it's implemented in pure python, but why not just filter those chunks after you get them? import re import spacy def filtered_chunks(doc, pattern): for chunk in doc.noun_chunks: signature = ''.join(['<%s>' % w.tag_ for w in chunk]) if pattern.match(signature) is not None: yield chunk nlp = spacy.load('en') doc = nlp(u'Great work!') pattern = re.compile(r'(<JJ>)*(<NN>|<NNS>|<NNP>)+') print(list(filtered_chunks(doc, pattern)))
{ "pile_set_name": "StackExchange" }
Q: How to remove all elements from JPanel in super class using Action Listener in subclass? I'm new to Java so please help :) I have one super class called MainFrame with main method and constructor class Run(). I get menubar for JFrame from subclass caled MenuBar. Menu bar has multiple subclasses with implemented ActionListeners. I have been getting an error whenever I try to use ActionListener to call a method from MainFrame superclass that removes all elements from JPanel that is initialized in MainFrame constructor method Run() Code for MainFrame: import java.awt.Color; import java.awt.Dimension; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.Arrays; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; public class MainFrame { JFrame mainFrame; JPanel mainPanel; JPanel[] pagePanels, tablePanels; JScrollPane scrollBar; private double zoom=1; private int width; private int height; private GridBagConstraints c; //private Page blankPage = new Page(); MenuBar menubar; Page blankPage; public static void main(String[] args) { MainFrame generator = new MainFrame(); generator.Run(); } public void Run() { pagePanels = new JPanel[100]; tablePanels = new JPanel[100]; menubar = new MenuBar(); blankPage = new Page(); c = new GridBagConstraints(); mainFrame = new JFrame("Code Generator v.1.0"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); c.gridx=0; c.insets = new Insets(20,0,20,0); //get size of screen GetScreenSize(); mainPanel=new JPanel(new GridBagLayout()); scrollBar=new JScrollPane(mainPanel); scrollBar.setPreferredSize(new Dimension(width,height)); //create main frame with height and width equal to screen size (fullscreen) mainFrame.setJMenuBar(menubar.getMenuBar()); mainFrame.getContentPane().add(scrollBar); mainFrame.setSize(width,height); mainFrame.setVisible(true); } public void GetScreenSize(){ GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); width = gd.getDisplayMode().getWidth(); height = gd.getDisplayMode().getHeight(); } public void RemoveAllfromMainPanel(){ mainPanel.removeAll(); } } Code for subclass MenuBar is: import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; public class MenuBar extends MainFrame{ public JMenuBar getMenuBar(){ JMenuBar menubar = new JMenuBar(); //add menus to menu bar JMenu file = new JMenu("File"); menubar.add(file); //add items to File menu JMenuItem newReport = new JMenuItem("New report"); file.add(newReport); newReport.addActionListener(new newReport()); JMenuItem exit = new JMenuItem("Exit"); file.add(exit); exit.addActionListener(new exitAction()); return menubar; } class exitAction implements ActionListener { public void actionPerformed(ActionEvent event) { System.exit(0); } } class newReport implements ActionListener { public void actionPerformed(ActionEvent event) { RemoveAllfromMainPanel(); } } } I think that it has to do something with inheritance but that is the topic that I have recently started to study. Can you please explain to me why am i getting this error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at MainFrame.TEST(MainFrame.java:125) at this line: mainPanel.removeAll(); Thank you in advance! Cheers! A: Your MenuBar shouldn't be extending from MainFrame. This is not the same instance that is created by your run method from your main method, meaning that mainPanel has not yet being initialised. Instead, you should be passing MenuBar a refernce of an instance of MainFrame when you create it menubar = new MenuBar(this); And on you MenuBar... public class MenuBar { private MainFrame mainFrame; public MenuBar(MainFrame mainFrame) { this.mainFrame = mainFrame; } /* other code */ class newReport implements ActionListener { public void actionPerformed(ActionEvent event) { mainFrame.RemoveAllfromMainPanel(); } } }
{ "pile_set_name": "StackExchange" }
Q: How to write in a RichTextBox on a Form from a function in C# I have a RichTextBox member named richTextBox1 in my class Form1. I'm trying to append text to the text box from a method: public partial class Form1:Form { public Form1() { InitializeComponent(); } public static void info(string str) { Form1 fm1 = new Form1(); fm1.richTextBox1.AppendText(str); } // ... } I have a set up an event handler for a button's Click event in the same class, which calls the info method above: info("Hello World"); When clicking on the button, I expected to see the text in the richTextBox1. However, it's not working and I can't find the problem. Please explain what is wrong. A: You're creating a new instance of your form every time the button is clicked. What you want to do is append the text to the text box existing in the same instance as the button: public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void info(string str) { this.richTextBox1.AppendText(str); } } Notice that the static keyword isn't there anymore.
{ "pile_set_name": "StackExchange" }
Q: Solution for TC / server closet in TIGHT area? A non-profit volunteer organization that I do some admin work for is in the process of planning a major renovation to their building, which is more or less a converted house (no basement, uninsulated attic, pretty much every other inch of space in use). We currently have the network hardware and servers - 1x 2U switch, 1x 1U router, patch panel, 5U UPS, 12U of servers of different heights, all Proliant - in a mechanical room, split between the network gear on a 12U wall-mounted rack and the servers on a big beefy wall-mounted shelf. Since we're doing a major renovation to the building, I'd like to plan for a new TC / server closet from the beginning. The problem is that, as the building is a converted house and even relatively small at that, space is at a premium. I don't think it will be possible to expand the structure enough to allow for any "real" sized TC. Does anyone have any ideas for setting up a short rack with both network equipment and servers in the minimum space possible? I assume the most we'll be able to come up with is something the size of a normal home closet (say, 3-4 feet wide, maybe 6 feet deep at best). The best theory I can come up with is to put a half-height rack all the way forward against the door (something with air movement like a screen door or metal mesh) and leave just enough space for a small-ish person to get around to the back of the rack, leaving about 2 feet behind the back of the rack and the wall. If this were just network equipment, I'd do a wall mount rack, but the need to keep the servers in the same space complicates things a bit... A: Every rack you'll find will be about 800mm wide. Most racks are either 600mm or 800mm deep. I suspect that 600mm racks will be too shallow for your usage. You'll want around 400mm along one side and the back to give you room to get to the back. You probably want a little more space to get at the back if you can. You will need at least a metre of space at the front of the rack to allow you to get servers in and out. This means that you're going to need at least 1200mm x 2200mm space for a rack. I don't see how you're going to be able to use any less space, unless you have another way of getting at the back of the rack. Obviously you don't need to get a full height rack and can use some of the space above it for other purposes.
{ "pile_set_name": "StackExchange" }
Q: How do you express "try"? I know that -てみる can mean "try", but my understanding of it is that it means "try it and see what it's like" or "give it a try". But is there a way of expressing "try" that emphasizes that effort was made to succeed? As an example, saying "I am trying to do Kendo" in Japanese: 剣道をしてみる。 sounds like I'm going for a brief "trial" to see how I like it. How would I express that I am making a strong effort to succeed at it? A: As a native speaker, I would say: 剣道をがんばっている。 or 剣道でがんばっている。 But, these are a little bit colloquial. When I want to be more formal, I will say: 剣道に励んでいる。 or, simply, いっしょうけんめい剣道をしている。
{ "pile_set_name": "StackExchange" }
Q: Segmentation fault in C/GMP: calculate factors with Pollard Rho I am an experienced programmer, but new to C. I am trying to learn C so I can use the gmp library to write fast big-integer programs; eventually I intend to write the performance parts of my programs in C functions that are called via a foreign function interface from other languages. As a vehicle for learning both C and the gmp library I have written the pollard rho integer factorization program shown below (yes, I know this isn't the best possible implementation of pollard rho, but it is simple, and at the moment I just want to get started). My program compiles correctly but when run it dies with the message "Segmentation fault." I assume that means I've got my pointers messed up somewhere, but I don't see it. Probably more than one. Can someone please look at my program and tell me where I've gone wrong? And point out any style issues or anything else I can improve? Many thanks, Phil /* rho.c -- pollard rho factorization * usage: rho n -- prints factors of n then exits * compile as gcc -lgmp -o rho rho.c */ #include <stdlib.h> #include <stdio.h> #include <gmp.h> typedef struct list { void *data; struct list *next; } List; List *insert(void *data, List *next) { List *new; if (! (new = malloc(sizeof(List)))) return NULL; new->data = data; new->next = next; return new; } List *insert_in_order(void *x, List *xs) { if (xs == NULL || mpz_cmp(x, xs->data) < 0) { return insert(x, xs); } else { List *head = xs; while (xs->next != NULL && mpz_cmp(x, xs->next->data) < 0) { xs = xs->next; } xs->next = insert(x, xs->next); return head; } } void rho_factor(mpz_t f, mpz_t n, long long unsigned c) { mpz_t t, h, d, r; mpz_init_set_ui(t, 2); mpz_init_set_ui(h, 2); mpz_init_set_ui(d, 1); mpz_init_set_ui(r, 0); while (mpz_cmp_si(d, 1) == 0) { mpz_mul(t, t, t); mpz_add_ui(t, t, c); mpz_mod(t, t, n); mpz_mul(h, h, h); mpz_add_ui(h, h, c); mpz_mod(h, h, n); mpz_mul(h, h, h); mpz_add_ui(h, h, c); mpz_mod(h, h, n); mpz_sub(r, t, h); mpz_gcd(d, r, n); } if (mpz_cmp(d, n) == 0) { rho_factor(f, n, c+1); } else if (mpz_probab_prime_p(d, 25)) { mpz_set(f, d); } else { rho_factor(f, d, c+1); } mpz_clears(t, h, d, r); } void rho_factors(List *fs, mpz_t n) { mpz_t f; mpz_init_set_ui(f, 0); while (! (mpz_probab_prime_p(n, 25))) { rho_factor(f, n, 1); fs = insert_in_order(f, fs); mpz_divexact(n, n, f); } mpz_clear(f); insert_in_order(n, fs); } int main(int argc, char *argv[]) { mpz_t f, n; mpz_init_set_ui(f, 0); List *fs = NULL; if (argc<2) { printf("usage: rho n\n"); return 1; } mpz_init_set_str(n, argv[1], 10); if (mpz_probab_prime_p(n, 25)) { printf("%s\n", argv[1]); return 0; } printf("%s", argv[1]); rho_factors(fs, n); while (fs != NULL) { printf(" %s", mpz_get_str(NULL, 10, fs->data)); fs = fs->next; } return 0; } EDIT1: Thanks to Daniel Fischer, I have made some progress, and am no longer getting a segmentation fault. The code shown below correctly prints the factor 127 when rho_factor is called with n = 1234567, but rho_factors returns a null list, so there is still something wrong with rho_factors. I assume the problem is that I can't keep re-initializing the same variable the way I am doing, but I don't know the right way to do it. Somehow I need to make a copy of each factor that I find, then insert that copy in fs. Many thanks, Phil /* rho.c -- pollard rho factorization * usage: rho n -- prints factors of n then exits * compile as gcc -lgmp -o rho rho.c */ #include <stdlib.h> #include <stdio.h> #include <gmp.h> typedef struct list { void *data; struct list *next; } List; List *insert(void *data, List *next) { List *new; if (! (new = malloc(sizeof(List)))) return NULL; new->data = data; new->next = next; return new; List *insert_in_order(void *x, List *xs) { if (xs == NULL || mpz_cmp(x, xs->data) < 0) { return insert(x, xs); } else { List *head = xs; while (xs->next != NULL && mpz_cmp(x, xs->next->data) < 0) { xs = xs->next; } xs->next = insert(x, xs->next); return head; } } void rho_factor(mpz_t f, mpz_t n, long long unsigned c) { mpz_t t, h, d, r; mpz_init_set_ui(t, 2); mpz_init_set_ui(h, 2); mpz_init_set_ui(d, 1); mpz_init_set_ui(r, 0); while (mpz_cmp_si(d, 1) == 0) { mpz_mul(t, t, t); mpz_add_ui(t, t, c); mpz_mod(t, t, n); mpz_mul(h, h, h); mpz_add_ui(h, h, c); mpz_mod(h, h, n); mpz_mul(h, h, h); mpz_add_ui(h, h, c); mpz_mod(h, h, n); mpz_sub(r, t, h); mpz_gcd(d, r, n); } if (mpz_cmp(d, n) == 0) { rho_factor(f, n, c+1); } else if (mpz_probab_prime_p(d, 25)) { mpz_set(f, d); } else { rho_factor(f, d, c+1); } mpz_clears(t, h, d, r, NULL); } void rho_factors(List *fs, mpz_t n) { while (! (mpz_probab_prime_p(n, 25))) { mpz_t f; mpz_init_set_ui(f, 0); rho_factor(f, n, 1); fs = insert_in_order(f, fs); mpz_divexact(n, n, f); } insert_in_order(n, fs); } int main(int argc, char *argv[]) { mpz_t f, n; mpz_init_set_ui(f, 0); List *fs = NULL; if (argc<2) { printf("usage: rho n\n"); return 1; } mpz_init_set_str(n, argv[1], 10); if (mpz_probab_prime_p(n, 25)) { printf("%s is prime\n", argv[1]); return 0; } rho_factor(f, n, 1); printf("%s\n", mpz_get_str(NULL, 10, f)); printf("%s", argv[1]); rho_factors(fs, n); while (fs != NULL) { printf(" %s", mpz_get_str(NULL, 10, fs->data)); fs = fs->next; } return 0; } EDIT2: Got it. Thanks to Daniel Fischer. Final version shown below. /* rho.c -- pollard rho factorization * usage: rho n -- prints factors of n then exits * compile as gcc -lgmp -o rho rho.c */ #include <stdlib.h> #include <stdio.h> #include <gmp.h> typedef struct list { void *data; struct list *next; } List; List *insert(void *data, List *next) { List *new; new = malloc(sizeof(List)); new->data = data; new->next = next; return new; } List *insert_in_order(void *x, List *xs) { if (xs == NULL || mpz_cmp(x, xs->data) < 0) { return insert(x, xs); } else { List *head = xs; while (xs->next != NULL && mpz_cmp(x, xs->next->data) < 0) { xs = xs->next; } xs->next = insert(x, xs->next); return head; } } void rho_factor(mpz_t f, mpz_t n, long long unsigned c) { mpz_t t, h, d, r; mpz_init_set_ui(t, 2); mpz_init_set_ui(h, 2); mpz_init_set_ui(d, 1); mpz_init_set_ui(r, 0); while (mpz_cmp_si(d, 1) == 0) { mpz_mul(t, t, t); mpz_add_ui(t, t, c); mpz_mod(t, t, n); mpz_mul(h, h, h); mpz_add_ui(h, h, c); mpz_mod(h, h, n); mpz_mul(h, h, h); mpz_add_ui(h, h, c); mpz_mod(h, h, n); mpz_sub(r, t, h); mpz_gcd(d, r, n); } if (mpz_cmp(d, n) == 0) { rho_factor(f, n, c+1); } else if (mpz_probab_prime_p(d, 25)) { mpz_set(f, d); } else { rho_factor(f, d, c+1); } mpz_clears(t, h, d, r, NULL); } void rho_factors(List **fs, mpz_t n) { while (! (mpz_probab_prime_p(n, 25))) { mpz_t *f = malloc(sizeof(*f)); mpz_init_set_ui(*f, 0); rho_factor(*f, n, 1); *fs = insert_in_order(*f, *fs); mpz_divexact(n, n, *f); } *fs = insert_in_order(n, *fs); } int main(int argc, char *argv[]) { mpz_t f, n; mpz_init_set_ui(f, 0); List *fs = NULL; if (argc<2) { printf("usage: rho n\n"); return 1; } mpz_init_set_str(n, argv[1], 10); if (mpz_probab_prime_p(n, 25)) { printf("%s is prime\n", argv[1]); return 0; } printf("Factors of %s:", argv[1]); rho_factors(&fs, n); while (fs != NULL) { printf(" %s", mpz_get_str(NULL, 10, fs->data)); fs = fs->next; } printf("\n"); return 0; } A: You cannot reuse an mpz_t like that: void rho_factors(List *fs, mpz_t n) { mpz_t f; mpz_init_set_ui(f, 0); while (! (mpz_probab_prime_p(n, 25))) { rho_factor(f, n, 1); fs = insert_in_order(f, fs); mpz_divexact(n, n, f); } mpz_clear(f); insert_in_order(n, fs); } When GMP reallocates the storage pointed to via f, the old storage is freed. That may well happen in the while loop, but not necessarily. If it doesn't, all list entries point to the same number, however. But after the loop, when you mpz_clear(f), every data pointer in the list fs has become a wild pointer, and when you then insert_in_order(n, fs), you dereference previously freed pointers. (That very probably happens already during some insert in the while loop, but here it is guaranteed.) Also, in rho_factor, you should call mpz_clears(t, h, d, r, NULL); the argument list to mpz_clears must be NULL-terminated. Further problems: You pass a List *, so the changes made to fs in rho_factors don't affect the fs in main. Pass a List ** and dereference it where appropriate, also you forgot to assign the final insert_in_order's returned value. The local variable f goes out of scope at the end of the block, leading to corruption. malloc pointers to mpz_t to keep them alive. void rho_factors(List **fs, mpz_t n) { while (! (mpz_probab_prime_p(n, 25))) { mpz_t *f = malloc(sizeof(*f)); mpz_init_set_ui(*f, 0); rho_factor(*f, n, 1); *fs = insert_in_order(*f, *fs); mpz_divexact(n, n, *f); } *fs = insert_in_order(n, *fs); } and in main List *fs = NULL; /* snip */ rho_factors(&fs, n); should do it. Finally (?), you have a glitch in insert_in_order, the comparison in the while loop is backwards.
{ "pile_set_name": "StackExchange" }
Q: Physics not working when game is running on device Unity I have my bouncing ball game. The ball bounces up when it hits the ground and when it hits the left wall it changes direction to right and when it hits the right wall it changes direction to left and continues to bounce. Now the problem is that sometimes physics system does not register the collision between the ball and left/right wall, so the ball just passes through them and goes out of play, I have no idea whats going on. I will attach two pictures, one from game view and other from scene view. Again I say everything works great, the ball bounces and hits the wall then changes the direction but sometimes the collision between a wall and a ball is not registered and the ball just passes through the wall like there is no physics and goes out of camera view. A: If you are using physics simulation, don't just change the Transform of your object - this would most likely break the physics (but if you just use colliders as triggers, this might be OK). If you use physics, you should move your ball with AddForce. But here you could encounter various problems. The first problem is keeping the speed constant. You could specify max bounciness to the ball physics material and then call AddForce only when the ball changes the direction it moves (you also could just try to change the already applied velocity). Another option is to do AddForce with the ForceMode.VelocityChnage and specify to it the difference between current and desired velocities on each frame. Unfortunately this is not implemented for 2D physics, but some guys in Unity forums created the exetension method for that. There is also an easier way: you could just AddForce on each frame, but right after you could clamp the velocity by using _rigidbody.velocity = Vecotr2.ClampMagnitude(_rigidbody.velocity, Mathf.Abs(_maxSpeed));. This, btw, could break the physics a bit, since you're changing the velocity directly. You also should take care about the global treshold values in Edit->Project Settings->Physics 2D. But as you could see there is no Bounce Treshold value for 2D physics (there is for 3D). This means that when the ball will collide with a collider under a very small angle, it will "stick" to the collider and you have no option to control it - it is just hardcoded into physics settings (that problem 100% was in 4.6, not sure about Unity 5). So you should check that there is no such problem in your game. Another problem appears, when your ball is moving too fast. This is pretty much similar to what you are getting right now: the ball may pass through the colliders. Physics in Unity is calculated in FixedUpdated. FixedUpdate is invoked each 0.02 seconds (you could see and change this value in Edit->Project Settings->Time). If the ball moves too fast it could pass through the collider between frames - and then there is no collision. You could try to adjust the Interpolate and Collision Detection settings of your Rigidbody2D (the same for 3D), but this would not help if you move your object via Transform - physics can't predict such a movement. You should move with physics. But, if changing those values doesn't help you, then you have the last resort option to use raycasting. There is a special script called DontGoThroughThings in Unity wiki, which does it for you. You only would need to convert it to 2D (or find it somewhere, I am pretty much sure someone already did it). You could try to move your ball only by using Rigidbody2D.velocity. This may work, but may not. Velocity is physics, that's true, but changing it manually may break the physics calculations again. Most likely this would be seen when the ball will hit the other moving objects with "normal" physics. Another problem could be gravity. This happens because when you change the value manually, you remove the forces that were just applied to the object, and it will behave unnaturally. So you need to try it and see if it works the way you want. There is a probability that you can't go with it. Controlling the physics yourself manually (by checking collisions manually in scripts by using positions and sizes of the objects) is not an option for games with many moving objects (because there is really a lot of work), but could be used for simple games like an arkanoid. Manual collisions in 2D aren't that difficult, but there are some problems to solve. The two most important are collisions with edges and collisions with moving objects. I hope that you now have a bit better understanding on the subject. I'm not sure what exactly to recommend in your case, but you could try some (or all) of the options described above. I only hope you wouldn't need to write your own physics engine.
{ "pile_set_name": "StackExchange" }
Q: Install and publish Laravel package without composer I want to use this package: https://github.com/lucadegasperi/oauth2-server-laravel/wiki/Installation for using OAuth 2.0 in Laravel I can't install it correctly. First, I cannot update the composer, so I have to change "minimum-stability": "stable" to "minimum-stability": "dev". By updating the composer, all my packages are being replaced bij dev versions. And second, I can not publish my package by typing this command in my terminal: php artisan config:publish lucadegasperi/oauth2-server-laravel. I get this error: php artisan config:publish lucadegasperi/oauth2-server-laravel {"error":{"type":"ErrorException","message":"file_put_contents(\/Applications\/XAMPP\ /xamppfiles\/htdocs\/api-dashboardv2\/app\/storage\/meta\/services.json): failed to open stream: Permission denied","file":"\/Applications\/XAMPP\/xamppfiles\/htdocs\ /api-dashboardv2\/vendor\/laravel\/framework\/src\/Illuminate\/Filesystem\ /Filesystem.php","line":69}} I tried chmod -R 777 app, but it is unable to change the file mode on app. I am using XAMMP for developing. Can I install and publish this package without composer or something? UPDATE: I get the following error now: PHP Fatal error: Class 'League\OAuth2\Server\Storage\Adapter' not found in /Applications/XAMPP/xamppfiles/htdocs/api-dashboardv2/vendor/lucadegasperi/oauth2-server-laravel/src/Storage/FluentAdapter.php on line 18 {"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Class 'League\OAuth2\Server\Storage\Adapter' not found","file":"/Applications/XAMPP/xamppfiles/htdocs/api-dashboardv2/vendor/lucadegasperi/oauth2-server-laravel/src/Storage/FluentAdapter.php","line":18}} And, is it possible to set "minimum-stability": "dev" back to 'stable' and only get the dev version of the OAuth package? A: As others have mentioned you should be fine by giving it write permission as described in the Docs chmod -R 775 app/storage Note that 775 should be sufficient. Here's a nice answer pointing out the difference... Regarding the stability config in your composer.json You can define the stability on each package! "lucadegasperi/oauth2-server-laravel": "@dev" Composer docs Update [The bug has been fixed in the meantime] Apparently someone just made very recent changes to the project that broke some things. They are already trying to fix it... Github Issue
{ "pile_set_name": "StackExchange" }
Q: Deleting deep in an array with immutablejs I am trying to perform a complex deletion in Immutablejs, without, what I always seem to do, converting to JS in the middle of the process. In the following array, I would like to delete every second {y: } object series: [ { name:"1", data: [ {y: 1}, {y: 2}, {y: 3} ] }, { name:"2", data: [ {y: 1}, {y: 2}, {y: 3} ] }, { name:"3", data: [ {y: 1}, {y: 2}, {y: 3} ] } ] So that I would get this : series: [ { name:"1", data: [ {y: 1}, {y: 3} ] }, { name:"2", data: [ {y: 1}, {y: 3} ] }, { name:"3", data: [ {y: 1}, {y: 3} ] } ] Can someone point me in the correct direction how to do this with ImmutableJS? If I just use filter or array reduce I can arrive at a really clean solution that looks like this : series.forEach(function (elem) { let data = elem.data; data.splice(index, 1); }); I am just hoping that immutable has an equally clean looking solution. The doc for removeIn doesn't go deep enough : https://facebook.github.io/immutable-js/docs/#/removeIn A: You're modifying every element of series so I think you're on the right track with .map(). Then you want to use .removeIn to deeply remove something. let seriesList = Immutable.fromJS(series) seriesList = seriesList.map(elem => elem.removeIn(['data', indexToRemove])); // equivalent form with .update() instead of .removeIn() seriesList = seriesList.map(elem => elem.update('data', data => data.remove(indexToRemove)));
{ "pile_set_name": "StackExchange" }
Q: Use jQuery selector as method I have page with many inputs inside a set of different divs. A subset of those inputs are created dinamically and they can be also deleted. By creating and deleting elements i could have a list of inputs named as shown: <div id="first"> <input type="text" name="elem[0][elem_option][0][price]" value=""> <input type="text" name="elem[0][elem_option][1][price]" value=""> <input type="text" name="elem[0][elem_option][5][price]" value=""> <input type="text" name="elem[0][elem_option][21][price]" value=""> <input type="text" name="elem[3][elem_option][0][price]" value=""> <input type="text" name="elem[3][elem_option][1][price]" value=""> <input type="text" name="elem[3][elem_option][3][price]" value=""> <input type="text" name="elem[3][elem_option][8][price]" value=""> </div><!-- first --> <div id="second"> <input type="text" name="elem[1][elem_option][1][price]" value=""> <input type="text" name="elem[1][elem_option][2][price]" value=""> <input type="text" name="elem[1][elem_option][7][price]" value=""> <input type="text" name="elem[1][elem_option][8][price]" value=""> <input type="text" name="elem[5][elem_option][5][price]" value=""> <input type="text" name="elem[5][elem_option][6][price]" value=""> <input type="text" name="elem[5][elem_option][8][price]" value=""> <input type="text" name="elem[5][elem_option][9][price]" value=""> </div><!-- second--> .... I need to select all elements with a name that ends with [price] and save in a different variable of each div. I tried a jQuery selector used as method of getelementbyid: first_price_inputs = document.getElementById('first').jQuery('input[name$="[price]"]') second_price_inputs = document.getElementById('second').jQuery('input[name$="[price]"]') But i get this error: Uncaught TypeError: Object #<HTMLDivElement> has no method 'jQuery' please help! A: Try this: first_price_inputs = jQuery('#first input[name$="[price]"]'); second_price_inputs = jQuery('#second input[name$="[price]"]'); Look here: http://jsfiddle.net/qRDkq/
{ "pile_set_name": "StackExchange" }
Q: How to store temporary data in an Azure multi-instance (scale set) virtual machine? We developed a server service that (in a few words) supports the communications between two devices. We want to make advantage of the scalability given by an Azure Scale Set (multi instance VM) but we are not sure how to share memory between each instance. Our service basically stores temporary data in the local virtual machine and these data are read, modified and sent to the devices connected to this server. If these data are stored locally in one of the instances the other instances cannot access and do not have the same information. Is it correct? If one of the devices start making some request to the server the instance that is going to process the request will not always be the same so the data at the end is spread between instances. So the question might be, how to share memory between Azure instances? Thanks A: Depending on the type of data you want to share and how much latency matters, as well as ServiceFabric (low latency but you need to re-architect/re-build bits of your solution), you could look at a shared back end repository - Redis Cache is ideal as a distributed cache; SQL Azure if you want to use a relation db to store the data; storage queue/blob storage - or File storage in a storage account (this allows you just to write to a mounted network drive from both vm instances). DocumentDB is another option, which is suited to storing JSON data.
{ "pile_set_name": "StackExchange" }
Q: g++ unordered_map has no at() function? I've been developing using Visual Studio 2010, and then compiling a Linux 64 version on another machine. To cover the difference between the 2 different compilers/environments, we have conditional include statements: #ifdef __linux__ #include <tr1/unordered_map> #endif #ifdef _WIN32 #include <unordered_map> #endif using namespace std; // covers std::unordered_map using namespace std::tr1; // covers tr/unordered_map unordered_map<string,string> map; For unordered_map, I've been using this documentation: cplusplus.com, which shows an at() method to look up a key in the map. (Unlike the [] operator, this won't insert key into the map if not found.) When I tried to compile the code on the Linux machine, gcc throws an error saying test_map.cpp:18: error: 'class std::tr1::unordered_map, std::allocator >, std::basic_string, std::allocator >, std::tr1::hash, std::allocator > >, std::equal_to, std::allocator > >, std::allocator, std::allocator >, std::basic_string, std::allocator > > >, false>' has no member named 'at' The version of gcc on this machine is: g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46) I tried compiling on a newer install of Linux with version: gcc version 4.4.6 20120305 (Red Hat 4.4.6-4) (GCC) and got the same error. So my question has 2 parts: Is there a work around so I can still use the unordered_map.at() function? Where would I find the API docs for Linux unordered_map so I can be aware of any other discrepancies? (I looked at GNU online docs but I could figure out where to find the API reference that shows class and functions.) UPDATE I learned a lot from the responses posted here, so thanks to all. us2012's answer explained how to work around the compile issue, but in the end, I switched to using boost::unordered_map as suggested by John Dibling. (I decided to take everyone's warnings about the experimental C++11 support seriously, as well as also not wanting to inadvertently force a compiler setting on clients who are using our library.) This gave me a clean compile in both Windows and Linux, and no code change was required (other than removing the reference to std and tr1). Also I switched to use http://cppreference.com site, which has straightened me out with other problems already as well. (Surprisingly, this site never came up in any of my Google searches for C++ API docs.) Thanks again, for everyone's great explanations. A: You're in a pretty sticky spot. GCC 4.4.6, which is what's in the RHEL6 distro, is pre-C++11. The TR1 libraries predate C++11, and many of the components that were introduced to C++11 were signifigantly changed from TR1 before Standardization was complete. unordered_map is one of those components. In the TR1 days, unordered_map didn't have an at() member function. This is present in the C++11 spec. Your VS2010 compiler is using the C++11 spec (at least for unordered_map, to a degree), but GCC 4.4.6 has no concept of C++11. You are compiling against 2 different languages, in effect. It's all still C++, at least at some level, so there should be an opportunity to find some common ground. For what it's worth, I don't think that I would personally use anything from TR1 for production work -- but that's me. As suggested elsewhere, to achieve the same effect you can find the key. The bottom line for you I think is this. In GCC 4.4, C++0x support (note I don't say C++11) is experimental. If it were me, I would not use any of the std=c++0x functionality for production work. I would also not use TR1 for production work. This leaves you three choices: Don't use a hash map at all Use a hash map from Boost, or another reputable 3rd party library Write your own hash map. A: GCC 4.4 already supports these features as part of -std=c++0x. There is no need for the tr1 namespace, and the include can just be <unordered_map>. Either way, don't be too liberal with using namespace, especially with namespaces that may have considerable overlap, this becomes a big problem. For more information about the use of namespaces, have a look at GOTW.
{ "pile_set_name": "StackExchange" }
Q: Filtering Values in Pandas Dataframe or Series I am trying to filter values from a column in a pandas Dataframe but I seem to be receiving booleans instead of actual values. I am trying to filter our data by month and year. In the code following below you will see I am only filtering out by year but I have tried month and year multiple times in different ways: In [1]: import requests In [2]: import pandas as pd # pandas In [3]: import datetime as dt # module for manipulating dates and times In [4]: url = "http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.csv" In [5]: source = requests.get(url).text In [6]: from io import StringIO, BytesIO In [7]: s = StringIO(source) In [8]: election_data = pd.DataFrame.from_csv(s, index_col=None).convert_objects(convert_dates="coerce", convert_numeric=True) In [9]: election_data.head(n=3) Out[9]: Pollster Start Date End Date Entry Date/Time (ET) \ 0 Politico/GWU/Battleground 2012-11-04 2012-11-05 2012-11-06 08:40:26 1 YouGov/Economist 2012-11-03 2012-11-05 2012-11-26 15:31:23 2 Gravis Marketing 2012-11-03 2012-11-05 2012-11-06 09:22:02 Number of Observations Population Mode Obama Romney \ 0 1000.0 Likely Voters Live Phone 47.0 47.0 1 740.0 Likely Voters Internet 49.0 47.0 2 872.0 Likely Voters Automated Phone 48.0 48.0 Undecided Other Pollster URL \ 0 6.0 NaN http://elections.huffingtonpost.com/pollster/p... 1 3.0 NaN http://elections.huffingtonpost.com/pollster/p... 2 4.0 NaN http://elections.huffingtonpost.com/pollster/p... Source URL Partisan Affiliation \ 0 http://www.politico.com/news/stories/1112/8338... Nonpartisan None 1 http://cdn.yougov.com/cumulus_uploads/document... Nonpartisan None 2 http://www.gravispolls.com/2012/11/gravis-mark... Nonpartisan None Question Text Question Iteration 0 NaN 1 1 NaN 1 2 NaN 1 In [10]: start_date = pd.Series(election_data["Start Date"]) ...: start_date.head(n=3) ...: Out[10]: 0 2012-11-04 1 2012-11-03 2 2012-11-03 Name: Start Date, dtype: datetime64[ns] In [11]: filtered = start_date.map(lambda x: x.year == 2012) In [12]: filtered Out[12]: 0 True 1 True 2 True ... 587 False 588 False 589 False Name: Start Date, dtype: bool A: I think you need read_csv with url address first and then boolean indexing with mask created by year and month: election_data = pd.read_csv('http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.csv', parse_dates=[1,2,3]) print (election_data.head(3)) Pollster Start Date End Date Entry Date/Time (ET) \ 0 Politico/GWU/Battleground 2012-11-04 2012-11-05 2012-11-06 08:40:26 1 YouGov/Economist 2012-11-03 2012-11-05 2012-11-26 15:31:23 2 Gravis Marketing 2012-11-03 2012-11-05 2012-11-06 09:22:02 Number of Observations Population Mode Obama Romney \ 0 1000.0 Likely Voters Live Phone 47.0 47.0 1 740.0 Likely Voters Internet 49.0 47.0 2 872.0 Likely Voters Automated Phone 48.0 48.0 Undecided Other Pollster URL \ 0 6.0 NaN http://elections.huffingtonpost.com/pollster/p... 1 3.0 NaN http://elections.huffingtonpost.com/pollster/p... 2 4.0 NaN http://elections.huffingtonpost.com/pollster/p... Source URL Partisan Affiliation \ 0 http://www.politico.com/news/stories/1112/8338... Nonpartisan None 1 http://cdn.yougov.com/cumulus_uploads/document... Nonpartisan None 2 http://www.gravispolls.com/2012/11/gravis-mark... Nonpartisan None Question Text Question Iteration 0 NaN 1 1 NaN 1 2 NaN 1 print (election_data.dtypes) Pollster object Start Date datetime64[ns] End Date datetime64[ns] Entry Date/Time (ET) datetime64[ns] Number of Observations float64 Population object Mode object Obama float64 Romney float64 Undecided float64 Other float64 Pollster URL object Source URL object Partisan object Affiliation object Question Text float64 Question Iteration int64 dtype: object election_data[election_data["Start Date"].dt.year == 2012] election_data[(election_data["Start Date"].dt.year == 2012) & (election_data["Start Date"].dt.month== 10)] A: you can use pandas date filtering if you make Start Date the index get all of 2012 election_data.set_index('Start Date')['2012'] get all of Jan, 2012 election_data.set_index('Start Date')['2012-01'] get all between Jan 1, 2012 and Jan 13, 2012 election_data.set_index('Start Date')['2012-01-01':'2012-01-13]
{ "pile_set_name": "StackExchange" }
Q: HTML5 Placeholder Attribute on Textarea via jQuery in IE10 i was wondering about some weird behaviour in Internet Explorer 10. On my page, I am adding a textarea with jquery, including a placeholder attribute. Something like this: $('body').append($('<textarea placeholder="Placeholder..."></textarea>')); The placeholder attribute works perfectly fine in IE10 usually... except in this case. I tested it with elements being already on the page in this fiddle: http://jsfiddle.net/Aqnt5/1/ As you can see, one textarea (the one added dynamically) treats the placeholder attribute like an actual value - the most annoying behaviour I could imagine... Does anyone know of this effect and maybe also a workaround? Thanks in advance! EDIT I also just realised that it works as expected, after you remove the value by hand. You can remove it via jQuery.val('') as well to make it work. I am really confused by this behaviour... But this should be a suitable 'workaround'. See this fiddle: http://jsfiddle.net/Aqnt5/5/ A: Unfortunately I do not have IE10 to test this on, but this works everywhere else; $('body').append('<textarea></textarea>'); $('textarea').attr('placeholder', 'placeholder'); And just double-check that your DOCTYPE is correct for HTML5 Here is a one-liner (broken into several lines here to make it more visible) that you can also do - $('body') .append('<textarea></textarea>') .find('textarea') .attr('placeholder', 'placeholder'); A: Fiddle: http://jsfiddle.net/Aqnt5/5/ You can remove the value with jQuery, to make it behave correctly: $('body').append($('<textarea placeholder="Placeholder..."></textarea>').val('')); I dont know why they put the placeholder as a value in the first place...
{ "pile_set_name": "StackExchange" }
Q: How to invalidate $http call with cache:true when header changes I'm fetching a remote resource and caching the result: $http({ method:'GET', cache:true, url:'...' }); This works fine. However, when the user changes the languge in the UI, I also change the Accept-Language header on all AJAX calls. The problem is caching is done based on URL so if a call is made using en-US as Accept-Language that gets cached and any other calls, regardless of language, are served from cache. I don't want to add the language to the URL. What are my options? A: $cacheFactory can be used to invalidate cache when the user changes language. You could try to decorate it, or use wrap it in a service perhaps
{ "pile_set_name": "StackExchange" }
Q: A Function That Creates "Hello World!" The classic string "Hello world!" can be translated to list of characters with ascii-codes: [72; 101; 108; 108; 111; 32; 87; 111; 114; 108; 100; 33] Is there a mathematical function to generate this sequence of numbers (without explicitly enumerating them)? A: Yes, see below but you probably do not want this. It is certainly less compact than the original list of values because you have to store more than twice the amount of data, if you want exact rational coefficients. Moreover, if you're writing a program, beware that 19531322383 does not fit in 32 bits. http://www.wolframalpha.com/input/?i=interpolate+72+101+108+108+111+32+87+111+114+108+100+33
{ "pile_set_name": "StackExchange" }
Q: Remove empty columns by awk I have a input file, which is tab delimited, but I want to remove all empty columns. Empty columns : $13=$14=$15=$84=$85=$86=$87=$88=$89=$91=$94 INPUT: tsv file with more than 90 columns a b d e g... a b d e g... OUTPUT: tsv file without empty columns a b d e g.... a b d e g... Thank you A: This might be what you want: $ printf 'a\tb\tc\td\te\n' a b c d e $ printf 'a\tb\tc\td\te\n' | awk 'BEGIN{FS=OFS="\t"} {$2=$4=""} 1' a c e $ printf 'a\tb\tc\td\te\n' | awk 'BEGIN{FS=OFS="\t"} {$2=$4=RS; gsub("(^|"FS")"RS,"")} 1' a c e Note that the above doesn't remove all empty columns as some potential solutions might do, it only removes exactly the column numbers you want removed: $ printf 'a\tb\t\td\te\n' a b d e $ printf 'a\tb\t\td\te\n' | awk 'BEGIN{FS=OFS="\t"} {$2=$4=RS; gsub("(^|"FS")"RS,"")} 1' a e A: remove ALL empty columns: If you have a tab-delimited file, with empty columns and you want to remove all empty columns, it implies that you have multiple consecutive tabs. Hence you could just replace those with a single tab and delete then the first starting tab if you also removed the first column: sed 's/\t\+/\t/g;s/^\t//' <file> remove SOME columns: See Ed Morton or just use cut: cut --complement -f 13,14,15,84,85,86,87,88,89,91,94 <file> remove selected columns if and only if they are empty: Basically a simple adaptation from Ed Morton : awk 'BEGIN{FS=OFS="\t"; n=split(col,a,",")} { for(i=1;i<=n;++i) if ($a[i]=="") $a[i]=RS; gsub("(^|"FS")"RS,"") } 1' col=13,14,15,84,85,86,87,88,89,91,94 <file>
{ "pile_set_name": "StackExchange" }
Q: Maze generation prim algorithm not all cells are traversed I'm trying to implement Prim maze generation algorithm: Start with a grid full of walls. Pick a cell, mark it as part of the maze. Add the walls of the cell to the wall list. While there are walls in the list: Pick a random wall from the list. If the cell on the opposite side isn't in the maze yet: Make the wall a passage and mark the cell on the opposite side as part of the maze. Add the neighboring walls of the cell to the wall list. If the cell on the opposite side already was in the maze, remove the wall from the list. Removing some implementation details my implementation looks like this: Cell[][] maze is the matrix with cells. each cell has left/right/up/button walls. the frontiers walls marked as boolean frontier and are not part of implementation because I want to keep my maze framed. public Cell[][] prim(){ List<Wall> walls = new ArrayList<Wall>(); //Pick a cell, mark it as part of the maze int initialCellI = rnd(sizeX)-1; int initialCellJ = rnd(sizeY)-1; Cell randomCell = maze[initialCellI][initialCellJ]; randomCell.setPartOftheMaze(true); //Add the walls of the cell to the wall list. if ((randomCell.getLeft() != null) && (!randomCell.getLeft().isFrontier())) walls.add(randomCell.getLeft()); if ((randomCell.getRight() != null) && (!randomCell.getRight().isFrontier())) walls.add(randomCell.getRight()); if ((randomCell.getButtom() != null) && (!randomCell.getButtom().isFrontier())) walls.add(randomCell.getButtom()); if ((randomCell.getUp() != null) && (!randomCell.getUp().isFrontier())) walls.add(randomCell.getUp()); //While there are walls in the list: while (!walls.isEmpty()){ //Pick a random wall from the list. Wall randomWall = randomElement(walls); //pick the cell opposite to this wall. Cell opositeSideCell = getNeightbourCell(randomWall, maze); if (opositeSideCell.isPartOftheMaze()){ //If the cell on the opposite side already was in the maze, remove the wall from the list. walls.remove(randomWall); } else{ // Make the wall a passage and mark the cell on the opposite side as part of the maze. this.removeWall(randomWall, maze); opositeSideCell.setPartOftheMaze(true); //Add the walls of the cell to the wall list. if ((opositeSideCell.getLeft() != null) && (!opositeSideCell.getLeft().isFrontier())) walls.add(opositeSideCell.getLeft()); if ((opositeSideCell.getRight() != null) && (!opositeSideCell.getRight().isFrontier())) walls.add(opositeSideCell.getRight()); if ((opositeSideCell.getButtom() != null) && (!opositeSideCell.getButtom().isFrontier())) walls.add(opositeSideCell.getButtom()); if ((opositeSideCell.getUp() != null) && (!opositeSideCell.getUp().isFrontier())) walls.add(opositeSideCell.getUp()); } } return maze; } My problem is that my maze is not completed and not all cells are traversed. Sometimes a few cells only traversed, almost all cells are done. I believe I'm missing something bur can't figure out what. Please help. See picture below for partial traversed maze. A: Well, I solved this issue. This pure Java issue and has nothing to do with algorithm. I compared between two walls. public class Wall{ Point p1; Point p2; } public class Point{ int x; int y; } If I implement Wall class equals() and hashCode() using p1 and p2. then in leftCell.rightWall will be equal to rightCell.leftWall and it was the problem.
{ "pile_set_name": "StackExchange" }
Q: Servlet.service() for servlet LoginController threw exception java.lang.ClassNotFoundException: Decoder.BASE64Encoder Servlet.service() for servlet LoginController threw exception java.lang.ClassNotFoundException: Decoder.BASE64Encoder try{ String pass=request.getParameter("password"); String plainData=pass,cipherText,decryptedText; KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); Cipher aesCipher = Cipher.getInstance("AES"); aesCipher.init(Cipher.ENCRYPT_MODE,secretKey); byte[] byteDataToEncrypt = plainData.getBytes(); byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt); cipherText=new BASE64Encoder().encode(byteCipherText); System.out.println("cipherText"+cipherText); ld=new LoginDao(); String encryptedpass=ld.validatepass(cipherText); System.out.println(); } catch(Exception ex){ } A: Add commons-codec jar in lib directory of your web project and use new Base64().encodeToString(String) to encode Your Web application war file structure is like WebContent --- WEB-INF ----web.xml (Deployment Descriptor) ---- lib --- Add your libraries here i.e.common-codec.jar and others
{ "pile_set_name": "StackExchange" }
Q: Проблема с размерами изображений Есть картинка 0.jpg ее вес: 109 кб, размер: 1920x1080. Когда закидываю в Unity, показывает вес 5.9 мб, это как понимать? Когда навожу на картинку в Unity, мне в конце показывает: Only POT textures can be compressed to ETC1 format Сколько не пытался искать про этот формат, ни как не пойму, что нужно сделать то? Если я пытаюсь в вкладке Import Settings -> Android Settings Пытаюсь поставить ETC1, сжатие, мне пишет: Cannot compress to ETC1. The split alpha channel and compression to ETC1 requires a packing tag. Помогите разобраться, что нужно сделать с картинкой, чтобы она весила столько же сколько и должна? Я вообще не понимаю, как мне такой формат конвертнуть и что нужно вообще сделать? Главное, чтобы качество не потерялось, а то иначе это бессмысленность какая-то. A: Слова качество и .jpg ставить рядом это преступление. Несмотря на то, что формат остаётся .jpg, при импорте юнити меняет кодировку с сжатой на что-то вроде .png, только хуже, отсуда и вес. С сжатой версии работать в реальном времени не возможно, там нет записей о пикселях, её ещё расшифровывать и реконструировать нужно, поэтому с .jpg в реал-тайм рендере вообще дел не имеют. Собственно она весит ровно "столько же сколько и должна" на самом деле. Если картинка будет изначально в .png весить будет меньше. POT (Power Of Two) длина и ширина картинки должна быть кратна двум. Что касается второго сообщения, на и на тебе в помощь. П.C. ты в принципе хренью страдаешь. Атласные паки для объединения множества мелких картинок в одну, это экономит draw call при рендеринге, а не ради веса. Вес уменьшается только в специализированном совте... графические редакторы и текстурпаки. А с одной большой картинкой без толку, в этом нет смысла.
{ "pile_set_name": "StackExchange" }
Q: How can I make an arrow from a point in one axis to a point in another? I have created this bit of code, which is the beginning of an illustration of how a neighborhood around a point in a manifold maps to a region in the plane: \documentclass{standalone} \usepackage{pgfplots} \usetikzlibrary{calc} \pgfplotsset{compat=1.12} \begin{document} \begin{tikzpicture} \begin{axis}[ name=mfd, declare function={ f(\x,\y)=10-(\x^2+\y^2); }, declare function={ c_x(\t)=(cos(\t)+(sin(5*\t)/10))/3+1; }, declare function={ c_y(\t)=(sin(\t))/2-1; }, declare function={ c_z(\t)=f(c_x(\t),c_y(\t)); }, ] \addplot3[surf,domain=-2:2,domain y=-2:2,]{f(x,y)}; \addplot3[black,opacity=1.0,variable=t,domain=0:360,dashed,thin] ({c_x(t)},{c_y(t)},{c_z(t)}); \addplot3[black,opacity=1.0,only marks,mark=text,text mark=$\cdot$] (1,-1,{f(1,-1)}); \end{axis} \begin{axis}[ at={($(mfd.north east)+(1cm,-5cm)$)}, anchor=north west, declare function={ c_x(\t)=(cos(\t)+(sin(5*\t)/10))/3+1; }, declare function={ c_y(\t)=(sin(\t))/2-1; } ] \addplot[variable=t,domain=0:360]({c_x(t)},{c_y(t)}); \addplot[black,opacity=1.0,only marks,mark=text,text mark=$\cdot$] (1,-1); \end{axis} \end{tikzpicture} \end{document} However, I'm struggling to find the best way to make an arrow from the dot in the middle of the (topological) circle on the 3D surface to the corresponding point int the plane, since they are in separate axis environments. Is there a good way to do this? A: Add a coordinate at the end of each of the plots, and then draw a normal arrow after the second axis. \documentclass{standalone} \usepackage{pgfplots} \usetikzlibrary{calc} \pgfplotsset{compat=1.12} \begin{document} \begin{tikzpicture} \begin{axis}[ name=mfd, declare function={ f(\x,\y)=10-(\x^2+\y^2); }, declare function={ c_x(\t)=(cos(\t)+(sin(5*\t)/10))/3+1; }, declare function={ c_y(\t)=(sin(\t))/2-1; }, declare function={ c_z(\t)=f(c_x(\t),c_y(\t)); }, ] \addplot3[surf,domain=-2:2,domain y=-2:2,]{f(x,y)}; \addplot3[black,opacity=1.0,variable=t,domain=0:360,dashed,thin] ({c_x(t)},{c_y(t)},{c_z(t)}); \addplot3[black,opacity=1.0,only marks,mark=text,text mark=$\cdot$] (1,-1,{f(1,-1)}) coordinate (a); \end{axis} \begin{axis}[ at={($(mfd.north east)+(1cm,-5cm)$)}, anchor=north west, declare function={ c_x(\t)=(cos(\t)+(sin(5*\t)/10))/3+1; }, declare function={ c_y(\t)=(sin(\t))/2-1; } ] \addplot[variable=t,domain=0:360]({c_x(t)},{c_y(t)}); \addplot[black,opacity=1.0,only marks,mark=text,text mark=$\cdot$] (1,-1) coordinate (b); \end{axis} \draw [-stealth,shorten <=3pt,shorten >=3pt] (a) to[bend left] (b); \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Limiting the number of characters in a JTextField I want to set the maximum length of a JTextField, so that you can't enter more characters than the limit. This is the code I have so far... textField = new JTextField(); textField.setBounds(40, 39, 105, 20); contentPane.add(textField); textField.setColumns(10); Is there any simple way to put a limit on the number of characters? A: You can do something like this (taken from here): import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; class JTextFieldLimit extends PlainDocument { private int limit; JTextFieldLimit(int limit) { super(); this.limit = limit; } JTextFieldLimit(int limit, boolean upper) { super(); this.limit = limit; } public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if (str == null) return; if ((getLength() + str.length()) <= limit) { super.insertString(offset, str, attr); } } } public class Main extends JFrame { JTextField textfield1; JLabel label1; public void init() { setLayout(new FlowLayout()); label1 = new JLabel("max 10 chars"); textfield1 = new JTextField(15); add(label1); add(textfield1); textfield1.setDocument(new JTextFieldLimit(10)); setSize(300,300); setVisible(true); } } Edit: Take a look at this previous SO post. You could intercept key press events and add/ignore them according to the current amount of characters in the textfield. A: Since the introduction of the DocumentFilter in Java 1.4, the need to override Document has been lessoned. DocumentFilter provides the means for filtering content been passed to the Document before it actually reaches it. These allows the field to continue to maintain what ever document it needs, while providing the means to filter the input from the user. import java.awt.EventQueue; import java.awt.GridBagLayout; import javax.swing.JFrame; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; public class LimitTextField { public static void main(String[] args) { new LimitTextField(); } public LimitTextField() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JTextField pfPassword = new JTextField(20); ((AbstractDocument)pfPassword.getDocument()).setDocumentFilter(new LimitDocumentFilter(15)); JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new GridBagLayout()); frame.add(pfPassword); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class LimitDocumentFilter extends DocumentFilter { private int limit; public LimitDocumentFilter(int limit) { if (limit <= 0) { throw new IllegalArgumentException("Limit can not be <= 0"); } this.limit = limit; } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { int currentLength = fb.getDocument().getLength(); int overLimit = (currentLength + text.length()) - limit - length; if (overLimit > 0) { text = text.substring(0, text.length() - overLimit); } if (text.length() > 0) { super.replace(fb, offset, length, text, attrs); } } } } A: It's weird that the Swing toolkit doesn't include this functionality, but here's the best answer to your question: textField = new JTextField(); textField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { if (txtGuess.getText().length() >= 3 ) // limit to 3 characters e.consume(); } }); I use this in a fun guessing game example in my Udemy.com course "Learn Java Like a Kid". Cheers - Bryson
{ "pile_set_name": "StackExchange" }
Q: Javascript Gross & Net Pay Calculator So I am making an elementary gross pay and net pay calculator in javascript/HTML. The webpage calculator takes the user inputted hours and rate, and spits out gross pay, and gross pay with tax. For some reason, it won't display the correct formula. Somewhere I made a grave error. If someone can steer me in the right direction that would be awesome. Heres the code: <!DOCTYPE html> <html> <title>Gross + Net Pay</title> <h1>Gross + Net Pay Calculator</h1> <p id="demo"></p> <p id="demo2"></p> <script> function myFunction() { var rate = document.getElementById("payrate"); var hours =document.getElementById("hours"); var gross = hours * rate var net = gross * .9 if (gross != null) { document.getElementById("demo").innerHTML = gross; } if (net != null) { document.getElementById("demo2").innerHTML =net; } } </script> <body> <form> Pay Rate: <input type="text" id="payrate"><br> Hours Worked: <input type="text" id="hours"><br> <input type="submit" value="Calculate Gross + Net Pay" onclick="myFunction()"> </form> </body> </html> A: Here is the corrected code. You had some typos, missing colons and you are also posting this via form. You don't need that unless you are handling this info in a different page. <!DOCTYPE html> <html> <title>Gross + Net Pay</title> <h1>Gross + Net Pay Calculator</h1> <p id="demo"></p> <p id="demo2"></p> <script> function myFunction() { var rate = document.getElementById("payrate").value; var hours =document.getElementById("hours").value; var gross = hours * rate; var net = gross * .9 ; if (gross != null) { document.getElementById("demo").innerHTML = gross; } if (net != null) { document.getElementById("demo2").innerHTML =net; } } </script> <body> Pay Rate: <input type="text" id="payrate"><br> Hours Worked: <input type="text" id="hours"><br> <input type="submit" value="Calculate Gross + Net Pay" onclick="myFunction()"> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: NodeJS, Socket IO session and Express session I'm using https://www.npmjs.com/package/express-socket.io-session to sync my sessions between socket.io and express.However, when I set a session via socket.io (with socket.handshake.session.foo for example), I can't access on it with express: I got undefined with req.session.foo.How can I solve that? What's the problem?Here's: my code of app.js: // Requires global.config = require("./config.js"); var express = require("express"); var session = require("express-session"); global.sha1 = require("sha1"); global.moment = require("moment"); var rhandler = require("./handler.js"); global.mySQL = require("./mysql.js"); var entities = new require("html-entities").XmlEntities; global.Users = {}; var app = express(); var server = require("http").createServer(app).listen(config.server.port); global.Handler = new rhandler(); app.set("view engine", "ejs"); app.use("/assets", express.static("public")); var socketIO = require("socket.io"); var io = socketIO.listen(server); var session = require("express-session")({ secret: config.express.secret, resave: true, saveUninitialized: true }); var sharedsession = require("express-socket.io-session"); // Use express-session middleware for express app.use(session); // Use shared session middleware for socket.io // setting autoSave:true io.use(sharedsession(session, { autoSave:true })); io.sockets.on("connection", function(socket) { socket.on("login", function(obj, callback) { socket.handshake.session.test = "test"; }); }); app.get("/", function(req, res) { console.log(req.session.test); res.end(); }); A: Making my comments into an answer since it solved your problem. Per the doc, you should be accessing socket.handshake.session.foo, not socket.handshake.foo. And, to retain a modification to the session, I've found you need to add socket.handshake.session.save() after modifying the session.
{ "pile_set_name": "StackExchange" }
Q: Autowiring two beans implementing same interface - how to set default bean to autowire? Background: I have a Spring 2.5/Java/Tomcat application. There is the following bean, which is used throughout the application in many places public class HibernateDeviceDao implements DeviceDao and the following bean which is new: public class JdbcDeviceDao implements DeviceDao The first bean is configured so (all beans in the package are included) <context:component-scan base-package="com.initech.service.dao.hibernate" /> The second (new) bean is configured separately <bean id="jdbcDeviceDao" class="com.initech.service.dao.jdbc.JdbcDeviceDao"> <property name="dataSource" ref="jdbcDataSource"> </bean> This results (of course) in an exception when starting the server: nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.sevenp.mobile.samplemgmt.service.dao.DeviceDao] is defined: expected single matching bean but found 2: [deviceDao, jdbcDeviceDao] from a class trying to autowire the bean like this @Autowired private DeviceDao hibernateDevicDao; because there are two beans implementing the same interface. The question: Is it possible to configure the beans so that 1. I don't have to make changes to existing classes, which already have the HibernateDeviceDao autowired 2. still being able to use the second (new) bean like this: @Autowired @Qualifier("jdbcDeviceDao") I.e. i would need a way to configure the HibernateDeviceDao bean as the default bean to be autowired, simultaneously allowing the usage of a the JdbcDeviceDao when explicitly specifying so with the @Qualifier annotation. What I've already tried: I tried setting the property autowire-candidate="false" in the bean configuration for JdbcDeviceDao: <bean id="jdbcDeviceDao" class="com.initech.service.dao.jdbc.JdbcDeviceDao" autowire-candidate="false"> <property name="dataSource" ref="jdbcDataSource"/> </bean> because the Spring documentation says that Indicates whether or not this bean should be considered when looking for matching candidates to satisfy another bean's autowiring requirements. Note that this does not affect explicit references by name, which will get resolved even if the specified bean is not marked as an autowire candidate.* which I interpreted to mean that I could still autowire JdbcDeviceDao using the @Qualifier annotation and have the HibernateDeviceDao as default bean. Apparently my interpretation was not correct, though, as this results in the following error message when starting the server: Unsatisfied dependency of type [class com.sevenp.mobile.samplemgmt.service.dao.jdbc.JdbcDeviceDao]: expected at least 1 matching bean coming from the class where I've tried autowiring the bean with a qualifier: @Autowired @Qualifier("jdbcDeviceDao") Solution: skaffman's suggestion to try the @Resource annotation worked. So the configuration has autowire-candidate set to false for jdbcDeviceDao and when using the jdbcDeviceDao I refer to it using the @Resource annotation (instead of @Qualifier): @Resource(name = "jdbcDeviceDao") private JdbcDeviceListItemDao jdbcDeviceDao; A: I'd suggest marking the Hibernate DAO class with @Primary, i.e. (assuming you used @Repository on HibernateDeviceDao): @Primary @Repository public class HibernateDeviceDao implements DeviceDao This way it will be selected as the default autowire candididate, with no need to autowire-candidate on the other bean. Also, rather than using @Autowired @Qualifier, I find it more elegant to use @Resource for picking specific beans, i.e. @Resource(name="jdbcDeviceDao") DeviceDao deviceDao; A: What about @Primary? Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML. @Primary public class HibernateDeviceDao implements DeviceDao Or if you want your Jdbc version to be used by default: <bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao"> @Primary is also great for integration testing when you can easily replace production bean with stubbed version by annotating it. A: For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.
{ "pile_set_name": "StackExchange" }
Q: What am I missing about PHP? It's like this mythical thing that a dominating portion of developers say is just the best option for back-end development, a part of development about which I know virtually nothing beyond the absolute basics. So I've looked up PHP tutorials a bunch of times, trying to figure out why it's so powerful and common, but it's annoying as hell-- all the tutorials treat you like a new programmer. You know, this is how you make an If Else statement, here's a for loop, etc. The "Advanced Topics" show you how to make POST and GET statements and whatnot. But there must be more to it! I don't get it! That's practically no different from JavaScript. What am I missing about this language? What else can it do? Where's the power and versatility? I've heard it called a function soup; where are all the functions? Please chide me. I'm clearly missing something. A: PHP is terrible. For more information you can check Php a fractal of bad design I have been working with it close to 13 years now, the last 5 not as a hobby, not even dared to jump deep into its OO capabilities, and I am still finding bugs, gotchas, ahas and plain insane behavior on daily basis. So if you want to find something unique in PHP that elevates it beyond the other languages - there isn't. So why it became the alpha dog then: You have no choice - unless you start a project from scratch there is usually something already written in PHP that works. (inertia) It was extremely easy to prototype and iterate - this is more of a historical reason, there are other languages that are good at that now, but c. 1999 there weren't many of them. Played nice with apache, mysql and was free - maybe the most important thing in this list. Hosting was easy to find Easy database access - there were dark times when there were such things as DAO with wild recordsets out to get you. For a mfc developer the idea that your whole DB layer was mysql_connect, mysql_query with simple sql was a godsend. Simple tool for a simple task - php is really good at getting data from a DB and putting it in a punched hole in your html. And at the dawn of time that was website development. A: The big reason for PHP's popularity can also be attributed to its ease of use. Anyone (quite literally) can program simple PHP after checking out a few examples of code and trying it a few times. Other web programming languages require a whole lot more effort to create even the simplest of programs, and barring C and Java, there's not much in the way of online examples. Most people don't want to install humongous IDEs, build a dedicated web server, and arrange for a DNS, when all they want is to spice up their website with some extra features. Perhaps they have heard enough horror stories about Javascript that they want to use something else. In comes PHP. No IDE required, just any regular text editor that comes pre-installed in pretty much all computers. Then just upload a couple of files to a web host, maybe adjust permissions for a few files, and that's it. Fire and forget, if you please. Certainly not pretty or elegant, but it works and is quick. Testing is just pressing F5, without any compiling, delivering, and deploying. For something more elaborate, just a quick install of WAMP/LAMP, and change a couple of settings in a text file, and off you go in the comfort of your home computer in an environment that is almost "real", so you can easily see the changes on the fly. I highlighted a few points which I feel are the biggest reason for PHP's popularity. A: Check out http://www.php.net/manual/en/ It's tough to really list all the things you can do with server-side code over client-side code, although if someone else made such a list I would find it really interesting. It's certainly very easy to think of things that you should do on the server-side, since on the client side anyone can read and modify your code.
{ "pile_set_name": "StackExchange" }
Q: the transition of a creates a border on an other element If you hover between the two borders, you'll get an ugly (but very small) border around them. Can someone help me (and please explain me why I get this result)? I tried to set a transparent border on every element - but with no effect. Best regards, Sandro * { margin: 0; padding: 0; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; } .content { height: 100vh; width: 50vw; position: absolute; left: 50%; transform: translateX(-50%); } .content .line-left { width: 3px; height: 100%; background-color: #286090; position: absolute; left: 25px; bottom: 0; } .content .line-left::after { content: ''; width: 3px; height: 100%; background-color: #bfbfbf; position: absolute; bottom: 0; } .content .line-right { width: 3px; height: 100%; background-color: #286090; position: absolute; top: 0; right: 25px; } .content .line-right::after { content: ''; width: 3px; height: 100%; background-color: #bfbfbf; position: absolute; top: 0; } .content:hover .line-left::after, .content:hover .line-right::after { height: 0; transition: height 2s cubic-bezier(.15,.65,1,.15); } <div class="content"> <div class="line-left"></div> <div class="line-right"></div> </div> A: It seems to be a rendring issue. Here is another idea to obtain the same effect without issue and with less of code. We define 4 lines with gradient: two on each side and at the same position. On hover we simply decrease the height of the grey ones and we increase the height of the blue ones. The top/bottom will define the direction of the animation: * { margin: 0; padding: 0; box-sizing: border-box; } .content { height: 100vh; width: 50vw; position: absolute; left: 50%; transform: translateX(-50%); background: linear-gradient(#286090,#286090) bottom 0 right 25px, linear-gradient(#bfbfbf,#bfbfbf) top 0 right 25px, linear-gradient(#286090,#286090) top 0 left 25px, linear-gradient(#bfbfbf,#bfbfbf) bottom 0 left 25px; background-size:3px 0, 3px 100%; background-repeat:no-repeat; transition:2s cubic-bezier(.15, .65, 1, .15); } .content:hover { background-size:3px 100%, 3px 0; } <div class="content"> </div>
{ "pile_set_name": "StackExchange" }
Q: Test if a font is installed (Win32) How can I test if a font is installed? Ultimately, I want to implement a HTML-like font selection, i.e. when specifying e.g. "Verdana,Arial", it should pick the first font that is installed. This Question provides an answer for .NET - it seems the recommended way is to create the font, and then cmpare the font face actually used. Is that the most efficient way? A: You can either try to create the font and see what you get (thus using the OS's font name matching/substitution). Or you can enumerate installed fonts and do that matching yourself. The "most efficient" way will depend on the details of a "match", and, in all likelihood, how many fonts are installed. On a system with, say, 50 fonts you will probably find performance is significantly different to a system with 1000 fonts installed. In the end you can only profile on representative systems, if you first approach (keep it simple) turns out to be a performance bottleneck. A: You can use EnumFontFamiliesEx to enumerate the list of Fonts on the system, or if you pass a font name you can enumerate the fonts for that family.
{ "pile_set_name": "StackExchange" }
Q: Obtaining the split value after java string split I have a string that is dynamially generated. I need to split the string based on the Relational Operator. For this I can use the split function. Now I would also like to know that out of the regex mentioned above, based on which Relational Operator was the string actually splitted. An example, On input String sb = "FEES > 200"; applying List<String> ls = sb.split(">|>=|<|<=|<>|="); System.out.println("Splitted Strings: "+s); will give me the result, Splitted strings: [FEES , 200 ] But expecting result: Splitted strings: [FEES , 200 ] Splitted Relational Operator: > A: You could use 3 capturing groups with an alternation for the second group: (.*?)(>=|<=|<>|>|<)(.*) Regex demo Explanation (.*?) Match any character zero or more times non greedy (>=|<=|<>|>|<) Match either >= or <= or <> or > or < (.*) Match any character zero or more times For example: String regex = "(.*?)(>=|<=|<>|>|<)(.*)"; String string = "FEES >= 200"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(string); if(matcher.find()) { System.out.println("Splitted Relational Operator: " + matcher.group(2)); System.out.println("Group 1: " + matcher.group(1) + " group 3: " + matcher.group(3)); } Demo java A: I suggest to use regex, which is more flexible in your case. String sb = "FEES > 200"; Pattern pat = Pattern.compile("(.*?)(>=|<=|<>|=|>|<)(.*)"); Matcher mat = pat.matcher(sb); if (mat.find()) { System.out.println("Groups: " + mat.group(1) + ", " + mat.group(3)); System.out.println("Operator: " + mat.group(2)); }
{ "pile_set_name": "StackExchange" }
Q: How do I force an input to stay on the same line as its label with Bootstrap form-control class? I'm trying to force a <label/> and its <input/> to stay on the same line. I'm using the form-control class to make the <input/> pretty. However, when I do so, it REALLY wants to put itself on a separate line. I'm avoiding using rows and columns because I want the label right next to the textbox, not to move around depending on the size of the screen. <div> <label class="form-label">Search</label> <input type="text" class="form-control"> </div> I want this: Search [______________________] I get this: Search [_____________________] How do I force them to stay on the same line? http://embed.plnkr.co/qA2s5RGRpvfRa7rhiq1n/preview A: What you are looking for is referred by Bootstrap as an inline form or horizontal form. <form class="form-inline" role="form"> <div class="form-group"> <label class="form-label">Search</label> <input type="text" class="form-control"> </div> </form> Make sure your form has the form-inline class on it and realistically they should be wrapped in a form-group. The inline form make everything in one line. <form class="form-horizontal" role="form"> <div class="form-group"> <label class="col-sm-2 control-label">Search</label> <div class="col-sm-10"> <input type="text" class="form-control"> </div> </div> </form> When using form-horizontal, the form-group acts like a row, so you can move content to separate lines :) With that, you would need to use grid properties so the label/input is properly aligned.
{ "pile_set_name": "StackExchange" }
Q: Create a shell script to logon to a server and email disk usage I would like to create a shell script that it will login to a server, get the disk usage from the server, email to me, and then exit from server. Also, if possible to do it daily. This is what I have: #!/usr/bin/bash ssh -p 1111 [email protected] CURRENT=$(df / | grep / | awk '{ print $5}' | sed 's/%//g') mail -s 'Disk Space Alert' [email protected] << EOF Disk usage is at: $CURRENT% EOF fi the name of the shell script is example.sh When I run it, it keeps asking me for password and once I am logged in nothing happens. A: First, generate a public key for use to log-in to the remote system without a password: ssh-keygen -t rsa -b 4096 -C "your_username" This will generate a 4096-bit RSA key in your ~/.ssh/ directory with your user-name as the label. Then, add this new key to your ssh-agent so that it is used when you connect via SSH. ssh-agent -s ssh-add ~/.ssh/id_rsa If you set a custom name during key generation, replace id_rsa with that name. Now, copy your public key contents to your clipboard. clip < ~/.ssh/id_rsa.pub Next, log-in to the remote server with ssh -p YOURPORT [email protected] and edit the remote user's authorized_keys file. vim .ssh/autorized_keys Paste in the contents you just copied to your clipboard. This allows connections from your computer to the remote host without password, instead using certificates (usually much more secure, anyway). Now, you need to make a script, example-script.sh, in your remote host's home directory(make sure to chmod a+x example-script.sh afterward to set it as executable). #!/usr/bin/env bash CURRENT=$(df / | awk '/\// { print $5}' | sed 's/%//g') mail -s 'Disk Space Alert' [email protected] << EOF Disk usage is at: $CURRENT% EOF And now, create a script in your local home directory, local-script.sh to run the command later easily(again, make sure to make it executable after). #!/usr/bin/env bash ssh -P YOURPORT [email protected] ./example-script.sh This script allows you to run ./local-script.sh from your home directory to run your remote script in just one line. You can then add this as an alias to your .bashrc file so that you can just run local-script or whatever other alias you may want. You can also use the absolute path(/home/your_username/local-script.sh) in crontab to make it run at a specific time every day. A: Firstly to explain why nothing happens, most likely because of the syntax. Your ssh command is of the form: ssh server, which is when you only want to login, and then manually type some commands interactively. But if you want some command to be run automatically after login, you should be doing : ssh server somecommand, so just having somecommand on the next line will not work. Well, if you want a system to both email disk space info whenever you want, and at the same time support scheduled emails, I would recommend a three part system: one script on the server that obtains the disk info and email logic, for example at /home/yourusername/script.sh crontab to run the script.sh for your arbitrary, on-a-whim requests you can ssh and execute the script script.sh This is the script you put on the server, for example at /home/yourusername/script.sh. #!/bin/bash s="Disk Space Alert: $(df / | grep / | awk '{ print $5}')" mail -s $s [email protected] # Feedback echo $s I removed the sed because it simply removed % sign but then you were adding it back later, this seems a redundant use of sed so I removed it. Secondly, I have condensed the disk usage info to fit just in the subject line, if this doesn't work then of course you can revise it to your original form, but let everyone know either way so we can learn if there were any errors etc crontab Edit crontab on your server, for example ssh into your server and then proceed with these commands $ crontab -e You know the format is # m h dom mon dow command so for daily every day 8 am 0 8 * * * /home/yourusername/script.sh So as long as you have tested the script already and know it works to send emails, then crontab will run the script and cause the email to be sent at 8 am every day arbitrary request to get disk info emailed You just ssh but put the script command on the end ssh -p 1111 [email protected] /home/yourusername/script.sh This uses ssh syntax ssh server somecommand so it logs in, executes whatever command and returns results to your local standard out. Because it has the feedback line, not only should it email, but you also see the Disk Space Alert: ... message so that you at least get immediate feedback that your script was run or not.
{ "pile_set_name": "StackExchange" }
Q: Meaning of “we’ll cut him down as for the border he rides” Welsh History 101B: My neighbour from England has come across raiding, Slain six of my kinsmen and burned down my hall. It cannot be borne, this offence and injustice: I’ve only killed four of his, last I recall. I’ll send for my neighbours, Llewellyn and Owain; We’ll cut him down as for the border he rides. But yesterday Owain stole three of my cattle, So first I’ll retake them, and three more besides. I didn’t get the meaning of “we’ll cut him down as for the border he rides”. Please can anybody explain? A: We’ll cut him down as for the border he rides. Ah, one of the things one can do in English, but which is non-idiomatic and thus generally only appears in poetry, is re-arrange clause order like this, sticking the prepositional phrase in the middle of things. "As" here means "while", and the more conventional place for "for the border" would be at the end: We'll cut him down [while] he rides for the border. "Cut him down" is idiomatic, and means more literally "murder him with swords", though also is used to refer, poetically, to murdering people with other weapons like firearms. A: We’ll cut him down as for the border he rides. means "We will kill him while he rides towards the border".
{ "pile_set_name": "StackExchange" }
Q: How to apply a class on when mouse is hovering on it? I defined a CSS class "active", and want to apply this class on a <li> tag only when the mouse is hovering on it. How to do that? Here is a Bootstrap example: <ul class="list-group"> <li class="list-group-item">First item</li> <li class="list-group-item">Second item</li> <li class="list-group-item">Third item</li> </ul> And when the mouse is hovering on any <li>, apply class "active" on it. Hope CSS could provide something like this, because I want to avoid writing same plain CSS text again and again. .list-group-item:hover { include .active; } Thanks. A: you should avoid using unnecessary javascript when you can do it simply with CSS, like everyone else pointed out already but nonetheless jquery way would be $('.list-group-item').hover(function(){ $(this).addClass('active'); },function(){ $(this).removeClass('active'); }); first block is when the mouse is over the element, second is when it leaves it https://jsfiddle.net/o9na7ps0/1/
{ "pile_set_name": "StackExchange" }
Q: Generating adjacency matrix on random cout of graphs with output the matrix I've developed program, which may work with graphs and its edges (connections between vertices): http://ideone.com/FDCtT0 /* Oleg Orlov, 2012(c), generating randomly adjacency matrix and graph connections */ using System; using System.Collections.Generic; class Graph { internal int id; private int value; internal Graph[] links; public Graph(int inc_id, int inc_value) { this.id = inc_id; this.value = inc_value; links = new Graph[Program.random_generator.Next(0, 4)]; } } class Program { private const int graphs_count = 10; private static List<Graph> list; public static Random random_generator; private static void Init() { random_generator = new Random(); list = new List<Graph>(graphs_count); for (int i = 0; i < list.Capacity; i++) { list.Add(new Graph(i, random_generator.Next(100, 255) * i + random_generator.Next(0, 32))); } } private static void InitGraphs() { for (int i = 0; i < list.Count; i++) { Graph graph = list[i] as Graph; graph.links = new Graph[random_generator.Next(1, 4)]; for (int j = 0; j < graph.links.Length; j++) { graph.links[j] = list[random_generator.Next(0, 10)]; } list[i] = graph; } } private static bool[,] ParseAdjectiveMatrix() { bool[,] matrix = new bool[list.Count, list.Count]; foreach (Graph graph in list) { int[] links = new int[graph.links.Length]; for (int i = 0; i < links.Length; i++) { links[i] = graph.links[i].id; matrix[graph.id, links[i]] = matrix[links[i], graph.id] = true; } } return matrix; } private static void PrintMatrix(ref bool[,] matrix) { for (int i = 0; i < list.Count; i++) { Console.Write("{0} | [ ", i); for (int j = 0; j < list.Count; j++) { Console.Write(" {0},", Convert.ToInt32(matrix[i, j])); } Console.Write(" ]\r\n"); } Console.Write("{0}", new string(' ', 7)); for (int i = 0; i < list.Count; i++) { Console.Write("---"); } Console.Write("\r\n{0}", new string(' ', 7)); for (int i = 0; i < list.Count; i++) { Console.Write("{0} ", i); } Console.Write("\r\n"); } private static void PrintGraphs() { foreach (Graph graph in list) { Console.Write("\r\nGraph id: {0}. It references to the graphs: ", graph.id); for (int i = 0; i < graph.links.Length; i++) { Console.Write(" {0}", graph.links[i].id); } } } [STAThread] static void Main() { try { Init(); InitGraphs(); bool[,] matrix = ParseAdjectiveMatrix(); PrintMatrix(ref matrix); PrintGraphs(); } catch (Exception exc) { Console.WriteLine(exc.Message); } Console.Write("\r\n\r\nPress enter to exit this program..."); Console.ReadLine(); } } The example there is using the const value, but you could erase const and fill Random int. At the ideone as you see the result is ok and are able to see the generated matrix (result): 0 | [ 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, ] 1 | [ 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, ] 2 | [ 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, ] 3 | [ 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, ] 4 | [ 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, ] 5 | [ 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, ] 6 | [ 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, ] 7 | [ 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, ] 8 | [ 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, ] 9 | [ 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, ] ------------------------------ 0 1 2 3 4 5 6 7 8 9 Graph id: 0. It references to the graphs: 8 Graph id: 1. It references to the graphs: 4 8 Graph id: 2. It references to the graphs: 4 2 4 Graph id: 3. It references to the graphs: 1 0 1 Graph id: 4. It references to the graphs: 7 5 Graph id: 5. It references to the graphs: 9 7 Graph id: 6. It references to the graphs: 6 9 Graph id: 7. It references to the graphs: 3 6 Graph id: 8. It references to the graphs: 5 2 5 Graph id: 9. It references to the graphs: 2 0 9 Press enter to exit this program... A: class Graph What this class represents is not a whole graph, it's a single vertex (or node). Because of that, you should rename this class to either Vertex or Node. internal int id; You shouldn't have non-private fields, use properties for that. For more information about reasons, read Jon Skeet's article Why properties matter. Also, I don't understand why are you marking fields internal, since the whole class is already internal (that's the default for top-level classes). You should mark them public, so that if you decide to make the class public in the future, you don't have to change the fields (or rather properties, see previous point) too. One more thing: you should also change the name to Id, that's the naming convention used for non-private members. class Program All methods of this class are static, so you should make the whole class static. Although it might also make sense to put all the graph-related code into a separate (non-static class). A good name for this new class might be Graph. private const int graphs_count = 10; This should be static readonly, rather than const. const fields should be used only for values that you know will never change. This is most important if you're writing a library, but it's a good habit to get used to it everywhere. private static List<Graph> list; list is a very unclear name, a better name would be something like graphs (or nodes after you fix the name of the class Graph). public static Random random_generator; Again, the naming convention for non-private members is something like RandomGenerator, you should change that. And again, public fields should be changed to public properties. private static void Init() private static void InitGraphs() Having methods that have to be called before a class can be used is a sign of bad design. You should use constructor for that. Graph graph = list[i] as Graph; There is no need for the as here, the type if list[i] is already Graph. list[i] = graph; This line doesn't do anything, you should remove it. In C#, classes are reference types, so if you change members of the local variable graph here, list[i] will be also changed (because it refers to the same object). private static bool[,] ParseAdjectiveMatrix() This is again a very confusing name. There is no such thing as “adjective matrix”, it's called adjacency matrix, so you should rename this method. Also, “parsing” usually means reading some string. A better name for this method would then be CreateAdjacencyMatrix. int[] links = new int[graph.links.Length]; There doesn't seem to be any reason for this array, you could simplify your code to: for (int i = 0; i < graph.links.Length; i++) { int linkedId = graph.links[i].id; matrix[graph.id, linkedId] = matrix[linkedId, graph.id] = true; } Or even better, use foreach: foreach (var linked in graph.links) { matrix[graph.id, linked.id] = matrix[linked.id, graph.id] = true; } private static void PrintMatrix(ref bool[,] matrix) You should get rid of the ref here. ref is useful if you want to change some variable of the caller (and not just its contents) or in very rare cases when you want to avoid copying a large value type. But matrix is an array, which is a reference type, and you don't change it, so the ref has no use here. Console.Write(" ]\r\n"); You should use Console.WriteLine(" ]") here instead. This applies to other places in your code where you use \r\n too.
{ "pile_set_name": "StackExchange" }
Q: how to link css file at html page i have some script..it lies in some direktori : var/www/html/dataTables-1.6/media/css/demo_page.css how to put in html page? <link href=......??? rel="stylesheet" type="text/css" media="all"> A: Assuming html is your webroot, place the following in your head tag. <link href="/dataTables-1.6/media/css/demo_page.css" rel="stylesheet" type="text/css" media="all"> Is this what you were asking?
{ "pile_set_name": "StackExchange" }
Q: « Spectre toujours masqué qui nous suis côte à côte » : pourquoi pas « suit » (3e sing.) ? Ô fantôme muet, ô notre ombre, ô notre hôte, Spectre toujours masqué qui nous suis côte à côte, Et qu’on nomme demain ! [ Victor Hugo, Napoléon II - ds. Les Chants du crépuscule, extrait ] Dans le deuxième vers de l'extrait, on a un sujet (spectre) et un pronom relatif (qui) qui y fait référence et puis un accord du verbe suivre qui n'est pas à la troisième personne du singulier (suit). Comment et pourquoi ? A: Les vers précédents expliquent tout : il parle au fantôme / spectre. Nul ne te fait parler, nul ne peut avant l'heure Ouvrir ta main froide. Le verbe est donc (tu) suis et non pas (il) suit. A: Le verbe n'est pas à la troisième personne du singulier tout simplement parce qu'il est à la deuxième personne du singulier, puisque le sujet est la personne à qui s'adresse le discours. La deuxième personne ne nécessite pas le pronom tu, c'est seulement le cas le plus courant. Prenons un exemple simple où le sujet est un pronom relatif : Toi qui es grand, attrape ce livre sur l'étagère du haut. Le sujet de es est qui, mais c'est l'interlocuteur, donc on conjugue à la deuxième personne. On ferait de même à la première personne : Moi qui suis grand, je peux attraper ce livre sur l'étagère du haut. Il est nettement plus rare de se passer de tu dans une proposition principale. Dans mon premier exemple, « toi qui est grand » n'est pas le sujet du verbe attraper, c'est une apostrophe ; le verbe attraper est à l'impératif et n'a donc pas de sujet grammatical. Dans mon deuxième exemple, le sujet est repris par le pronom je. En français moderne, je crois même que la reprise du pronom est indispensable, mais on pourrait trouver une construction comme « (?) moi qui suis grand puis attraper ce livre » dans la langue littéraire classique, et surtout en poésie. A: Il s'agit d'une apostrophe (2) ou d'une interpellation, et « ô », généralement une interjection, en est souvent l'introducteur spécifique dans la langue littéraire. La particularité est que « [l]e mot en apostrophe appartient à la deuxième personne grammaticale » (Le bon usage, Grevisse et Goosse, ed. Duculot, au §376, que l'on consultera pour plus de détails), ce qui correspond au vocatif1 en latin, d'où (tu) suis : Adieu, meuse endormeuse et douce à mon enfance, Qui demeures aux prés, où tu coules tout bas [ Peguy, Morceaux choisis] Il ne faut pas confondre ces cas avec ceux de l'apposition et de l'injure (+ impératif, par exemple). On dit (LBU) cependant que la nuance est en effet parfois assez subtile et l'exemple présenté ainsi que le suivant sont donc matière à réflexion : Ô plaisir, bélier qui te fêles le front et qui recommences. [ Colette, Le pur et l'impur, Pl. ] 1 Tel le fameux prototype césarien « tu quoque, filī » , que César a sans doute dit en grec, si du tout.
{ "pile_set_name": "StackExchange" }
Q: Dock Windows 7 gadgets against screen edge I've got four gadgets on my Windows 7 desktop. I want them to dock against the edge of the screen, such that maximized windows don't cover them (the "Always On Top" option doesn't meet my needs). Is there a setting or tool which will allow this? A: mydigitallife has this info: Workaround to Run Windows Vista Bar Style Sidebar in Windows 7 Close all gadgets on desktop. Take ownership and grant full control permissions for Administrators user group of the following files located in C:\Program Files\Windows Sidebar folder: settings.ini sidebar.exe And inside the en-US Folder: sbdrop.dll.mui Sidebar.exe.mui Rename to backup the 4 files listed above. Download Win7-Sidebar-Fix.zip. Extract and copy the contents of the ZIP file to their corresponding folders in C:\Program Files\Windows Sidebar folder, overwrite and replace existing files if applicable. Re-add gadgets to desktop.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to tell if we're being called inside a constructor? I want to make a nonstatic method that only constructors of the same instance of the class (or one of its subclasses) may call. Is there an elegant way to do this, short of a key-oriented access protection pattern? class MyClass { public: void foo() { assert(foo was called from the constructor); //how?! if (some condition or other) throw ExceptionThatOnlyClientsThatConstructTheObjectCanHandle(); //hence my requirement } }; class MySubClass : public MyClass { public: MySubClass() { blah(); //correct use of foo() through blah() foo(); //correct use of foo() directly } void blah() { foo(); } //correctness depends on who called blah() }; int main() { MySubClass m; m.foo(); // incorrect use of foo() m.blah(); // incorrect use of foo() through blah() return 0; } Edit: see my comments below, but I think this is either a special case of (1) transitive key-oriented access control or (2) making sure exceptions are handled. Seeing it like that, the constructor thing is a red herring. A: No. This is not possible without some other variable telling you. The best thing you can do is make the methods private so only your class can call it. Then make sure that only the constructor calls it. Other than that, it you only want the constructor calling it, have you tried not using a function and just putting the code there?
{ "pile_set_name": "StackExchange" }
Q: ReaderT static environment Declaration of the ReaderT monad transformer, which adds a static environment to a given monad. What does it mean to add a static environment to a given monad? Someone suggested that this is a duplicate to another question. I believe that this question is unique because I'm asking what it means to have a static environment and also my question pertains to ReaderT. Even if it is similar to Reader, they are still different. A: It means that the environment cannot be updated: you can only read from it (hence the name of ReaderT). This is in contrast to monad transformers like StateT which provide you an environment you can both read and write to. Inside a reader monad, you can reach the envionment using the ask function: ask :: Monad m => ReaderT r m r Inside a state monad, you have a similar function for reading called get as well as another function which writes to the state called put: get :: Monad m => StateT s m s put :: Monad m => s -> StateT s m () Examples Here is a sample usage of both ReaderT and StateT. Let's suppose my underlying monad will be IO so that I will be able to print things along the way. The contrived example here is a number guessing program - the environment is just a number that you are trying to guess (so Int). guess takes a number and checks whether the number is the same one as the one in the environment. If not, it prints a message to the screen. In either case, it returns whether your guess was successful. guessReader :: Int -> ReaderT Int IO Bool guessReader guess = do actual <- ask if guess == actual then return True else do lift $ putStrLn ("The number was " ++ show actual) return False However, suppose now you want a way of changing the number you are trying to guess randomly after a guess. Then, since you need to change the environment, you will need to use StateT. import System.Random (randomRIO) guessState :: Int -> StateT Int IO Bool guessState guess = do actual <- get if guess == actual then return True else do lift $ putStrLn ("The number was " ++ show actual) newActual <- lift $ randomRIO (0,10) put newActual return False Then, if you run the reader version several times, note that the value you are trying to guess never changes. That is not the case with the state version, which resets to a new number every time you make a wrong guess: ghci> runReaderT (guessReader 3 >> guessReader 4 >> guessReader 5) 5 The number was 5 The number was 5 True ghci> evalStateT (guessState 3 >> guessState 4 >> guessState 5) 5 The number was 5 The number was 6 The number was 2 False
{ "pile_set_name": "StackExchange" }
Q: Regular expression to match headers and sub headers followed by a bullet list I am trying to capture the text in headers/subsections and the bullet list that follows it with: re.finditer('(?!^\* )(?P<description>^.+?)(?P<items>^\* .+?^)(?!^\* )', text, flags=re.DOTALL | re.MULTILINE) with this sample text: Header A Subheader A * Item A * Item B * Item C Header B Subheader B Description B * Item 1 * Item 2 * Item 3 Random Header C * Item X * Item Y * Item Z The expression works except on Random Header C and its bullet list. A workaround is to add two trailing line breaks \n\n after * Item F. Any idea how to match the last section or if there is a better method for doing this? https://regex101.com/r/yG7sJ6/1 A: You can use this regex to capture missing items: (?P<description>^.+?)(?P<items>(?:^\* [^\n]+(?:\n|$))+) RegEx Demo
{ "pile_set_name": "StackExchange" }
Q: Extracting information from Musicxml I am new to programming and Python, but a lot of my current research concerns extracting data from musicxml files. I have a piece of music and want to extract the number of accidentals that occur in a piece that do not form part of the key signature. I have no idea how to do this, please could someone help? Here's an example of one measure from the musicxml file I am looking at: <measure number='19'> <print new-system='no'/> <note> <rest/> <duration>768</duration> <voice>1</voice> <type>quarter</type> <staff>1</staff> </note> <backup> <duration>768</duration> </backup> <note> <pitch> <step>E</step> <octave>4</octave> </pitch> <duration>2304</duration> <tie type='start'/> <voice>2</voice> <type>half</type> <dot/> <staff>1</staff> <notations> <tied type='start'/> <slur type='stop' number='1'/> </notations> </note> <backup> <duration>1536</duration> </backup> <note> <pitch> <step>E</step> <alter>3</alter> <octave>3</octave> </pitch> <duration>1536</duration> <voice>1</voice> <type>half</type> <staff>1</staff> </note> <note> <chord/> <pitch> <step>G</step> <alter>4</alter> <octave>3</octave> </pitch> <duration>1536</duration> <voice>1</voice> <type>half</type> <staff>1</staff> </note> <backup> <duration>2304</duration> </backup> <note> <pitch> <step>E</step> <octave>2</octave> </pitch> <duration>2304</duration> <voice>5</voice> <type>half</type> <dot/> <staff>2</staff> </note> </measure> The problem translates to searching through the musicxml file and counting the number of times <pitch> <step>*</step> <alter>**</alter> ... occurs where * is not (F or C) and also finding the number of times that * is F or C and is not followed by the <alter> tag. Any help or advice would be much appreciated! A: I can't help with Python details, but I have two MusicXML-related suggestions: 1) Your question is phrased in terms of accidentals, but your code focuses on the alter element. The alter element is used for pitch alteration; the accidental element is what is used for written accidentals. Which one are you looking for? The duality between how much sounds and how it appears in notation is common in MusicXML, and important to understand for doing research with MusicXML files. 2) If you are new to programming and Python, I would suggest using a higher-level toolkit designed expressly for musicology with good MusicXML support. You will move the problem domain up to a higher level which should let you make progress a lot faster. The obvious choice for this is the music21 toolkit, which is also written in Python. There's lots more information at http://web.mit.edu/music21/. Good luck with your research! A: python has an xml.dom module that allows you to quickly navigate through xml files. If you have any experience with web development, it's very similar to javascript's document object model. from xml.dom.minidom import parse, parseString def get_step(note): stepNode = note.getElementsByTagName("step")[0] #get the text from the Text Node within the <step>, #and convert it from unicode to ascii return str(stepNode.childNodes[0].nodeValue) def get_alter(note): alters = note.getElementsByTagName("alter") if len(alters) == 0: return None return alters[0] def is_rest(note): return len(note.getElementsByTagName("rest")) > 0 def is_accidental(note): return get_alter(note) != None dom = parse("data.xml") notes = dom.getElementsByTagName("note") #rests don't have steps or alters, so we don't care about them. Filter them out. notes = filter(lambda note: not is_rest(note), notes) #compile a list of notes of all accidentals (notes with <alter> tags) accidentals = filter(is_accidental, notes) #remove notes that are F or C accidentals_that_are_not_f_or_c = filter(lambda note: get_step(note) not in ["F", "C"], accidentals) #compile a list of notes that don't contain the alter tag non_accidentals = filter(lambda note: not is_accidental(note), notes) #remove notes that are not F or C non_accidentals_that_are_f_or_c = filter(lambda note: get_step(note) in ["F", "C"], non_accidentals) print "Accidental notes that are not F or C:" if len(accidentals_that_are_not_f_or_c) == 0: print "(None found)" else: for note in accidentals_that_are_not_f_or_c: print get_step(note) print "Non-accidental notes that are F or C:" if len(non_accidentals_that_are_f_or_c) == 0: print "(None found)" else: for note in non_accidentals_that_are_f_or_c: print get_step(note), get_step(note) in ["F", "C"] output: Accidental notes that are not F or C: E G Non-accidental notes that are F or C: (None found)
{ "pile_set_name": "StackExchange" }
Q: Why doesn't my OpenGL ES view update when using the following code? I am programming an OpenGL game for the iPhone, and have this code that is called 24 times a second, meant to update the view: [gameWorld update]; glColor3f(1.0f, 0.85f, 0.35f); glBegin(GL_QUADS); { glVertex3f(gameWorld.player.x, gameWorld.player.y, 0); glVertex3f(gameWorld.player.x+10, gameWorld.player.y, 0); glVertex3f(gameWorld.player.x+10, gameWorld.player.y+20, 0); glVertex3f(gameWorld.player.x, gameWorld.player.y+20, 0); } glEnd(); Where [gameWorld update] calls the code necessary to change the gameWorld.player.x based on what key is pressed (this works). My problem is that the yellow rectangle drawn on the screen doesn't move after the glBegin() block. Any ideas why? A: glBegin()/glEnd() is not supported on OpenGL ES 1.1. You might want to take a look at this post which explains how to perform similar operations. Basically, for drawing a triangle: glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, triVertices); glDrawArrays(GL_TRIANGLES, 0, 3);
{ "pile_set_name": "StackExchange" }
Q: Marrying a second woman behind your wife's back: is it wrong and can Quran/Hadith prove this? Salam alaykum. Please note that I myself am not in this position, rather I am in the position of knowing men who say they do "halal cheating"; namely marrying a second woman making the sexual activities with the second wife permissible in islam. I am not knowledgeable enough to do more than to advise them it is wrong to trick your first wife and not take her choice into account or her comfort. However, what I wonder is if someone may be able to cite islamic texts to show that in islam it is actually wrong to hide such a thing from your first wife. I am sure that many of these men would, in knowledge that it is haram or makruh to lie to your first wife, stop having these thoughts. The entire "halal cheating" seems to be a form of self-validation for people who are no better in spirit than the fornicators who have extramarital sex, as they also give in to their compelling desire for lust. I am very grateful for anyone who would be able to provide islamic citations! A: It is legal in Islam for a man to marry more than one woman. فانكحوا ما طاب لكم من النساء مثنى وثلاث ورباع Then marry those that please you of [other] women, two or three or four. — Quran 4:3 If the marriage was proper, e.g. in the presence of two witnesses and the wali of the bride, with proper offer and acceptance etc. then it is a valid Nikah and is incomparable with fornication or extramarital sex. There is no blame for satisfying desire, provided that it is through legal means. Neither is the consent of the first wife required nor is the husband obliged to inform her. What he is obliged to do however is to administer justice between his wives, e.g. in division of nights between them. And he is also advised to remain with a single spouse for that purpose. فإن خفتم ألا تعدلوا فواحدة But if you fear that you will not be just, then marry only one — Quran 4:3 It is not legally required to seek the approval of the first wife, however doing so may be recommended as part of courtesy and good treatment: وعاشروهن بالمعروف And live with them in kindness. — Quran 4:19 لتسكنوا إليها وجعل بينكم مودة ورحمة That you may find tranquillity in them; and He placed between you affection and mercy. — Quran 30:21 أكمل المؤمنين إيمانا أحسنهم خلقا، وخياركم خياركم لنسائهم خلقا The most complete of the believers in faith is the one with the best character among them. And the best of you are those who are best to your women. — Jami at-Tirmidhi
{ "pile_set_name": "StackExchange" }
Q: Links apps in Docker Swarm Mode I would like to know how do we link webapp to database in docker swarm mode. I'm very new to docker swarm mode and had a basic cluster setup on my local machine. Any links would be great. Example: Hosting a drupal application (Connected drupal cms containers with mysql database container). Thanks A: Correct, using custom networks is the way forward. A very simple example to get you started; Create an "overlay" network (overlay networks allow containers to communicate, even if they are running on different nodes in the swarm); docker network create --driver=overlay my-network Create a database service named my-db, and attach it to the my-network network. There is no need to "publish" the database port, because drupal will connect with the database over the my-network network. Only publish database-ports if you want the database to be publicly accessible. docker service create \ --name=my-db \ -e MYSQL_ROOT_PASSWORD=topsecret \ -e MYSQL_DATABASE=drupal\ -e MYSQL_USER=drupal-user \ -e MYSQL_PASSWORD=secret \ --network=my-network \ mysql:5.7 Create a drupal service (named mysite), and also attach it to the same network. Publish the site's ports, because you want it to be publicly accessible docker service create \ --name=mysite \ --network=my-network \ --publish=8080:80 \ drupal:8.2-apache After the services are created, and the containers are running (you can check the status with docker service ls), you can visit <host-ip>:8080 in your browser. In swarm mode, <host-ip> can be the IP-address of any host in your swarm. The "routing mesh" will automatically route the network connection to the node that a container runs on. Now, to configure drupal, using the username/password you set in MYSQL_USER and MYSQL_PASSWORD, and using my-db as hostname for the database (under advanced options) - when using docker networks, you can connect to other services on the same network through their name. This is just a very quick example. Some things to look into are; Volumes (save uploads, and user-data in a volume, so that the information can persist when updating your container) Secrets; passing username and password as environment variables is insecure. Docker 1.13 will introduce docker secrets, which allow you to pass the database credentials in a more secure way. Documentation is not live yet, but you can find them on GitHub
{ "pile_set_name": "StackExchange" }
Q: Groovy Split CSV I have a csv file (details.csv) like ID,NAME,ADDRESS 1,"{foo,bar}","{123,mainst,ny}" 2,"{abc,def}","{124,mainst,Va}" 3,"{pqr,xyz}","{125,mainst,IL}" when I use (Note: I have other closure above this which reads all csv files from directory) if(file.getName().equalsIgnoreCase("deatails.csv")) { input = new FileInputStream(file) reader = new BufferedReader(new InputStreamReader(input)) reader.eachLine{line-> def cols = line.split(",") println cols.size() } Instead of getting size 3 I am getting 6 with values 1 "{foo bar}" "{123 mainst ny}" spilt(",") is splitting data by comma(,) but I want my results as 1 "{foo,bar}" "{123,mainst,ny}" How can I fix this closure. Please help! Thanks A: Writing a csv parser is a tricky business. I would let someone else do the hard work, and use something like GroovyCsv Here is how to parse it with GroovyCsv // I'm using Grab instead of just adding the jar and its // dependencies to the classpath @Grab( 'com.xlson.groovycsv:groovycsv:1.0' ) import com.xlson.groovycsv.CsvParser def csv = '''ID,NAME,ADDRESS 1,"{foo,bar}","{123,mainst,ny}" 2,"{abc,def}","{124,mainst,Va}" 3,"{pqr,xyz}","{125,mainst,IL}"''' def csva = CsvParser.parseCsv( csv ) csva.each { println it } Which prints: ID: 1, NAME: {foo,bar}, ADDRESS: {123,mainst,ny} ID: 2, NAME: {abc,def}, ADDRESS: {124,mainst,Va} ID: 3, NAME: {pqr,xyz}, ADDRESS: {125,mainst,IL} So, to get the NAME field of the second row, you could do: def csvb = CsvParser.parseCsv( csv ) println csvb[ 1 ].NAME Which prints {abc,def} Of course, if the CSV is a File, you can do: def csvc = new File( 'path/to/csv' ).withReader { CsvParser.parseCsv( it ) } Then use it as above
{ "pile_set_name": "StackExchange" }
Q: How to use information returned from Google Authentication provider to provide access to data I'm trying to use the Google Authentication provider and then use the information for an authenticated user in a Database Rule to restrict access to data. For example, say I sign in with my Google id [email protected]. Something kind of like the following (taken from the firestore docs): let provider = new firebase.auth.GoogleAuthProvider(); let result = await firebase.auth().signInWithPopup(provider); let token = result.credential.accessToken; let user = result.user; // ... In the above user.email would be [email protected] at this point. Now how do I use that info in a rule to allow writing to the data. I thought it would be something like: match /events/{events} { allow write: if request.auth.uid = // Something? } but I cannot figure out how to know what to compare to uid. Ideally it would be the email address (i.e. something human-readable). My goal here is that I as the administrator keep a list of authorized users, and then they can come log into my app and access the data. A: Like Doug Stevenson wrote in the comments you have to use request.auth.token.email. If you want to compare the email in your security rules, you also have to store the email address of the user in your firestore db so you can compare like this: match /events/{events} { allow write: if request.auth.token.email == resource.data.email; } or you do it with the uid like this: match /events/{events} { allow write: if request.auth.uid = resource.data.uid; } Of course you have to store the uid in your firestore db, too.
{ "pile_set_name": "StackExchange" }
Q: Detect first FOSFacebookBundle login I implemented successfully the FOSFacebookBundle with the FOSUserBundle. Everything works great. Now, I'd like to be able to detect the first connection of an user with the FOSFacebookBundle. I have a FacebookAuthenticationSuccessHandler which is called every time a Facebook authentication successes, but I'd like to declare a kind of "FirstFacebookAuthenticationSuccessHandler", called only if the user didn't exist yet. The goal of this handler is to be able to send a welcome email to each new user. For the classic registration, I simply use a RegistrationSuccessListener. Do you have any idea on how I could do this? A: Answering my own question as I found the solution. 1/ I created (and registered) a new event listener called NewFacebookUserListener: ... /** * {@inheritDoc} */ public static function getSubscribedEvents() { return array( MyCustomEvents::NEW_FACEBOOK_USER => 'onNewFacebookUser' ); } public function onNewFacebookUser(UserEvent $event) { // we get the user $user = $event->getUser(); // and now you can do what you wish } 2/ In my FacebookProvider (located under Security/User/Provider), I added a few lines to dispatch this new event: $user->setFBData($fbdata); // we send a "FB user created" event $dispatcher = $this->container->get('event_dispatcher'); $dispatcher->dispatch(MyCustomEvents::NEW_FACEBOOK_USER, new UserEvent($user, $this->container->get('request'))); And as expected, the event is dispatched only when a new Facebook user is created.
{ "pile_set_name": "StackExchange" }
Q: VBA hyperlinks names and addresses I'm trying to pull all hyperlinks in an excel spreadsheet into a new worksheet. I want column A to show the text from the hyperlink, and column B to show the hyperlink address. I've written the code below, and all of column B works fine, however the values in column A are not all coming over, and they don't match the hyperlink addresses in column B. What am I doing wrong? Thanks in advance Sub extract_links() Dim hyp As Hyperlink Dim ReadCols As Long Dim ReadWriteRow As Long ReadWriteRow = 1 ReadCols = 6 ActiveWorkbook.Sheets(2).Range("a:b").Clear For c = 1 To ReadCols For Each hyp In ActiveWorkbook.Sheets(1).Columns(c).Hyperlinks ActiveWorkbook.Sheets(2).Range("a" & ReadWriteRow).Value = ActiveWorkbook.Sheets(1).Cells(ReadWriteRow, c).Value ActiveWorkbook.Sheets(2).Range("b" & ReadWriteRow).Value = hyp.Address ReadWriteRow = ReadWriteRow + 1 Next Next c End Sub A: This time you need to change this: ActiveWorkbook.Sheets(2).Range("a" & ReadWriteRow).Value = ActiveWorkbook.Sheets(1).Cells(ReadWriteRow, c).Value into this: ActiveWorkbook.Sheets(2).Range("a" & ReadWriteRow).Value = hyp.Range.Value
{ "pile_set_name": "StackExchange" }
Q: MeeGo v1.2 SDK download I'd like to develop some apps to my mobile device N9, but I can't actually find where to download MeeGo v1.2 SDK. I tried developer.meego.com but there link broked. I could just download for linux, but not for Win7 64x Also tried other download sites, but there was all trojan warnings from antivurus. Anybody can help out ? Thanks ! A: Old Nokia QT SDKs are apparently still available at Developer Wiki site
{ "pile_set_name": "StackExchange" }