Posts

Showing posts from September, 2010

mysql - New table (with derived_data) or SQL query? -

from best-practice point of view, better create new table in database derived_data field other tables, or calculate using sql-query everytime? details: more precicely, have table orders(id_order,date,time,sum) , want track daily profits , preview them everytime administrator selects drop-down menu. shall make sql-query everytime asks it, or new table profits(date,day_profit) with derived_data field takes value other tables? for simple calculations ( a+b ), them in select . for aggregates ( count(sales), sum(revenue) ) results regularly calculate, build "summary table(s)". for example, daily counts, totals, etc, broken down region . otherwise take group by , etc. note can compute weekly or monthly totals daily table, not build more tables. see my summary tables blog . for thousand rows, not important; million or billion vital performance in "data warehousing". keep in mind summary table no-no (to database purists) since holds 'redunda

go - Parsing S&P 500 Data from Wikipedia in GoLang -

i trying figure out how parse table of s&p 500 stock page: https://en.wikipedia.org/wiki/list_of_s%26p_500_companies . python has nice libraries lxml take care of i'm trying same thing in golang. have looked making requests "net/http" not sure how perform actual parsing. thank you. i'd use lib: https://github.com/puerkitobio/goquery it gives easy use jquery selectors. i made example data: http://play.golang.org/p/kdwuiipxsu

Android can't read iPhone recorded audio files -

