Posts

Showing posts from April, 2013

c# - Enum Parse C++ Or Analog -

in c# use code: enum computer_name_format { computernamenetbios, computernamednshostname, computernamednsdomain, computernamednsfullyqualified, computernamephysicalnetbios, computernamephysicaldnshostname, computernamephysicaldnsdomain, computernamephysicaldnsfullyqualified } string format = "computernamednsfullyqualified"; (computer_name_format)enum.parse(typeof(computer_name_format), format) how use in c++ ? there no such function in c or c++. can make std::map<std::string, computer_name_format> m that. fill map doing m["computernamenetbios"] = computernamenetbios; etc. use auto f = m.find(format); if (f != m.end()) { ... value in f.second ... }

android - how to fetch all column Values based on Email -

i want fetch column table tblreg, has column registration,name,password,email , contact out email checked while registration ,it unique column.. value exist once in table of 1 email. i having login matching email password , passing value of email through intent in home activity keyname want fetch detail sqllite based on email,i receiving getextra through intent. here code of home activity public class activity_home extends activity { databasehandler dbh = new databasehandler(this); string regid,emailid,name,contact,data; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_activity_home); textview lblemail = (textview) findviewbyid(r.id.textview1); textview lblreg = (textview) findviewbyid(r.id.textview1); textview lblname = (textview) findviewbyid(r.id.textview1); dbh.open(); try { data = getintent().getextras().ge...

javascript - Responsive webpage for different window/screen size -

so came across web page top travel destination tripadvisor. if change browser window size, ui changes gracefully fit new window size. font size, element's width, changes accordingly fit wimdow size. could tell me how go building these kind of responsive webpages? i know question broad in scope want know there frameworks building webpages these. you can use css media queries different screen size @media (max-width: 1024px) {} @media (max-width: 768px) {} @media (max-width: 480px) {} @media (max-width: 320px) {}

google app engine - Confusion relating to public and private keys and JWT -

i'm trying out jwt (json web tokens) in go web service. here's i've done far: package jwt import( "fmt" "net/http" "github.com/gorilla/mux" "github.com/dgrijalva/jwt-go" "io/ioutil" ) var privatekey []byte var publickey []byte func jsonwebtokenshandler(w http.responsewriter, r * http.request){ // create token encodetoken := jwt.new(jwt.signingmethodhs256) // set claims encodetoken.claims["latitude"] = "25.000" encodetoken.claims["longitude"] = "27.000" // sign , complete encoded token string tokenstring, err := encodetoken.signedstring(privatekey) decodetoken, err := jwt.parse(tokenstring, func(token *jwt.token) (interface{}, error) { if _, ok := token.method.(*jwt.signingmethodhmac); !ok { return nil, fmt.errorf("unexpected signing method: %v", token.header["alg"]) } ...

operating system - Difference between switch & bus architecture? -

i going through operating systems textbook got stuck @ switch architecture . please explain , how different bus architecture ? switch architecture , bus architecture 2 aspects of computer networks. the main differences between 2 in bus architecture, paths different components of network shared , response time slow when large number of users there because of single path particular resource(shared memory). in case of switch networks there concurrent paths resource , these paths point point. due reason throughput of switch based architecture more of bus based architecture multiple paths available shared resource , if user not getting off resource, other users not stalled unlike bus architecture stalled due single path.

How can I throttle uploads in Node.js / Express 4? -

i throttle file uploads in express 4. mean bytes per second, not number of api calls. i want able simulate slow connection file uploads can test out progress animations. i want limit file upload endpoint , not other endpoints. how can this? ideally, i'd add middleware on specific endpoint , specify transfer speed in bytes/s. if on osx , interested in occasional testing (as opposed standardized test response) i'd take @ apple network link conditioner. here's info . also appears recent versions of chromium , assume chrome have built in network throttling options in dev tools.

How to hide a div class in Wordpress? CSS -

this div class, have included entire code below. need hide on wordpress on site. how go it? i tried . section_wrapper clearfix { display : none; } in custom css not work. how hide this? <div class="section_wrapper clearfix"> example code below: <div class="section_wrapper clearfix"> <!-- additional html content --> </div> since section_wrapper , clearfix classes give them styling have include .(dot) before them , have use 1 among 2 of them. for example .section_wrapper{ display:none; } if write this .section_wrapper .clearfix{ display:none; } it means giving styling element having class clearfix under element having class section_wrapper

c++ - How to use the tool include-what-you-use together with CMake to detect unused headers? -

the tool include-what-you-use can used detect unneeded headers. using cmake c++ software project. how can instruct cmake run include-what-you-use automatically on source files of software project? cmake 3.3 introduced new target property cxx_include_what_you_use can set path of program include-what-you-use . instance cmakelists.txt cmake_minimum_required(version 3.3 fatal_error) add_executable(hello main.cc) find_program(iwyu_path names include-what-you-use iwyu) if(not iwyu_path) message(fatal_error "could not find program include-what-you-use") endif() set_property(target hello property cxx_include_what_you_use ${iwyu_path}) is able build file main.cc #include <iostream> #include <vector> int main() { std::cout << "hello world!" << std::endl; return 0; } and @ same time have include-what-you-use give out warning included header vector not needed. user@ubuntu:/tmp$ ls ~/hello cmakelists.txt main.cc use...

Creating custom dropdown list in angularjs -

i below result. there button. when click on button open list have checkbox , buttons ok, cancel.i make many operation: check, uncheck search... , list close when click ok or cancel or go out of control. how best result in angularjs? hi ask better use. panel or drop-down list or... maybe know similar solution? want know how make in html side?

Google Maps Javascript Api V3 data.remove isn't removing a feature -

i'm working on little pet project edit personal maps drawing polygons , finding when call map.data.remove(feature), feature removed map.data isn't removed visual map. of javascript doesn't relate data layer has been omitted. additional steps, removal, or function calls need remove feature map well? ... function custommaptype() { } custommaptype.prototype.tilesize = new google.maps.size(256,256); custommaptype.prototype.maxzoom = 7; custommaptype.prototype.gettile = function(coord, zoom, ownerdocument) { var div = ownerdocument.createelement('div'); var baseurl = 'static/tiles/images/'; var x = ((coord.x % math.pow(2, zoom)) + math.pow(2, zoom)) % math.pow(2, zoom); baseurl += zoom + '_' + x + '_' + coord.y + '.png'; div.style.width = this.tilesize.width + 'px'; div.style.height = this.tilesize.height + 'px'; div.style.backgroundcolor = '#1b2d33'; div.style.backgro...

mysql - How to validate uniqueness of field based on another table -

i want validate roll_no field in students model based on student_section model field section , student_section.rb class studentsection < activerecord::base validates :standard_id, :presence=> {:message=>" cannot blank"} validates :section_id, :presence=> {:message=>" cannot blank"} validates :student_id, :presence=> {:message=>" cannot blank"} end i add validation in student.rb as class student < activerecord::base validates :student_id, :presence=> true validates :student_name, :presence=> true validates_format_of :email, :with => /\a([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i validates :phone, :length=>{:in => 8..15} validates :admission_no, :uniqueness=> { scope: :org_id} validates :roll_no, :uniqueness=> { scope: @student_section.section_id} end but throws unknown field section_id first, should make relationship between student , studentsection . if understa...

javascript - ng-click expression in view setting $scope.var's value -

<button ng-click="showtext==true">click</button> <p ng-show="showtext">my p</p> i don't want go the controller.js set showtext equal true show p why above shortcut doesn't work? just use = (assignment operator) instead of == (comparison operator) == doing comparison instead of assigning value showtext. markup <button ng-click="showtext=true">click</button> <p ng-show="showtext">my p</p> plunker hope :)

angularjs - Angular 1.4 + ngNewRouter + ES6 : Cannot read property '$routeConfig' of undefined -

i trying throw basic working example of angular 1.4 app written both new router ecmascript 6. have been fiddling code non stop , don't understand why getting error being thrown: failed instantiate module bookshelf due to: typeerror: cannot read property '$routeconfig' of undefined i have angular app being bootstrapped in index.html file so: <!doctype html> <html> <head lang="en"> <meta charset="utf-8"> <title>home</title> </head> <body> <div class="container"> <ng-viewport></ng-viewport> </div> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-new-router/dist/router.es5.js"></script> <script src="bower_components/angular-messages/angular-messages.js"></script> <script src="https://google.github...

Would you ever implement a linked list in Javascript? -

i'm learning data structures formally first time. me, of benefits traditionally described of linked lists (easier memory allocation , faster input , deletion body of list) seem moot in js given way arrays work (like objects numbered keys). can give example of why i'd want use linked list in javascript? as comments note, you'd if need constant time insertion/deletion list. there 2 ways array reasonably implemented allow populating non-contiguous indices: as actual c-like contiguous block of memory large enough contain indices used; unpopulated indices contain reference dummy value wouldn't treated populated entries (and excess capacity beyond max index left garbage, since length says it's not important) as hash table keyed integers (based on c-like array) in either case, cost insert @ end going amortized o(1) , spikes of o(n) work done whenever capacity of underlying c-like array exhausted (or hash load threshold exceeded) , reallocation ne...

exception - java.util.NoSuchElementException when using Scanner.next() -

java noob working on project i'm supposed display data obtained text file onto grids. project written, output displays exception: run: exception in thread "main" java.util.nosuchelementexception @ java.util.scanner.throwfor(scanner.java:862) @ java.util.scanner.next(scanner.java:1371) @ inputoutput.readdatafile.populatedata(readdatafile.java:50) @ boggle.boggle.main(boggle.java:27) java result: 1 build successful (total time: 0 seconds) boggle.java:27 links line of code in main method of superclass boggle.java. line supposed call 1 of methods in class readdatafile.java. line reads dataread.populatedata(); (//2. on comments below), , in context main method looks like: public static void main(string[] args) { //main() method begins // todo code application logic here readdatafile dataread = new readdatafile("boggledata.txt"); //1. instance of class readdatafile created dataread.populatedata(); ...

osx - Is there danger in installing 2 versions of Anaconda for Python on one machine? -

some background: have intel mac osx (running yosemite) , use pycharm community edition main ide. code in python 3.4 however, i'm taking mit ocw courses use python 2. make easier on myself when using mit's skeleton files have downloaded python 2.7 , switch pycharm interpreter depending on project. here's question: i'm wondering if run trouble downloading 2.7 , 3.4 versions of anaconda. if ok, need special import commands depending on version of python i'm coding in? thanks! happy add clarity / more info if isn't enough answer questions. there's no danger, it's not recommended way of achieving this. rather, should use conda , package manager comes anaconda, create environment other version of python. instance, if started anaconda3, conda create -n python27 python=2.7 anaconda would create environment called python27 in ~/anaconda/envs/python27 python 2.7 , packages anaconda. point ~/anaconda/bin/python or ~/anaconda/envs/python27...

android - Change horizontal progress bar indeterminate color -

is possible change horizontal indeterminate color? of take standard theme color. i change orange? i know have change circle color not sure change horizontal color tried theme, custom progress bar in drawable etc couldn't work. here xml: <progressbar android:id="@+id/status_progress" style="?android:attr/progressbarstylehorizontal" android:layout_width="match_parent" android:layout_height="15dp" android:layout_below="@id/status_text" android:indeterminate="true" android:indeterminateonly="true" /> progressbar.getindeterminatedrawable() .setcolorfilter(progressbar.getcontext().getresources().getcolor(<colorid>), porterduff.mode.src_in);

html - Background Color with Bootstrap -

i seem having problems lining background color of row in bootstrap. background right of second placeholder box solid color, right it's taking account additional padding, , it's not aligning properly. background color pertrudes past main header image. any suggestions? you'll need extend width of page in jsfiddle see i'm talking about. js fiddle: http://jsfiddle.net/aukme1mb/ <div class="container"> <div class="row"> <div class="col-md-12"> <img class="img-responsive" src="http://placehold.it/1140x360"> </div> </div> <div class="row bg"> <div class="col-md-5"> <img class="img-responsive" src="http://placehold.it/458x304"> </div> <div class="col-md-7"> <p>text here</p> </div> </div...

sql - H2 and FOREIGN KEY -

Image
i ran problem: i going create 2 tables in h2. when tried create second table, error occured: column c_task not found here code: create table s_task (c_task int primary key, n_task varchar(255), point_count int); create table s_achievement(c_achievement int primary key, n_reward varchar(255), picture varchar(255), foreign key (c_task) references s_task(c_task), exec_count int); did not define linking field you defining relationship (a foreign key) column not exist in table s_achievement . foreign key link between column on child table (the "many" table) , column on parent table (the "one" table). code says wish link field "c_task" on "s_achievement" there no "c_task" field on table. example take example customers (parent table) have 0 or more invoices (child table), , every invoice must owned 1 customer. similarly, invoice table in turn parent line items table. you have tables , columns: customer_ ...

javascript - Passing Query Parameters Into Component EmberJS -

i have large number of query parameters route right now, , have component resides in route's template. i want query parameters updated upon change inside component, pass in query parameters via component like: {{comp-name query_param1=query_param1 ... query_param=query_param20 }} i update query params in component with: {{input value=query_param_x}} however, gets tedious , overwhelmingly long passing in 20 parameters. there way make more concise? note: application developing on ember 1.12 , not using ember-data. you can create object contains params, similar this: params = { query_param1, query_param2, ... } pass in params object instead of each individual param: {{comp-name params=params}} also, try think if component needs many parameters. there way break down less complex, smaller components, etc.

Spark streaming not working -

i have rudimentary spark streaming word count , not working. import sys pyspark import sparkconf, sparkcontext pyspark.streaming import streamingcontext sc = sparkcontext(appname='streaming', master="local[*]") scc = streamingcontext(sc, batchduration=5) lines = scc.sockettextstream("localhost", 9998) words = lines.flatmap(lambda line: line.split()) counts = words.map(lambda word: (word, 1)).reducebykey(lambda x, y: x + y) counts.pprint() print 'listening' scc.start() scc.awaittermination() i have on terminal running nc -lk 9998 , pasted text. prints out typical logs (no exceptions) ends queuing job weird time (45 yrs) , keeps on printing this... 15/06/19 18:53:30 info sparkcontext: created broadcast 1 broadcast @ dagscheduler.scala:874 15/06/19 18:53:30 info dagscheduler: submitting 1 missing tasks resultstage 2 (pythonrdd[7] @ rdd @ pythonrdd.scala:43) 15/06/19 18:53:30 info taskschedulerimpl: adding task set 2.0 1 tasks 15/06/19 1...

c# - How to display WCF HTTP codes in service response -

i'm working through web service using wcf , entity framework , know how view or return http status codes calling clients. the code have follows: iuserservice.cs [operationcontract] [webinvoke(method = "get", responseformat = webmessageformat.json, bodystyle = webmessagebodystyle.wrappedrequest, uritemplate = "/getusers")] list<user> getusers(); userservice.svc.cs public list<user> getusers() { var usercontroller = new usercontroller(); return usercontroller.getusers(); } usercontroller.cs public list<user> getusers() { list<user> serverresponse = new list<user>(); try { using (var db = new myentities()) { list<user> userlist = db.users.tolist(); foreach (user userrecord in userlist) { user u...

html - Navigation displaying slightly different in Firefox -

Image
on site i'm working on, i've got looking pretty same on main browsers (checking chrome, safari & firefox). all except pesky 1px gap on navigation items, noticeable on active items (when background filled). you can visit site here: http://lumbre.breadadams.com/ this gap i'm talking about i've messed height , line-height , padding , etc. of multiple elements (nav, ul , such), nothing seems trick. however if increase font-size 1.2em 1.3em fits, doesn't on chrome. increasing font 0.1 @ time makes alternate between fitting on chrome , firefox basically. #navigation-container #main-nav ul > li.menu-item-has-children > a::after { content: ""; font-family: fontawesome; margin-left: 4px; position: absolute; } here answer amigo! just add position: absolute; it's :after (the small icon) needs position absolute. it's causing bit of upper space, when give position absolute, friend!

How do I change column count of a GridLayout dynamically in Android Studio? -

i want set number of column of gridlayout width of window. but, these sort of codes don't work in oncreate() function. gridlayout glayout = (gridlayout)findviewbyid(r.id.a_grid_layout); glayout.setcolumncount(4); if want set numbers of columns based on width of gridlayout, must override onmeasure method. provides widthspec , heightspec parameters, can actual width , height in pixels using measurespec.getsize(). there, calculate how many columns you'd show based on width of gridlayout found, , use setcolumncount make display number of columns.

c# - System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code -

i worked c#(started work). @ first created model. , model created mvc 5 controller views, using entity framework. thought correct (that necessary table created model, , can worked local database), when run application , go page http://localhost:49640/controllername error: additional information: network-related or instance-specific error occurred while establishing connection sql server. server not found or not accessible. verify instance name correct , sql server configured allow remote connections. (provider: sql network interfaces, error: 52 - unable locate local database runtime installation. verify sql server express installed , local database runtime feature enabled.) i tried find solution, didn't. understood can problems connectionstrings in web.config or problems connection server, how solve problem? my connection strings: <connectionstrings> <add name="defaultconnection" connectionstring="data source=(localdb)\v11.0;attachdbfilename=|...

mysql() refuses to read characters in php -

i copied code word database causing problems when want retrieve them mysql() in php. i've identified problem is, dashes 1 causing error retrieving it: tue – thur: i have convert dash following 1 in order mysql() able retrieve it: (it's unnoticeable causes error took me time figure out happening) tue - thur: this causing error: it’s but not one: it's this 1 causing problem: course…much more! i have change one: course...much more because had copy huge amounts of text database hard me spot part of text causing problem. looks identical. so, question is, knows tool or can use paste text , me either point me problematic characters or change them ones won't cause problem? note now know in order fix have change encoding of string i'm inserting database unicode utf8. there idea how can string converted? to convert unicode string utf8 discovered php function utf8_decode after pass string unicode characters, weird character set ...

display current date -1 in sybase -

i trying display previous day's date sybase using select query: select dateadd(day,-1,convert(char(10), getdate(), 23)) this query displays 2015-06-18 00:00:00.0 i expect output 2015-06-18 . how can that? try select dateadd(day,-1,convert(date, getdate(), 365))

c# - How to stop a if for a second before executing the rest of the commands -

i been working on script pause menu , don't know how make stop before start executing next line code, ask because execute "if" multiple times, because detects i'm still pressing cancel button. (i use c# , work on unity 5) thanks using unityengine; using system.collections; public class menupausa : monobehaviour { public gameobject menupausa; private bool pausamenu = false; // use initialization void start () { } // update called once per frame void update () { if (input.getbuttondown("cancel") || pausamenu == false) { menupausa.setactive (true); time.timescale = 0; waitforseconds(1); pausamenu = true; } else { menupausa.setactive (false); time.timescale = 1; invoke("waiting",0.3f); } } } i use coroutine kinda this: bool paused = false; void update () { if (paused) // exit method if paused return; if (input.getbuttondown("pausebutton...

asp.net - Jquery PhoneMask - Unexpected Behavior -

i using jquery phonemasking started behave weird. able mask on textbox on focus , when start entering numbers fills in alternate positions separated _ ends 5 numbers. "( 9 ) 8_6-_5_6". here code. <asp:textbox id="txtphone1" runat="server" cssclass="phonemask" tooltip="phone 1" maxlength="20" validationgroup="childvalidationgroup"></asp:textbox> <input type="hidden" id="nophonemask" class="nophonemask" runat="server" value="0" /> function fncphonemasking() { if ($('.nophonemask').val() == "0") { $('.phonemask').mask("(999) 999-999"); } } $(function () { fncphonemasking(); }); can me out wrong? seems correct cannot find solution behavior.

jquery - Progress Bar Increment/Decrement -

i need progress bar semantic ui . i'm trying replicate first example increment/decrement button, life of me, can't work, on matter or sample javascript code appreciated. the code page located here , , looking @ section in particular: $buttons .on('click', function() { var $progress = $(this).closest('.example').find('.ui.progress') ; if( $(this).hasclass('increment') ) { $progress.progress('increment'); } else { $progress.progress('decrement'); } }) ; as can see, each button added click event. then, $progress assigned closest found progress bar. finally, check class of button (to know if in/decrement) , .progress value gets used accordingly. while @ it, here's html use buttons: <div class="example"> <div class="ui progress"> <div class="bar"> <div class="progress"></div> ...

ruby - What is the best way to assign nil to a default association? -

so if have factory such (address factory) , want create test creates person no address require 'faker' factorygirl.define factory :person address first { faker::name.first_name } last { faker::name.last_name } end end i expect following work (but doesn't): create(:person, address: nil) what best way set properly?

phantomjs - What tools should I use Selenium or nightwatch or other to automate data entry on few similar websites at the same time?. -

i need enter pretty same date on few handful of similar sites using web automation tools/ software. not doing testing want use automation side of tools. need enter data same time ( real time possible ). wondering if 1 tool has advantage on other using automation.

java - Spring Webservices gives 406 error -

i have created simple spring webservices example when try response getting error : http status 406 - the resource identified request capable of generating responses characteristics not acceptable according request "accept" headers. this spring controller: @controller public class datacontroller { @requestmapping("studentlist") public @responsebody list<student> getstudentlist() { list<student> studentlist = new arraylist<student>(); studentlist.add(new student(2, "a1", "b1", "a@gmail.com", "123456")); studentlist.add(new student(3, "a2", "b2", "b@gmail.com", "123456")); studentlist.add(new student(4, "a3", "b3", "c@gmail.com", "123456")); return studentlist; } } this student.java file: @xmlrootelement public class student { int id; string ...

java - Where are the JAXB schemas published? -

the jaxb 1.0 , jaxb 2.0 schemas supposed available bindings schema jaxb site. unfortunately, last updated in 2005 , of links broken. official location of schemas? there should authoritative source v1.0, 2.0, 2.1 , 2.2. jaxb xml schemas jaxb 1.0 xml schema jaxb 2.0 xml schema it seems there no version 2.2 of schema. recent 2.1. and old post java.net forums (now unavailable) stated: i don't think has been published (we should fix that), if have jaxb-xjc jar file, can find inside jar. the relevant files in jaxb-xjc-2.2.11.jar are: com/sun/tools/xjc/reader/xmlschema/bindinfo/binding.xsd com/sun/tools/xjc/reader/xmlschema/bindinfo/xjc.xsd com/sun/tools/xjc/reader/xmlschema/bindinfo/xs.xsd from source repository: binding , xjc , xs schemas. note: these locations changed yet again in 2017.

mysql - How do I select all the dealers that did not have an order? -

Image
i trying join 2 tables , select dealers did not have promo code used on order. how can this? i'm trying below, it's not working right. in example want bob, since promo_code hasn't been used in orders. select d.`name` z_dealer d left outer join z_order o on (d.promo_code = o.promo_code) , o.promo_code null here tables... mysql> select * z_dealer; +----+------+------------+ | id | name | promo_code | +----+------+------------+ | 1 | john | holiday | | 2 | suzy | special | | 3 | bob | laborday | +----+------+------------+ mysql> select * z_order; +----+-------+------------+ | id | total | promo_code | +----+-------+------------+ | 1 | 10 | holiday | | 2 | 20 | special | | 3 | 15 | holiday | | 4 | 45 | special | +----+-------+------------+ select d.`name` z_dealer d left join z_order o on (d.promo_code = o.promo_code) o.promo_code null

regex - How to remove all except the first 3 and last of a specific character with sed -

i've looked on place can't find answer. i've used sed before i'm familiar syntax - 1 has me stumped. i want remove except first 3 instances , last instance of specific character. here specific example: input.csv: "first", "some text "quote" blaw blaw", 1 "second", "some more text "another quote" blaw blaw", 3 i want remove quotes (") except first 3 , last 1 looks this: output.csv: "first", "some text quote blaw blaw", 1 "second", "some more text quote blaw blaw", 3 any pointers? thanks. $ sed -r ':a; s/([^"]*"[^"]*"[^"]*")([^"]*)"([^"]*")/\1\2\3/; ta' input.csv "first", "some text quote blaw blaw", 1 "second", "some more text quote blaw blaw", 3 how works the code works looking first 5 quotes. removes fourth. process repeated looping unt...

