Thursday 15 July 2010

php - Better admin security -



php - Better admin security -

i seek create firs cms , have querstion security. right have seperated admin area , public area. admin area in folder "admin" , public area in folder "public". both folders in folder "cms". in both maps example: file called "index.php". , content same in admin's index.php have few more features example: in admin's navigation have logout , settings options. improve if 2 folders create 1 called "public" , both "index.php" connect 1 file , command $_session add together additional features navigation? example: if admin logged in session show settings , logout features navigation. when user logged out won't see settings , logout featuers in navigation because show when user has set session. so, improve , more secure have seperated admin , public folder or same if set in 1 file?

in cms, utilize same page public, users, , admins.

the different in showing functionality based on group.

i.e. normal visitors (public) users not see except published contents. if visitor signed in account, see peaces here , there (i.e. profile img, personal info, alter email/password). on other hand, admin has own extras well, such command users, messages, , etc.

off course of study times there totally new things not shared between these 3 levels of privileges. in case, create separate page them...

the of import things here check user grouping , based on grouping display part , hide part.

something like

if user grouping == 1 // admin { display admin_sidebar.php } elseif user grouping == 2 // fellow member { display member_profile.php link }

also off course of study need utilize sessions handle grouping after user logged in website.

hope helps...

php mysql session login

c - Space padding in printf doesn't work -



c - Space padding in printf doesn't work -

i need add together variable space padding before string. here's code:

unsigned int spaces = result % 16; printf("spaces=%d\n", spaces); // spaces=12, example. printf("% *s\n", spaces, my_string);

it doesn't work - spaces not added , i'm getting next warning in gcc:

warning: ' ' flag used ‘%s’ gnu_printf format [-wformat=]

how prepare that? there workaround this?

change this

printf("% *s\n", spaces, my_string);

to this

printf("%*s%s\n", spaces, " ", my_string);

this should rid of warning , give desired effect.

[edit]

i saw found answer. alexis says right , produce same effect. alexis's version cleaner, say, giving solution, credits on him.

you this:

int width = 5; printf ("%*d%*d\n", width, 10, width, 12);

which print this:

10 12

source

so, if think it, this:

printf("%*s\n", spaces, "foo");

why alexis's version synonym version in comment?

because compiler performs concatenation of 2 sequential strings (i.e. whitespace in between) one.

this action called string literal concatenation. read more in wikipedia.

c printf

c# - Check box Checked state is Not working in Custom paging in Devexpress Gridview -



c# - Check box Checked state is Not working in Custom paging in Devexpress Gridview -

hi using devexpress gridview. in implementing custom paging. after implementing custom paging checkbox checked state not working in gridview. if check row in first page when go sec page , if come 1 time again first page, previous checked column not in checked state.

can 1 help me solve problem.

thanks

you reloading page after pagination losing context checkboxes checked. first shoot, without code hard more pissible issues of problem.

c# asp.net

Android sdk manager disapear quickly in eclipse -



Android sdk manager disapear quickly in eclipse -

when click on android sdk manager button,

the android sdk manager window doesn't open! see this:

and nil else! can't see packages installed or not...

in console appear:

[2014-10-07 22:42:24 - sdk manager] [sdk manager] access denied. [2014-10-07 22:42:24 - sdk manager] [sdk manager] exception in thread "main" java.lang.unsatisfiedlinkerror: no swt-win32-3550 or swt-win32 in swt.library.path, java.library.path or jar file [2014-10-07 22:42:24 - sdk manager] [sdk manager] @ org.eclipse.swt.internal.library.loadlibrary(unknown source) [2014-10-07 22:42:24 - sdk manager] [sdk manager] @ org.eclipse.swt.internal.library.loadlibrary(unknown source) [2014-10-07 22:42:24 - sdk manager] [sdk manager] @ org.eclipse.swt.internal.c.<clinit>(unknown source) [2014-10-07 22:42:24 - sdk manager] [sdk manager] @ org.eclipse.swt.widgets.display.<clinit>(unknown source) [2014-10-07 22:42:24 - sdk manager] [sdk manager] @ com.android.sdkmanager.main.showsdkmanagerwindow(main.java:402) [2014-10-07 22:42:24 - sdk manager] [sdk manager] @ com.android.sdkmanager.main.doaction(main.java:376) [2014-10-07 22:42:24 - sdk manager] [sdk manager] @ com.android.sdkmanager.main.run(main.java:150) [2014-10-07 22:42:24 - sdk manager] [sdk manager] @ com.android.sdkmanager.main.main(main.java:116)

what should i've done? help me please...

try accessing via .exe file in sdk tools install folder instead of through eclipse. eclipse has many little bugs have made habit much possible without using eclipse ha.

android eclipse sdk

Simple HTML/JavaScript not saving cookie on harddrive -



Simple HTML/JavaScript not saving cookie on harddrive -

the next code failing result in saved .txt cookie on harddrive @ next location: c:\users\<user>\appdata\roaming\microsoft\windows\cookies

i debug page chrome element inspector , no cookie showing up. there i've misunderstood creating simple cookie?

<!doctype html> <html> <body> <script> document.cookie="username=test cookie; expires=thu, 18 dec 2020 12:00:00 utc"; alert("done"); </script> </body> </html>

you're looking in folder net explorer's cookies, not chrome's cookies.

browsers may not back upwards cookies documents opened file:// uris.

javascript html cookies

java - Android parse base64Binary pgm to Bitmap -



java - Android parse base64Binary pgm to Bitmap -

i need convert base64binary-string in format pgm bitmap in android. don't have usual base64-encoded bitmap. base64binary-string came xml file

<referenceimage type="base64binary" format="pgm" widthpx="309" heightpx="233" bytesperpixel="1" > ndy4ojo9qefdruvhrkllte9oufftu1vwv1hzwltzwvlzwlpbw1xdxmbgymjjzgnlzwrkzgrlzmznz2znawpqa21ub29ubm9vb3bwchbxchfyc3fzcnjzcnjydh[...]vlaw1xbwltcxfxcxfxd.

pattern.compile("<referenceimage .*>((?s).*)<\\/referenceimage>"); ... string sub = r; //base64binary string pattern-matched xml file byte[] decodedstring = base64.decode(sub.getbytes(), base64.no_wrap); //probably wrong decoding (needs ascii binary?) bitmap decodedbyte = bitmapfactory.decodebytearray(decodedstring, 0, decodedstring.length); //always null due wrong byte-array

i think understand pgm images typically stored ascii (like in xml) or binary (0..255). think base64.decode needs binary-variant, not ascii have. bitmapfactory.decodebytearray doesn't understand decoded byte-array , returns null.

so how can convert base64binary-pgm-ascii-string valid byte-array in order create valid bitmap?

i think base64-decoding fine. android's bitmapfactory has no direct back upwards pgm format. i'm not sure how add together back upwards it, seems create bitmap using 1 of createbitmap(...) mill methods quite easily.

