Posts

Showing posts from April, 2012

objective c - EXC_BAD_ACCESS in c++.string file after starting navigation with Skobbler -

Image
after updated project , introduced pods, i'm having strange bug happens when want start navigation on route, after calculating it. this error , have no idea how did come that, didnt made significant changes in code, other having skmaps in project via cocoapods , not dragging manually // char_traits<char> template <> struct _libcpp_type_vis_only char_traits<char> { typedef char char_type; typedef int int_type; typedef streamoff off_type; typedef streampos pos_type; typedef mbstate_t state_type; _libcpp_inline_visibility static void assign(char_type& __c1, const char_type& __c2) _noexcept {__c1 = __c2;} _libcpp_inline_visibility static _libcpp_constexpr bool eq(char_type __c1, char_type __c2) _noexcept {return __c1 == __c2;} _libcpp_inline_visibility static _libcpp_constexpr bool lt(char_type __c1, char_type __c2) _noexcept {return (unsigned char)__c1 < (unsigned char)__c2;} _libcpp_inline_visibility static int compar

php - Variables that can be echoed -

i created function know if can pass variable language structure echo useful output (for example, arrays output array , not see useful). function echo_able($var) { if (is_string($var)) return true; if (is_numeric($var)) return true; if (is_object($var) && method_exists($var, '__tostring')) return true; return false; } is there other types forgot? because php bit messy, can not find way know sure types of variable can echoed. the php documentation doesn't list can echoed. any variable can echoed. when that, content converted string, using language rules. problem not can't echo something, maybe not result want. need pay attention type of conversion happen default , if want. edit: looks objects can not converted string unless there __tostring method implementation. manual, can see behavior changed. it worth noting before php 5.2.0 __tostring() method called when directly combined echo or print. since php 5.2.0, called

Weird permalink after install a new database Wordpress -

i moved old database yahoo servers new place. new server had database, did integrate old database new database. in yahoo, website had following permalink: mysite.com/wordpress/services/web-design for yahoo servers mandatory use additional file if domain, if site developed in wordpress (... mysite.com/wordpress/) can put whatever name want file there should file. bad seo, moved site new place. in new server, permalinks are: mysite.com/services/web-design everything ok, when try open "graphic design" page permalink this: mysite.com/services/js-jquery-2/ first tried confirm maybe there post or page created strange name. after checking fine, there no page or post name. made full search word "js-jquery-2" throughout server (using keyword search function dreamweaver) (i have server backup on computer.) no word found in entire server. maybe @ database, strange word maybe saved there not know how locate it, in case finding word perhaps not solution. other

c# - CefSharp crashes with "Destroying nonempty message queue" -

we writing program uses cefsharp data javascript heavy webpages. after operating while, after finished before, message logged console saying destroying nonempty message queue , program freezes. i @ loss can't pause debugger when message appears, vs crashes debugger timeout when trying. what causes message queue deleted? at moment did not solve problem, instead have figured out way tell when process has crashed (basically wait 3 minutes , if don't have reply browser assume crashed), when process stopped return partial result user , user's responsibility ask rest of data. regarding crash itself, isn't clear why seems doing crash render process, , because don't ask on wcf channel have no idea has crashed.

excel - convert xlsx file to csv -

i trying find fast way save xlsx files csv files same filename xlsx file (just in csv format). have recorded macro shortcut, issue whenever try new file saves same filename recorded initial macro (i.e. see below, because have file labelled in code as: 3wdl_1 (2014-08-07)10secdatatable sit.csv ). there need replace 3wdl_1 (2014-08-07)10secdatatable sit.csv make macro save same filename actual workbook working with. so have folder full of xlsx files , want use shortcut/macro on each xslx file convert them csv files have same name original xlsx file, , saved same folder. i need replace 3wdl_1 (2014-08-07)10secdatatable sit.csv portion of code work new xlsx file open up. otherwise may old fashioned way mouse thanks in adcance, paddy sub saveascsvfile chdir "c:\users\paddy\desktop\new csv files whole cgm date ok!" activeworkbook.saveas filename:= _ "c:\users\paddy\desktop\new csv files whole cgm date ok!\" & _ "3wdl_1 (2014-08-07)10