i record audio file ios application , send android application through web server. android application gets file when use mediaplayer class try , play it, reports error "unable to create media player" @ line mediaplayer.setdatasource(androidfilepath); mention, ios devices can read files sent app. after research found may encoding issue. tried many recording settings provided here on none has worked. here code use record audio file: avaudiosession *audiosession = [avaudiosession sharedinstance]; [audiosession setcategory:avaudiosessioncategoryrecord error:nil]; nsmutabledictionary *recordsettings = [[nsmutabledictionary alloc] initwithcapacity:10]; [recordsettings nsnumber numberwithint: kaudioformatmpeg4aac] forkey: avformatidkey]; [recordsettings setobject:[nsnumber numberwithfloat:16000.0] forkey: avsampleratekey]; [recordsettings setobject:[nsnumber numberwithint:1] forkey:avnumberofchannelskey]; [recordsettings setobject:[n

html - Invalid File on file upload PHP -

upload_file.php $allowedexts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma", "mp4"); $extension = pathinfo($_files['file']['name'], pathinfo_extension); if ((($_files["file"]["type"] == "video/mp4") || ($_files["file"]["type"] == "audio/mp3") || ($_files["file"]["type"] == "audio/wma") || ($_files["file"]["type"] == "image/pjpeg") || ($_files["file"]["type"] == "image/gif") || ($_files["file"]["type"] == "image/jpeg")) && ($_files["file"]["size"] < 20000000) && in_array($extension, $allowedexts)) { if ($_files["file"]["error"] > 0) { echo "return code: " . $_files["file"]["error"] . "

android - Fragment container with Viewpager, tabs, and drawerlayout doesn't work -

i have drawerlayout, viewpager, , tablayout in activity_main.xml have 2 fragments homefragment , bookingfragment , i'm trying launch bookingfragment activity's on itemclick. have tried multiple solutions creating framelayout id container , put pager inside , user in fragment transaction , tried making empty framelayout same id , put above pager, didn't work. here's code method i'm trying start fragment from public void starttransaction(){ fragment newfragment = new bookingfragment(); fragmenttransaction transaction = getsupportfragmentmanager().begintransaction(); transaction.add(r.id.pager, newfragment); transaction.addtobackstack(null); transaction.commit(); } here's activity_main.xml <android.support.v4.widget.drawerlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.andr

square root - How do I the calculate the sqrt of a natural or rational number in coq? -

i'm learning coq , i'm trying make own point , line data types. i'd make function returns length of line, can't seem find sqrt function return calculation. tried used coq.reals.r_sqrt , apparently that's used abstract math, won't run calculation. so tried importing coq.numbers.natural.abstract.nsqrt , coq.numbers.natint.nzsqrt. neither put sqrt function environment. this have far... require import coq.qarith.qarith_base. require import coq.numbers.natint.nzsqrt. require import coq.numbers.natural.abstract.nsqrt. require import coq.zarith.binint. inductive point : type := point : q -> q -> point. inductive line : type := line : point -> point -> line. definition line_fst (l:line) := match l | line x y => x end. definition line_snd (l:line) := match l | line x y => y end. definition point_fst (p:point) := match p | point x y => x end. definition point_snd (p:point) := match p | point x y => y

mysql - Stored Procedure - Error #1064 -

getting error during creating stored procedure callable statement: know thing simple going wrong, i'm unable figure out! my query: use demo; 1. create procedure 2. insert_emp_data (in id int, in name varchar(2), in age int, in image blob) 3. begin 4. insert emp_data values(id, name, age, image); 5. end; / sql query: create procedure insert_emp_data (in id int, in name varchar(2), in age int, in image blob) begin insert emp_data values(id, name, age, image); mysql said: documentation #1064 - have error in sql syntax; check manual corresponds mysql server version right syntax use near '' @ line 4 appreciate help! thank time! when write stored procedure in mysql, should use delimiter statement. in addition, should name columns not conflict column names. and, when using insert list columns name. so: delimiter $$ create procedure insert_emp_data ( in in_id int, in in_name varchar(2), in in_age int, in in_image blob )

javascript - Why is this.state.name not being used properly in my component? -

i have teamname store stores name of team , changes on depending on whether name clicked/hovered. teamstore.js: function setname(name) { _team = name; _original = name; } //set temp team name when sidemenu item being hovered function sethover(team) { _original = _team; _team = team; } function removehover() { //console.log(_original); _team = _original; } i have thumbnail.jsx listens store , triggers _updatearticle method when this.state.name changes. however, not working properly. the articles don't change when item being hovered. the articles change hovered item on hover leave (which shouldn't) should go original 1 clicked. thumbnail.jsx: var thumbnail = react.createclass({ mixins: [reactfiremixin], getteamstate() { return teamstore.getselected() ; }, getinitialstate() { return { name: this.getteamstate(), articles: [] }; }, getdefaultprops() {

spring - tilesConfigurer: java.lang.IllegalArgumentException: Cannot resolve ServletContextResource without ServletContext -

updated i seem have done uniquely wrong cannot find reference problem. i trying integrate tiles extant spring thymeleaf/webflow/hibernate app. everything works fine until add tilesconfigurer applicationcontext: <!-- configures tiles layout system--> <bean id="tilesconfigurer" class="org.thymeleaf.extras.tiles2.spring4.web.configurer.thymeleaftilesconfigurer"> <property name="definitions"> <list> <value>/web-inf/**/views.xml</value> </list> </property> </bean> after adding configurer, test fail, but app still runs in tomcat8 . here typical test class: package jake.prototype2.test.service; import static org.junit.assert.assertfalse; import static org.junit.assert.asserttrue; import static org.junit.assert.fail; import java.util.list; import org.junit.test; import org.junit.runner.runwith; import org.springframework.beans.factory.annotation.autowir

android - Get GCM Registration ID directly from server -

while publishing android app, created blunder. commented code used fetch gcm registration id , send our server persistence. have device id of users, however, gcm registration id missing on our server side. there way, can register users , gcm registration id server directly using respective device id? also, if gives me correct solution, beer treat assured! in short no. gcm instanceid token identifies app on device, more device's id needed generate token. google play services on client device used generate application's instanceid token . token cannot generated device id. each app on device should have unique instanceid token, being able generate externally device known parameters security issue.

How to eliminate white space after backslash (Python 3.4) -

looking advice text formatting. trying print results of simple unit conversion (imperial metric) keep getting these spaces when trying print double apostrophe symbol. code: print("you entered ", imp_height_flt, "\" converts " \ "%.2f" % imp_height_converted, "m.") when run program get: you entered 5.9 " converts 1.80 m. i'm trying eliminate space between 9 , double apostrophe. use formatting whole string: print("you entered %.1f\" converts " "%.2fm." % (imp_height_flt, imp_height_converted)) or tell print() function not use spaces separator: print("you entered ", imp_height_flt, "\" converts " "%.2f" % imp_height_converted, "m.", sep='') the default sep argument ' ' , space, can set empty string. note backslash @ end of first line not needed @ since (..) parentheses form logical line alread

swing - java JFormattedTextField -

i have jformattedtextfield dateformat. format "ddmmyy". format allows quick input.on focus lost want text in field change localdate easier read: input: "200295". converting localdate getvalue() gives localdate of 20. february 1995. , good, text "1995-02-25" ( localdate.tostring() ). when field loses focus, want text displayed in field change localdate.tostring() without actual value of field change 200295/ 20. feb 1995. is there way make text overlay field instead of changing value/text of it? sscce of have been thinking far: main class: public class formatdatetest { public static void main(string[] args) { swingutilities.invokelater(new runnable() { public void run() { new theframe(); } }); } } frame class: public class theframe extends jframe{ jpanel panel; jpanel textpanel; jformattedtextfield datefield; jbutton button; jtextarea textarea; dateformat format; public theframe() { butto

java - StringBuilder and CharSequence incompatible -

i'm beginner in java language , following oracle java tutorial gain more insight of language. when i'm studying interface part, got confused when tried exercise: "write class implements charsequence interface found in java.lang package. implementation should return string backwards. select 1 of sentences book use data. write small main method test class; make sure call 4 methods." when i'm doing this, found strange. @ first, download java.lang.charsequence interface source code , add interface file in home directory, , my implementation of 'subsequence' complains stringbuilder cannot casted charsequence type. here code: public charsequence subsequence(int start, int end) { if (start < 0) { throw new stringindexoutofboundsexception(start); } if (end > s.length()) { throw new stringindexoutofboundsexception(end); } if (start > end) { throw new stringindexoutofboundsexception(start - end); }

python - Percent signs in url -

is possible change url contains percent signs like http%3a%2f%2funiversities.ac%2fshow_article.php%3fid%3d61&amp to normal url readable human like http://universities.ac/show_article.php?id=61 using selenium? this doesn't have selenium. can use urlparse module in standard library. from urlparse import unquote # python2 urllib.parse import unquote # python3 unquote('http%3a%2f%2funiversities.ac%2fshow_article.php%3fid%3d61&amp')

`require': cannot load such file - Ruby + Rspec -

im having trouble loading dependences in ruby app (non-rails). its folder tree project -> bin -> lib -> modules -> file1.rb -> file2.rb -> spec -> file2_spec.rb my file is require 'file1' module file2 end my spec is require 'spec_helper' require_relative '../lib/modules/file2' in error message shows rspec spec/query_util_spec.rb /home/gustavo/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- file1 (loaderror) i tried add "require_relative" file1 in spec , still not work. i'll grateful give me directions change file2.rb this: require './file1' module file2 end

activerecord - Rails using 'where' to search association -

i want select notices belong character via has_one association have nil supernotice . how code this? notice.rb: belongs_to :character has_one :active_comment_relationship, class_name: "commentrelationship", foreign_key: "commenter_id", dependent: :destroy has_one :supernotice, through: :active_comment_relationship, class_name: "notice", source: :commentee accepts_nested_attributes_for :active_comment_relationship has_many :passive_comment_relationships, class_name: "commentrelationship", foreign_key: "commentee_id", dependent: :destroy has_many :comments, through: :passive_comment_relationships, class_name: "notice", source: :commenter character.rb: has_many :notic

write(), printf(), and function references in C -

a few questions simple scenario: #include <unistd.h> #include <stdio.h> void empty(){}; int main() { printf("%p\t%lu\n", empty, sizeof(empty)); write(1, empty, 100); return 0; } what happening when use function's name reference? it shows size of 1 printf still treats pointer , yet void pointer of size 8. additionally, onto write function: essentially want replicate printf %p writing value of memory address rather value @ address better handle on how works :^) thanks!

html - Bootstrap navbar width larger than viewport -

my navbar larger content. tried problem clicking threw browser css, nothing ist working. havent changed on bootstrap nor have overwritten thats in relation navbar. my css & html: /* =============================================================================================== allgemeine settings ===============================================================================================*/ html, body{ height: 100%; width: 100%; max-width: 100%; font-family: arial; } body{ overflow-x:hidden; } .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } /* =============================================================================================== landing-page settings ============================================================================

c# - Data validation in Entity Framework -

i'm using entity framework asp.net web pages (razor 3). have validation code ready, i'm using entity frameworks own validation process. there problem, example there decimal field named amount in model , database. use this: item.amount = decimal.parse(request.form["itemamount"]); here problem, if input non numeric, error (obviously). can fix checking if input numeric if that, there many validation checks way. mean, check if it's numeric first in code, entity framework checks value again i'm using 2 different validation process, seems bad me. ofcourse there client side too, maybe can use numeric textboxes, still i'm not sure. any ideas? here full code, it's horrible, i'm pretty new entity framework (like 3-4 days): if (ispost) { try { worker curworker = new worker(); try { curworker = m.workers.find(decimal.parse(request.form["workerid"])); } catch (exception)

ios - Setting BOOL to "YES" in custom delegate -

i've make delegate 2 different view controllers can communicate , i'm stuck trying set bool yes in child view controller. childviewcontroller.h @protocol pagetwoviewcontrollerdelegate; @interface pagetwoviewcontroller : uiviewcontroller { uibutton *takephototransition; } @property (nonatomic, weak) id<pagetwoviewcontrollerdelegate> delegate; @end @protocol pagetwoviewcontrollerdelegate <nsobject> - (bool)didpushtakephoto; @end childviewcontroller.m ... - (ibaction)takephototransition:(id)sender { id<pagetwoviewcontrollerdelegate> strongdelegate = self.delegate; if ([strongdelegate respondstoselector:@selector(didpushtakephoto)]) { strongdelegate.didpushtakephoto = yes; // error: no setter method 'setdidpushtakephoto:' assignment property } nslog(@"button push recieved"); } how can past error , set bool yes when button pushed? you getting confused between method , property. the definition of protocol "p

python - Open process and save specific images in related folder -

i'm looking way open , crop several tiff images , save new croped images created in same folder (related script folder). my current code looks this: from pil import image import os,platform filespath = os.path.join(os.environ['userprofile'],"desktop\python\originalimagesfolder") file in os.listdir(filespath): if file.endswith(".tif"): im = image.open(file) im.crop((3000, 6600, 3700, 6750)).save(file+"_crop.tif") this script returning me error: traceback (most recent call last): file "c:\users...\desktop\python\script.py", line 22, in im = image.open(file) file "c:\python34\lib\site-packages\pil\image.py", line 2219, in open fp = builtins.open(fp, "rb") filenotfounderror: [errno 2] no such file or directory: 'image1name.tif' 'image1name.tif' first tif image i'm trying process in folder. don't how script can give file's n

Best way to center content in android linear layout -

Image
i've created following splash screen layout using android developer studio. wanted center content consist of 2 text views , image view. following xml. <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/splash_gradient"> <relativelayout android:layout_width="fill_parent" android:layout_height="fill_parent"> <imageview id="@+id/splashscreen" android:layout_width="100dp" android:layout_height="250dp" android:paddingbottom="100dp" android:layout_centerinparent="true" android:gravity="center_vertical|center_horizontal" android:src="@drawable/splash_logo" /> <textview andro

three.js OBJLoader and precompressed gzip obj not loading -

this may unsupported library. wondering if has come across this. have tried loading obj , there no problem. if pre-compress gzip format not load , callback never called. nice gzip obj files since compression. there's nothing special in code. var loader = new three.objloader(manager); loader.load(meshurl, function (sceneobject) { sceneobject.traverse(function (child) { if (child instanceof three.mesh) { child.material = material; } }); }, onprogress, onerror); update meshurl if pointing external url uncompressed obj file, loads normal. onprogressed called , behaves you'd expect. if pointing pre-compressed gzip version of same obj, onprogress method called progress.total 0 caused code funk out. fixed, handle progress better hate answer own question turns out onprogress still being called total value being 0 if content gzipped. solution store total elsewhere, in case db loads referenced url , calc percentage loaded way. pl

meteor - Use Autoform with a custom object -

there way use autoform edit/update plain javascript object (no mongo.collection/server call)? thanks! there is. see autoform docs here on how can it.

excel - object doesn't support named arguments -

i'm writing vba code write data sql server, there no problem connection., when debug code in record set part system throws runtime error 446 object doesn't support named arguments here code `sub copyfromdatabase() dim conn adodb.connection dim recordconn adodb.connection set conn = new adodb.connection set recordconn = new adodb.connection conn.connectionstring = "provider=sqloledb.1;integrated security=sspi;persist security info=true;data source=ph03\historian;use procedure prepare=1;auto translate=true;packet size=4096;workstation id=ocg;use encryption data=false;tag column collation when possible=false;initial catalog=historianstorage" conn.open 'on error goto closeconnection recordconn .activeconnection = conn .source = "connectiontable" .locktype = adlockreadonly .cursortype = adforwardonly .open end on error goto closerecord worksheets.add range("a2").copyfromrecordset recordconn closerecord: recordconn.close 'closeconnectio

.net - windbg Type Failures after Windows update -

Image
i enabled windows updates , after updates windbg environment having type reference failures: when using !analyze -v command on dump files created after updates. ntdll symbols loads following path: c:\symbol\wntdll.pdb\bbb0846a402c4052a16b67650bbfe6b02\wntdll.pdb thereafter following type reference failures: type referenced: ntdll!_peb type referenced: ntdll!_heap_failure_information type referenced: nt!image_nt_headers32 whats strange dump files created prior windows updates not have these failures , ntdll symbols loads from: c:\symbol\wntdll.pdb\69ddfbcbbc14421d8cb974f8edc414102\wntdll.pdb i have used dbh tool on both symbol files 69ddfbcbbc14421d8cb974f8edc414102\wntdll.pdb displays information. can please provide insight. windbg version 6.3.9600.17298 sdk 8.1.

swift - Array not getting sorted -

i have array of structs . in struct have 2 nsdate objects: textlabel , detailtextlabel . i'm trying sort textlabel newest oldest date/time. , want detailtextlabel ordered based on textlabel . , want vice versa. here's code: struct item { let textlabel : nsdate let detailtextlabel : nsdate } var myitem = [item]() myitem.insert(item(textlabel: mydatesecond, detailtextlabel: anotherdatesecond), atindex: 0) myitem.insert(item(textlabel: mydatethird, detailtextlabel: anotherdatethird), atindex: 0) myitem.insert(item(textlabel: mydatefirst, detailtextlabel: anotherdatefirst), atindex: 0) @ibaction func sortbuttonsaction(sender: uibutton) { if sender == firstbtn { myitem.sort({$0.textlabel.compare($1.detailtextlabel) == nscomparisonresult.orderedascending}) } else if sender == secondbtn { myitem.sort({$0.detailtextlabel.compare($1.textlabel) == nscomparisonresult.orderedascending}) } self.tableview.reloaddata() } here's ha

Magento Get arg_name in observer -

i can set observer listen when 1 of controller method tigger, however, want pass parameter observer, how can parameter in observer? arg_value thanks lot <events> <controller_action_predispatch_mycompany_mymodule_controllername_recalculation> <observers> <mycompany_mymodule> <class>mycompany_mymodule_model_observer</class> <method>processgo</method> <args> <arg_name>arg_value</arg_name> </args> </mycompany_mymodule> </observers> </controller_action_predispatch_mycompany_mymodule_controllername_recalculation> </events> please try following <events> <event_to_observe> <observers> <observer_name> <type>singleton</type> <class>namespace_module_model_observerclass</class> <method>observermethod</method> <args>

android - Drawer Menu and Tabs working together -

i want implement bottom tabs fragment tab host , drawer menu in action bar activity. tabs or drawer menu item open same fragment. so can 1 me out .. my code as.. @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.menu_main, menu); menuitem item = menu.finditem(r.id.action_settings); item.setvisible(false); return true; } @override public boolean onoptionsitemselected(menuitem item) { if (mdrawertoggle.onoptionsitemselected(item)) { return true; } return super.onoptionsitemselected(item); } private void selectitemfromdrawer(final int position) { fragment fragment = null; switch (position) { case 0: fragment = new search(); // mtabhost.setcurrenttab(0); break; case 1: fragment = new featured(); // mtabhost.setcurrenttab(1); break; case 2: fragment = new saved(); //

javascript - jQuery to set div height -

with function below allows me set divs max height using specific class need adjust allow me set height of each row dynamically. example: the menuboxesparagraph boxes within row different height boxes within rowx need able max .menuboxesparagraph height each "row" , able set row height based on whatever max - might have .menuboxesparagraph box 298px high - highest box within specific row - row height should height <div class="row"> <div class="menu1 menuboxesparagraph"> <p>content row</p> </div> </div> <div class="rowx"> <div class="menu1 menuboxesparagraph"> <p>content row x</p> </div> </div> current jquery: $(document).ready(function() { var max = -1; $('.menuboxesparagraph').each(function() { var h = $(this).height(); max = h > max ? h : max; }); $(".menuboxespara

java - @OneToMany Column Returns LazyInitializationException - Spring -

i have following mapping in user dto store map of user properties: @entity(name = "user") public class user{ @id @column(name = "id") private long userid; @onetomany @joincolumn(name = "properties") private map<long, property> properties= new linkedhashmap<long, lkpait>(); } @entity(name = "property") public class property{ @id @column(name = "id") private long propertyid; @column(name = "name") private string propertyname; } and following @controller method @requestmapping(value = "/getuser", produces = "application/json", method = requestmethod.get) public @responsebody page<lkpfeed> getlookupfeeds(model model) { page = 1; page<user> users = userrepo.getusers(new pagerequest(page, 100)); //returns 100 users return feeds; } the @controller method executes fine (all users found) when return statement execute

python - flask-sqlalchemy. multilevel join and and sort -

posts table: class post(usermixin,db.model): __tablename__ = "posts" id = db.column(db.integer,primary_key= true) timestamp = db.column(db.string(20),index = true) author = db.column(db.integer,db.foreignkey("users.id")) post = db.column(db.string(500),index = true) comments = db.relationship("comment",backref = "post_id", lazy = "joined") comments table: class comment(usermixin,db.model): __tablename__ = "comments" id = db.column(db.integer,primary_key = true) comment_author_id = db.column(db.integer,db.foreignkey("users.id")) id_of_post = db.column(db.integer,db.foreignkey("posts.id")) timestamp = db.column(db.string(60),index = true) comment = db.column(db.string(500),index = true) comment_replies = db.relationship("reply",backref = "comment_id",lazy = "dynamic") users table: class user(usermixin,db.model):

How to fit the tab width screen in android -

Image
i implement tab layout using android support library , looks like here tab width not fit screen , layout <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.tablayout android:id="@+id/sliding_tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabmode="scrollable" /> <android.support.v4.view.viewpager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="0px" android:layout_weight="1" android:background="@android:color/white" /> </linearlayout>