see pgm spec details on how parse header, or see my implementation java se (if around, you'll find class supports ascii reading, if needed).

could there's no header, , can height/width xml. in case, dataoffset 0 below.

when header parsed, know width, height , image info starts:

int width, height; // header int dataoffset; // == end of header // create pixel array, , expand 8 bit grayness argb_8888 int[] pixels = new int[width * height]; (int y = 0; y < height; y++) { (int x = 0; x < width; x++) { int grayness = decodedstring[dataoffset + i] & 0xff; pixels[i] = 0xff000000 | grayness << 16 | grayness << 8 | gray; } } bitmap pgm = bitmap.createbitmap(metrics, pixels, width, height, bitmapconfig.config. argb_8888);

java android bitmap base64 pgm

java - Found unsupported keytype (8) for Principal -



java - Found unsupported keytype (8) for Principal -

i using java 7 , kerberos authenticate hadoop.

in debug log seeing next error:

ordering keys wrt default_tkt_enctypes list default etypes default_tkt_enctypes: 23 18 17 16 3 1. added key: 3version: 1 **found unsupported keytype (8) hdfs/aaa.aaa@example.com** added key: 23version: 1 added key: 16version: 1 added key: 17version: 1 added key: 18version: 1

how right error?

sorry it's bit late, i've encountered missing local_policy.jar , us_export_policy.jar files in directory: $java_home/jre/lib/security/.

other times, mis-configured krb5.ini file.

java hadoop aes kerberos

eclipse - How do I convert an app engine WAR folder into a single WAR file -



eclipse - How do I convert an app engine WAR folder into a single WAR file -

currently have created web application , have deployed via gae(google app engine). creates war folder. need able convert project deployed on tomcat.

is there anyway can convert war folder single war file, or know how convert app engine project in eclipse work tomcat.

any help appreciated.

i assume have created project using google app engine plugin eclipse. project construction looks similar eclipse dynamic web project structure, difference war folder eclipse project called webcontent.

first need add together dynamic web module facet project. right click on project , select properties, on properties window take project facets , check dynamic web module option, click apply ok

at stage eclipse alter icon of project , create webcontent folder, delete folder , tell eclipse utilize war folder instead. 1 time again right click on project , select deployment assembly remove webcontent folder , add together war folder.

finally export project war file, select project form file menu select export, take web --> war file, come in destination file, etc...

note: i've not tried myself not sure if war run under tomcat or not

eclipse google-app-engine tomcat

scala - What is the right way to have a static object on all workers -



scala - What is the right way to have a static object on all workers -

i've been looking @ documentation spark , mentions this:

spark’s api relies heavily on passing functions in driver programme run on cluster. there 2 recommended ways this:

anonymous function syntax, can used short pieces of code. static methods in global singleton object. example, can define object myfunctions , pass myfunctions.func1, follows:

object myfunctions { def func1(s: string): string = { ... } } myrdd.map(myfunctions.func1)

note while possible pass reference method in class instance (as opposed singleton object), requires sending object contains class along method. example, consider:

class myclass { def func1(s: string): string = { ... } def dostuff(rdd: rdd[string]): rdd[string] = { rdd.map(func1) } }

here, if create new myclass , phone call dostuff on it, map within there references func1 method of myclass instance, whole object needs sent cluster. similar writing rdd.map(x => this.func1(x)).

now uncertainty happens if have attributes on singleton object (which supposed equivalent static). same illustration little alteration:

object myclass { val value = 1 def func1(s: string): string = { s + value } } myrdd.map(myclass.func1)

so function still referenced statically, how far spark goes trying serialize referenced variables? serialize value or initialized 1 time again in remote workers?

additionally, in context have heavy models within singleton object , find right way serialize them workers while keeping ability reference them singleton everywhere, instead of passing them around function parameters across pretty deep function phone call stack.

any in-depth info on what/how/when spark serialize things appreciated.

this less question spark , more of question of how scala generates code. remember scala object pretty much java class total of static methods. consider simple illustration this:

object foo { val value = 42 def func(i: int): int = + value def main(args: array[string]): unit = { println(seq(1, 2, 3).map(func).sum) } }

that translated 3 java classes; 1 of them closure parameter map method. using javap on class yields this:

public final class foo$$anonfun$main$1 extends scala.runtime.abstractfunction1$mcii$sp implements scala.serializable { public static final long serialversionuid; public final int apply(int); public int apply$mcii$sp(int); public final java.lang.object apply(java.lang.object); public foo$$anonfun$main$1(); }

note there no fields or anything. if @ disassembled bytecode, phone call func() method. when running in spark, instance serialized; since has no fields, there's not much serialized.

as question, how initialize static objects, can have idempotent initialization function phone call @ start of closures. first 1 trigger initialization, subsequent calls no-ops. cleanup, though, lot trickier, since i'm not familiar api "run code on executors".

one approach can useful if need cleanup explained in blog, in "setup() , cleanup()" section.

edit: clarification, here's disassembly of method makes call.

public int apply$mcii$sp(int); code: 0: getstatic #29; //field foo$.module$:lfoo$; 3: iload_1 4: invokevirtual #32; //method foo$.func:(i)i 7: ireturn

see how references static field holding singleton , calls func() method.

scala apache-spark

Running PHP Selenium Webdriver tests programmatically, without phpunit command -



Running PHP Selenium Webdriver tests programmatically, without phpunit command -

my question quite simple. i'm coming python world, it's simple execute selenium testing code within program, writing like:

from selenium import webdriver driver = webdriver.firefox() driver.get("http://www.python.org") driver.close()

when using php, things getting harder: wrote that

require 'vendor/autoload.php'; class mytest extends phpunit_extensions_selenium2testcase { public function setup() { $this->setbrowser('firefox'); $this->setbrowserurl('http://www.python.org'); } public function testtoto() { $this->url('/'); } }

...which kinda works when execute phpunit mytest.php.

but instanciate test class in php code, , execute selenium commands "programmatically", like:

$mytest = new mytest(); $mytest->testtoto();

and here sucks :(

php fatal error: uncaught exception 'phpunit_extensions_selenium2testcase_exception' message 'there no active session execute 'url' command.

so is there way execute selenium code straight php script without executing command line things phpunit?

edit: trying achieve? project build testing application must able launch tests within ui built end user user friendly drag , drop builder (the user chooses test wants execute first, another, , on). avid ececuting phpunit commands ugly php exec: me, best alternative launch test case methods programmatically!

i think pain comes trying utilize phpunit webdriver integration, without using phpunit.

you can write code python illustration using standalone webdriver implementation (that not need phpunit). recommend 1 written facebook:

https://github.com/facebook/php-webdriver

but there more:

http://docs.seleniumhq.org/docs/03_webdriver.jsp#php

you can utilize these implementations within phpunit tests. don't phpunit webdriver implementation.

with these it's trivial write illustration in php.

php selenium phpunit

ios - UIActivityViewController completion handler is !completed when using AirDrop -



ios - UIActivityViewController completion handler is !completed when using AirDrop -

i using uiactivityviewcontroller share text , url works great when sending text , url.

i need utilize completion handler perform additional actions depending whether user cancelled uiactivityviewcontroller or sent something.

the completion handler (activityviewcontroller.completionhandler ios 7 deprecated in ios 8 activityviewcontroller setcompletionwithitemshandler) returns bool completed value correctly returns true when sending email sms facebook twitter when sending via airdrop user must press cancel dismiss uiactivityviewcontroller 1 time sent , receive false completion handler.

does know if there's way of knowing user has sent using airdrop when uiactivityviewcontroller dismissed?

thanks

i've found of involvement unfortunately couldn't test airdrop didn't want function between idevices. sorry that.

anyway, seek setcompletionwithitemshandler checking activitytype:

[activityviewcontroller setcompletionwithitemshandler:^(nsstring *activitytype, bool completed, nsarray *returneditems, nserror *activityerror) { nslog(@"completed: %@, \n%d, \n%@, \n%@,", activitytype, completed, returneditems, activityerror); }];

if activitytype of type com.apple.airdrop.etc (just guess) user has tapped on icon. hope can help.

ios uiactivityviewcontroller uiactivity uiactivitytypeairdrop

Android fragments xml crash -



Android fragments xml crash -

i maintain getting crash when alter set content view xml layout , not sure whats wrong. programme supposed have 2 fragments, list view on left , webview on right when in landscape , list in portrait. sorry code, can not figure out going on.

here main activity

public class mainactivity extends activity { static final string logtag = mainactivity.class.getsimplename() + "_tag"; static resources mres = null; static fragmentmanager mfrgmntmngr = null; static mainactivity mthisact = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); fragmentmanager.enabledebuglogging(true); setcontentview(r.layout.activity_main_1view); mres = getresources(); mfrgmntmngr = getfragmentmanager(); mthisact = this; } static boolean isinlandscapeorientation() { homecoming mres.getconfiguration().orientation == configuration.orientation_landscape; } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); homecoming true; } @override public boolean onoptionsitemselected(menuitem item) { // handle action bar item clicks here. action bar // automatically handle clicks on home/up button, long // specify parent activity in androidmanifest.xml. int id = item.getitemid(); if (id == r.id.action_settings) { homecoming true; } homecoming super.onoptionsitemselected(item); } public void displaytwaintext(int mcurposition) { // todo auto-generated method stub if ( isinlandscapeorientation() ) { // check fragment shown, replace if needed. twaintitlewebviewfragment ttxtfrgmnt = (twaintitlewebviewfragment) mfrgmntmngr.findfragmentbyid(r.id.twain_title_list); if (ttxtfrgmnt == null || ttxtfrgmnt.getdisplayedtwainindex() !=mcurposition) // create new fragment show selection. ttxtfrgmnt = twaintitlewebviewfragment.newinstance(mcurposition); // execute transaction, replacing existing // fragment within frame new one. log.d(logtag, "about run fragmenttransaction..."); fragmenttransaction frag_trans = mfrgmntmngr.begintransaction(); frag_trans.setcustomanimations(r.animator.bounce_in_down, r.animator.fade_out); frag_trans.setcustomanimations(r.animator.bounce_in_down, r.animator.slide_out_right); frag_trans.replace(r.id.list, ttxtfrgmnt); frag_trans.commit(); } } else { // otherwise need launch new activity display // dialog fragment selected text. intent intent = new intent(); intent.setclass(mthisact, twaintitleviewactivity.class); intent.putextra(mres.getstring(r.string.twain_index_key), mcurposition); this.startactivity(intent); } } }

this activity_main1view.xml in lay out folder

<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment class="com.example.hw_07_final_.titlelistfragment" android:id="@+id/twain_title_list" android:layout_width="match_parent" android:layout_height="match_parent" /> </linearlayout>

this 1 in layout-land

<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment class="com.example.hw_07_final_.titlelistfragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="#00550033"/> <framelayout android:id="@+id/twain_text" android:layout_weight="4" android:layout_width="0dp" android:layout_height="match_parent" /> </linearlayout>

this log cat

you cannot have numbers or uppercase letters when naming xml files.

activity_main1view.xml should activity_mainview.xml excluding "1" layout name.

android xml android-fragments

Newbie in python : pyodconverter with Apache OpenOffice 4 on Windows -



Newbie in python : pyodconverter with Apache OpenOffice 4 on Windows -

i don't know python, , need convert documents pyodconverter on windows (xp , 7). utilize simple illustration given here : http://www.oooninja.com/2008/02/batch-command-line-file-conversion-with.html

"c:\program files\openoffice.org2.4\program\soffice.exe" -headless -nologo -norestore -accept=socket,host=localhost,port=2002;urp;staroffice.servicemanager "c:\program files\openoffice.org2.4\program\python" documentconverter.py test.odt test.pdf

it works charm path soffice.exe openoffice 3, openoffice 4 message :

importerror: no module named uno

and goes on every other module imported (from os.path import abspath, isfile, splitext com.sun.star.beans import propertyvalue com.sun.star.task import errorcodeioexception com.sun.star.connection import noconnectexception)

but if re-create , execute documentconverter.py in same directory python.exe, works. must path issue.

i can't phone call documentconverter.py dir, must called dir but can modify documentconverter.py or add together other files in same dir.

i see directory construction between openoffice 3 , 4 has changed no clue why works 3 , not 4. thought ?

you have modify search path when using documentconverter.py openoffice 4.

python.exe openoffice 4 seems utilize relative search path instead of absolute ones, that's why error when executing documentconverter.py directory one, openoffice 4 installed.

i solve problem adding next lines of code before 'import uno' command in documentconverter.py:

import sys sys.path.append("c:\program files (x86)\openoffice 4\program")

python windows openoffice.org

java - HiLo Game With Random Number Generator -



java - HiLo Game With Random Number Generator -

i have 1 real quick question hilo game. when go , test works except when want display how many tries took them guess. i'm trying doesn't count initial guess, counts ones after shows 1 less guess is. here code.

edit:i have quick question. want programme not count guess if out of range 0 10. how go doing because when run programme counts guess 1 of tries.

class="snippet-code-js lang-js prettyprint-override">import java.util.random; // random number generator class import java.util.scanner; // reads user inputs public class hilo { public static void main (string[] args) { //declare variables final int max = 10; int answer, guess; int numberoftries = 0 ; string again; scanner keyboard = new scanner(system.in); do { system.out.print (" i'm thinking of number between 0 , " + max + ". guess is: "); guess = keyboard.nextint(); //guess random generator = new random(); //random number generator. 0 10. answer = generator.nextint(max) +1; if (guess > 10)//if guess bigger 10 error message { system.out.println ("error – guess out of range 0 10."); } if (guess < 0)//if guess smaller 0 error message { system.out.println ("error – guess out of range 0 10."); } while (guess != reply )//if guess not reply { if (guess > reply )//if guess more reply { system.out.println ("you guessed high! \ntry again:"); guess = keyboard.nextint(); } if (guess < reply )//if guess less reply { system.out.println ("too low! \ntry again:"); guess = keyboard.nextint(); } numberoftries=numberoftries+1; }//end of loop // display result if ( guess == answer) { numberoftries += 1; system.out.println ("you win!"); system.out.println("it took " + numberoftries + " tries!") ; system.out.println(); system.out.print( "do want play again(y/n)?"); } keyboard.nextline(); // skip on come in key again = keyboard.nextline(); numberoftries=0; }while (again.equalsignorecase ("y") ); } // end of class } //end of main

thank you!

you should set numberoftries += 1 within if ( guess == reply ), way counts right reply well

if ( guess == answer) { numberoftries += 1; // <--- adds final guess system.out.println ("you win!"); system.out.println("it took " + numberoftries + " tries!") ; system.out.println(); system.out.print( "do want play again(y/n)?"); }

java

javascript - Always block elements jQuery -



javascript - Always block elements jQuery -

i have created safari extension blocks elements facebook , wondering possible create block time. example, blocks elements when load facebook, when click facebook logo in top left corner elements come back, have manually reload page block them again. elements come when click doesn't reload page.

thanks.

here code.

jquery(document).ready(function(){ $("#content").find("#sidenav").find("#listsnav").css( "display", "none" ); });

it depends on facebook when click logo.

if makes ajax request, can hear event , re-hide elements then. example:

$( document ).ajaxcomplete(function() { $("#content").find("#sidenav").find("#listsnav").css( "display", "none" ); });

if runs local javascript hear click event, , 1 time again run code. example, assuming logo has id of #logo...

$("#logo").click(function(){ $("#content").find("#sidenav").find("#listsnav").css( "display", "none" ); });

in addition, suggested satpal, ids meant unique page don't need find them hard way, reference them straight so:

$("#listsnav").hide();

javascript jquery html css facebook

python - CSV readinf TypeError: 'int' object is not iterable -



python - CSV readinf TypeError: 'int' object is not iterable -

python newbie here. maintain getting error when trying sort csv list

i have code write csv file works ok in writes name , 3 scores e.g. john, 3,2,2,

f = open('test.csv', "a") try: author = csv.writer(f) writer.writerow( (name, myscore, myscore2, myscore3) ) print("your entries have been added") finally: f.close()

but want read csv , sort output

sample = open('test.csv','r') test1 = csv.reader(sample,delimiter=',', quotechar='|') sort = sorted(test, key=operator.itemgetter(0)) row in sort: print (row)

tried itemgetter(1)), 2,3 etc.. same int object not iterable error? missing obvious (not me!) can help me work out. thanks.

python csv

debugging - How to debug Cyclone II FPGA board in Quartus II -



debugging - How to debug Cyclone II FPGA board in Quartus II -

i'm writing programme in verilog , have variables see values of programme running on cyclone ii board, can't figure out console (if there one...). there way this? i've read $display function can't figure out output in quartus ii. unfortunately, can't seem find much info on this. help!

verilog has 2 main uses:

it's hdl (hardware description language) used describe synthesizable logic. part utilize create fpga or asic. it's scripting language used test , validate hardware designs through simulation.

for reason online tutorials find not emphasize distinction. start part 2 (which includes things $display) because newcomers trying things in simulator. constructs used scripting have no effect when code goes through synthesis used in fpga. there slight overlap, not work how might expect. if write for loop in simulator loop other programming language. if set synthesizable code within loop replicated loop (creating whole bunch of parallel fpga paths, 1 every pass through loop). scripting parts impact synthesis can thought of more metaprogramming.

you implement (or find existing implementation, called "ip" in hdl land) uart , print out info yourself, complex , costly (in terms of fpga area) exercise in fpga. typically debug fpga bring out debug pins , @ them oscilloscope or logic analyzer (even inexpensive 1 saleae logic). extremely inexpensive in terms of fpga resources. possibility log debug info inside fpga in block ram , read out later. both altera (with signaltap) , xilinx (with chipscope) provide both fpga code , gui drive via jtag port. quartus ii should give free license signaltap long agreed share anonymous statistics them. lastly knew, chipscope not free, , why hobby projects utilize altera fpgas.

debugging verilog quartus-ii

c# - ColumnMapping error with SqlBulkCopy without USE -



c# - ColumnMapping error with SqlBulkCopy without USE -

i have next scenario:

component a creates database d component b loads info d using sqlbulkcopy

each of a , b have it's own independent sqlconnection.

and unusual situation: used 1st step (which executed a) create database script generated sql server management studio ends statement:

utilize d go

with script works fine. however, if delete lastly statement (the use), error while executing sqlbulkcopy on b:

given columnmapping not match column in source or destination.

i'm sure b's connection points correctly on d database (i can read sqlbcp preparation statements via profiler). tried fully-qualified name datatable (db.schema.table) nil went better.

i quite confused because utilize 2 separate connections. thought not matter.

can please provide hint?

some more info: can this:

class { private sqlconnection ac; string createscript; public void dowork() { ac = new sqlconnection("connection string db x"); new sqlcommand(createscript,ac).executenonquery(); new b().dowork(); } } class b { private sqlconnection bc; public void dowork() { bc = new sqlconnection("connection string db d"); ...data table preparation here ... sqlbulkcopy bcp = new sqlbulkcopy(bc); bcp.writetoserver(dt); } }

and somewhere in main:

a.dowork();

the database d created, bc connected it. difference in use in create script.

update: i'm quite sure somewhere there deed pooling. there not shared connection strings, no 2 same connection strings present, of them have pooling=false. however, if write simple console frontend calling same same arguments in component (in case assembly in dll) b - works.

c# sqlbulkcopy use columnmappings

python 3 unable to scrape -



python 3 unable to scrape -

i trying translate indonesian language english language using google translate.(because play game has lot of indonesians)

lang = id inp = input("enter translate: \n").replace(" ","%20") htmlfile = request("https://translate.google.co.in/#" + lang + "/en/" + inp, headers = {'user-agent': 'mozilla/5.0'}) htmltext = urlopen(htmlfile).read().decode('utf-8') regex = '<span id="result_box" class="short_text" lang="en">(.+?)</span>' pattern = re.compile(regex) trans = re.findall(pattern, htmltext) print(trans)

when give input []. here inspect element

<span id="result_box" class="short_text" lang="en"> <span class="hps"> greeting </span>

i need "greeting" part

it's not problem urllib, problem because of regex. default . in regex match character not of newline or carriage homecoming characters. need enable dotall mode (?s) create . match newline characters also.

regex = r'(?s)<span id="result_box" class="short_text" lang="en">(.+?)</span>'

example:

>>> import re >>> s = """<span id="result_box" class="short_text" lang="en"> ... ... <span class="hps"> ... ... greeting ... ... </span>""" >>> re.findall(r'(?s)<span id="result_box" class="short_text" lang="en">(.+?)</span>', s) ['\n\n <span class="hps">\n\n greeting\n\n '] >>> re.findall(r'(?s)<span id="result_box" class="short_text" lang="en">(?:(?!</).)*?(\w+)\s*</span>', s) ['greeting']

python

[ERLANG]: Why answer returns list in a list rather than list? -



[ERLANG]: Why answer returns list in a list rather than list? -

given module

-module(p1). -export([f2/2]). f2([a, | b]) -> {a, b}; f2([a, b | _]) -> {a, b}; f2([a]) -> a; f2(_) -> no_match.

i asked seek input value

p1:f2([1,1,[1,1]]).

my reply input value matches first function clause of f2, , such gives result:

{1,[1,1]}

but according given reply sheet, reply is

{1,[[1,1]]}

i can't quite head around why list within list, rather list in answer. appreciate explanation this, give thanks you.

you should how head-tail works in erlang. tail list; 1 element list, empty list, list.

lets illustration in shell:

2> fun = fun([h | t]) -> {h, t} end. #fun<erl_eval.6.90072148> 3> fun([a]). {a,[]} 4> fun([a,b]). {a,[b]} 5> fun([a,[a,b]]). {a,[[a,b]]} 6> fun([a,b,c]). {a,[b,c]} 7> fun([a,b,c,d]). {a,[b,c,d]}

so in case returning a repeted 1 , b list of remaining elements. in our case 1 element remains, homecoming one-element list. , element two-element list, hence list in list [[1, 1]].

list erlang tuples

mongodb - Running mongod in the background in Linux -



mongodb - Running mongod in the background in Linux -

i run mongodb on vagrant,i have used next command:

sudo mongod --fork --logpath /var/log/mongodb.log --dbpath ./data

i have tried modifying above statement all(cumulatively) , each of these options:

--logappend --journal --port 27017 , --port 27018

i error(with request add together journaling durability , notification mongod re-create log temporary file if journaling or logappend disabled):

forked process: 5360 output going to: /var/log/mongodb.log error: kid process failed, exited error number 100

i have mongodb installed on pc , uses 27017 port,will conflict error in running mongod

mongodb ubuntu vagrant

jsp - How to set values in drop down using JSTL from db -



jsp - How to set values in drop down using JSTL from db -

i have populated arraylist() info in drop downwards using jstl. when tried set value bean getter method 'designate' (a submitted db value). exception occurs. suggestions please. in advance...!!

servlet attribute

request.setattribute("result2", ldesignation);

jstl tag

<jsp:usebean id="userprofile" class= "com.package.dao.userprofile" scope="request"/> <jsp:setproperty name="userprofile" property="*" /> <strong>designation</strong>: <select id="designate" name="designate"> <option value="desigtype">select designation</option> <c:foreach var="desig" items="${result2}"> <option value="${desig.key}" ${desig.key == ${userprofile.designate ? 'selected="selected"' : ''}>${desig.value}</option> </c:foreach> </select> <br>

exception

javax.el.propertynotfoundexception: property 'key' not found on type java.lang.string @ javax.el.beanelresolver$beanproperties.get(beanelresolver.java:266) @ javax.el.beanelresolver$beanproperties.access$300(beanelresolver.java:243) @ javax.el.beanelresolver.property(beanelresolver.java:353) @ javax.el.beanelresolver.getvalue(beanelresolver.java:97) @ org.apache.jasper.el.jasperelresolver.getvalue(jasperelresolver.java:104) @ org.apache.el.parser.astvalue.getvalue(astvalue.java:183) @ org.apache.el.valueexpressionimpl.getvalue(valueexpressionimpl.java:184) atorg.apache.jasper.runtime.pagecontextimpl.proprietaryevaluate(pagecontextimpl.java:967) @ org.apache.jsp.home_jsp._jspx_meth_c_005fforeach_005f0(home_jsp.java:510) @ org.apache.jsp.home_jsp._jspservice(home_jsp.java:279) @ org.apache.jasper.runtime.httpjspbase.service(httpjspbase.java:70) @ javax.servlet.http.httpservlet.service(httpservlet.java:727) @ org.apache.jasper.servlet.jspservletwrapper.service(jspservletwrapper.java:432) @ org.apache.jasper.servlet.jspservlet.servicejspfile(jspservlet.java:390) @ org.apache.jasper.servlet.jspservlet.service(jspservlet.java:334) @ javax.servlet.http.httpservlet.service(httpservlet.java:727) @ org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:303) @ org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:208) @ org.apache.tomcat.websocket.server.wsfilter.dofilter(wsfilter.java:52) @ org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:241) @ org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:208) @ org.apache.catalina.core.applicationdispatcher.invoke(applicationdispatcher.java:748) atorg.apache.jasper.jasperexception: exception occurred processing jsp page /home.jsp @ line 158 155: <strong>designation</strong>: <select id="designate" name="designate"> 156: <option value="desigtype">select designation</option> 157: <c:foreach var="desig" items="${result2}"> 158: <option value="${desig.key}" ${desig.key == ${userprofile.designate ? 'selected="selected"' : ''}>${desig.value}</option> 159: </c:foreach> 160: 161: </select> <br>

found reply setting bean value variable , checking if status in foreach loop.

<strong>designation</strong>: <select id="designate" name="designate"> <option value="desigtype">select designation</option> <option value="${selecteddesig}" selected>${selecteddesig}</option> <c:foreach var="designate" items="${result2}"> <c:if test="${designate != selecteddesig}"> <option value="${designate}">${designate}</option> </c:if> </c:foreach> </select> <br>

jsp servlets jstl

python - Lookups in lists / set and modification of elements -



python - Lookups in lists / set and modification of elements -

i have created function finds if items within lists mutual , if modify specific elements within lists(lists nested). problem lookups within list o(n). if have huge lists spend much time on lookups. here function using lists:

def union_finder(list_of_lists_unions): while list_of_lists_unions: processed_list = list_of_lists_unions.pop(0) item in processed_list: loc_list,pointer_list in enumerate(list_of_lists_unions): location,iteration in enumerate(pointer_list): if item == iteration: #if status alter element matches on lists if(something): count +=1 index_dict[item] = count list_of_lists_unions[loc_list][location] = str(index_dict[item]) + str('@')

the function works perfectly. illustration if set input this:

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30], [1, 2, 3, 4, 29, 30], [100, 200, 300, 28, 29, 30]]