python - Migrate cPickled objects to a new class with the same __getstate__ format -

i'm using cpickle serialize , deserialize instances of class. i've moved few classes different packages , i'm noticing cpickle/pickle stores class name , package comes from. >>> class a(object): pass >>> dumps(a()) 'ccopy_reg\n_reconstructor\np1\n(c__main__\na\np2\nc__builtin__\nobject\np3\nntrp4\n.' notice how __main__ stored because ran code in main python interpreter. if try unpickle many objects have stored way, i'll importerror complaining since moved classes around, old class doesn't exist in location expected. i haven't changed format of __getstate__ or __setstate__ . i've changed location of class needs deserialized. there way migrate these objects don't run problems? if want migrate data, must provide reference new object @ old location, , dump data again: old_location.a = new_location.a data = loads(pickle_data) pickle_data = dumps(data) and now, pickle_data contains reference new_loca

MySQL - Select Club Name and list all members in one query? -

i have "clubs" table , "members" table i'd query return club name (clubs.name) , each member's nickname (members.nickname) i can them using inner join, select clubs.name `club name`, members.nickname `member handle` clubs inner join members on clubs.club_id = members.club_id but shows club.name field each member.nickname. | club name | member handle | ------------------------------- | club yellow | jim-bob | | club yellow | clem | | club yellow | mustache pete | | club green | ladyhawke | | club green | rosie | is @ possible receive result so? | club name | member handle | ------------------------------- | club yellow | jim-bob | | | clem | | | mustache pete | | club green | ladyhawke | | | rosie | thanks no in mysql can not generate result this, need use application level it. can format data i.e. member-handle comma-separat

asp.net web api - WebApi 2 -cant determined DataProtection.IDataProtector Dependency Injection with structuremap -

i'm using this beriliant project base of mvc project. when use webapi project there problem in idataprotector injection. redesign base , upload here , , add console project testing authorizing webapi. this structuremap initialization : private static readonly lazy<container> _containerbuilder = new lazy<container>(initstructuremap, lazythreadsafetymode.executionandpublication); public static icontainer container { { return _containerbuilder.value; } } return new container(ioc => { ioc.for<iunitofwork>().hybridhttporthreadlocalscoped().use(() => new dbcontext()); ioc.for<idataserializer<authenticationticket>>().use<ticketserializer>(); ioc.for<isecuredataformat<authenticationticket>>().use<securedataformat<authenticationticket>>(); }); and in webapiconfig class di this: var container = structuremapm

How to set radio button in angularjs with Object -

i have created radio buttons in angularjs using array of objects using ng-value , ng-model. ` <div ng-controller="democontroller"> <div ng-repeat="detail in details"> <input type="radio" ng-model="$parent.selectedval" ng-value="detail" name="test"> </div> {{selectedval}} </div> ` on selection of radio button model populated corresponding object value. not sure how initialize using controller object. var app = angular.module('myapp', []); app.controller("democontroller",democontroller); function democontroller($scope) { $scope.selectedval={name:"def",age:4} ; $scope.details=[{name:'abc',age:2},{name:'xyz',age:3},{name:'def',age:4}]; } you should reference selected value details array instead of creating new instance: $scope.details = [{ name:'abc', age:2 }, { name:'

java - Tomcat JNDI Resouce Not Accessible -

i have gone through posts on above subject have not been able resolve this. situation this: 1) have defined set of resources in conf/server.xml (globalnamingresources) of tomcat 8.0.20 2) have declared resourcelink in tomcat conf/context.xml 3) web application getting name not bound exception. as per understanding, resources declared in server.xml accessible context if mapped in resourcelink, conf/context.xml loaded web applications , resources should available not. missing something. below files: the exception javax.naming.namenotfoundexception: name [comp/env] not bound in context . unable find [comp]. @ org.apache.naming.namingcontext.lookup(namingcontext.java:818) @ org.apache.naming.namingcontext.lookup(namingcontext.java:166) @ org.apache.naming.selectorcontext.lookup(selectorcontext.java:157) @ javax.naming.initialcontext.lookup(initialcontext.java:417) @ com.hm.vigil.platform.db.databaseconnectionmanager.<init>(databaseconnectionmanager

python 2.7 - What does reduce() do without mapper() in MRJob? -

i new python , trying build recommendation system following instruction http://www.yekeren.com/blog/archives/1005 , what confuses me : def reducer3_init(self): self.pop = { } file = open(self.options.item_pop, "r") line in file.readlines(): movieid_jstr, pop_jstr = line.strip().split("\t") movieid = json.loads(movieid_jstr) pop = json.loads(pop_jstr) self.pop[movieid] = pop file.close() def reducer3(self, key, values): yield key, sum(values) / math.sqrt(self.pop[key[0]] * self.pop[key[1]]) the reduce3 has no corresponding mapper ,how execute ? , json.load() do? lot thanks!! the documentation says: class mrjob.step.mrstep(**kwargs) used mrjob.steps. see multi-step jobs sample usage. accepts following keyword arguments. parameters: mapper – function same function signature mapper(), or none identity mapper. it idiom map default

math - Approximation Algorithm- using expectation -

note: don't have understand approximation algorithms answer this hello. need prove algorithm approximation using expectation. algorithm takes x_i \in {0,1,2} such i\in 1,...n+2 , there constants c_i \in 0,1,2 such i\in 1,...,n , find assignment variables such x_i +x_(i+1)+x_(i+2) != 0 \mod(3) i such number of indexes such x_i +x_(i+2) = c_i \mod(3) maximized. following: choose x_1 , x_2 \in 0,1,2 independently , uniformly @ random , each i\in 3,...,n+2 given values of x_(i-2),x_(i-1) assign x_i 1 of 2 values in {b\in 0,1,2 | x_(i-1)+x_(i-2)+b != 0 \mod(3)} uniformly @ random. the assignment each x_i independent x_j such j<i-2 . need prove algorithm gives 1/3 approximation problem described, using expectation(meaning proving x random variable assign question, e[x]=1/3 ) struggling defining such x , calculating this, keep getting 2\3 instead of 1\3. can calculation? you can prove x_i uniformly distributed on {0, 1, 2} , x_i pairwise i

php - PDO fetch() returning empty string -

i getting frustrated. have 2 functions have similar "instructions" ie: return values users table in database. the second 1 works fine, first 1 returning empty value. here code: public function validateuser($username, $password) { $stmt = "select password users username = :username limit 1"; if(!($grabuser = $this->db->prepare($stmt))) { return null; } $grabuser->bindparam(":username", $username, pdo::param_str); $grabuser->execute(); $data = $grabuser->fetch(); if(count($grabuser->fetchcolumn()) <= 0) { return null; } echo $data['password'].'s'; if(!password_verify($password,$data['password'])) { return null; } return $this->core->encrypt($data['password']); } i'm trying display $data['password'] on page test whether returns value database, returning empty, whereas query is returning column

c++ - how do i access an array returned as a pointer from a function using a subscript? -

i have created function returns pointer array of strings. function should traverse linked list , should assign data each node array of string. here function: //function traverse every node in list string *dynstrstk::nodestrings(int count) { stacknode *nodeptr = nullptr; stacknode *nextnode = nullptr; int = 0; //position nodeptr @ top of stack nodeptr = top; string *arr = new string[count]; //traverse list , delete each node while(nodeptr != nullptr && < count) { nextnode = nodeptr->next; arr[i] = nodeptr->newstring; nodeptr = nextnode; cout << "test1: " << arr[i] << endl; } return arr; } i want use pointer array returned function above, , want assign new array in different function test each subscript in array condition. i having trouble accessing new array , can't print out string in each new array element. arr = stringstk.nodestrings(count); co

sql - Clustered Index Error in Azure for a Table that Has a Clustered Index -

Image
i running command on sql azure. delete dbo.users i getting error. msg 40054, level 16, state 1, line 1 tables without clustered index not supported in version of sql server. please create clustered index , try again. i try create clustered index. create unique clustered index idx_users on dbo.users(id); i error. msg 1902, level 16, state 3, line 4 cannot create more 1 clustered index on table 'dbo.users'. drop existing clustered index 'pk_dbo.users' before creating another. do or not have clustered index? i had similar issue unable delete records table. after reading post, sql azure not recognizing clustered index , paired post checked dependencies through mssms on security_user table; 0-n relationship table, security_userhistory , had fk-reference table. reference not indexed , (strangely enough) triggered error in question. after applying clustered index fk-table security_userhistory referencing pk-table security_user

tkinter - Having trouble with this method of changing and showing a new window in python -

i having quite trouble using classes in python. first code used in changing , showing new window works cluttered decided use class. there might wrong in code. can atleast see it? thank you. hoping fast response. import random, sys, os, rabinmiller, cryptomath tkinter import * import tkinter tk pil import image, imagetk tkinter.filedialog import askopenfile class mainframe(tk.tk): def __init__(self, *args, **kwargs): tk.tk.__init__(self, *args, **kwargs) container = tk.frame(self) #frame1.title("rsa cryptosystem") #frame1.config(bg="black") container.columnconfigure(0, weight=1) container.rowconfigure(0, weight=1) self.frames = {} f in (startpage, decryptionpage, encryptionpage, makekeypage): frame = f(container, self) self.frames[f] = frame frame.grid(row=0, column=0, sticky=(n, w, e, s)) self.show_frame(startpage) def show_frame(self, cont):

swing - Creating a Simple Bar Chart in Java - Reads Data and Outputs Bar Graph -

im required create simple bar chart 1 of projects. program requires input of 1 9 integers greater zero. program required display simple bar graph integers displayed above bars. professor did not explain program me , first time working graphics. the program requires: a class "simplebarchart" (which extend frame) private variables bar[] bars , int [] inputdata among others (like private graphics g, private int windowwid, windowht, etc) , following functions. uses auxiliary class bars shown: class bar { public int height, width, value, nix, nwy; public bar() {} public bar(int height, int width, int value, int nix, int nwy) { this.height = height; etc } } next constructor simplebarchart(), calls readdata(), createbars(), , drawbars(). a function private void readdata(), reads inputdata bar-chart. use code given below, uses joptionpane. a function private void createbars() create bars array on assigning width, height, value (bars[i].value = inputdata[i]), nix

ui-router bootstrap modal deep-linking? -

parenta.bootstrapmodal , parentb.bootstrapmodal loading same modalcontroller . modalcontroller gets data modalfactory . all child states identical . yuck! here's have today: $stateprovider.state( 'parenta', { url: '/parenta', template: '<p>parent <ui-view /></p>', controller: ['modalfactory', function(modalfactory) { ...do stuff , store in factory }] } ).state( 'parenta.bootstrapmodal', { url: '/bootstrapmodal', template: '<span>child modal</span>', controller: 'modalcontroller' <------- duplicate route } ).state( 'parentb', { url: '/parentb', template: '<span>parent b</span>', controller: ['modalfactory', function(modalfactory) { ...do stuff , store in parent b factory }] } ).state(

javascript - is there better ways other than including require('mongoose') in every models file? -

i require mongoose in main app.js file once. can pass user. var mongoose = require('mongoose'); without loading again? in each file. doesn't script job each time require same module? var user = require('./models/user') from node documentation modules cached after first time loaded. means (among other things) every call require('foo') same object returned, if resolve same file. multiple calls require('foo') may not cause module code executed multiple times. take @ caching . it still possible require mongoose module globally. instead of var mongoose = require('mongoose'); write mongoose = require('mongoose'); . able access mongoose other module.

javascript - react lifecycle methods understanding -

i newbie react.js , trying hard understand several methods in react lifecycle methods. so far, still have confuses me: 1) as far understanding, difference between componentwillupdate , componentwillreceiveprops componentwillreceiveprops called when parent change props , can use setstate (setstate of child inside componentwillreceiveprops ). for example: https://github.com/bgerm/react-table-sorter-demo/blob/master/jsx/app.jsx var app = react.createclass({ getinitialstate: function() { return {source: {limit: "200", source: "source1"}}; }, handlesourcechange: function(source) { this.setstate({source: source}); }, render: function() { return ( <div> <datasourceselectors onsourcechange={this.handlesourcechange} source={this.state.source} /> <tablesorter datasource={urlfordatasource(this.state.source)} config={config} headerrepeat="5" /> </div> ); } }); in tableso

