Posts

Showing posts from July, 2013

c# - How to get list of SQL Servers 2016 on local machine ( in the most correct way )? -

unfortunately old ways listed in topic how list of sql server instances on local machine? seems working new versions of sql servers have. i have sql server 2016. i can server list register don't think can call "correct way". so question correct way list? thank suggestions!

express - AngularJS $resource returns empty object and doesn't update with data -

Image
i have basic get/post api right angularjs , express/node. i'm trying make spa angular can add, get, , delete boards (basically post-it notes web). every time button clicked, fires $scope.addboard, $resource object makes post request. it fires alright, returns empty object updates html automatically empty data only. if want board populated information, have manual refresh of whole page. tried incorporating call , using promise, can't either option work. there way can html update automatically full data after post request made angular way?? services.js krelloapp.factory('boards', ['$resource', function($resource) { return $resource('api/boards/:id', {}, { get: {method: 'get', isarray: true}, add: {method: 'post', transformresponse: []} }); }]); controller.js krelloapp.controller('boardcontroller', ['$scope', '$resource', '$location', '$http', 'boards', function($s...

asp.net - Autogenerated number with the use of date and time c# -

having trouble on how going autogenerate number use of date , time. example, need generate kind of number, 16-9685 with, 16 = year , 9685 randomized , shown in textbox. tried 1 unfortunately, doesn't work. helping var random = new random(system.datetime.now.year); int randomnumber = random.next(-1000, -1); textboxsesid.text = randomnumber.tostring(); // keep _r member, not local random _r = new random(); ... // gen random number int rand = _r.next(1, 10000); // "2016-" prefix string yearprefix = datetime.now.year + "-"; // remove first 2 digits of year prefix, "16-" yearprefix = yearprefix.substring(2); // put year prefix random number textbox textboxsesid.text = yearprefix + rand;

listview - Android #View.getHeight() doesn't return correct value -

i have listview in screen. listview fills 2/3 of screen (so height varies on different devices). have - lets 50 items in array list - need put x number of items in visible user (e.g on small screen 3, on normal screen 5, on tablet 8). so way i'm doing getting height of listview in px, dp size , since know height of each row 60dp divide height of listviwe in dp format height of row (which 60dp). returns number of items visible user , pass number getcount() method of adapter populate amount of items. this code, have observer assigned in oncreate() method this.mlistview.getviewtreeobserver().addongloballayoutlistener(mlistviewgloballistener); viewtreeobserver.ongloballayoutlistener mlistviewgloballistener = new viewtreeobserver.ongloballayoutlistener() { @override public void ongloballayout() { removelistviewlistener(); if (mlistview == null || madapter == null) { ...

Reading data from csv file put into dictionary python -

blockquote help me read csv file. have csv file test8.csv , want read data file , put dict , csv file : 1st row matrices size of value dict create, 2nd row key of dict , next matrix of value of key : file csv: 1,5 offense involving children 95 96 35 80 100 2,2 battery,theft 173,209 173,224 output expectation: dict={['offense involving children']: [(95,), (96,), (35,), (80,), (100,)], ['battery', 'theft']:[(173, 209), (173, 224)]} this piece of code, , don't have idea continue: _dir = r'd:\s2\semester 3\tesis\phyton\hasil' open(os.path.join(_dir, 'test8.csv'), 'rb') csv_file: datareader= csv.reader(csv_file, delimiter=' ', quotechar='|') that isn't csv file , csv module can't you. in csv file, each line has equal number of columnar fields separated known character such comma. need write own parser data. this script build dictionary (except uses tuple k...

jquery - Error in update and insert query in php mysql -

i trying update seen(a bool in database) if seen button clicked , delete row if delete button clicked. doesn't seem work nor data(mysql_error) back. last else part works , data. this php code : if(isset($_post["seen"])){ $fid=$_post["id"]; $sql="update feedback set seen=1 id=$fid"; mysql_query($sql,$con); echo mysql_error($con); } else if(isset($_post["delete"])){ $fid=$_post["id"]; $sql="delete feedback id=$fid"; mysql_query($sql,$con); echo mysql_error($con); } else{ $sql="select * feedback"; $result=mysql_query($sql,$con); while($row=mysql_fetch_array($result)){ $jsondata[]=$row; } echo json_encode($jsondata); } and js code: $("#seen").click(function(){ $.post("main_php.php",{},function(data){ alert(data); }); }); $("#delete").click(function(){ var fid = $('#id').val(); $.post...

excel vba - VBA - Closing or clicking OK in MsgBox from another workbook, -

hi following code in excel vba, sub () workbooks.open ("a.xls") activeworkbook.worksheets("1").select activesheet.commandbutton1.value = true end sub i'm opening workbook (the code inside protected can't modify workbook "b") , clicking run button on worksheet, , returns msgbox ok button. i want know how can use vba close msgbox or clicking "ok" ...i tried use, `application.displayalert = false` before opening workbook "b" not work.. thanks help! there might approach using sendkeys -- sendkeys notoriously temperamental. here more reliable approach: 1) if don't have organized this, have click-event handler of button 1-line sub looks like: private sub commandbutton1_click() process end sub where process sub heavy lifting. in general, think idea have event handlers functioning dispatchers subs. 2) change code process (or whatever choose name it) in following way: a) modify ...

Why is a variable of a predefined type included under "generic"? (Ada) -

i'm in college cs, , started data structures , algorithms class. professor prefers (practically forces us) use ada. in order ahead, started looking things , found snippet of code describing how generic stack might written: generic max: positive; type element_t private; package generic_stack procedure push (e: element_t); function pop return element_t; end generic_stack; what stuck out me variable "max." since of type positive, didn't seem logical generic. perhaps i'm still new idea, thought idea behind generic empty shell , can interchanged different data types upon instantiating. maybe don't understand generics enough. if not, please enlighten me? having variable in formal part of generic way pass constant (at compile time) configure generic. such constant can used define other variables in data structures (like array (1..max)), cannot achieved passing value parameter subprogram. also, ensures both push , pop used same "max...

mysql - INSERT query in PHP Failing (returns blank error) -

this question has answer here: can mix mysql apis in php? 5 answers i'm using following code in attempt insert user-provided values in <form> sql table. when insert query used in phpmyadmin, insertion successful, unsuccessful in following php. connection database successful. <?php $servername = "localhost"; $username = "***"; $password = "***"; $db_name = "my_db"; $trip; $odom; $gals; $ppg; if (isset($_request['trip'])){ $trip = $_request['trip']; $odom = $_request['odom']; $gals = $_request['gals']; $ppg = $_request['ppg']; } // create connection $conn = mysqli_connect($servername, $username, $db_name, $password); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } echo "connected "; here...

sql - How to turn repeated ranking(1-5) row data to column data in TSQL -

i have table data: id sale weekday 1 12 1 2 15 2 3 16 3 4 17 4 5 18 5 6 11 1 7 13 2 8 14 3 9 15 4 10 20 5 11 25 1 12 14 2 13 18 3 14 21 4 15 11 5 .. .. i'd turn into: mo tu th fr 12 15 16 17 18 11 13 14 15 20 25 14 18 21 11 .. thank you! try this select sum(case when weekday = 1 sale else 0 end) mn, sum(case when weekday = 2 sale else 0 end) tu, sum(case when weekday = 3 sale else 0 end) we, sum(case when weekday = 4 sale else 0 end) th, sum(case when weekday = 5 sale else 0 end) fr ( select *, row_number()over(partition weekday order id ) seq_no tablename ) group seq_no as mentioned in sample data if table has 5 days week select sum(case when weekday = 1 sale else 0 end) mn, sum(case when weekday = 2...

PHP comment in array? -

i'm trying comment out snippet between ~/**********/~ in below code inside of php function: $photobody[]="<tr><td colspan=\"".$cols."\"> <table width=\"100%\" border=\"0\"> <tr><td width=\"33%\"> <div align=\"left\" class=\"caption\">".$prev."</div></td> <td width=\"33%\"> ~/***** <div align=\"center\" class=\"caption\">photos <strong>".($photonum-(($rows*$cols)-1))."</strong> <strong>".$endnum."</strong> of <strong>".count($photos)."</strong> <br />".$photopage."</div> ****/~ </td><td width=\"33%\"> <div align=\"right\" class=\"caption\">".$next....

ios - ipa size is increased instead of decreasing Xcode 7.2 -

previously using xcode7.0.1 using xcode7.2 , size of ipa file of project around 44mb . have deleted 22mb of unused images project, size of overall project decreased 22mb , generated ipa file size increased instead of decreasing. size 53mb . ideas possible reason kind of peculiar behaviour? i followed similar discussion on github nothing out of it. for generating ipa file followed following steps: xcode -> product -> archive try disabling bitcode feature of app. enabled default. for disabling feature use link after disabling it, make sure app working fine.. make sure clean project before creating ipa file.

php - Multiple entries in SQL? -

how can store multiple entries in sql in 1 field? example in field phone want let users enter more phones private, home, business etc. any hellp on how can create trat form , how store data in sql? i guess can store them using serialize() function in php how make form , collect information? form: home phone: 321321333 other: 333213213 add also make can edit name field if users want put home tel instead of home phone or pager instead other. any help? please? user serialize() , said. however, working add button need javascript. here form: <form action="action.php" method="post"> <div id="phonenumbers"> <input type="text" value="home phone">: <input type="text" name="0-value" value="(xxx)xxx-xxxx"> </div> <button onclick="addanother();">add phone number</button> <input type="submit> </form> ...

c# - VoIP app on Windows 10 Mobiles got exception The group or resource is not in the correct state to perform the requested operation -

i build voip app on wp 8.0 sdk , deploy on microsoft lumia 535 running windows 10 mobile insider preview build 10586.36. make outgoing call failed, tracing log show reason group or resource not in correct state perform requested operation(hresult = -2147019873) when call function requestnewoutgoingcall of class voipcallcoordinator . after got exception, app can't start outgoing calls when go homescreen, kill app , restart app many times. app can request new incoming call successfully, showing incoming call screen , active call when pressed answer. right still don't know how reproduce bug. have ideas why request new out going call got exception , how working around bug.

node.js - Mongodb db.serverStatus() memory section doesn't show actual value -

i'm trying create chart regarding db.serverstatus() output of remote or local mongodb connections. this command outputs: "mem": { "bits": 64, "resident": 258, "virtual": 4807, "supported": true, "mapped": 2288, "mappedwithjournal": 4576 }, which suits needs. unfortunately i've realized data never gets actual memory data , never change. (i've monitored 10 minutes) am doing wrong ? or there other way actual memory usages ? p.s. i've examined mongostat couldn't make work through meteor-js since it's executable. thanks in advance

navbar - SideNav opening the page in the same window (Yii2) -

Image
i trying use sidenav url open page in same window not redirecting different place. how can ? when click link in sidenav page should open in same window. <?= sidenav::widget([ 'type' => sidenav::type_default, 'heading' => 'dashboard', 'items' => [ [ 'url' => '#', 'label' => 'purchase', 'icon' => 'home', 'items' => [ ['label' => 'suppliers', 'icon'=>'glyphicon transport', 'url'=>'../site/about'], ['label' => 'leaf entry', 'icon'=>'leaf', 'url'=>'#'], ['label' => 'payments', 'icon'=>'phone', 'url'=>'#...

c# - Suggest design: almost every object in app has loggger -

i'm writing application. use nlog logging. in application every object can write log. define protected member that: protected logger logger; protected virtual logger logger { { return logger ?? (logger = logmanager.getlogger(this.gettype().tostring())); } } in case need copy/paste code every base class in application. or see other option: define app-specific root object logger in , subclass it. semantically sounds wrong because not true "is-a" situation me. are there better options? sometimes wish c# support multiple inheritance or mixins.... you write extension method: public static logger logger(this object obj) { return logmanager.getlogger(obj.gettype()); } the drawback bit slower created instance not cached (except internally in nlog, implementation detail), yourself: public static logger logger(this object obj) { logger logger; type type = obj.gettype(); // s_loggers static dictionary<type, logger> if (!s_l...

javascript - Iterate through a hash from the Rails controller in js -

in rails controller have made hash looks this: @data = { term => { node_id => { :name, :matchcode, :credits, :parts => [{ :mp_id, :matchcode, :nr, :selected }] }} now want iterate in js through hash keys , values. @ first need term tried like: for(var s in '#{@data}') { console.log(s); } but seems did wrong it's first time use rails.. passing data server side ruby controller client side javascript code not simple. firstly, javascript has no idea ruby variables, above string '#{data}' evaluates itself. there couple of ways of passing such data: firstly, can set html attribute on dom element server side , read in javascript. might simplest solution when passing string or number, hash quite messy need convert form understandable javascipt - json. though simple do, adds complexity , dirty. second option gon gem. provides object can assign data in controller. handles transf...

php - How to manage a ManyToOne relation with symfony 2 and doctrine -

i’m discovering symfony 2 , training myself on wonderful framework. have newbie questions... i followed tutorial in order manage relations doctrine : http://symfony.com/doc/current/book/doctrine.html well, during tests had question , problem. first question: symphony best practices says it’s better use annotations doctrine mapping instead of yaml in other .orm.yml file. good, totally agree that. "using annotations convenient , allows define in same file". if choose use annotations, guess not need .orm.yml mapping file anymore? suppose have table named usertype. have created entity class usertype.php , added mapping information annotations directly in class. try, adding statement: use doctrine\orm\mapping orm; or not in usertype.php class, symfony display error: no mapping file found named 'usertype.orm.yml' class 'appbundle\entity\usertype if don‘t create usertype.orm.yml file. so question: if choose use annotations, still need .orm.yml mappin...

android - Emulator not installing/running app -

when startup android emulator test application, run problem. i 2 windows open @ bottom of android studio 1 avd:nexus_5_api_23 other 1 app . in avd:nexus_5_api_23 window shows: /volumes/seagate/tools/emulator -netdelay none -netspeed full -avd nexus_5_api_23 haxm working , emulator runs in fast virt mode emulator: emulator window out of view , recentered emulator: updatechecker: skipped version check and app window shows: device connected: emulator-5554 i'm not sure what's going on. i have created other emulators run same issue every-time. my android studio up-to-date. , to test it's not of codes fault. created new project sample code, , still, doesn't run. when run app, should see install command run in app window. effect of device ready: nexus_5_api_23_x86 [emulator-5554] target device: nexus_5_api_23_x86 [emulator-5554] installing apk: /home/username/documents/programming/java/sample/app/build/outputs/apk/app-debug.apk uploading...

how to upload .flv to remote red5 server LIVE in real time? -

i want live webcast of ceremonies. can record .flv files using webcam , ffmpeg software. now, if hire red5 media server hosting company visitors can download website. problem how can upload .flv files live ( when video shooting still in progress ) please how achieve this i assume recording them mean saving them disk , not streaming video? if case need use upload form or have ftp / scp access hosted server. pick 1 of apps installed , place flv files in applications "streams" directory. once files in-place you'll need way play them back, require player (plenty of free ones out there jwplayer). looking for.

python - How to keep track of status with multiprocessing and pool.map? -

i'm setting multiprocessing module first time, , basically, planning along lines of from multiprocessing import pool pool = pool(processes=102) results = pool.map(whateverfunction, myiterable) print 1 as understand it, 1 printed all processes have come , results complete. have status update on these. best way of implementing that? i'm kind of hesitant of making whateverfunction() print. if there's around 200 values, i'm going have 'process done' printed 200 times, not useful. i expect output like 10% of myiterable done 20% of myiterable done pool.map blocks until concurrent function calls have completed. pool.apply_async not block. moreover, use callback parameter report on progress. callback function, log_result , called once each time foo completes. passed value returned foo . from __future__ import division import multiprocessing mp import time def foo(x): time.sleep(0.1) return x def log_result(retval): results.a...

matrix - Android ImageView scale image and center -

i need scale image inside imageview, need use matrix doing so, so do; private void scaleimage(float scalefactor, float focusx,float focusy) { matrix displaymatrix= new matrix(); matrix.postscale(scalefactor, scalefactor); displaymatrix.set(matrix); imageview.setimagematrix(displaymatrix); } the problem no matter not able center image inside imageview, i need put image @ center (leaving white margins if image smaller view) i have been bangin head hours, please help. i have looked extensively @ https://stackoverflow.com/a/6172226/1815311, without success. all have find new x , y coordinates place image , translate matrix, image moves center of imageview. entire scaleimage method can this: private void scaleimage(float scalefactor, float focusx, float focusy) { matrix displaymatrix = new matrix(); matrix matrix = imageview.getimagematrix(); float x = (imageview.getwidth() - imageview.getdrawable().getintrinsicwidth() * scalefactor...

Print character using linux x86 assembly and at&t syntax -

i'm trying print character stdout using write in linux x86 assembly, using at&t syntax. code doesn’t work: .data .text .global main main: movl $4,%eax movl $1,%ebx movl $53,%ecx //'5' movl $4,%edx int $0x80 movl $1,%eax movl $0,%ebx int $0x80 what's problem?

git - Accidentally created new branch with existing name -

i'm starting use branches git, , created yesterday branch foo , pushed remote. today wanted work on home, after running pull typed without thinking git checkout -b foo . i know shouldn't have added -b option, because got message switched new branch 'foo' , none of code wrote yesterday shows in folders figure accidentally messed branch names. i tried renaming branch using git branch -m foo bar hoping deal local branch , deduplicate branch names, alas git checkout foo issued message error: pathspec 'foo' did not match file(s) known git. how can retrieve branch created yesterday? the problem ran created new branch did not track remote branch wanted. i think "right" way correct set branch track intended remote branch: git checkout foo git branch -u origin/foo after doing can move local branch current commit of remote branch git reset origin/foo you can add , commit local changes. pull , push usual. (an alternative reset...

javascript - D3JS : Create distinct arc paths -

Image
i'm trying draw arcs corresponding data. plnkr actually there 2 numbers in data. whenever i'm trying create 2 arcs, merging together. var pi = math.pi, arcradius = 55, arcthickness = 2; var gaugedata = [32, 57]; var svg = d3.select('.circles').append('svg'); var arcfunc = d3.svg.arc() .innerradius(55) .outerradius(57) .startangle(0) .endangle(function(d) { return d * (pi /180); }); svg.attr("width", "400").attr("height", "400") .selectall('path').data(gaugedata).enter().append('path') .attr('d', function(d) { return arcfunc(d); }) .attr('fill', '#555') .attr('cx', function(d, i) { return * 100 + 30; }) .attr('cy', function(){ return 50; }) .attr("transform", "translate(200,200)"); the arcs like: please help. in advance. i'm assuming gaugedata degree value total sweep of arc. so, ...

ios - Search for parse user to return multiple results -

i have uitableviewcontroller , in uisearchbar searches parse.com users. when search type "abc", want users string "abc" not closets match. .h @property (weak, nonatomic) iboutlet uisearchbar *searchbar; @property (nonatomic, strong) pfuser *founduser; @property (nonatomic, strong) pfrelation *friendsrelation; @property (nonatomic, strong) nsarray *allusers; @property (nonatomic, strong) pfuser *currentuser; .m - (void)viewdidload { [super viewdidload]; self.searchbar.delegate = self; } -(void)viewdidappear:(bool)animated{ [super viewdidappear:animated]; pfquery *query = [pfuser query]; [query orderbyascending:@"username"]; [query findobjectsinbackgroundwithblock:^(nsarray *objects, nserror *error){ if (error) { nslog(@"error: %@ %@", error, [error userinfo]); } else { self.allusers = objects; [self.tableview reloaddata]; } }]; self.curre...

R - How to Plot Multiple Density Plots With ggvis -

Image
how 1 go plotting multiple density plots on same set of axes? understand how plot multiple line graphs , scatter plots together, matter of having density plots share common x-axis tripping me up. data set such: name x1 x2 x3 123 123 123 b 123 123 123 c 123 123 123 thanks help! edit: here details missing may make question clearer. i have data frame attr_gains looks example above, , variable names str , agi , , int . far, have been able density plot of str variable alone code: attr_gains %>% ggvis(x=~str)%>% layer_densities(fill :="red", stroke := "red") what overlay 2 more density plots, 1 agi , int each, have 3 density plots on same set of axes. directly documentation: plantgrowth %>% ggvis(~weight, fill = ~group) %>% group_by(group) %>% layer_densities() link your case: set.seed(1000) library('ggvis') library('reshape2') ########################################...

android - Customize default camera app -

is there way add button or other view default camera application? note don't want create custom camera app add view default. possible? unless interested in custom rom development.the answer no however,you can check out xda university ,if interested in former.you need download source android camera app , make changes app.. all these things called rom development.but certainly,you wont able change in default camera app.the above thing give way learn how make own camera app , may own customised android rom?

actionscript 3 - AS3 Check if movieclips inside array are all the same color -

i've created simple puzzle game , have uploaded kongregate, want upload highscores (the least amount of moves = better) using api. make sure no 1 can cheat system (submitting score before puzzle finished) need make sure none of pieces in puzzle black. pieces of puzzle movieclips , inside array called buttons. i've got this: public function sumbitscore(e:mouseevent) { (var v:int = 0; v < buttons.length; v++) { if (buttons[v].transform.colortransform.color != 0x000000) { _root.kongregatescores.submit(1000); } } } but think submit score checks movieclip not black , it'll ignore rest. i think way go keep track of whether or not 'empty button' found in for-loop. after loop submit score if no empty tiles found or let player know puzzle has completed before submitting. i've added comments in code below: // (i changed function name 'sumbitscore' ...

mysql - Join tables keeping empty results -

i have 2 tables need cross , return many results ids of 1 of them. the first table of roles/tasks: id | rolename ---+--------- 1 | check_in 2 | cleaning 3 | taxi 4 | guide 5 | car_rental 6 | meals 7 | house_owner 20 | custom and table has columns: id | client_booking_id | staff_role_id | confirmed | staff_cost i need query gives me many results nr of columns in first table. because each unique client_booking_id there 1 (if any) of tasks/roles. so if do: select sr.role_name, sr.id, ss.staff_cost, ss.confirmed staff_role sr left join staff_schedule ss on sr.id=ss.staff_role_id i result nr of rows want. need match specific client_booking_id did select sr.role_name, sr.id, ss.staff_cost, ss.confirmed staff_role sr left join staff_schedule ss on sr.id=ss.staff_role_id ss.client_booking_id=1551 // <-- new line and gives me 2 results because in second table have booked 2 tasks id . but need result tasks not match, null values. how c...

php - Cant import data due to illegal double -

i having annoying problem trying import wordpress db backup using wootickets sell tickets event , customers db complaing on xampp a illegal double here in insert statement shown below. hudreds of these values scattered thruought the file persume used security. insert fl_postmeta ( meta_id , post_id , meta_key , meta_value ) values ( 165743, 3313, '_tribe_wooticket_security_code', 'e801d16bb2' ); mysql said: documentation 1367 - illegal double '342e880385' value found during parsing my question why case when exported linux platform xamp testing how fix this the value 342e880385 should put inside single quotes, so: insert fl_postmeta ( meta_id , post_id , meta_key , meta_value ) values ( 162936, 3115, '_tribe_wooticket_security_code', '342e880385' ); otherwise, mysql try parse number.

java - I am trying to set the color of the button,but the color doesn't get set -

how set color of button in swing. here code. what's problem code.can help? import java.awt.*; import javax.swing.*; class myb extends jbutton { public void paint(graphics g) { g.setcolor(color.red); } public static void main(string s[]) { jframe f=new jframe("frame"); jbutton b=new jbutton(); b.setbounds(100,100,50,50); f.add(b); f.setsize(800,800); f.setlayout(null); f.setvisible(true); } } overriding paint not proper way set component's color. can call setbackground method set jbutton 's color. like so: import java.awt.*; import javax.swing.*; class myb { public static void main(string[] args) { swingutilities.invokelater(new runnable(){public void run(){ jframe f=new jframe("frame"); jbutton b=new jbutton(); b.setbounds(100,100,50,50); b.setbackground(color.red); ...

c - Calculate multiplicative inverse of positive real number -

i wanted calculate multiplicative inverse of positive real number without using division. after reading through various pages on newton raphson method, implemented following code calculating inverse: #define precision 0.1e-5 double inverse(double num) { double ans = num; while (ans * num > 1 + precision || ans * num < 1 - precision) { ans = ans * (2 - num * ans); } return ans; } now, problem is, not inverse value. loop goes on infinitely. so, 1st thing noticed was: value of ans become negative, added statement if (ans < 0) ans *= -1; so ans remains positive always. 2nd point noticed: if initialization ans = 0.5 correct answer few values of num = (1, 2, 3, 5) . so, assumption is, implementation isn't working because of inappropriate initialization of variable ans . so, questions: 1 .can method used calculate inverse of positive real numbers? 2 .if yes, there conditions required initial value assumed when using newton raphson m...

python - Is there anyway to avoid locks in mongodb -

i trying migrate data 1 collection other collection in same database in mongodb. have around 50k records. while inserting mongodb locked , affecting application. there way handle locking system in mongodb ? thanks, prats as per article: goodbye global lock – mongodb 2.0 vs 2.2 global locking that known affect mongodb supposedly gone when using version >=2.2. if have old instance, , upgrade out of scope, i'd try breaking migration smaller batches (max 100 documents @ time, if small enough), , waiting small amounts of time (50ms or so) between each batch runs. ugly , slow workaround, might allow continue, while being onnline @ time... edit hmmm, strange, version should free global write lock situation. i'd try smaller batches approach... edit2 , sammaye right: might old io bottleneck issue too... try see how disks fare in aspect sure.

How to close the clipboard ressource in C#? -

below code how put text string windows clipboard. looking command close clipboard resource after not locked anymore app. know how close clipboard ressource explicitely in c#? this code string s = "hello world"; thread stathread3 = new thread ( delegate() { try { new setclipboardhelper(dataformats.text, s).go();} catch (exception ex) { /* exception handling */ } } ); stathread3.setapartmentstate(apartmentstate.sta); stathread3.start(); stathread3.join(); // here close clipboard // ???? this code of class setclipboardhelper class setclipboardhelper : stahelper { readonly string _format; readonly object _data; public setclipboardhelper(string format, object data) { _format = format; _data = data; } protected override void work() { var obj = new system.windows.forms.dataobject( _format, _data ); clipboard.setdataobject(obj, true); } } ...

php - Database insertion error -

Image
this question has answer here: how can prevent sql injection in php? 28 answers the below echo statement, $statement = "insert $tbl_name values(" . $_get['username'] . "," . $_get['password'] . "," . $_get['passwordhintquestion'] . "," . $_get['passwordhintanswer'] . "," . $_get['firstname'] . "," . $_get['lastname'] . "," . $_get['genderselect'] . "," . $_get['date_in_format'] . "," . $_get['nationality'] . "," . $_get['refemail'] . ")" ; echo $statement; gave ouput as, insert ge_user_table values([object htmlinputelement],[object htmlinputelement],[object htmlinputelement],[object htmlinputelement],[object htmlinputelement],[object htmlinputelement],[object nodelist],[o...

python - how to increase frame payload size in android autobahn websocket -

i using android autobahn websocket establish connection between android , python tornado socket server . below autobahn websocket code using in android . public void start() { final string wsuri = ip; try { mconnection.connect(wsuri, new websockethandler() { @override public void onopen() { log.d(tag, "connected " + wsuri); } @override public void ontextmessage(string payload) { log.d(tag, "got echo: " + payload); try{ inputstream stream = new bytearrayinputstream(base64.decode((payload).getbytes(), base64.default)); bitmap bitmap = bitmapfactory.decodestream(stream); image.setimagebitmap(bitmap); } catch (exception e) { log.d("got exception:", e.tostring()); } } @override public void onclose(...

html - How can I know the namespace of a 'serviceprovider' class in Laravel 5.2? -

i use laravel 5.2 . found error message... fatal error: class 'html' not found (view: d:\websites\htdocs\eloquent\resources\views\nerds\create.blade.php) to solve problem, use following command... composer require illuminate/html and update composer the path of 'service provider' downloaded ... vendor > illuminate > html > htmlserviceprovider.php in app.php file following line not solving problem. illuminate\html\htmlserviceprovider::class; what should write instead? would please help? add these 2 lines inside aliases in app.php . code should this 'aliases' => [ // other aliases 'form' => illuminate\html\formfacade::class, 'html' => illuminate\html\htmlfacade::class, ]

python - Read csv with tab delimiter produces errors -

Image
i have csv file, uses '\t' tab delimiter. contains 5 columns. tried this: import numpy np #b=np.loadtxt(r'train_set.csv',dtype=str,delimiter=' ') my_data = np.genfromtxt('train_set.csv', delimiter='\t') print my_data but getting following errors: traceback (most recent call last): file "./wordcloud.py", line 7, in <module> my_data = np.genfromtxt('train_set.csv', delimiter='\t') file "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 1667, in genfromtxt raise valueerror(errmsg) valueerror: errors detected ! line #14 (got 4 columns instead of 5) line #21 (got 4 columns instead of 5) line #135 (got 4 columns instead of 5) any ideas please? not know python (yet :))! the dataset (which examine right now) looks this: edit: if do: my_data = np.genfromtxt('train_set.csv', delimiter=' ') then getting no errors, output is: [ nan na...

Avoid Udp port forwarding in unity [c#] -

i'm creating simple online game unity 5 , unet; after following couple of videos introduction i've tried messing around project of video series: http://forum.unity3d.com/threads/unity-5-unet-multiplayer-tutorials-making-a-basic-survival-co-op.325692/ . can create local server , connect using 127.0.0.1, i've tryied friend connect 2 different computers (connected 2 different routers) using public ip of router , port 7777, works after doing udp port forwarding on router. here question, want able create game , make friends able connect pc don't want people go across port forwarding stuff. i've red upnp don't want use because (if understanded well) it's compatible every router , it's not safe. i've red methods behind udp hole punch you'll need server (and don't have money that). think solution avoid udp port forwarding? there way can use used udp port microsoft services or stuff that? in advance! davide

jquery - External link open accordion -

i see lots of examples still don't ! try open accordion panel on page. my goal: when click on specific link on page a, redirected inside accordion data-id='32' on page b. my working url:www.mysite.ccc/page/?sub=32#milmedia url redirect id 32 not opening id 32. <ul class="accordion"> <li class="accordion__item"><div class="underline-list__item js-accordion-open" data-id="30"><div class="underline-list__link"> <div class="underline-list__text"><h3>title</h3><span class="accordion_button"><span class="accordion_button_icon"></span></span></div></div></div> <div class="accordion__content js-accordion-content"><div class="wysiwyg"> content </div></div></li> <li class="accordion__item"><div class="underline-list__item js-accordion-o...

Javascript: check date in future in dd/mm/yyyy format? -

i'm trying check users input field see if in future , if in dd/mm/yyyy format have no idea why format part of code doesn't fire @ all! in fact nothing seems working on jsfiddle @ least "check date in future" function works locally. i don't know correct way of going this. to explain this, i've created fiddle and full javascript code. need stay pure javascript way: function checkdate(){ //var senddate = document.getelementbyid('send_year').value + '/' + document.getelementbyid('send_month').value + '/' + document.getelementbyid('send_day').value; var senddate = document.getelementbyid('returning_date').value; senddate = new date(date.parse(senddate.replace(/-/g,' '))) today = new date(); today.sethours(0,0,0,0) if (senddate < today) { //alert('the date can\'t in past. please pick date.'); document.getelementbyid('error8').inn...

ios - Swift: property observers for computed properties -

as far know, swift allows set property observers either stored , computed properties. if computed property value depends on backing store, property observers not fired when these backing store values changed: public class baseclass { private var privatevar1: int = 0 private var privatevar2: int = 0 public var property: int { { return privatevar1 * privatevar2 } set { print("some setter without effect") } } private func changesomevalues() { privatevar1 = 1 privatevar2 = 2 } } public class subclass : baseclass { override var property: int { didset { print("didset \(property)") } } } didset of subclass isn't called when changesomevalues called. let's consider case: have such baseclass in third-party framework. define subclass in our app. question is: how can rely on subclass observers without knowledge property nature: ...

database - DB2- Compiling all stored procedures -

i'm working legacy db has 100's of stored procedures, views , materialized views. have introduce column in 1 of table , want check working in order before. i'm looking query can go , compile stored procedures under schema, run views/materialized views fetching 10 rows them. can please me that? thanks, -mike

smtp - A basic gmail BruteForce program in python -

i trying figure out why isn't code working. trying improve python skill adding code another, when tried execute keeps giving me syntax error. import itertools import smtplib smtpserver = smtplib.smtp("smtp.gmail.com", 587) smtpserver.ehlo() smtpserver.starttls() user = raw_input("enter target's gmail address: ") def print_perms(chars, minlen, maxlen): n in range(minlen, maxlen+1): perm in itertools.product(chars, repeat=n): print(''.join(perm)) print_perms("abcdefghijklmnopqrstuvwxyz1234567890", 2, 4) symbols in print_perms: try: smtpserver.login(user, password) print "[+] password cracked: %s" % symbols break; except smtplib.smtpauthenticationerror: print "[!] password inccorect: %s" % symbols the output is file "main.py", line 22 ...

php - Select statement fill data in a foreach -

i'm trying create php file when clicking 'edit' link job id , list number of rows jobref in applications table. this list of applications different jobs have available on website. <?php require 'mysqlcon.php'; if(isset($_get['id'])) { $stmt = $pdo->query('select applications applicationid = :id'); $results = $stmt->fetchall(); echo "<table><tr><td>job reference</td><td>job title</td><td>job location</td><td>job description</td><td>salary</td><td>availability</td> <td>category</td><td>apply</td>"; foreach ($results $row) { echo "<tr><td>".$row['applicationid']."</td>". "<td>".$row['jobref']."</td>", "<td>".$row['fname']."</td>", "<td>".$row['lname']."</td...

python - call model from within self model in django -

i want access self model within same model: want , show parent of each category item(if exist) class category(models.model): title = models.charfield(...) parent_id = models.foreignkey("category") ref_id = models.charfield(...) def __unicode__(self): p1 = none p2 = none p3 = none final = '' p3 = self if p3.parent_id: p2 = self.__class__.objects.get(id=p3.parent_id) if p2.parent_id: p1 = self.__class__.objects.get(id=p2.parent_id) final = smart_text('{}-{}-{}').format(p1.title,p2.title,p3.title) else: final = smart_text('{}-{}').format(p2.title,p3.title) else: final = smart_text('{}').format(p3.title) return final class category(models.model): title = models.charfield(...) parent_id = models.foreignkey('category',null=true,blank=true) ...

Yii module actions url -

i have in main project views/layouts/main.php following 'events' module actions array('label'=>'events', 'url'=>'#', 'visible'=>userutility::isuser(), 'items'=>array( array('label'=>'konzerte', 'items'=>array( array('label'=>'erstellen', 'url'=>array('events/booking/create')), array('label'=>'verwalten', 'url'=>array('events/booking/admin')), )), if click on 'erstellen' module action works perfectly. if click on verwalten afterwards error error 404 unable resolve request "events/events/concert/admin".* the controller action adds events/ in front of if i'm on page events module. how can overcome problem? you can try create url createabsoluteurl() or add slash before /events array('lab...

google compute engine - Booting from custom image in GCE. Boot hang at "Booting from 0000:7c00" -

i doing training on big data , since based on cloudera platform downloaded cloudera quickstart vm virtual box. i don't have enough hardware open laptop decided try out gce. followed instructions convert virtual box images raw , tar.gz google gce bucket. until point, went fine. i able crate new instance , attached disk created out previous instance without issue. after booting instance realized unresponsive, , external ip not reachable. looked @ serial console , found out shows messages until ""booting 0000:7c00" , nothing. seems boot issue related disk maybe... i tried mounting disk secondary 1 working instance in gce , able see contents. disk seems ok. see below outputs lvm commands. pvs pv vg fmt attr psize pfree /dev/sdb2 vg_quickstart lvm2 a-- 63.51g 0 vgs vg #pv #lv #sn attr vsize vfree vg_quickstart 1 2 0 wz--n- 63.51g 0 lvs lv vg attr lsize pool origin data% meta...