Posts

Showing posts from May, 2011

ios - Added site is not blocked with content blocker -

hi writing simple content blocker app. in app want allow user add website wants block , block reasons content blocker doesn't block newly added website reasons. used sfcontentblockermanager.reloadcontentblocker(withidentifier: blockeridentifier) prints success reasons doesn't work. import uikit import cartography import swiftyjson import safariservices protocol myprotocol{ func deletesite(num:int) } class viewcontroller: uiviewcontroller, uitableviewdelegate, uitableviewdatasource, myprotocol { var tableview: uitableview = uitableview() var arr = [string]() func deletesite(num: int) { if let path = bundle.main.path(forresource: "blockerlist", oftype: "json"){ guard let data = nsdata(contentsof: url(fileurlwithpath: path)) else{ return } // json(data: data data)[num] = nil var jsonobj = json(data: data data) // jsonobj.arrayobject?.remove(at: num) print(jsonobj) if jsonobj != js...

fabricjs - Is there a method for recalculating/updating the bounding rect of an object in fabric.js? -

i trying make modifiable cubic bezier curve in fabric.js. problem have when update curve dragging control points, bounding rectangle of curve not update. i have (ugly) code here: http://codepen.io/andershj/pen/pbwqzx?editors=1000 as can see example, bounding rect not update after updating curve. is there method updating/recalculating bounding rect? ... canvas.on({ 'object:modified' : onobjectmodified }); function onobjectmodified(e) { canvas.setactiveobject(e.target.line.curve); // there method recalculate bounding rect when object modified? } ... it's bit tricky can solve this: function onobjectmodified(e) { e.target.line.curve.pathoffset = null; e.target.line.curve._setpositiondimensions({}); canvas.setactiveobject(e.target.line.curve); }

sql server - Out of Memory in vb.net -

i inserting , retrieving image database. can insert having hard time retrieving file. used varbinary(max) datatype of image. this code inserting: dim ms new memorystream picturebox1.image.save(ms, picturebox1.image.rawformat) dim img() byte img = ms.toarray() cmd.commandtext = "insert stud values ('" & studno.text & "', '" & password.text & "', '" & fname.text & "', '" & mname.text & "', '" & lname.text & "', @img, '" & gender.text & "', '" & mm.text & "/" & dd.text & "/" & yyyy.text & "', '" & phone.text & "', '" & address.text & "', 'student', '" & secquest.text & "', '" & answersq.text & "', '" & textbox1.text & "', ...

vb.net - "Please Wait" Form not rendering when called -

i writing program lot of processes @ once. keep user thinking program crashed, decided add "please wait" window. works fine except 1 thing: form doesn't render until 30 seconds later. before "please wait until..." text supposed in form white rectangle. can please tell me how can fix issue? thanks! edit: as assumed had crystal ball , read virtual mind, forgot include code >.>;; here is: private sub button3_click(sender object, e eventargs) handles button3.click dim pleasewait new testespere centerform(pleasewait) pleasewait.show() dim quantity, quantity_purchased integer dim tracking_usps, lybro_id, recipient_name, order_id, order_item_id, payments_transaction_id, product_id, description, listing_id, sku, batch_id, buyer_email, buyer_name, address_1, address_2, city, state, zip, country, special_comments, upc, status_shipment, loc, tracking, etc, eff string dim total_price, peso, order_price, shipping...

javascript - jquery module loading with webpack -

i stumbled across webpack , think can improve application. before try guess want explain problem. i'm writing javascript app without front end framework, handlebar , jquery, using node.js backend. says app has dashboard, profile , contact. found many script doesn't have in index.html. need validation library or jquery plugin contact page, isn't waste load when user come dashboard page? that's 3 pages, image if app has 50 pages. webpack right tool problem?

wordpress - What is the best payment gateway for conference fee collection? -

currently designing international conference web using wordpress. for registration process, need payment gateway money registration fee in different currencies, indian rupee , dollars , pounds, what best payment gateway conference fee collection allows me money in different currencies different countries? ps: note that, our conference expect not more 150 participants. so try cheap , best possible. there other suggestion regarding issue?? heidelpay or stripe . use them conferences, too. though conference create website hosts 400 people, amount not changing conditions much.

java - Android: Searching simple library for drawing undirected graphs -

Image
i searching simple library draw undirected graphs. show simple network map in android app, containing nodes , links between them. to make more clear, i'm thinking of simple that: graph graph = new graph(); node = new node("name of node a"); // name should displayed node b = new node("name of node b"); link ab = new link(a,b, "name of link"); // name should displayed graph.add(a); graph.add(b); graph.add(ab); ab.setcolor(color.red); bitmap result = graph.getbitmap(500, 500); // 500,500 = size in px there graph libraries java available, haven't found 1 works android. (they're using java ui stuff not available in android.) does know such library works android?

Sort C# ListBox Items -

Image
i'm using c# adapter method, add elements list , after call list fill listbox, here button that: private void button1_click(object sender, eventargs e) { listcustomers.items.clear(); list < customer > customers = customerlist.getcustomers(); list < customersaldo > customerssaldo = customerlistsaldo.getcustomers(); int total = 0; int totalcustomer = 0; foreach(customer customer in customers) total++; listcustomers.items.clear(); totalcustomer = total; int x = totalcustomer; foreach(customersaldo customer2 in customerssaldo) { if (x >= 1) { listcustomers.items.add("costumer id # " + x + " is: " + customer2.saldo); x--; } } } this get, it's ok want know if exists way example: costumer #1 saldo... costumer #2 saldo... costumer #3 saldo... if see code have variable x , variable total number of costumers, think sort has start variable, don't know how it, can do? re...

javascript - How to "view" the canvas being drawn on live -

i've not experimented canvases before. i've made project involves canvas gets continually extended, new rows of "data" being appended bottom of it. i've got actual rendering part working fine; final output want be... intention project able watch gets drawn on screen. however, instead happens canvas hangs few seconds, , displays @ once. happens in chrome @ least, i've not tested other browsers. i'm using loop following: for(var = 0; < 500; i++){ addrow(data, canvas); } and want view each row it's being drawn. any ideas how this? since javascript single-threaded, canvas cannot redrawn while loop running. you have create idle moments in between calls addrow , javascript thread freed act on new data. making calls addrow asynchronous; easiest way (ab)use standard function settimeout 1 . settimeout takes function , executes function asynchronously, after given delay (if omit delay parameter, delay of 0ms assumed). called ...

scala - linking error on parsing java.time.LocalDate in scalajs -

when want parse localdate in scalajs, linking error occur: java.time.localdate.parse("2016-11-11") here error message: [error] referring non-existent method java.time.localdate$.parse(java.lang.charsequence)java.time.localdate [error] called example.scalajsexample$$anonfun$myview$1.applyorelse(scala.collection.immutable.list,scala.function1)java.lang.object [error] called example.scalajsexample$$anonfun$myview$1.applyorelse(java.lang.object,scala.function1)java.lang.object [error] called scala.concurrent.future$class.$$anonfun$1(scala.concurrent.future,scala.partialfunction,scala.util.try)java.lang.object but using java.time.localdate.of(2016,11,11) works without error. what problem?! because java.time.localdate.parse not implemented. might try of alternative libraries java.time support, if 1 of them supports it. otherwise, guess contribute implementation.

multithreading - C# ProgressBar Databindings in backgroundworker -

i'm no expert in c# i'm trying update progressbar in background worker. i'm using following code: progressbar1.databindings.add("value", _dm, "progress", true, datasourceupdatemode.onpropertychanged); this works when executed without background worker, on gui thread. progress property property updates (using inotifypropertychanged) progress of backgroundworker (where don't have access to). how can make work updates use of backgroundworker instead of putting on gui thread? my code (simplified): class downloadmanager : inotifypropertychanged { public event propertychangedeventhandler propertychanged; private double _progressvalue; public double progress { { return _progressvalue; } private set { if (!value.equals(_progressvalue)) { _progressvalue = value; propertychanged?.invoke(this, new propertychangedeventar...

android - Moving navigation drawer items to right -

i need please me. have navigation drawer in app. want move navigation drawer right . moved navigation want move menu items right too. my screenshot of navigation drawer activity_main: <?xml version="1.0" encoding="utf-8"?> <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.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_marginleft="100dip" android:fitssystemwindows="true" tools:opendrawer="end"> <include layout="@layout/app_bar_main" android:layout_width="match_parent" android:layout_height="match_parent" /> ...

javascript - How to make a text that changes and animates? -

i practicing html , css, along basic javascript. want make text changes after period like: i hello ii hello ii iii hello iii or that, idea. want change after small period half second. after searching internet , stackoverflow, haven't found solution yet. can direct me on how properly? use setinterval , below function that: var el = document.getelementbyid("foo"); var countofi = 1; setinterval(function() { if (countofi > 10) countofi = 1; var = new array(countofi).fill('i').join(""); el.innerhtml = + " hello " + i; countofi++; }, 500) <div id="foo"></div>

mysql - PHP | MySQLi prepared statements - Handling order by and order type parameters -

in order avoid sql injection made researched , based on this answer started use mysqli prepared statemets. went fine until got order by , order type parameters sent frontend based on user clicks. more specific have tables headers , user can arrange data considering name, price, date, etc , can choose between asc or desc . store input type hidden guess might able change using firebug . because of need sure can't inject database. $stmt = $dbconnection->prepare('select * mytable 1 order ? ?'); $stmt->bind_param('ss', $_get['order_by'], $_get['order_type']); it seems error. did researches , said there no solution this, person said solution hardcoded , person said have quit using prepared statements , try mysql_real_escape_string in answer linked say: if you're using recent version of php, mysql_real_escape_string option outlined below no longer available so gueess not way also. question remains, should next? there solutio...

How to add multilevel accordion in wordpress using jQuery UI -

i'm trying add multilevel accordion wordpress site. made fiddle here working in wordpress multilevel not working ! show first level multilevel showing. please help. i want use wordpress jquery library , add jquery ui theme function.php add bellow code function add_jquery_ui() { wp_enqueue_script( 'jquery-ui-core' ); wp_enqueue_script( 'jquery-ui-accordion' ); } add_action( 'wp_enqueue_scripts', 'add_jquery_ui' ); then add code theme footer.php before </body> section jquery(function($) { $(".lifetime-faq").accordion({ autoheight: false, collapsible: true, active: false }); $(function () { var icons = { header: "iconclosed", // custom icon class activeheader: "iconopen" // custom icon class }; $(".lifetime-faq").accordion({ icons: icons }); }); });

python - How to rotate ellipse in PIL(Pillow) -

so want add rotated ellipse (with transparency) onto image. how can this? so: def create_ellipse(fi): ellipse = image.new('rgba', (4*b, b*2), (255,255,255,0)) draw_ellipse = imagedraw.draw(ellipse, "rgba") draw = imagedraw.draw(im, 'rgba') l in range(b, -1, -1): colour = (red, green, blue, int(alpha/(b))) draw_ellipse.ellipse((b*2-l*2, b-l, b*2+l*2, b+l), fill=colour) rotated = ellipse.rotate(fi, expand=1, resample=image.bicubic) im.paste(rotated, (x0-2*b, y0-b), rotated) return im but main picture has gray background have problems opacity.

reverse engineering - Java deobfuscator supporting variable renaming? -

i'm trying reverse engineering .jar file (basically group of .class files). however, there 2 difficulties: some of variables, methods , classes named unicode characters , cannot displayed. makes source editing inconvenient. some of classes named java keywords (such if ). therefore java compiler complain when recompiling reverse-engineered source files. are there java deobfuscators can overcome these difficulties? there several tools can rename java identifers. example, can run proguard on rename everything. that being said, suggest reconsidering approach. java compilation , decompilation both lossy processes. decompilation useful reverse engineering, cannot expect able recompile decompiled code. if has been obfuscated, may forget it. the best way modify obfuscated code use krakatau assembler , disassembler . krakatau assembly can reversibly transformed , bytecode, meaning can edit arbitrary classes without messing things up, no matter how have been obfus...

ruby on rails - Create a form data when saving another form -

i need able save form's data when data form sent. should know 2 forms not related these 2 forms: <%= form_for(@relcliruta, remote: true, html: {class: "form-horizontal"}) |f| %> <!--ajax remote: true--> <div class="field"> <%= f.hidden_field :idruta, value: params[:id] %> </div> <div class="field"> <%= f.hidden_field :idcliente, value: cliente.id%> </div> <div class="field"> <%= f.hidden_field :idempresa, value: current_usuario.empresa_id %> </div> </div> <%= submit_tag "añadir", class: "btn btn-warning btn-xs"%> <%end%> <%= form_for(@reldayc, remote: true, html: {class: "form-horizontal"}) |f| %> ...

python - Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 while Installing PyNaCl -

i'm trying install pynacl on ubuntu 16.04 , i'm getting error on title; whole traceback: collecting pynacl using cached pynacl-1.0.1.tar.gz complete output command python setup.py egg_info: package libffi not found in pkg-config search path. perhaps should add directory containing `libffi.pc' pkg_config_path environment variable no package 'libffi' found package libffi not found in pkg-config search path. perhaps should add directory containing `libffi.pc' pkg_config_path environment variable no package 'libffi' found package libffi not found in pkg-config search path. perhaps should add directory containing `libffi.pc' pkg_config_path environment variable no package 'libffi' found package libffi not found in pkg-config search path. perhaps should add directory containing `libffi.pc' pkg_config_path environment variable no package 'libffi' found packag...

android - Fragments - statically defined fragments cannot be replaced -

i'm studying fragments in android. read tutorial https://www.tutorialspoint.com/android/android_single_fragments.htm . in tutorial, 2 fragment , 1 activity(main activity) defined. 2 fragments added main activity statically in xml file. in mainactivity class, 1 fragment's layout replaced root element of main activity invoking fragmenttransaction.replace(android.r.id.content, ls_fragment); however, in tutorial said : you cannot replace fragment defined statically in layout file via fragmenttransaction. if understand correctly, these 2 tutorials conflict, because statically defined fragments replaced in tutorialspoint's example , second tutorial says statically defined fragment cannot replaced.

function - Play or pause an audio file (onkeydown) with JavaScript -

i have following code that's working playing audio file when pressing on shift (keycode: 16). what want press shift again , pause song. should have possibility play/pause multiple times. html: <audio id="audio" src="audio/song.mp3" autostart="false"></audio> javascript: var sound = { 16: 'audio' }; document.onkeydown = function (e) { var soundid = sound[e.keycode]; if (soundid) document.getelementbyid(soundid).play(); else console.log("key not mapped : code is", e.keycode); } check audio paused, if is, play it, otherwise pause it var sound = { 16: 'audio' }; document.addeventlistener('keydown', function(e) { var soundid = sound[e.which || e.keycode]; if (soundid) { var elem = document.getelementbyid(soundid); if ( elem.paused ) { elem.play(); } else { elem.pause(); } } else { con...

multithreading - python logging shows no sys.stdout when from different thread -

i have strange problem logging in multithreaded python application. whenever debug application, see logging output in stdout, such 2016-11-05 21:51:36,851 (connectionpool.py:735 mainthread) info - requests.packages.urllib3.connectionpool: "starting new https connection (1): api.telegram.org" 2016-11-05 21:51:41,920 (converter.py:16 workerthread1) debug - converter: "resizing file test/test_input/" 2016-11-05 21:51:50,199 (bot.py:221 workerthread1) error - __main__: "moviepy error: failed read duration of file test/test_input/. however, when run code without debug, logs workingthread1 disappear, leaving mainthread ones. code unchanged , error remains. guess has multithreading. workerthread1 started pytelegrambotapi framework. have logs output sys.stdout : formatter = logging.formatter( '%(asctime)s (%(filename)s:%(lineno)d %(threadname)s) %(levelname)s - %(name)s: "%(message)s"') stream_handler = logging.streamhandler(sys...

html - CSS height auto clips contents on small device -

if height set auto, why on big screens whole content of responsive div shown, on smaller device height not adjusted go show contents, content clipped or cut, how fix issue? .mycontainer { height: auto; } <div class="mycontainer"> lots of text in divs </div> the above cut text content on smaller device. this basic vertical-align issue. don't have specific html or css...which helpful next time, going on template page sent: display properties of parallax-container , text container need changed display:table; , display:table-cell; can add vertical-align:middle; text container move text vertically without cutting off. however, since font same size on screens, might want use media queries compress on smaller screens, making better visibility on smaller devices well.

javascript - Ionic blank screen in browser but works on device -

originally when started project ionic serve working fine in project before, until recently. when using ionic serve blank white screen navbar showing. works fine when doing ionic build android , running on mobile. also don't see console errors, or network errors @ all.

.net - Why do we need to lock and object in C#? -

this i've never understood. seems hack create dummy object gets lock ed, example class account { decimal balance; private object thislock = new object(); public void withdraw(decimal amount) { lock (thislock) { if (amount > balance) { throw new exception("insufficient funds"); } balance -= amount; } } } from https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx . why couldn't language designers make class account { decimal balance; public void withdraw(decimal amount) { lock { if (amount > balance) { throw new exception("insufficient funds"); } balance -= amount; } } } would equivalent? the instance passed lock serves identify critical section . you may h...

java - Threadpool task executor timeout for working thread -

i using spring boot , have 1 async method. execute async have below configuration, questions if 5 thread hangs reason , lock application , none of new task executed (it keep accepting). how can set timeout working thread , lets 120 seconds, after timesout , execute new task. (yes using fixed thread pool unbounded queue keep accepting tasks) @enableasync @configuration public class asyncconfiguration implements asyncconfigurer { @override public executor getasyncexecutor() { threadpooltaskexecutor taskexecutor = new threadpooltaskexecutor(); taskexecutor.setcorepoolsize(5); taskexecutor.setmaxpoolsize(5); taskexecutor.initialize(); return taskexecutor; } @override public asyncuncaughtexceptionhandler getasyncuncaughtexceptionhandler() { return new simpleasyncuncaughtexceptionhandler(); } } you can create executor like: static class timeoutexecutorservice extends completableexecutors.delegatingcompletableexecutorservice { private final dur...

Cannot generate scatterplot in R. Printing plot returns NULL -

unable generate scatterplot, code: png(file = "monthvsuniquecode.png") p1<-plot(x = month_uc$new.col,y = month_uc$uniquecode, xlab = "month", ylab = "uniquecode", main = "month vs uniquecode" ) dev.off() print(p1) printing plot returns null. print(p1) null my month_uc dataframe has 56003 rows , 2 columns (uniquecode int, month char) note: i've learnt r 4 hours back. doing wrong? i believe basic plotting functions not allow plots assigned objects. can do: png(file = "monthvsuniquecode.png") plot(x = month_uc$new.col, y = month_uc$uniquecode, xlab = "month", ylab = "uniquecode", main = "month vs uniquecode" ) dev.off() to save png. or just: plot(x = month_uc$new.col, y = month_uc$uniquecode, xlab = "month", ylab = "uniquecode", main = "month vs uniquecode" ) to display it. ...

python - Delete h2 until you reach the next h2 in beautifulsoup -

considering following html: <h2 id="example">cool stuff</h2> <ul> <li>hi</li> </ul> <div> <h2 id="cool"><h2> <ul><li>zz</li> </ul> </div> and following list: ignore_list = ['example','lalala'] my goal is, while going through html using beautifulsoup, find h2 has id in list (ignore_list) should delete ul , lis under until find h2. check if next h2 in ignore list, if is, delete ul , lis until reach next h2 (or if there no h2s left, delete ul , lis under current 1 , stop). how see process going: read h2s down in dom. if id of in ignore_list, delete ul , li under h2 until reach next h2. if there no h2, delete ul , li stop. here full hmtl trying work with: http://pastebin.com/z3ev9c8n i trying delete ul , lis after "see_also" how accomplish in python? below solution came with. remove content don't want try: e...

Store the enum constants in variable -

this code works fine, question have code how store enum constant in variable, , why use enum? , statement mean housetype housetype; ? thank in advance. import java.util.scanner; public class homebuying { public enum housetype{unknown,singlefamily,townhouse,condominium}; public static void main(string[] args) { scanner input = new scanner(system.in); system.out.println("enter type of house want purchase"); //1.single family/n" " 2. townhouse/n" " 3. condominium/n"); int choice = input.nextint(); housetype housetype; switch(choice) { case 1: housetype = housetype.singlefamily; break; case 2: housetype = housetype.townhouse; break; case 3: housetype = housetype.condominium; break; default: housetype = housetype.unknown; break; } system.out.println(h...

regex negation - How to exclude certain characters from Html tags when webscraping data using python -

i trying webscrape data learn, problem when use find_all('td') cell value, 1 of cell value % sign ,this messes format , puts in different line (when convert later table output), how exclude % sign ? using python 2.7 r = requests.get("http://www.tradingeconomics.com/united-states/indicators") soup = beautifulsoup(r.content) ecodatasaved = "" record in soup.find_all('tr'): ecodata = "" data in record.find_all('td'): ##this % sign comes s = data.text ecodata = ecodata + "," + s.strip() ecodatasaved = ecodatasaved + "\n" + ecodata[1:]

java - How can I include in my program that the integers entered must be between 0 and 100? -

the exercise asked me calculate average, maximum, , minimum. code fulfills purpose, need include somewhere in code exam grades entered user must between 0 , 100. best way include this? here code. import java.util.scanner; import java.io.*; import java.text.decimalformat; public class hw { public static void main ( string[] args ) { int maxgrade = integer.min_value; int mingrade = integer.max_value; int count=0; int total=0; final int sentinel = -1; int score; scanner scan = new scanner( system.in); system.out.println( "to calculate class average, enter each test score."); system.out.println( "when finished, enter -1."); system.out.print( "enter first test score > "); score = scan.nextint(); while (score != sentinel ) { total += score; count ++; if( score > maxgrade) maxgrade = score; if( score < mingrade) mingrade = score...

shell - How to create a unix script that outputs data inside of an html table? -

#!/bin/bash echo "<html><table border=2>" echo"<tr><th>letter </th> <th>total</th> <th>start</th> <th> end</th></tr>" in $(cat "alphafile"); t=`grep -c $i /path/to/my/file`; b=`grep -c ^$i /path/to/my/file`; e=`grep -c $i$ /path/to/my/file`; echo"<tr><td> "$i" </td> <td> "$t" </td> <td> "$b" </td> <td> "$e" </td></tr>" done echo"</table></html>" this outputs correct data it's outputting literal syntax html table instead of creating table. how can make html recognized html output inside of html table? try installing bcat . on ubuntu can following (on mac try homebrew): sudo apt-get install ruby-bcat and doing this: yourscript.sh | bcat

python 2.7 - If statements and strings -

how can code respond string inputs? want if answer yes or no. tried this. yes = 'yes' yesorno = input('yes or no?') if yesorno == yes: print'you said yes' no matter typed input, say,'you said yes'. in python 2 input doesn't return string, object. want choice = raw_input('yes or no?\n') if choice == 'yes': print 'you said yes' else: print 'you said no' raw_input return string.

swift - How to access music files stored on the iOS device? -

my application having trouble locating files in music folder on ios device. if files held below application data (in playpen), no problem. when go looking "music" folder, using following lines: dest_dir = try! filemanager.default.url(for: .musicdirectory, in: .alldomainsmask, appropriatefor: nil, create: false) musicdir = dest_dir if uiapplication.shared.canopenurl(musicdir) { print("found music directory") }else { print("did not find music directory") } when code executes canopenurl , permissions complaint. i tried accessing user directory (thinking navigate music). any clues on how application can access files , playlists held under music system folder on ios device? there no such thing "the music folder" in ios. access user's music library , use media player framework. example (assuming have obtained necessary authorization user): let query = mpmediaquery() let result = query.items

javascript - Want to close the sidepanel using the minus icon -

currently sidepanel opens using plus symbol , closed using close btn on sidepanel. plus symbol changes minus doesn't go plus when sidepanel closed , want able click minus symbol , close sidepanel well. hope made point clear. here jsfiddle related it: https://jsfiddle.net/bob_js/h9yfbden/1/ html <div class="container"> <i class="glyphicon glyphicon-plus-sign cd-btn"></i> </div> <div class="cd-panel-nvv from-right"> <header class="cd-panel-header"> <a href="#0" class="cd-panel-close"></a> </header> <div class="cd-panel-container"> content </div> </div> css .glyphicon-plus-sign, .glyphicon-minus-sign{ top: 30%; position: absolute !important; z-index: 1; color: rgb(255, 133, 102); background-color: #fff; border-radius: 50%; border: 1px solid ...

python - PeeWee PostgreSQL Database creation: does not exist -

i'm attempting create postgresql database using peewee . upon connecting following error: file "peewee_test.py", line 44, in psql_db.connect() file "c:\python27\lib\site-packages\peewee.py", line 3602, in connect self.initialize_connection(self._local.conn) file "c:\python27\lib\site-packages\peewee.py", line 3514, in exit reraise(new_type, new_type(*exc_args), traceback) file "c:\python27\lib\site-packages\peewee.py", line 3600, in connect **self.connect_kwargs) file "c:\python27\lib\site-packages\playhouse\postgres_ext.py", line 385, in _connect conn = super(postgresqlextdatabase, self)._connect(database, **kwargs) file "c:\python27\lib\site-packages\peewee.py", line 3990, in _connect conn = psycopg2.connect(database=database, **kwargs) file "c:\python27\lib\site-packages\psycopg2__init__.py", line 164, in connect conn = _connect(dsn, c...

python - Two Implementations of MergeSort with Vastly Different Running TImes -

i beginner learning algorithms fun, , trying implement merge sort in python. below implementation. slow when feed 100000 list. def mergesortedlist(l, r): lr = [0]*(len(l)+len(r)) ##merged output (lr combined) i= 0 ##counter left side j= 0 ##counter ride side k = 0 while <= len(l) , j <= len(r): if == len(l): lr[k:]= r[j:] return lr elif j == len(r): lr[k:] = l[i:] return lr elif l[i] < r[j]: lr[k]= l[i] i+=1 k+=1 else: ##left side bigger right side lr[k]=r[j] j+=1 k+=1 def mergesort(n): if len(n) <= 1: return n else: sub1 = n[0:round(len(n)/2)] sub2 = n[round(len(n)/2):] return mergesortedlist(mergesort(sub1), mergesort(sub2)) here's implementation found somewhere online website ( http://interactivepython.org/courselib/static/p...

java - How do you make variables made inside a method available to all other methods in a class? -

i'm coding newb , want learn more java. i'm taking introductory programming course in high school , trying play around outside of class. program i'm creating supposed print out few instructions , questions in console, want retrieve user input using scanner , variable. goal of program user able create 'drawing' based on pure instinct, drawing displayed after fact. here's problem. i'm asking user , storing information in variables native main method, need use information in paintcomponent method. i tried adding static in front of variable such as: static int emptyrectw1 = kboard.nextint(); shows error " illegal modifier parametic emptyrectw1; final permitted. " i knew long shot trying out, that's best i've got. i'm using java eclipse ide. help, looks way learn mess , have else point out mistake! :) here's code: import java.util.scanner; import java.awt.graphics; import java.awt.color; import java.awt.container; impor...

java - About servlets in Spring MVC -

Image
these errors in picture. not know how work it, , have tried change library, without success. please me if can. thank you. this seems more of issue eclipse work-space or way have created project. should check build path , make sure libraries present. also in left pane, don't see reference libraries list down libraries in use.

python - Flask: cannot import name 'app' -

trying run python file updater.py ssh server , run commands every few set intervals or so. i'm using apscheduler run function update_printer() __init__.py . got working outside of application context error suggested import app __init__ .py. isn't working out well. keep getting cannot import name 'app' error. app.py from queue_app import app if __name__ == '__main__': app.run(debug=true) __init__.py from flask import flask, render_template apscheduler.schedulers.background import backgroundscheduler queue_app.updater import update_printer app = flask(__name__) app.config.from_object('config') @app.before_first_request def init(): sched = backgroundscheduler() sched.start() sched.add_job(update_printer, 'interval', seconds=10) @app.route('/') def index(): return render_template('index.html') updater.py import paramiko import json queue_app import app def update_printer(): ssh = paramik...

java - How to get a random item from a list with some preference -

this question has answer here: random weighted selection in java 6 answers i want randomly select item list sort of preference increase probability of items picked on others in java. have done normal random selection want include this. thinking of increasing number of particular item, duplicating multiple times in list, don't feel it's right way go. my other idea might involve 2 dimensional array, maybe apples have integer point of 6, orange have point of 3. way apples have more preference orange. i'm suggesting, don't know how use multidimensional arrays. any ideas welcome. assuming preference mean setting itmes selected more number of times in several runs. lets have items 0,1,2,3,4,5,6,7,8,9 do grouping group 1(preference 2 - low preference) 0,1,2,3,4,5,6,7,8,9 group 2(preference 1 - medium preference) 0,1,2,3,4,5,6 group 3(...