xml not retrived by javascript -

this may seem trivial have tried possible methods async=true (onreadystatechange) async=false (xmlhttp open) source http://www.w3schools.com/dom/dom_httprequest.asp 3.xmlhttp.open("get","http://"+location.host+"/cd_catalog.xml",false) source open xml , display data in div basically want javascript , xml in same folder , use javascript return values. the actual program working on: var xmlsolver = function makexmlsolver(){}; xmlsolver.getallauthorsinstock()=function() { var author=xmldoc.getelementsbytagname ("author").childnodes.nodevalue; return author; }; xmlsolver.getallbooksinstock()=function() { var title=xmldoc.getelementsbytagname ("title").childnodes.nodevalue; } and xml <?xml version='1.0'?> <!-- file represents fragment of book store inventory database --> <bookcollection> <book genre="philosophy" publicationdate="1991&qu

ui-router move from nestedState to another parentState -

i can't seem navigate directly parenta.childstate parentb state. how 1 in 1 move? $stateprovider.state( 'parenta', { url: '/parenta', template: '<p>parent <ui-view /></p>', controller: function() {} } ).state( 'parenta.childstate', { url: '/childa', template: '<span>child a</span>', controller: function(){} } ).state( 'parentb', { url: '/parentb', template: '<span>parent b</span>', controller: function(){} } ); assume application @ state parenta.childstate , click link below should take me parentb state. <a ui-sref="parentb">link goes parenta state</a> how can go directly parentb state? thanks help. answering own question. i'm asking here default behavior. should work out of box. problem own code interrupting re