edit

i trying utilize set(), because lookup complexity o(1) (as documentation says). thing using lists can modify elements within iterations. sets don't allow me modify specific elements within them. thought locate items want within set, cast list create modifications want , recast set. efficient ? there other way utilize set's lookup speed? list's complexity lookups o(n) much because lists somethimes pretty long , if seek compare 2 lists len(list1) = m, len(list2) = n , m*n lookups (x in s).

python list set lookup nested-lists

java - NPE when creating visible Activities Robolectric 2.3 -



java - NPE when creating visible Activities Robolectric 2.3 -

for illustration have 2 activities mainactivity , nextstartedactivity.

oncreate() method in mainactivity

... intent intent = (new intent(this, nextstartedactivity.class).putextra("start", 1)); startactivity(intent);

for mainactivity invocation works fine

activity = robolectric.buildactivity(mainactivity.class).create().visible().get();

oncreate() in nextstartedactivity

... request_status = getintent().getextras().getint("start"); textureview.setsurfacetexturelistener(this); ...

when utilize invocation above nextstartedactivity, have java.lang.nullpointerexception @ nextstartedactivitytest.java:89 when use

activity = robolectric.buildactivity(nextstartedactivity.class).get();

all works fine.

please, give me understanding in differences of ways different activities. , equal setupactivity()?