loops - GPA Calculator in C -

i'm trying code calculate class's average gpa. problem i'm having seem have made mistake in do...while code, because, when run it, loops asking me input gpa, rather asking if want calculate average or not. #include<stdio.h> int main() { float fagpa[30], fsum = 0, favg = 0; int x, y; char cresp = '\0'; printf("\t\tgpa calculator\n"); printf("\nenter 30 gpas calculator.\n"); do{ printf("\nenter gpa: "); scanf("%f", &fagpa[x]); x++; printf("\ncalculate gpa average (y/n)?\n"); scanf("%c", &cresp); } while(x < 30 && cresp != 'y' || x < 30 && cresp != 'y'); for(y = 0; y < (x + 1); y++) fsum += fagpa[y]; favg = (fsum / (y - 1)); printf("\nthe class gpa is:%.2f", favg); return 0; } there 2 issues here. first, need discard new lines on scanf. see h...

Java multidimensional array for android app -

i doing app have many exercises (for working out) each contain 5 different strings. linked workouts arrays of exercises (but more 1 workout can have same exercise , don't want waste memory), , workouts displayed in different categories (weight loss, body building, etc..). if doing in c (which language program in) have exercises array of structure called exercise, workout linked lists each link being pointer exercise, int reps , int sets. , workouts organized in array of pointer pointing first element of linked list (so workout can in multiple categories). there way implement in java? working backwards method in c, why not have like: class exercise { private string exname; private int reps; private int sets; and making constructor: public exercise(string newname, int newreps, int newsets) { exname = newname; reps = newreps; sets = newseats; that's part different c. here, you're doing making exercise object contains necessary information, re...

asp.net - Sitecore - Require login -

Image
so sitecore site trying make user logged in , can not use extranet\annoymous account. have read , tried implementing sitecore extranet login on website but missed something, asp forms authentication has side issues returns original page , ignoring user's option of desktop or page editor. the part frustrated seems logic built sitecore. example if try go http://site/sitecore/shell , not logged in site core redirects me login page. how can turn on entire site. update my security editor looks even if unprotect sitecore object , deny access main object can still site. in web.config sites section looks <sites> <site name="shell" virtualfolder="/sitecore/shell" physicalfolder="/sitecore/shell" rootpath="/sitecore/content" startitem="/home" language="en" database="core" domain="sitecore" loginpage="/sitecore/login" content="master" contentstartitem=...

ruby on rails - Passing Two Parameters on a JSON POST Request in Rspec -

i have json rails 4 api i'm testing rspec. i'm having trouble passing 2 parameters in post :create request. here current test: require 'spec_helper' module api module v1 describe api::v1::productscontroller, type: :controller before @api_app = factorygirl.create(:api_app, request_origin: "0.0.0.0") @store = factorygirl.create(:store) end after(:all) product.all.each {|l| l.destroy} apiapp.all.each {|a| a.destroy} end describe "post 'create' " context "creates product correct parameters" "returns successful response string success message" json = { :format => 'json', product:{first_name:"hello", last_name:"you", email:"email@email.edu",street1:"103 abc street", city:"pittsburgh", phone:"4125361111", store_id:@store.i...

spring boot basic http authentication with multiple roles throws 403 forbidden error -

i trying configure spring boot-embedded tomcat basic http authentication multiple roles, of url's similar few of them specific each role. here first role basic http authentication pops , working fine. below code, @configuration @enablewebmvcsecurity @enableglobalmethodsecurity(prepostenabled = true) public class testsecurityadapter extends websecurityconfigureradapter { @override protected void configure(httpsecurity http) throws exception { http.csrf().disable() .authorizerequests().antmatchers(null, getappadminrolepaths()).authenticated() .anyrequest().hasanyrole("appadmin") .and() .httpbasic(); http.csrf().disable() .authorizerequests().antmatchers(null, getappuserrolepaths()).authenticated() .anyrequest().hasanyrole("appuser") .and() .httpbasic(); http.authorizerequests().antmatc...

Python: Why isn't this working? -

i making game , board 2d array, have procedure print maze , each time prints it should show 'x' player standing. problem keeps 'x' player standing: -1 x -1 -1 -1 2 3 -1 -1 -1 4 5 -1 6 7 -1 9 8 -1 b -1 -1 -1 c d -1 -1 -1 e f -1 1 -1 h g 2 x -1 -1 -1 x 3 -1 -1 -1 4 5 -1 6 7 -1 9 8 -1 b -1 -1 -1 c d -1 -1 -1 e f -1 1 -1 h g there 2 'x's when there should 1 don't know why. def printmaze(maze, x, y): oldroom = maze[y][x] u = x - 1 v = y - 1 maze[v][u] = oldroom maze[y][x] = 'x' in range(9): z in range(4): print str(maze[i][z]).rjust(2), print '' if x , y coordinates of player, first thing set oldroom equal player is. isn't x currently? instead of shuffling around values in maze array, why not check if current location you're printing player is, , print x instead? def printmaze(maze, x, y): in range(9): z in range(4): ...

javascript - Pointing package.json to a specific React commit installs react-tools (not react) -

when add line package.json: "react": "git://github.com/facebook/react.git#08e4420019f74b7c93e64f59c443970359102530" ...and run npm install , find node_modules/react-tools installed when expect see node_modules/react . what doing wrong here? the code @ git://github.com/facebook/react.git not same code gets installed when npm install react . instead, code contains series of build steps used build npm package. far know, there not way use specific sha of react repo npm package; need clone repo, build project, , copy somewhere can require it.

regex - In PHP, what is the most efficient way to match a string against a list of keywords? -

i have list of keywords, , need check whether of these occurs in string. e.g.: /* keywords */ rock paper scissors /* strings */ "this town rocks!" /* match */ "paper patient" /* match */ "hello, world!" /* no match */ i put keywords in array, loop through , preg_match() or substr() on each iteration, seems bit cpu-expensive. i've mucked aroud regexps bit, without success. what efficient way (in terms of lean code , low cpu loads) this? note comparison must case-insensitive. a regex alternatives ensure string scanned once, rather n times n keywords. pcre library optimized. preg_match('/rock|paper|scissors/i', $string); it gets faster if keywords have common prefixes , take advantage of (essentially building trie , inlining it): preg_match('/rock|paper|sci(?:ssors|ence)/i', $string); and there's preg_grep($regex, $array_of_strings); that match against array of strings , return ones match. ...

Justify more than one item inside a td in different directions, HTML, CSS -

i want left-justify 1 item, , right-justify other item inside single td. doable? thanks. test.php <table border = '1'> <tr><td>left-justified right-justified</td></tr> <tr><td>texttexttexttexttexttexttext</td></tr> </table> try this... <table border = '1'> <tr> <td> <span >left-justified</span> <span style="float:right;"> right-justified</span> </td> </tr> <tr> <td> texttexttexttexttexttexttext </td> </tr> </table>

c# - Can DataGridViewCheckBoxCell accept CheckState.Indeterminate programatically, but not via clicking? -

i have followowing datagridviewcheckboxcell part of datagridview : datagridviewcheckboxcell cell = new datagridviewcheckboxcell(true) {value = checkstate.unchecked}; grdrow.cells.add(cell); grdrow.tag = key; grdfilter.rows.add(grdrow); later on, update state based on whether other check boxes checked. var numchecked = cells.count(c => c.value.equals(true)); cbcell.value = (numchecked == cells.count) ? checkstate.checked : (numchecked == 0 ? checkstate.unchecked : checkstate.indeterminate); this works great. however, if user clicks checkbox, cycles between checked, unchecked, , indeterminate. want cycle between checked , unchecked . if set tristate false on cell, no longer allows me set value checkstate.indeterminate . is there way behavior want? update: i've tried trapping cellvaluechanged event so: void datagridview_cellvaluechanged(object sender, datagridviewcelleventargs e) { var changedcell = grdfilter.rows[e.rowindex].cells[e.columnindex]; ...

mysql - Use PDO's bind param multiple times as variable -

i searching on internet , didnt find solution. lets want use 1 paramerer in pdo multiple times. select * `users` inner join `user_names` on `users`.`id`=`user_names`.`id` `user_names`.`name` concat('%', ? ,'%') or `users`.`name` concat('%', ? ,'%') how can avoid use ? 2 times ? looking this: select ? `search_name`, * `users` inner join `user_names` on `users`.`id`=`user_names`.`id` `user_names`.`name` concat('%', `search_name` ,'%') or `users`.`name` concat('%', `search_name` ,'%') thank you you can join subselect contains parameter value or (like below) complete search string. select * `users` inner join `user_names` on `users`.`id`=`user_names`.`id` cross join (select concat('%', x.name, '%') searchstring) x `user_names`.`name` x.searchstring or `users`.`name` x.searchstring

c++ - Why is a pointer to NULL-charater not converted to false -

i thought pointer pointed null can converted 0 . wrote following program: #include <iostream> #include <regex> #include <string> #include <cstdlib> bool is_strtoi(const std::string& str) { char *p; std::strtol(str.c_str(), &p, 10); return *p == '\0'; } bool is_strtoi1(const std::string& str) { char *p; std::strtol(str.c_str(), &p, 10); return p; //pointer null should converted false; } int main () { std::string test1("123asd2"); std::string test2("123123"); std::cout << is_strtoi1(test1) << std::endl; std::cout << is_strtoi1(test2) << std::endl; std::cout << "---" << std::endl; std::cout << is_strtoi(test1) << std::endl; //prints 1 std::cout << is_strtoi(test2) << std::endl; } accroding 4.12 section of standard: a 0 value, null pointer value, or null member pointer value converted...

google maps api 3 - Page reloads if a second textSearch performed -

i use google maps javascript api embed map following code: var loc = new google.maps.latlng(geolocation.latitude, geolocation.longitude); var mapoptions = { zoom: 13, center: loc }; var maprequest = { location: loc, types: ["car_repair"], radius: 5000, query: "midas" }; var map = new google.maps.map(document.getelementbyid(mapid), mapoptions); var infowindow = new google.maps.infowindow(); var service = new google.maps.places.placesservice(map); service.textsearch(maprequest, getmapcallback); map loads expected , life wonderful. i want user able change query parameter , run search within same map. maprequest.query = "honda"; service.textsearch(maprequest, getmapcallback); when run code in chrome console, new search runs expected. however, when execute code above on button click, page reloads. can please explain inconsistency? thanks in advance time! your button click submitting form causing page reload...

c# - Checking if a DateTime value is more than N days old -

i have procedure meant delete items in t-sql database more specified number of days old. starts out like [httppost] public actionresult flushlinks (string numdaysold) { // deletes database references links submitted on numdaysold days ago datetime currentdatetime = datetime.now; foreach (linkdate thislinkdate in pd.dates) { timespan thistimespan = new timespan(convert.toint16(numdaysold), 0, 0, 0); if ((currentdatetime - thislinkdate.dtime) > thistimespan) { foreach (assetlink thislink in pd.links) if (thislink.linkguid == thislinkdate.linkguid) pd.links.deleteonsubmit(thislink); but reason isn't working because when called numdaysold=30 deleted including items recent stamps ( 2015-06-18 16:36:00 , 2015-06-18 16:10:00 , etc., of type smalldatetime in database) is there wrong procedure? why don't compare dates using datetime.adddays() function, since it's ...

javascript - jquery if more than 4 images add tag to div -

so bad jquery , need code. doing carousel , there going 4 images , want static (disable carousel, remove html tag or smth.) if resolution >1000px enable carousel. if there 5 image enable it. sorry bad english, :) http://www.w3schools.com/js/js_if_else.asp the attr() jquery should allow test size of >= , trying do. http://api.jquery.com/attr/

css - :hover over <div> does not apply to all its child elements -

i using angularjsjs create list ng-repeat directive. list contains 3 divs inside itself, layed out using floats. idea change background color of entire div whenever user moves mouse inside div's area. below code using: html <div class="concert-item" ng-repeat="(key, concert) in value"> <div class="selfie item-float-left"> <img alt src="[[[concert.author.selfie]]]" class="img-circle"/> </div> <div class="item-float-left"> <p class="event-header">[[[concert.author.displayname]]]</p> <p>[[[concert.venue]]]</p> <p>[[[concert.dateinms | timefiltershort]]] @ [[[concert.begintimeshort]]]</p> </div> <div class="item-float-right"> <a href="https://maps.google.com/?q=[[[concert.street]]],[[[concert.zi...

sql - Split string and number columns -

let's have table such as itemid classid ------------------------ 1 10, 13, 12 2 5, 7 and copy data table so itemid numbering classid ---------------------------------- 1 1 10 1 2 13 1 3 12 2 1 5 2 2 7 separating comma-delimited classid field individual rows, retaining order had in first table populating numbering row on insert. numbering column has sequential integers each batch of classid , why classid needs kept in order. i have attempted following function: create function dbo.split ( @string nvarchar(max) ) returns @splittedvalues table( value int ) begin declare @splitlength int declare @delimiter varchar(10) set @delimiter = ',' while len(@string) > 0 begin select @splitlength = (case charindex(@delimiter, @string) when 0 datalen...