html - Svg object doesn't scale properly -

i trying making svg object responsive scales nicely when viewing on phone or tablet. the tutorial used didn't @ all. made text disappear entirely. yeah, i'm using svg mask text gifs. (please understand i'm have started learn general basics , don't assume know you're saying.) look @ fiddle details. if jsfiddle not working check live example . html <h3> <svg> <pattern id="p-fire" viewbox="30 100 186 200" patternunits="userspaceonuse" width="216" height="200" x="-70" y="20"> <image xlink:href="http://tympanus.net/codrops-playground/assets/images/posts/23145/fire.gif" width="256" height="300"> </image></pattern> <text text-anchor="middle" x="50%" y="50%" dy=".35em" class="animatedtext"> blind guardian </text> </svg> </h3> css

recursion - Sorted Singly Linked List to BST Java -

i have sorted linked list, , void return method, need recursively construct balanced binary search tree list (which referred second parameter). , parameters can have ll head, root being created, , length of list. the method cannot destructive ll, , test tree afterwards have printtree , treedepth: public static void makebalancedtree(listnode head, treenode root, int count) { //here } public static void printtree(treenode root) { if(root != null) { //print recursive left, center, recursive right printtree(root.left); system.out.print(root.data + " "); printtree(root.right); } } public static int depth(treenode root) { if (root == null) return -1; int deep; //return larger of 2 subtree's depths, +1 deep = math.max(depth(root.right), depth(root.left)); return deep+1; } public static int countlist(listnode head) { int count = 0; listnode cursor = new listnode();

C# Polymorphism/Lists -

i've been having trouble this. i'll summarise briefly. i have 4 classes. 1 "person" class. other 3 "rental", 2 classes inheriting that, "rentalbyday" , "rentalbykm". within "person" class, there list of rental objects. issue i'm having i'm not sure how add list rental objects created. class person { private string _firstname; private string _lastname; public person(string lastname, string firstname) { _lastname = lastname; _firstname = firstname; } public string lastname { { return _lastname; } } public string firstname { { return _firstname; } } public list<rental> _rentedlist = new list<rental>(); public readonlycollection<rental> rentedlist { { return _rentedlist.asreadonly();} } public void addrental(rental rental) { _rentedlist.add(rental); } public void printrent

In App Voices (iOS) -

if had list of names in app , wanted people pronounce names correctly. how go enabling user select name , voice relay how it's said through iphone. (for example siri voice pronouncing "fred flintstone" user know how right way) you use avspeechsynthesizer class, documented here: https://developer.apple.com/library/ios/documentation/avfoundation/reference/avspeechsynthesizer_ref/

raspberry pi - Raspbian: Reset Bash environment variables -

i trying crontab working on raspberry pi , think messed environment variables. can execute file gui right-clicking , choosing execute. cannot same file run command line. can use ls see file (chrometab.sh), when type chrometab.sh , "bash: chrometab.sh: command not found" . i think messed environment variables when put in crontab. shell=/bin/sh path=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin i followed examples in script doesn't run via crontab works fine standalone . any idea i'm doing wrong? update: ok, let me clarify efforts took on part before posting question on stackoverflow before getting anymore downvotes. first of s. adam nissley suggestions. in answer steps listed above. running home path, or qualified path not work stated. error: bash: chrometab.sh: command not found ./chrometab.sh i have ensured read/write , execute permissions on file with chmod +x ./chrometab.sh also, bash script starts off following shebang

css selectors - Proper CSS syntax for assigning style attributes to a pseudo-class for multiple classes'? -

i trying set color (font-color) attribute placholder pseudo class multiple classes of inputs. (so want inputs class .red-va or .blue-va have placeholder text of given color) i can (and have) done this: .red-va::-webkit-input-placeholder { color: white; } .red-va:-moz-placeholder { /* firefox 18- */ color: white; } .red-va::-moz-placeholder { /* firefox 19+ */ color: white; } .red-va:-ms-input-placeholder { color: white; } .blue-va::-webkit-input-placeholder { color: white; } .blue-va:-moz-placeholder { /* firefox 18- */ color: white; } .blue-va::-moz-placeholder { /* firefox 19+ */ color: white; } .blue-va:-ms-input-placeholder { color: white; } basically 2 sets of css each input class, browser support requiring 4 different approaches each. is there more elegant / streamlined way of doing this? unfortunately, without making use of preprocessor (since css), best can group each set of vendor prefixes both .red-va , .blu

Android app crashes right after lanuch with simple java coding -

i'm going make short , precise; *i'm running ubuntu 14.04+ *running eclipse while connected nexus 4 (android 4.3) *started programing android application had option program @ android level 5.1 (at start of program asks set). so launched program @ first , gave error error: application requires api version 22. device api version 18 (android 4.3) i read online , changed things around in my <uses-sdk android:minsdkversion="22" android:targetsdkversion="22" /> to <uses-sdk android:minsdkversion="18" android:targetsdkversion="18" /> but app lanuches , crashes right away. error produced in logcat gc_for_alloc freed 495k, 6% free 9168k/9704k, paused 12ms, total 12ms and thats program stops @ in console activitymanager: starting: intent { act=android.intent.action.main cat= [android.intent.category.launcher] cmp=self.name.firstandroidprogram/.mainactivity lastly here code in java package

How to use Graphviz as a library in a C++ project in Eclipse -

i'm trying use graphviz in project in c++. i'm trying follow the guide . issue when try write #include <gvc.h> i get fatal error: gvc.h: no such file or directory i've installed graphviz , can run: dot -tps a.dot -o example.bmp and desired image. don't know should make work project. it's unclear how include library in eclipse or find files. 1 of things tried put source code of graphviz in project , use #include "gvc.h" but faced other include problems within in library code. i've been searching solution while couldn't find any. thanks!

Why Doctrine2 doesn't automatically quote all SQL identifiers? -

doctrine manual says: doctrine not quote identifiers automatically because leads more problems, solve. what problems there quoting everything? this quote comes older version of documentation, under basic mapping section. latest documentation doesn't include text anymore, but still true . the limitations , known issues section of latest documentation sheds light on this: for compatibility reasons between supported vendors , edge case problems doctrine 2 not automatic identifier quoting. because of different quoting strategies used in different sql vendors, , way sql generated orm, quite hard come solution works cases. , it's harder maintain. might not impossible, doctrine team decided isn't worth time, , (perhaps more importantly) code complexity, try. for hint on how complex sql generation is, browse through code in git repository . it's common best practice use alphanumeric characters (and underscores) identifiers, , not use res

ios - Distinguish between distribution and development for apple push notificiations -

when start app, registers push notifications , depending on provisioning profile generate different push token. since both adhoc , appstore provisioning profiles connect same server, have somehow distinguish kind of token is, server can connect right apple server. (sandbox/production) how can achieve that? i believe best way achieve make development/production distinction when send token server, , have server annotate type of token in database. surely have sort of api call server passing in token. in call, pass in type of token well. ex: { "token" : "abcd....", "type" : "development" } to make distinction @ build time, can use preprocessor directives detect whether it's debug build, release build, or app store build. checking if debug enabled easy, make distinction whether it's adhoc or app store, consider creating user defined variable. this, clone release scheme , create 1 called app store . in build settings ,

c - munmap anonymous shared memory in forked child -

i'd know if necessary (or advisable) unmap shared memory (using munmap ) in child created via fork , if memory obtained in parent, before fork, using mmap(..., map_anonymous | map_shared,...) , unmapped in parent, wait child. know whether necessary (or advisable) close file in child, if file opened in parent (before fork, using fopen ) , closed in parent after child terminates. i thinking of using user-defined signal , signal handler in parent wait child processes, , process -- wheter parent or not -- close file , unmap memory. signal sent processes in group process, in error occurred (i not want pass return values). actually bit more complex, want know whether need this: void sig_handler() { if (getpid() == getpgrp()) // parent while (proc_count--) wait(null); // signal has been sent child processes // every single process this: fclose(memory->file); munmap(memory, size); exit(123); } or completely ok this: void sig_handl

c# - Delaying Excel Events with CalculationState -

it understanding can check if excel still calculating (i.e. refreshing query) using calculation state. added in line syntax ensure workbook not saved until queries had been refreshed in workbook (i created test workbook 1 query , saving before 1 refresh). did set incorrectly, or did mis-understand purpose of calculation state? public form_main() { initializecomponent(); backgroundworker1.workerreportsprogress = true; backgroundworker1.dowork += new doworkeventhandler(backgroundworker1_dowork); backgroundworker1_progresschanged += new progresschangedeventhandler(backgroundworker1_progresschanged); } private void btnopenrefreshsave_click() { backgroundworker1_runworkerasync(); } private void backgroundworker1_dowork(object sender, doworkeventargs e) { excel.application exapp; excel._workbook exbook; excel._worksheet exsheet; exbook = (excel._workbook)(exapp.workbooks.open("c:\\book1.xlsx")); exsheet = (excel._worksheet)(exbook.activeshe

c++ - Create function that calculates a boolean return value for a given (floating point) time value based on edge transitions -

i want create function (in c++) return true or false given floating point time value. true or false return value needs determined based on data set of true->false , false->true transition events have occurred @ specific times. i create array of of transition events based on dataset , compare every single 1 of them given time value find recent event precedes given time, seems horribly inefficient. there better way this? maybe sort of binary search? other problem dataset of transition events continuously updated on time , can't guarantee updates received in order (although have accurate timestamps associated them). step 1: sort events timestamp, o(n log n). step 2: given time, search interval contains it; binary search o(log n). step 3: if transition @ beginning of interval t->f, answer false; if f->t, answer true. (for times before first event, @ first event , guess.)

validation - Validating numeric uniqueness of two attributes in Rails -

i have model track has 2 attributes: disc represents disc track belongs , number represents numeric order of track on album. i'd validate uniqueness of track number there can 1 unique track number per disc. instance on disc 1 (or disc 2) there can 1 track track number of 1. is there pre-existing way in rails' uniqueness validation 1 attribute dependent on another? if not best way write custom validation? you can try validates_uniqueness_of scope : validates_uniqueness_of :number, scope: [:disc, album_id] by way, on database level should validate unique index : add_index :table_name , [:number, :disc, :album_id], unique: true or use gem providing composite primary key feature.

javascript - Displaying different data through portrait/landscape view -

Image
is there way of handling when user turns portrait landscape view on web application? when looking web app on portrait view , see normal data. and when turn device landscape view see different data. my question: there way of accomplishing pure javascript , css? or have rely on api? update: found way of doing pure/plain js using device orientation api , i've found example accomplishes i'm trying can't make work because if statement interrupting me every time rotation greater 90 , if put variable check if rotation 90. function init() { var compass = document.getelementbyid('compass'), comp = document.getelementbyid("comp"); if(window.deviceorientationevent) { window.addeventlistener('deviceorientation', function(event) { var alpha; //check ios property if(event.webkitcompassheading) { alpha = event.webkitcompassheading; /