if npe occurring on line:

request_status = getintent().getextras().getint("start");

then problem not creating intent in test, code expects. seek this:

intent intent = new intent(robolectric.getshadowapplication().getapplicationcontext(), nextstartedactivity.class); intent.putextra("start", 1); robolectric.buildactivity(nextstartedactivity.class).withintent(intent).create().get();

java android unit-testing robolectric

Generate DDL for Oracle Stored Procedure Dependency Graph -



Generate DDL for Oracle Stored Procedure Dependency Graph -

with toad know can view dependency (uses) graph of stored procedure using schema browser. and, oracle utility procedure deptree_fill can similar. want script out of stored procedures, functions , table definition dlls file can utilize recreate objects in database. there tool or existing script purpose? own searching has not found solution. in particular case stored procedure uses dozen other procedures, few functions , 20 tables.

edit 1

maybe original question not clear. looking take stored procedure interested in , script , of dependency graph 1 or more files.

the schema dealing has hundreds of objects in , dependency graph has ~50 objects in it. i'd rather not dig through big lists in toad or write oracle script myself if can avoid it.

hmm, quite easy find in google. table ddl: how oracle create table statement in sql*plus

code of stored procedures can found in table user_source.

also, exporting schema db can utilize oracle utilities: http://docs.oracle.com/cd/b28359_01/server.111/b28319/exp_imp.htm#g1070082

oracle stored-procedures oracle-sqldeveloper toad

php - Unable to retrieve and id from posted data -



php - Unable to retrieve and id from posted data -

i trying add together comments on joke thread, having problem grabbing joke_id should used amend comments on post.

the problem face is, thread no comments on not add together joke_id database, , thread comments on works fine. have no thought why.

this working illustration of talking about:

http://ehustudent.co.uk/cis21732825/cis3122/jokehut_4/read/joke/14

this thread working (i emphasised joke_id test purposes)

and thread not work:

http://ehustudent.co.uk/cis21732825/cis3122/jokehut_4/read/joke/4

the comment , name added database, joke_id downwards '0' , have no thought why.

here code in view:

<?php //assigning values foreach($results $row){ $name = $row->name; $joke = $row->joke; $joke_id = $row->joke_id; $date_added = $row->date_added; $vote = $row->vote; ?> } echo form_open('comments/insertcomment'); ?> <div class="new-com-bt"> <span>write comment ...</span> </div> <div class="new-com-cnt"> <input type="text" id="name-com" name="name-com" value="" placeholder="name optional" /> <textarea required="yes" class="the-new-com" id="the-new-com" name="the-new-com" placeholder="write comment here..."></textarea> <input type="hidden" name="joke_id" value="<?= $joke_id; ?>"> <input class="bt-add-com" type="submit" value="post comment"> <div class="bt-cancel-com">cancel</div> </div> <div class="clear"></div> <?php echo form_close(); ?>

here controller:

public function index(){ $this->getcomment(); } public function getcomment(){ $data['results'] = $this->comments_m->getcomments(); $this->load->view('template/header'); $this->load->view('template/sidebar'); $this->load->view('content/comment_box', $data); $this->load->view('template/footer'); } public function insertcomment(){ $data = array ( 'user' => 'user', 'comment' => 'comment', 'joke_id' => 'joke_id', 'id_post' => 'joke_id' ); $joke_id = $this->input->post('joke_id'); $this->comments_m->insertcomment($data); redirect(base_url('read/joke/'.$joke_id)); }

}

model:

//gets comments function getcomments ($joke_id){ $query = $this->db->query("select c.name, j.*, co.* jokes j left bring together category c on c.category_id = j.category_id left bring together comments co on co.joke_id = j.joke_id j.joke_id = '$joke_id' ") or die("no results found" ); if ($query->num_rows > 0) { homecoming $query->result(); } } //inserts comments function insertcomment (){ $data = array ( 'user' => $this->input->post('name-com'), 'comment' => $this->input->post('the-new-com'), 'joke_id' => $this->input->post('joke_id'), 'id_post' => $this->input->post('joke_id') ); if(strlen($data['user']) < 1){ $data['user'] = "guest"; } $this->db->insert('comments', $data); }

comments table:

create table if not exists `comments` ( `id` int(11) not null auto_increment, `user` varchar(40) not null, `comment` text not null, `joke_id` int(11) not null, `id_post` int(11) not null, `date` timestamp not null default current_timestamp, primary key (`id`) ) engine=innodb default charset=latin1 auto_increment=1 ;

jokes table:

create table if not exists `jokes` ( `joke_id` int(11) not null auto_increment, `joke` varchar(1024) not null, `category_id` int(11) not null, `vote` int(255) not null, `date_added` timestamp not null default current_timestamp on update current_timestamp, primary key (`joke_id`) ) engine=innodb default charset=latin1 auto_increment=1 ;

any help why joke_id doesn't insert/show on pages no jokes great.

thank you

php mysql sql codeigniter

angularjs - Go to grandparent state with ui-router -



angularjs - Go to grandparent state with ui-router -

with ui-router can utilize $state.go('^') go parent state without having specify it's total path. there similar way go grandparent state (my parent state abstract)?

in documentation examples can see ^ parent, maybe has solution this?

you can transition grandparent state with

$state.go('^.^')

angularjs angular-ui-router

listview - Pull down to discard - android -



listview - Pull down to discard - android -

i have listview slides up, triggered onclick event of view. want user able drag or pull downwards listview discard it. i'm looking implemented in google play music app can swipe downwards on playing music , bring bottom bar. however, don't have bottom bar want discard view completely. how implement this?

android listview animation

c# - How to convert Struct to a Class -



c# - How to convert Struct to a Class -

so i'm new c# , i've been tasked converting student_data struct class, lot of info found when looked online c++ didn't find useful. code works struggling modify fit task. console programme prints out values in array.

using system; using system.collections.generic; using system.linq; using system.text; namespace pupil { class programme { public struct student_data { public string forename; public string surname; public int id_number; public float averagegrade; public string ptitle; public string pcode; } public struct module_data { public string mcode; public string mtitle; public int mark; } static void populatestruct(out student_data student, string fname, string surname, int id_number, string ptitle, string pcode) { student.forename = fname; student.surname = surname; student.id_number = id_number; student.averagegrade = 0.0f; student.ptitle = ptitle; student.pcode = pcode; } static void populatemodule(out module_data module, string mcode, string mname, int score) { module.mcode = mcode; module.mtitle = mname; module.mark = score; } static void main(string[] args) { student_data[] students = new student_data[4]; populatestruct (out students[0], "mark", "anderson", 1, "title1", "code1"); populatestruct (out students[1], "john", "smith", 2, "title2", "code2"); populatestruct (out students[2], "tom", "jones", 3, "title3", "code3"); populatestruct (out students[3], "ewan", "evans", 4, "title4", "code4"); module_data[] modules = new module_data[4]; populatemodule (out modules [0], "mcode1", "mtitle1", 1); populatemodule (out modules [1], "mcode2", "mtitle2", 2); populatemodule (out modules [2], "mcode3", "mtitle3", 3); populatemodule (out modules [3], "mcode4", "mtitle4", 4); foreach (student_data value in students) { printstudent(value); } foreach (module_data value in modules) { printmodule(value); } } static void printstudent(student_data student) { console.writeline("name: " + student.forename + " " + student.surname); console.writeline("id: " + student.id_number); console.writeline("av grade: " + student.averagegrade); console.writeline("programme title: " + student.ptitle); console.writeline("programme code: " + student.pcode); console.writeline(" "); } static void printmodule(module_data module) { console.writeline("module code: " + module.mcode); console.writeline("module title: " + module.mtitle); console.writeline("module mark: " + module.mark); console.writeline(" "); } } }

you need rename struct class. i'd recommend looking @ microsoft's style guides , naming conventions c#

c# struct

Android - contentResolver.notifyChange() slowing performance -



Android - contentResolver.notifyChange() slowing performance -

i have mycontentprovider class overrides bulkinsert(). within method, utilize sqlite transaction insert 4,000 rows database, takes 25 seconds on samsung galaxy s4 device.

however, when remove line bulkinsert() method...

getcontext().getcontentresolver().notifychange(insertedid, null);

...the total insertion time drops 1 or 2 seconds.

so, there improve way phone call notifychange()?

i have tried calling in thread, this...

new thread(new runnable() { public void run() { getcontext().getcontentresolver().notifychange(insertedid, null); } }).start();

...but it's still slow and, reason, results in outofmemoryerror.

for completeness, here bulkinsert() method...

@override public int bulkinsert(uri uri, contentvalues[] valuesarray) { /* * open read / write database back upwards transaction. */ sqlitedatabase db = dbhelper.getwritabledatabase(); string tablename; switch (urimatcher.match(uri)) { case brands_search: tablename = brand_names_table; break; case products_search: tablename = products_table; break; case parent_companies_search: tablename = parent_companies_table; break; case products_data_search: tablename = products_data_table; break; default: //break; throw new illegalargumentexception("unsupported uri: " + uri); } /* * begin transaction */ db.begintransaction(); int numsuccessfulinsertions = 0; seek { (int = 0; < valuesarray.length; i++) { /* * insert values table */ long rowid = db.insert(tablename, null, valuesarray[i]); if (rowid > -1) { /* * increment numsuccessfulinsertions */ numsuccessfulinsertions++; /* * build uri of newly inserted row. */ uri insertedid = contenturis.withappendedid(uri, rowid); /* * notify observers of alter in info set. */ getcontext().getcontentresolver().notifychange(insertedid, null); } else { /* * don't give (as not insert attempts need succeed) */ //throw new exception("could not insert row"); } } /* * homecoming number of successful insertions */ homecoming numsuccessfulinsertions; } catch(exception e) { log.e(log_tag, "bulkinsert exception", e); /* * homecoming number of successful insertions */ homecoming numsuccessfulinsertions; } { /* * (or all) insertion attempts succeeded */ db.settransactionsuccessful(); /* * end transaction */ db.endtransaction(); } }

notify 1 time mass operation, not 1 time each record inserted. move phone call notifychange such follows loop.

android performance sqlite android-contentprovider android-contentresolver

visual studio - Wix - relationship between heatdirectory directory and preprocessorvariable -



visual studio - Wix - relationship between heatdirectory directory and preprocessorvariable -

i using heat harvest project confused relationship between defined preprocessor variable in visual studio like: sourcedir=$(solutiondir)myproject, <heatdirectory> directory=var.sourcedir , <heatdirectory> directory=$(solutiondir)myproject

which 1 defining source directory going harvested? me looks preprocessorvariable/defined preprocessor variable in vs overwriting directory 1 in headdirectory.

is correct?

one thing clear up, when phone call heat, directory harvest supplied via command line argument heat. sourcedir placeholder path in you'd find actual files harvested, relative directory chose harvest.

it's defined preprocessor variable or path specify light using -b option.

when phone call heat, can tell variable replace sourcedir , when phone call candle, you'll define it.

an example:

heat dir [options] -var var.myprojectdir <dir harvest>

will produce .wxs file $(var.myprojectdir) in place of sourcedir

when phone call candle:

candle [options] -dmyprojectdir=<my project path> <wxs files>

using -d alternative allow define value of preprocessor variable , reference when compile fragment files.

if don't utilize -var , -d options heat , candle, can utilize -b in light , wix utilize effort resolve files using paths. acts environment path variable, in utilize paths specified find files.

visual-studio wix installation heat

javascript - How make ui-sref work dynamically via element.append? -



javascript - How make ui-sref work dynamically via element.append? -

i trying create pagination directive. when total_for_pagination populated, proper html pagination created.

my html: max = max per page

<pagination data-number="{{ total_for_pagination }}" data-max="50"></pagination>

my directive:

link: function(scope, element, attrs){ scope.$watch(function(){return attrs.number;}, function(){ //need watch because there query db know how many elements page. var page_element = '<ul>'; for(var = 0; i*attrs.max<attrs.number; i+=1){ page_element += '<li class="pagination"><a ui-sref="users({start: '+i*attrs.max+', end: '+((i*attrs.max)+(attrs.max-1))+'})">'+i+'</a></li>'; } page_element += '</ul>'; element.append(page_element); }); }

what happening when inspect html they should ui-sref note changing state when click on it. when place same code, works fine.

what doing wrong? thanks!

what need here, utilize angular js core feature: $compile. see in action in this working example. line trick: $compile(element.contents())(scope);

that directive definition:

.directive("mydirective", function($compile){ homecoming { restrict: 'a', link: function(scope, element, attrs){ scope.$watch(function(){return attrs.number;}, function(){ var page_element = '<ul>' +'<li><a ui-sref="home">ui-sref="home"</a></li>' +'<li><a ui-sref="other">ui-sref="other"</a></li>' + '</ul>'; element.append(page_element); $compile(element.contents())(scope); }); } } })

which these states:

.state('home', { url: "/home", templateurl: 'tpl.html', }) .state('other', { url: "/other", templateurl: 'tpl.html', })

will need. check here. see bit related: form validation , fields added $compile

javascript angularjs angular-ui-router

parse nested json string in c# -



parse nested json string in c# -

i have json string

{"accountno":"345234533466","authvalue":"{\"topupmobilenumber\":\"345234533466\",\"voucheramount\":\"100\"}"}

to parse string have created class as

public class usercontext { public string accountno { get; set; } public string authvalue { get; set; } }

in authvalue gives me output {\"topupmobilenumber\":\"345234533466\",\"voucheramount\":\"100\"} absolutely correct. want modify class in such way want authvalue in string format , in seprate fellow member variable format.

so modify class in way gives error

public class usercontext { public string accountno { get; set; } public string authvalue { get; set; } public auth ????? { get; set; } } public class auth { public string topupmobilenumber { get; set; } public string voucheramount { get; set; } }

my requirement

authvalue whole json string required in variable want fellow member wise values

parsing logic

usercontext conobj1 = new usercontext(); conobj1 = jsonconvert.deserializeobject<usercontext>(context);

note : no modification in json string allowed.

i suggest using 2 classes - 1 json you're receiving, , 1 object model want use:

public class jsonusercontext { public string accountno { get; set; } public string authvalue { get; set; } } public class usercontext { public string accountno { get; set; } public auth authvalue { get; set; } } public class auth { public string topupmobilenumber { get; set; } public string voucheramount { get; set; } } ... var jsonusercontext = jsonconvert.deserializeobject<jsonusercontext>(json); var authjson = jsonusercontext.authvalue; var usercontext = new usercontext { accountno = jsonusercontext.accountno, authvalue = jsonconvert.deserializeobject<jsonusercontext>(authjson); };

c# json

matlab - Retrieve column and row elements based on single element -



matlab - Retrieve column and row elements based on single element -

given m x n matrix, how can obtain ordered (top-left bottom-right) entries column , row corresponding given index without indexed element itself?

for example, given 5 x 5 magic square matrix i'd retrieve column , row elements corresponding (4,2) element:

a = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9

this should yield:

b = 24 5 6 10 19 21 3 18

alternatively, requesting (5,5) element yield:

b = 15 16 22 3 11 18 25 2

or, (3,2) we'd have:

b = 24 5 4 13 20 22 12 18

if order of elements in output b isn't of import can utilize -

b = setdiff([a(:,col_id).' a(row_id,:)],a(row_id,col_id),'stable')

if order important, messy solution looks fit -

b = [a(1:row_id-1,col_id).' a(row_id,1:col_id-1) ... a(row_id,col_id+1:end) a(row_id+1:end,col_id).']

matlab

python - Why is my list comprehension causing the code to return my entire text document rather than only matches of words from permutations of a word? -



python - Why is my list comprehension causing the code to return my entire text document rather than only matches of words from permutations of a word? -

my code:

from itertools import permutations original = str(input('what word unscramble?: ')) inputfile = open('dic.txt', 'r') compare = inputfile.read().split('\n') inputfile.close() in permutations(original): auto = [print(now) in compare if in compare] #supposed compare iterations of input word text file.

i trying unscramble word finding permutations of word , running each permutation through text file of english language words see if real word or not. previous version stored permutations in list (now know that's bad idea). code here prints entire text file, , i'm not exclusively sure why. know i'm doing wrong list comprehension prints entire text file of words rather iterating through permutations of input word.

you can create code more python-idiomatic in multiple ways:

from itertools import permutations original = str(input('what word unscramble?: ')) open('dic.txt') input_file: compare = input_file.readlines() permutation in permutations(original): if permuation in compare: print(permutation)

does looking for?

python iteration permutation itertools

ios - UITextField not selectable -



ios - UITextField not selectable -

i'm attempting create sign in screen app i'm working on. right have 2 uitextfields image view behind them. when seek click on text field come in text, nil happens. i've spent lot of time trying figure out problem can't find has had similar problem. in loginviewcontroller's viewdidload method have next code:

`

[super viewdidload]; uiimageview *splashview = [[uiimageview alloc] initwithframe:self.view.frame]; splashview.image = [uiimage imagenamed:@"default-568h@2x.png"]; uitextfield *username = [[uitextfield alloc] initwithframe:cgrectmake(90, 320, 140, 30)]; username.placeholder = @"username"; username.borderstyle = uitextborderstyleroundedrect; username.returnkeytype = uireturnkeydone; username.textalignment = nstextalignmentleft; username.userinteractionenabled = yes; [splashview addsubview:username]; uitextfield *password = [[uitextfield alloc] initwithframe:cgrectmake(90, 365, 140, 30)]; password.placeholder = @"password"; password.borderstyle = uitextborderstyleroundedrect; password.textalignment = nstextalignmentleft; [splashview addsubview:password]; [self.view addsubview:splashview]; `

any help or advice appreciated thanks.

change place add together image:

[super viewdidload]; uiimageview *splashview = [[uiimageview alloc] initwithframe:self.view.frame]; splashview.image = [uiimage imagenamed:@"default-568h@2x.png"]; // image behind [self.view addsubview:splashview]; uitextfield *username = [[uitextfield alloc] initwithframe:cgrectmake(90, 320, 140, 30)]; username.placeholder = @"username"; username.borderstyle = uitextborderstyleroundedrect; username.returnkeytype = uireturnkeydone; username.textalignment = nstextalignmentleft; username.userinteractionenabled = yes; // alter [self.view addsubview:username]; uitextfield *password = [[uitextfield alloc] initwithframe:cgrectmake(90, 365, 140, 30)]; password.placeholder = @"password"; password.borderstyle = uitextborderstyleroundedrect; password.textalignment = nstextalignmentleft; //and alter [self.view addsubview:password];

if image other textfield add together view first this.

ios objective-c uitextfield textfield viewdidload

mysql - select last 25 records from SQL table -



mysql - select last 25 records from SQL table -

i want retrain lastly 25 entered records , delete remaining records according id.

delete * list id not in ( select * ( select * 'list' order id desc limit 25 ) rows )

delete * 'list' id not in ( select id 'list' order id desc limit 25 )

mysql sql

debugging - Python Remote Debuging with Pycharm -



debugging - Python Remote Debuging with Pycharm -

i have next set up: - linux machine have python code want run , launch debug server - windows machine have pycharm installed, want connect linux machine above debug code

can please tell me should on linux machine , how start debug server there. (noted: can not installed pycharm on machine)

thanks..

python debugging pycharm

smtplib - SMTPAuthenticationError when sending mail using gmail and python -



smtplib - SMTPAuthenticationError when sending mail using gmail and python -

this question has reply here:

how send email gmail provider using python? 9 answers

when seek send mail service using gmail , python error occurred type of question in site doesn't help me

gmail_user = "me@gmail.com" gmail_pwd = "password" = 'friend@gmail.com' subject = "testing sending using gmail" text = "testing sending mail service using gmail servers" server = smtplib.smtp('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) body = '\r\n'.join(['to: %s' % to, 'from: %s' % gmail_user, 'subject: %s' % subject, '', text]) server.sendmail(gmail_user, [to], body) print ('email sent')

error:

server.login(gmail_user, gmail_pwd) file "/usr/lib/python3.4/smtplib.py", line 639, in login raise smtpauthenticationerror(code, resp) smtplib.smtpauthenticationerror: (534, b'5.7.14 <https://accounts.google.com/continuesignin?sarp=1&scc=1&plt=akgnsbtl1\n5.7.14 li2yir27tqbrfvc02czpqzocqope_oqbuldzfql-msifsxobctq7tpwnbxioaaqopul9ge\n5.7.14 bugbioqhtepqjfb02d_l6rrdduhsxv26s_ztg_jyyavkrqgs85it1xzywtbwire8oivqkf\n5.7.14 xxtt7enlzts0xyqnc1u4_morbvw8pgynyeegkknknyxce76jrsdne1jgsqzr3pr47bl-kc\n5.7.14 xifnwxg> please log in via web browser , seek again.\n5.7.14 larn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 fl15sm17237099pdb.92 - gsmtp')

your code looks correct. seek logging in through browser , if able access business relationship come , seek code again. create sure have typed username , password correct

edit: google blocks sign-in attempts apps not utilize modern security standards (mentioned on back upwards page). can however, turn on/off safety feature going link below:

go link , select turn on https://www.google.com/settings/security/lesssecureapps

python smtplib

c - executing default signal handler -



c - executing default signal handler -

i have written application have registered number of signal handler different signals in linux . after process receives signal command transferred signal handler had registered. in signal handler work need do, , phone call default signal hander i.e sif_dfl or sig_ign . however, sig_dfl , sig_ing both macros expand numeric values 0 , 1 respectively, invalid function addresses.

is there way can phone call default actions i.e sig_dfl or sig_ign ?

in order accomplish effect of sig_dfl or sig_ing phone call exit(1) , nil , respectively . signals sigsegv have core dump . in general want default behavior same sig_dfl , ignore behavior same sig_ign , way operating scheme .

the gnu c library reference manual has whole chapter explaining signal handling.

you set signal handler (a function pointer) when install own handler (see manpages signal() or sigaction()).

previous_handler = signal(sigint, myhandler);

the general rule is, can reset previous handler , raise() signal again.

void myhandler(int sig) { /* own stuff .. */ signal(sig, previous_handler); raise(sig); /* when returns here .. set our signal handler 1 time again */ signal(sig, myhandler); }

there 1 disadvantage of general rule: hardware exceptions mapped signals assigned instruction caused exception. so, when raise signal again, associated instruction not same originally. can should not harm other signal handlers.

another disadvantage is, each raised signal causes lot of processing time. prevent excessive utilize of raise() can utilize next alternatives:

in case of sig_dfl function pointer points address 0 (which no valid address). thus, have to reset handler , raise() signal again.

if (previous_handler == sig_dfl) { signal(sig, sig_dfl); raise(sig); signal(sig, myhandler); }

sig_ign has value 1 (also invalid address). here can homecoming (do nothing).

else if (previous_handler == sig_ign) { return; }

otherwise (neither sig_ign nor sig_dfl) have received valid function pointer , can phone call handler directly,

else { previous_handler(sig); }

of course, have consider different apis (see manpages signal() , sigaction()).

c linux signals handlers

osx - PHP does not load environment variables if executed with sudo in CLI in Yosemite -



osx - PHP does not load environment variables if executed with sudo in CLI in Yosemite -

i setting environment variable follows:

launchctl setenv variablename value //for sudo sudo launchctl setenv variablename value

when check see if variables set, sudo , normal user, are:

launchctl getenv variablename

however, sudo, not loaded in php -i.

if run in terminal

php -i

i can see variables @ end of ouptut. if do:

sudo php -i

the variables not appear. how can create variables appear when using sudo , php ?

php osx environment-variables osx-yosemite

How to store predicates in configuration file in java -



How to store predicates in configuration file in java -

i have list of hashmap<string, real>. want access each element on list, apply predicate on , add together element list if predicate returns true.

for illustration suppose have list of hashmap - {(a, 15), (b, 17), (c, 12)}, {(a, 12), (b, 13), (d, 90)}. predicate a > 7 & b < 15 . apply predicate on each element of list , find sec element satisfy predicate. applying predicate should easy have access element , compare value values supplied predicate.

the part stuck how save such predicate in configuration file, such can converted class , new predicates can added without fiddling core code.

one way utilize nashorn javascript engine. write java script validation function each predicate, , store in java script file.

function pred1(a,b) { if(a>7 && b<15) homecoming true; else homecoming false; }

create , load predicate file. need mention predicate file paths in configuration file, , lookup paths configuration file.

properties property = new properties(); property.load(configuration file path goes here);

sample configuration file property:

predicatefilelist:test1.js,...

get property,

string[] filepaths = ((string)property.get("predicatefilelist")).split(",");

initialize , utilize script engine.

scriptenginemanager mill = new scriptenginemanager(); scriptengine engine = factory.getenginebyname("nashorn"); // utilize filepaths here instead of file name. scriptobjectmirror s = (scriptobjectmirror)engine.eval("load(\"test1.js" + "\");");

for each map in list, phone call predicate function passing arguments predicate function:

list.foreach(map->{ system.out.println(s.call(map.get("a"), m.get("b"))); });

java

php - Change background image on menu hover in Wordpress -



php - Change background image on menu hover in Wordpress -

here site (click here) 'm trying background image alter on hover of menu item, , i'm getting close! however, when hover, menu disappears , swap original image not smooth i'd like. ideas on how can improve this??

class="snippet-code-html lang-html prettyprint-override"><?php /* template name: page - projects */ ?> <?php get_header(); ?> <?php /* #start loop ======================================================*/ if (have_posts()) : while (have_posts()) : the_post(); ?> <?php /* #get fullscreen background ======================================================*/ $pageimage = get_post_meta($post->id,'_thumbnail_id',false); $pageimage = wp_get_attachment_image_src($pageimage[0], 'full', false); ag_fullscreen_bg($pageimage[0]); ?> <script type="text/javascript"> jquery(document).ready(function($) { //rollover swap images rel var img_src = "$pageimage"; var new_src = ""; $(".rollover").hover(function(){ //mouseover img_src = $(this).attr('src'); //grab original image new_src = $(this).attr('rel'); //grab rollover image $(this).attr('src', new_src); //swap images $(this).attr('rel', img_src); //swap images }, function(){ //mouse out $(this).attr('src', img_src); //swap images $(this).attr('rel', new_src); //swap images }); //preload images var cache = new array(); //cycle through rollover elements , add together rollover img src cache array $(".rollover").each(function(){ var cacheimage = document.createelement('img'); cacheimage.src = $(this).attr('rel'); cache.push(cacheimage); }); })(jquery); </script> <div class="contentarea"> <div id='cssmenu'> <ul> <li class='has-sub '><a href='#'>center consoles</a> <ul> <li class='sub'><a href='http://takeitto11.com/striper2015/portfolio/2oo-cc/'><img class="rollover" width="1500px" height="1000px" rel="http://takeitto11.com/striper2015/wp-content/uploads/2014/10/striper_hps_1500x150010.jpg" />200 cc</a></li> <li class='sub'><a class="220cc" href='#'>220 cc</a></li> <li class='sub'><a class="2605cc" href='#'>2605 cc</a></li> </ul> </li> <li class='has-sub '><a href='#'>dual consoles</a> <ul> <li class='sub'><a class="200dc" href='#'>200 dc</a></li> <li class='sub'><a class="220dc" href='#'>220 dc</a></li> </ul> </li> <li class='has-sub '><a href='#'>walk arounds</a> <ul> <li class='sub'><a class="200wa" href='#'>200 walk around</a></li> <li class='sub'><a class="220wa" href='#'>220 walk around</a></li> <li class='sub'><a class="2601wa" href='#'>2601 walk around</a></li> <li class='sub'><a class="2901wa" href='#'>2901 walk around</a></li> </ul> </li> </div> <div class="clear"></div> </ul>

thank you!!

php jquery css wordpress

android - Best practice for handling writing to external sd card? -



android - Best practice for handling writing to external sd card? -

my app allows users browse file scheme select location save file. unfortunately, 4.4 users no longer able save external sd cards. workarounds i've found online couched beingness "not particularly ideas", other applications succesfully saving external sd cards, assume these workarounds in use.

is there safe/smart workaround or recommended best practice dealing issue?

some code throws exception on 4.4.2 device:

public class sdsample extends activity { public void oncreate(bundle bundle) { super.oncreate(bundle); file external = new file("/storage/extsdcard/dcim/"); file textfile = new file(external, "textfile.txt"); seek { textfile.createnewfile(); fileoutputstream fos = new fileoutputstream(textfile); fos.write("hello".getbytes()); fos.close(); } grab (exception e) { //java.io.ioexception: open failed: eacces (permission denied) log.e("", log.getstacktracestring(e)); } } }

afaik there mediafile hack uses media content provider. not work on devices. e.g. here failed on samsung galaxy note3 neo. here found mediafile hack: http://forum.xda-developers.com/showthread.php?t=2634840

the official way solve problem storage access framework: http://developer.android.com/guide/topics/providers/document-provider.html

on android 4.4, works single files user has select. @ to the lowest degree have total access file, in info directories of other apps (on sd). far understood, it's not possible e.g. allow user take 1 directory , have total access in future.

this should come action_open_document_tree, it's api21. , i'm eger have lollipop on device sd slot, not test yet ;-) here moto g or lg g3? :) http://developer.android.com/reference/android/content/intent.html#action_open_document_tree

android

javascript - d3.js svg image dragging works, but raises many type errors -



javascript - d3.js svg image dragging works, but raises many type errors -

i working on little project d3.js (https://github.com/giordanoarman/note_app).

i used code enables panning, zooming , dragging of svg image. works fine, when open console see

uncaught typeerror: cannot read property 'x' of undefined

and plenty of

uncaught typeerror: cannot read property '0' of undefined.

i have tried re-write can not understand wrong. works fine, have clean output on console. can help me out?

it looks in dragged = function (d), d null. case "property '0'" errors there's lot of in d3.v3.js. have line number / file names these errors?

are svg images ever beingness hidden? cause events passing null value.

running code, both errors have origin, happens when click somewhere other top of svg. can't calculate offset between mouse , svg's location.

javascript svg d3.js drag

c++ - Check template argument of Base class against values in Derived -



c++ - Check template argument of Base class against values in Derived -

lets assume have interface class (made-up example, not real code)

template <int year> class auto { public: virtual void move(double x, double y) = 0; // etc etc };

and lot of derived classes like

template <int year> class model8556 : virtual public car<year> { private: void move(double x, double y) { // ... } int yearmax = 2000; // different every model int yearmin = 1990; // etc etc };

and take model somewhere via

car<foo>* mycar; switch (bar) { case 1: mycar = new model3434<foo>(); break; case 2: mycar = new model8295<foo>(); break; // etc }

i want check template argument of auto (or better: of derived classes) @ compile time. want template argument year remain in range (i.e. between yearmin , yearmax). however: range differs between derived classes. (edit:) as there lot of derived classes, prefer solution within car.

how accomplish behaviour? or bad design?

any help appreciated.

do mean this?

template <int year> class model8556 : virtual public car<year> { private: static const int yearmax = 2000; // assume meant static constant static const int yearmin = 1990; static_assert( yearmin <= year && year <= yearmax, // status "invalid template argument specified!" ); // error message };

demo. there no possibility set base of operations class current method; crtp doesn't work because derived class considered incomplete within car. however, alter in construction might help.

template <int year> class auto { // implementation, above }; template <int year, int yearmin, int yearmax> class carchecker : car<year> { // optionally declare constants here static_assert( yearmin <= year && year <= yearmax, "invalid template argument specified!" ); }; template <int year> class model8556 : public carchecker<year, 1990, 2000> // specify minimum , maximum here {};

c++ inheritance interface

ios - Calling NSStringFromClass on a Swift Class in Objective-C returns module mangled name -



ios - Calling NSStringFromClass on a Swift Class in Objective-C returns module mangled name -

i aware of this question regarding how can readable class name of objective-c class in swift.

what want accomplish getting readable class name of swift class within objective-c without mangling class name module.

so if have swift class:

class foo: nsobject{}

then within objective-c love utilize convenient nsstringfromclass convert class name string.

i expect nsstringfromclass([foo class]) homecoming @"foo" instead returns @"bar.foo" withbarbeing module name.

i came across gist seems little hacky , messy, there improve way? doesn't include typing class name manually string preferred.

swift 2.1

with swift 2.1 seems if sufficient

class yourclassname: nsobject { }

and use:

var str = string(yourclassname)

i have not tested objective-c code though

before swift 2.1:

just set @objc(yourclassname) in swift class:

@objc(yourclassname) class yourclassname: nsobject { }

and can utilize nsstringfromclass this:

nsstringfromclass(yourclassname.self)

it should work objective-c then.

ios objective-c swift xcode6

Sending email via Node.js using nodemailer is not working -



Sending email via Node.js using nodemailer is not working -

i've set basic nodejs server (using nodemailer module) locally (http://localhost:8080) can test whether server can send out emails.

if understand smtp alternative correctly (please right me if i'm wrong), can either seek send out email server someone's email business relationship directly, or can send email, still using node.js, via actual email account (in case personal gmail account), i.e using smtp. alternative requires me login acount remotely via nodejs.

so in server below i'm trying utilize nodejs send email personal email business relationship personal email account.

here's simple server :

var nodemailer = require('nodemailer'); var transporter = nodemailer.createtransport("smtp", { service: 'gmail', auth: { user: '*my personal gmail address*', pass: '*my personal gmail password*' } }); var http = require('http'); var httpserver = http.createserver(function (request, response) { transporter.sendmail({ from: '*my personal gmail address*', to: '*my personal gmail address*', subject: 'hello world!', text: 'hello world!' }); }).listen(8080);

however, it's not working. got email google saying :

google account: sign-in effort blocked if can switch app made google such gmail access business relationship (recommended) or alter settings @ https://www.google.com/settings/security/lesssecureapps business relationship no longer protected modern security standards.

i couldn't find solution above problem on nodemailer github page. have solution/suggestion ?

thanks! :-)

the reply in message google.

go : https://www.google.com/settings/security/lesssecureapps

set access less secure apps setting enable

for sec part of problem, , in response

i'm next steps nodemailer github page there no errors in code

i refer nodemailer github page, , piece of code :

var transporter = nodemailer.createtransport({ service: 'gmail', auth: { user: 'gmail.user@gmail.com', pass: 'userpass' } });

it differs code, in fact have : nodemailer.createtransport("smtp". remove smtp parameter , works (just tested). also, why encapsulating in http server? next works :

var nodemailer = require('nodemailer'); var transporter = nodemailer.createtransport({ service: 'gmail', auth: { user: 'xxx', pass: 'xxx' } }); console.log('created'); transporter.sendmail({ from: 'xxx@gmail.com', to: 'xxx@gmail.com', subject: 'hello world!', text: 'hello world!' });

node.js email smtp nodemailer

Edit on site with Javascript -



Edit on site with Javascript -

i have school assignment love have on site edit admin panel. coded cant work properly, every time double click in 1 , out replaces value previous value.

<script type="text/javascript"> $(function() { var bound = $("p").bind("dblclick", function(event) { event.stoppropagation(); var currentele = $(this); var value = $(this).html(); edit(currentele, value); }); }); function edit(currentele, value) { $(currentele).html('<input class="tedit" type="text" value="' + value + '" />'); $(".tedit").focus(); $(".tedit").keyup(function(event) { if (event.keycode == 13) { currentele.parent('p').html($(this).val().trim()); } }); $(document).click(function() { var value1234 = $(".tedit").val().trim(); $("p").removeclass(); currentele.html(value1234); }); } </script>

here jsfiddle http://jsfiddle.net/x6e16d3n/3/

the issue because every time edit create new click handler attached document has reference current element @ time of creation.

this handler still active when editing object , still has reference old element (look closures understand why) taking value add together p ever .tedit on screen in end updated same text.

one quick soloution take click handler out of dit function , declare once, check if edit on screen , if create edits parent html equal value of input box

$(function () { var bound = $("p").bind("dblclick", function (event) { event.stoppropagation(); var currentele = $(this); var value = $(this).html(); edit(currentele, value); }); }); function edit(currentele, value) { $(currentele).html('<input class="tedit" type="text" value="' + value + '" />'); $(".tedit").focus(); $(".tedit").keyup(function (event) { if (event.keycode == 13) { currentele.parent('p').html($(this).val().trim()); } }); } $(document).click(function () { if ($(".tedit").length) { var value1234 = $(".tedit").val().trim(); $("p").removeclass(); $(".tedit").parent().html(value1234); } });

example fiddle http://jsfiddle.net/x6e16d3n/11/

javascript

Add number of days to Date object in jQuery always shows wrong days in a month -



Add number of days to Date object in jQuery always shows wrong days in a month -

i want able traverse through date object adding single day loop. when loop , add together single day date object per each iteration end 30 days in month no matter month seek (even february). must jquery isn´t strongest syntax i´m looking guys. due practical matters in project need show 30 days in view no matter date select.

how can add together single day per each iteration still preserving days in each month?

var date = new date(2014, 10, 10); (var = 0; < 30; i++) { // stuff date object ... abbreviated date.setdate(date.getdate() + 1); //i thought enough, oct showing 30 days //should utilize method when adding days? }

that's november. months 0-bases.

var date = new date(2014, 10, 10); console.log(date) > mon nov 10 2014 00:00:00 gmt-0500 (est)

from the docs:

var thebigday = new date(1962, 6, 7); // 1962-07-07

jquery

ftp - Set folder and file permissions without SSH -



ftp - Set folder and file permissions without SSH -

my hosting provider refuses give access shared hosting plan via ssh. problem want set permissions folders 755 , files 644 have no thought how apply changes files&folders via ftp connection.

my guess utilize cron job, not find out how that. please advise

have tried using shell_exec via php? http://php.net/manual/en/function.shell-exec.php

check first if shell_exec function enabled in web hosting. alternative can looking alternative in ftp client.

ssh ftp cron file-permissions

c# - error: 'object' no definition/extension method -



c# - error: 'object' no definition/extension method -

using code (shown below) have got error this:

'object' not contain definition 'rendertransform' , no extension method 'rendertransform' accepting first argument of type 'object' found (are missing using directive or assembly language

i have no thought why showing error according examples (of this) should work. code:

public void rotate(object sender, int rotationamount, int centerx, int centery) { rotatetransform rotate = new rotatetransform(rotationamount); rotatetransform.centerx = centerx; rotatetransform.centery = centery; sender.rendertransform = rotatetransform; }

you have cast sender (which declared object) appropriate type:

uielement element = sender uielement; if (element != null) element.rendertransform = rotatetransform;

c# wpf

bash - parsing a logfile for error messages -



bash - parsing a logfile for error messages -

i'm trying write bash command able set variable (exitstatus) based on scanning of log file specific pattern.

inside log file, many error messages can present. problem 1 error message written on 2 lines. example:

error 77: invalid record detected @ position 88332: bad alignment detected [ird-21] error 77: invalid record detected @ position 88333: bad alignment detected [ird-21] error 77: invalid record detected @ position 88334: bad alignment detected [ird-21] error 77: invalid record detected @ position 88335: bad alignment detected [ird-21] error 88: bad format in string @ record 287 [syn-44] error 88: bad format in string @ record 288 [syn-44] error 88: bad format in string @ record 289 [syn-44] error 73: invalid table spec or stub @ record 1022 [invt-33]

if log file contains messages related error 77 [ird-21], or if there no errors @ it's fine, exitstatus remains 0. otherwise, exitstatus set 2.

i've been trying find , grep fact error message can spread on 2 lines destroying efforts. put, i'd inquire shell: "hey, bash, log file contains other errors ird-21?, if so, raise error".

also, have no command on log file format, comes our client.

any ideas on how this?

if want know if there's word error followed other 77, can (with gnu grep):

exitstatus=$(grep -qp 'error (?!77)' sample.log && echo 2 || echo 0)

bash grep find

c# - File Upload wrong filepath -



c# - File Upload wrong filepath -

i'm trying upload video on youtube using this code

i have changed var filepath = @"replace_me.mp4"; by

if (fileupload1.hasfile) { var filepath = fileupload1.filename; // replace path actual film file. using (var filestream = new filestream(filepath, filemode.open)) { var videosinsertrequest = youtubeservice.videos.insert(video, "snippet,status", filestream, "video/*"); videosinsertrequest.progresschanged += videosinsertrequest_progresschanged; videosinsertrequest.responsereceived += videosinsertrequest_responsereceived; await videosinsertrequest.uploadasync(); } }

but i'm getting error it's wrong path

how can solve that? have tried:

var filepath = fileupload1.postedfile.filename; var filepath = fileupload1.postedfile.tostring(); var filepath = path.getfilename(fileupload1.filename);

but same result..

you may have save file first using:

var newfile = server.mappath(fileupload1.filename); fileupload1.saveas(newfile);

or working filestream class try:

fileupload1.filecontent; // gets file stream

c# asp.net .net file-upload