Posts

Showing posts from July, 2012

swift - Access String value in enum without using rawValue -

i replace global string constants nested enum keys i'm using access columns in database. the structure follows: enum databasekeys { enum user: string { case table = "user" case username = "username" ... } ... } each table in database inner enum, name of table being enum's title. first case in each enum name of table, , following cases columns in table. to use this, it's pretty simple: myuser[databasekeys.user.username.rawvalue] = "johnny" but using these enums a lot . having append .rawvalue every instance pain, , it's not readable i'd be. how can access string value without having use rawvalue ? it'd great if can this: myuser[databasekeys.user.username] = "johnny" note i'm using swift 2. if there's better way accomplish i'd love hear it! while didn't find way using desired syntax enums, possible using structs. struct databasekeys {

javascript - Updating input value [HTML/JS] -

i have got problem updating values in input filed [html]. possible update them on change? tried way (i used code found on site): <input type="text" id='user' value='user' onchange="updateinput(this.value)"><br> <script> var cc2 = document.getelementbyid("user").value; function updateinput(ish){ document.getelementbyid("user").value = ish; } </script> <a href="#" onclick="alert(cc2)">test</a> after pressing "test" link still receiving alert value: "user" no matter put in input. please update updateinput following code function updateinput(ish){ cc2=ish; } this assign value of input cc2 var. on each change in input make cc2 holds latest value.

c - Flag SDL_HWPALETTE not recognized by gcc -

the flag sdl_hwpalette being marked undeclared in gcc, though sdl included (many sdl functions , such being used fine). need include other sdl.h use sdl_hwpalette ? i checked out docs sdl_setvideomode , function uses flag, , nothing declaring or additional includes mentioned sdl_hwpalette mentioned, , i'm didn't typo. code snipet : #include "sdl2/sdl.h" screen = sdl_setvideomode(640, 480, 0, sdl_hwpalette); error output : in function 'init': error: 'sdl_hwpalette' undeclared if using sdl2, sdl_setvideomode removed , enum. more info here: https://forums.libsdl.org/viewtopic.php?t=9163&sid=23359eedacf25591f8fe7c3423342de4 in sdl 2 need create window , renderer. check out headers and/or docs. regards, leszek

java - Why does HashMap.get(key) needs to be synchronized when change operations are synchronized? -

i use .get(...) , .put(...) , .clear() operations multiple threads on 1 hashmap. .put(...) , .clear() inside synchronized block .get(...) not. can't imagine cause problems in other code i've seen .get() pretty synchronized. relevant code get/put object value = map.get(key); if(value == null) { synchronized (map) { value = map.get(key); // check again, might have been changed in between if(value == null) { map.put(key, new value(...)); } } } and clear just: synchronized (map) { map.clear(); } the write operations invalidate caches because of synchronized , get(...) returns either null or instance. can't see go wrong or improve putting .get(...) operation synchronized(map) block. here 1 simple scenario produce problem on unsynchronized get : thread starts get , computes hash bucket number, , gets pre-empted thread b calls clear() , smaller array of buckets gets allocated thread wakes up, , may run index-out-of-boun

php - File input returning null value in Laravel 4.2 -

i have file input element on laravel , returning null value. have tried var_dump , dd() see values returned on form post , returns null. have read similar questions , tried apply several of suggested solutions problem yet have had no luck finding solution. i have checked max upload size wamp server , file size of images trying upload in kilobytes , no close 1mb. what doing wrong? this view <div class="container"> <a href=""> edit page </a> {{ form::open( array('route' => 'postsitetest', 'files' => true)) }} {{form::file('testlink')}} {{ form::token() }} <input type="submit" value="save changes" class="btn btn-primary btn-lg"> {{ form::close() }} </div> and controller public function postsitetest() { $file = input::file('testlink'); var_dump($file); $test = new facilitiespg(); $fi

Accept Trade Offer from Steam using Web-API & Java -

i have java steam trade bot reads through pending trade offers steam , declines them based on requirements. using official web api (using api key http://steamcommunity.com/dev/apikey ) communicate requests steam. variable trade own api interface (which have debugged , works declining offers). steamplug.steamrequest(method, query); basic http requester: public static string steamrequest(string method, string query) { try { url obj = new url(query); httpurlconnection con = (httpurlconnection) obj.openconnection(); con.setrequestmethod(method); int responsecode = con.getresponsecode(); if (responsecode != 200 && responsecode != 201) { return "err" + responsecode; } bufferedreader in = new bufferedreader( new inputstreamreader(con.getinputstream())); string inputline; stringbuilder response = new stringbuilder(); while ((inputline = in.readline())

ruby on rails - Restrict Index View to User's Records -

i'm working on ruby project , running roadblock. it's simple thing, keep running errors i'm turning help. i need restrict view records created particular user. in case, supplier's orders. here's current index controller (using will_paginate gem limit 30 per page): class orderscontroller < applicationcontroller before_action :set_order, only: [:show, :edit, :update, :destroy] before_filter :authenticate_supplier! def index @orders = order.all.order("created_at desc").paginate(:page => params[:page], :per_page => 30) end right now, orders show rather desired - orders put in particular supplier should show in index. attempted use along these lines, no luck: def index @orders = order.current_supplier.order("created_at desc").paginate(:page => params[:page], :per_page => 30) end using devise suppliers. devise used authentication, need authorization, recommend having on gem specific purpose, such

c# - Create a custom user collection of collections -

i need create generic collection of generic collections, should contain generic class. i've tried hard, haven't found answers.this how realizated collection looks like: https://github.com/infatum/pmc-data-model/blob/master/wtf/position.cs collection of position of generic class point. need create indexed collection of positions called matrix, indexed collection of matrix called container , indexed collection of containers, named containers. please, me! public class matrix<t> : icollection<t> t : position<t> { protected arraylist matrix; protected bool isreadonly; public matrix() { matrix = new arraylist(); } // ... } the trouble : type 't' cannot used type parameter 't' in generic type or method 'position'. there no implicit reference conversion 't' 'wtf.point' this task, given me: https://docs.google.com/document/d/1zyxxajrh0oynluufy0ht6zuazisiece73cga4qordlc/edit#heading=h.nwbuq

jquery - javascript load css but keep current style -

i have following code run after page loads: function prepare_bootstrap() { console.log("preparing bootstrap..."); var items = document.body.getelementsbytagname("*"); (var = items.length; i--;) { items[i].style.csstext = '!important'; } var style1 = document.createelement("link"); style1.rel = "stylesheet"; style1.href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"; document.body.appendchild(style1); var style2 = document.createelement("link"); style2.rel = "stylesheet"; style2.href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"; document.body.appendchild(style2); var script = document.createelement("script"); script.src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"; script.onload = script.onreadystatechange = func

Gnuplot plot specific lines from data file -

i have data file 24 lines , 3 columns. how can plot data specific lines, e.g. 3,7,9,14,18,21? use following command plot 'xy.dat' using 0:2:3:xticlabels(1) boxerrorbars ls 2 which plots 24 lines. i tried every command couldn't figure out way works. untested, this plot "<(sed -n -e 3p -e 7p -e 9p xy.dat)" using ... another option may annotate datafile, if seems, contains multiple datasets. let's created datafile this: 1 2 3 2 1 3 # seta 2 7 3 # setb 2 2 1 # seta setb setc then if wanted seta use sed command in plot statement sed -ne '/seta/s/#.*//p' xy.dat 2 1 3 2 2 1 that says... "in general, don't print ( -n ), but, if see line containing seta , delete hash sign , after , print line" . or if wanted setb , use sed -ne '/setb/s/#.*//p' xy.dat 2 7 3 2 2 1 or if wanted whole data file, stripped of our comments sed -e 's/#.*//' xy.dat if wanted setb , setc , use sed -ne '/

rxjs - BehaviorSubject 'grouped' -

i'm getting started rxjs see if can replace manual data streams. 1 thing i'm trying port situation whereby last value in stream remembered, future observers 'current' value subsequent ones. seems fulfilled behaviorsubject. however, need group of entities. example, might have data represents message user: { userid: 1, message: "hello!" } and want behaviorsubject-like object that'll store last message users. can rxjs out-of-the-box, or need myself? (if so, pointers appreciated). edit: after more thought, perhaps seems logical having 'incoming' subject, observer updates map, , function can call initialises observable map values, , merges incoming stream...? i use rxjs redux-like state setup. have behaviorsubject holds current state, , every time event/action fired current state gets passed through functions produce new state, subject subscribed to. here's simplified version of use: export default class flux { constructo

android - Kivy Language Dynamic Checkbox List -

i want dyanmically add checkboxes in kivy languages. know how achieve in python unaware how in kivy language. there should checkbox each file in below list: kivy.uix.filechooser import filesystemlocal file_system = filesystemlocal() file_list=file_system.listdir(app.get_running_app().user_data_dir+'\\') # returns list of files in dir file_list=[x x in file_list if x[-4:]=='.csv'] how can loop kivy? assuming there should loop on right side, since python code. have no clue how? starters can helpful. edit : class mergescreen(screen): result_label='' check_boxes={} def __init__(self,**kwargs): self.name='mergescreen' super(mergescreen, self).__init__(**kwargs) b=boxlayout(orientation='vertical') file_system = filesystemlocal() file_list=file_system.listdir(app.get_running_app().user_data_dir+'\\') # returns list of files in dir file_list=[x x in file_list if x[-4:

python - Doesn't NumPy/SciPy have complex numbers of "int" type? -

i writing numpy/scipy routines processing spectra, consist of complex numbers. according found following website, seems complex number formats floating-point formats. http://docs.scipy.org/doc/numpy/user/basics.types.html however, i'd make routine can handle spectra in fixed-point format. are there easy ways this?

parsing - Get Attribute Value PHP -

this source code getting remote source <div class=hello> <a class="abc" href="http://www.example.com" a1="page1" a2="wel-come" data-image="example.com/1.jpeg"> <div>you here</div> . . . <a class="abc" href="http://www.example.com" a1="page2" a2="aboutus" data-image="example.com/2.jpeg"> </div> i using php dom parser parsing html need output page1 http://www.example.com <img src="example.com/1.jpeg"> page2 http://www.example.com <img src="example.com/2.jpeg"> foreach($html->find('a') $element) { echo $element->a1; echo $element->image; echo "<img src='" . $element->image . "'/>"; } should work? if direct access ->a1 , ->image not work, attempt: $element->getattribute('a1') $element->getattribute('im

How to stop a Javascript Timer after the second countdown? -

i trying create pomodoro clock (a countdown timer 25-minutes of productivity , 5-minute countdown of break time), , having trouble stopping break time countdown. here's javascript have far: function starttimer(duration, display) { var timer = duration, minutes, seconds; var countdown = setinterval(function () { minutes = parseint(timer / 60, 10) seconds = parseint(timer % 60, 10); seconds = seconds < 10 ? "0" + seconds : seconds; display.textcontent = minutes + ":" + seconds; if (--timer < 0) { clearinterval(countdown); var breakclock = function() { $("#title").text(function(i, text){ return text === 'breaktime' ? 'productive countdown' : 'breaktime' }); var fiveminutes = 60 * .05, display = document.queryselector('#time'); starttimer(fiveminutes, displ

python - Baffling panda panel behavior -

after running import numpy np randn = np.random.randn pandas import * the following code creates panel: ## create pseudo panel data ## numindivs = 2 # number of individuals numwaves = 5 # number of time periods (waves) # create panel object wp = panel(np.random.randint(12, size=(numindivs, numwaves, 4)), minor_axis=['background', 'lnh', 'f', 't']) # generate random fixed background variable each indiv: n(2,1) wp.ix[:,:,'background'] = np.tile(randn(numindivs)+2,(numwaves,1)) # generate lnf , lnt wp.ix[:,:,'lnf'] = np.log(wp[:,:,'f']+1) wp.ix[:,:,'lnt'] = np.log(wp[:,:,'t']+1) yet, following code, identical except changing contents of 'background' column in penultimate section, generates error ("valueerror: not broadcast input array shape (2) shape (5)"): ## create pseudo panel data ## numindivs = 2 # number of individuals numwaves = 5 # number of time periods (waves) # create pa

ios - Parse push notification: How to use custom payload -

i'm using following json send push notification in parse. { "alert": "push title goes here", "sound": "", "url": "emap://video/4000" } the url emap://video/4000 points specific video inside app if type in safari , hit enter. want user sent video when clicks on notification. why doesn't above json achieve this? so sending payload : nsdictionary *data = @{ @"alert" : @"some generic message here", @"badge" : @"increment", @"sound" : @"default", @"url" : @"emap://video/4000" }; and when user interacts act accordingly : - (void)application:(uiapplication *)application didreceiveremotenotification:(nsdictionary *)userinfo { if (application.applicationstate == uiapplicationstateinactive) { [self handleremotenotificationwithpayload:userinfo]; } } -(void)handleremotenotificationwithpa

tableau - Aggregate by most recent not-null value -

i have dataset following columns [ product_id, country_id, date, number_of_installs, cumulative_installs_last_30_days ] i have no problem applying standard measures find sum, max or average number_of_installs within 3 dimensions (product_id, country_id, date(aggregated month or week)). however, have not been able aggregate cumulative_installs_last_30_days because variable cumulative, need return “most recent value” , tableau not have option built-in aggregation functions. how create calculated field enables addicional column in aggregated dataset recent not-null value of cumulativeinstalls_last_30_days within dimensions product_id, country_id , date(aggregated month or week)? here's dirty solution. in comments, noted wanted 30 days dynamic, accomplish that, create parameter, make integer, select range, , allow integer on zero. i'll call [number of days] . then create calculated field: total(sum(iif(datediff("day", [date], today()) < [number o

java - Find version number of certain plugins in Eclipse -

more need write code can find eclipse version number (4.7.0). can't in file (.eclipseproduct or about.mappings) , need make api call. so wondering whether i'll able find out version number of plugin org.eclipse.platform java program. i guess simplest way system properties, assuming you're within eclipse runtime-workbench. system.getproperty("eclipse.buildid") if you're not within eclipse context there's either installation files ".eclipseproduct" or through debugger.

ios - Submitting app to iTunes connect in a team -

i created bundle id in team's section, not showing in itunes connect. can not team-related actions in itunes connect? team account need create app in itunes connect? edit: found team's account needs add me itunes connect "users , roles". reason issue? according documentation, need either technical or admin role able create app record. documentation if not either, have admin reassign role technical.

debugging - Breakpoints not working with a service in Android -

i'm trying debug service i'm unable since breakpoints not work. yes, have used android.os.debug.waitfordebugger(), doesn't matter use (before line, in onstartcommand, in method) doesn't work. have breakpoints set, service not stop @ them. have tried them on normal activity, work fine there. in androidmanifest.xml add property android:process=":sync" service entry: <service android:name=".syncservice" android:exported="true" android:process=":sync" > <intent-filter> <action android:name="android.content.syncadapter"/> </intent-filter> <meta-data android:name="android.content.syncadapter" android:resource="@xml/syncadapter"/> </service> after start application in debug mode , when it's loaded click "attach process" button. in list should see 2 processes:

html - How to apply CSS to iframe? -

i have simple page has iframe sections (to display rss links). how can apply same css format main page page displayed in iframe? edit: not work cross domain unless appropriate cors header set. there 2 different things here: style of iframe block , style of page embedded in iframe. can set style of iframe block usual way: <iframe name='iframe1' id="iframe1" src="empty.htm" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe> the style of page embedded in iframe must either set including in child page: <link type="text/css" rel="stylesheet" href="style/simple.css" /> or can loaded parent page javascript: var csslink = document.createelement("link"); csslink.href = "style.css"; csslink.rel = "stylesheet"; csslink.type = "text/css"; fra

go - golang: cmd.Exec(): How I can read non-buffered stdout of apps? -

so have simple app starts other apps , reads output. package main import ( "bufio" "io" "log" "os/exec" "time" ) func main() { cmd := exec.command("perl", "-e", "my $x = 0; while (1) { print ++$x.qx'date'; sleep 1; }") stdout, _ := cmd.stdoutpipe() stderr, _ := cmd.stderrpipe() in := bufio.newreadersize(io.multireader(stdout, stderr), 100) cmd.start() defer cmd.wait() { log.printf("....") time.sleep(1 * time.second) l, _ := in.readstring('\n') log.printf(string(l)) } } the point of real app read output of running process , parse it.. doesn't works real apps don't explicitly sync/flush stdout (it takes ~60 lines of iperf output before starting printing). what efficient way read output byte-by-byte?

python - Summing all rows above the current row based on the values -

Image
i new python , stackoverflow please forgive me if question ask has been answered in previous thread. i working python data frame similar 1 below. wish have "build balance" each client sum of balances particular row. example cell d6 in attached image sum of balances john account appearing between row 2 , row 6. in advance. keep simple. keep simple? want begin? if new python say, use pandas working data frames. following sum column want , assign variable sum_column = df['column_name'].sum()

xslt - Spaces in output -

i trying transform xml document document comma dlimited string. however, when transform see lot of spaces. i not sure causing , should fix issue - xml file input <file> <row> <wid>wid0001</wid> <xtn>leave record</xtn> <status>in process</status> <eid>e001</eid> <amt>5000</amt> </row> <row> <wid>wid0003</wid> <xtn>leave record</xtn> <status>in process</status> <eid>e005</eid> <amt>3000</amt> </row> <row> <wid>wid0010</wid> <xtn>leave record</xtn> <status>in process</status> <eid>e010</eid> <amt>7000</amt> </row> <row> <wid>wid0007</wid> <xtn>leave record</xtn> <status>in process</status> <eid>e010</eid> <amt>0000

c - How does the user-mode kernel in UML interface with the underlying kernel on the host -

in user mode linux (uml) trace thread annuls system calls made user-space process , redirects them kernel running in user-space. @ point userspace kernel require assistance of host os. how user-mode kernel call underlying host kernel, normal system calls? or use kind of ioctl mechanism or else? i found simple explanation of uml design here . may useful you. uml constructs using ptrace system call tracing mechanism. when process in user space, system called intercepted ptrace. when in kernel, no interception. when process executes system call or receives signal, tracing thread forces process run in kernel. after transition, process state restored , continues. system call virtualization by switching user , kernel , system calls interception note: system call must annulled in host kernel. the process state preserved. when system call complete, process obtains returned value in saved registers , returned user mode. also, a

javascript - Change through list of photos in tab html -

hi i'm trying code html css , javascript website , i'm not used these language. i have "tabs" created css ul in html, , wanted put pictures in them javascript linked image onclick can change through photos clicked them. here code. script function <script> function changeimage(){ var image = document.getelementbyid('myimage'); if(image.src.match("img/test/image1.jpg")){ image.src = "img/test/image2.jpg"; } else if(image.src.match("img/test/image2.jpg")){ image.src = "img/test/image3.jpg"; } else if(image.src.match("img/test/image3.jpg")){ image.src = "img/test/image4.jpg"; } else if(image.src.match("img/test/image4.jpg")){ image.src = "img/test/image5.jpg"; } else if(image.src.match("img/test/image5.jpg")){ image.

HTTP Post using Apache http client with expect-continue option to an authorized http proxy, and get 400 response -

i using apache http client v4.5 http post authorized required http proxy server. because of other dependencies, tend use enabled expect-continue handshake in http client config. related code snips: credentialsprovider credsprovider = new basiccredentialsprovider(); credsprovider.setcredentials( new authscope(host, port, authscope.any_realm), new usernamepasswordcredentials(username, password)); credsprovider.setcredentials( new authscope(proxyhost, proxyport,authscope.any_realm), new usernamepasswordcredentials(proxyusername, proxypassword)); closeablehttpclient httpclient = httpclients.custom() .setdefaultcredentialsprovider(credsprovider).build(); try { httphost target = new httphost(host, port, "http"); httphost proxy = new httphost(proxyhost, proxyport); requestconfig config = requestconfig.custom() .setproxy(proxy)

r - Keeping specific column data while aggregating and summing other columns -

i new r, , using medium-sized retail store's transactional data practice. i'd create data frame has each customer's percentage of purchases in different categories of products, sum of total purchases. way, can send marketing emails people demonstrated preference in given category, exclude people have purchased less 5 times. sample data (except 100 categories in reality , 250,000 rows): +-------------+-------------+--------------------+------+------+------+ | transaction | customer_id | email | cat1 | cat2 | cat3 | +-------------+-------------+--------------------+------+------+------+ | 55 | 1 | email@address.com | 1 | 0 | 0 | | 55 | 1 | email@address.com | 1 | 0 | 0 | | 56 | 2 | email2@address.com | 0 | 0 | 2 | | 57 | 3 | email3@address.com | 3 | 0 | 0 | +-------------+-------------+--------------------+------+------+------+ step 1: aggre

security - aws ec2 instances in different vpc subnets access each other -

i have 2 aws ec2 instances living inside 2 different subnets of vpc. i allow ruby app running on first instance (say app#1 ) call endpoints of app (say app#2 ) running on 2nd instance. i users directly call endpoints of app#2 browser. here have tried (and failed): [sucess!] added known ip addresses of users inbound rules of load balancer security group of app#2 , have confirmed can access app#2 endpoints browsers. [fail!] added load balancer security group id of app#1 inbound rules load balancer security group of app#2 . logs tell me app#1 cannot access endpoints of app#2 . [fail!] added vpc security group id of app#1 inbound rules of load balancer security group of app#2 - nope, still doesn't work. (somehow, when launched instance app#1 , aws automatically created 2 security groups instance - 1 vpc , 1 load balancer... have no idea why/how happened...) [fail!] added cidr subnet app#1 in inbound rules of load balancer security group of app#2 . still

javascript - How to force to open link in Safari from WebApp in iOS? -

there link <a href="http://www.google.com">google</a> inside web page of uiwebview in app.how can force link opened safari when it's clicked?i've tried target="_blank" suggested, not work.does know that? and how <form> , how can make redirect safari when it's submitted? it's better approach through javascript , not javascript objective-c interaction . you can try following : <a href="#" onclick="window.open('http://www.google.com', '_system');">google</a> this works in phonegap.

ios - How do I fix the illegal configuration? -

i have .xib file , want table view controller, when create table view controller in .xib file error table views embedded sections , cells supported in storyboard documents . how fix this. below code actual table view. self.add = [play(name: title!), play(name: artist!), play(name: album!)] override func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int { return self.add.count //return count of objects in array } override func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cell = self.tableview.dequeuereusablecellwithidentifier("cell", forindexpath: indexpath) as! uitableviewcell var play: play play = add[indexpath.row] cell.textlabel?.text = play.name return cell } xibs sort of out dated, , when invented, didnt have prototype cells make in ui builder. when storyboards introduced functionality made well, except not ported xib editor, cant us

installation - MySQL installer console is executed in Commercial mode -

Image
i have install mysql server community edition version 5.6.x silent installation. planned use mysql-installer-community-5.6.26.0.msi msiexec /i /quiet command , run mysqlinstallerconsole.exe install , configure server silently. i found problem mysql installer while installing, it's running in commercial mode after installation. tried reinstall again in many times via same procedure results not different. how can force installer run in community mode? it runs in commercial mode if "mysql installer - community" application has never been launched. running command "community" prefacing "install" should work. mysqlinstallerconsole.exe community install server;5.6.24;x86:*:port=3306;rootpasswd=password;servicename=mysql -silent

ringcentral - Whether require and use are similiar in php? -

use ringcentral\sdk; or require('/home/developer/workspace/ringcentral/demo/sdk.php'); instead of using 'use' - php 5.6 command ,it better use require - php 5.3 ? sdk class file contains following code class sdk { const version = '0.5.0'; /** @var platform */ protected $platform; /** @var context */ protected $context; public function __construct($appkey, $appsecret, $server) { $this->context = new context(); $this->platform = new platform($this->context, $appkey, $appsecret, $server); } public function getplatform() { return $this->platform; } public function getsubscription() { return new subscription($this->context, $this->platform); } public function getcontext() { return $this->context; } } you have require autoloader allow spl autoload resolve use statements: // if use composer require('vendor/autoload.php'); // or require phar require('path-to-sdk/ringcentral.phar&#

php - Magento --> Want to display the list of product in grid with pagination and search bar in frontend -

i want display list of vendor product in grid view pagination , search bar. have searched in google didnt clear solution that. can help? refer mage/catalog/block/product/list.php file collection , phtml file pls refer catalog/product/list.php file you can stuff display product @ frontend may helpful you. and create cms page {{ block type="your block type" template="your phtml file" }}

Yii2 adminpanel authorization -

i want project`s program should this: have divided admin 2 groups mainadmin secondadmin 1) there mainadmin , number of secondadmins. main admin can create, edit secondadmins , while creating , editing, mainadmin should able create passwords , usernames secondadmins. 2) when secondadmins login should see page.with page secondadmins can create child admins , give them own usernames , passwords. see yii2 roles build own way restrict access , access control class you can that: public function behaviors() { return [ 'access' => [ 'class' => accesscontrol::classname(), 'rules' => [ [ 'allow' => true, 'actions' => ['login', 'mainpage'], 'roles' => ['secondadmin'], ], [ 'allow' => true,

sql server - Which type of user should you create? -

i plan pass exam "querying microsoft sql server 2012". i want proper logical answer , understand more. question is: you use contained database named contosodb withina domain. need create user can log on contosodb database. need ensure can port database different database servers within domain without additional user account configurations. type of user should create? possible answers: a. user mapped certificate b. sql user without login c. domain user d. sql user login source: which type of user should create? the answer c obviously. type of users isn't linked actual sql server instance, in domain, account based on domain user (so b , d invalid, since bound instance). certificates don't have it, make invalid too.

c# - Styling a TreeList cell Exception -

i'm trying style cells in listtree based on value of cell. every time run code following exception, , can't figure out going wrong. an unhandled exception of type 'system.windows.markup.xamlparseexception' occurred in presentationframework.dll c# value checking public class statusstyle : markupextension, ivalueconverter { public style red { get; set; } public style green { get; set; } public style orange { get; set; } public style gray { get; set; } public style blue { get; set; } #region ivalueconverter members public object convert(object value, system.type targettype, object parameter, system.globalization.cultureinfo culture) { if (value.tostring().equals("trade")) { return red; } return null; } public object convertback(object value, system.type targettype,

ios - View Items are not visible in Main.StoryBoard -

Image
this question has answer here: why storyboard ui elements not showing on uiviewcontroller in xcode 6? 4 answers hi first attempt use xcode(6.4). face 1 issue created viewcontoller buttons,label etc. once shutdown pc , start today views empty not showing in main.storyboard. once run in emulator working. attaching here screenshot. and viewcontroller in main.storyboard like i hope blender mistake please me find out. you using size classes in storyboard, if add of controller specific view this after adding view when change view then added controller disabled view. that added controller accessible view only.

debian - -bash: cannot execute binary file on cloned drive -

i cloned sd card of 1 of raspberry pi onto larger sd card. everything went smooth , able expand root partition. system boots nicely , able ssh it. seems behave normally, on previous sd, except few programs. i cannot run lynx nor curl on cloned card... many other programs running fine not these 2 though run smoothly on original card. when run either lynx or curl, get: -bash: /usr/bin/lynx: cannot execute binary file any tips on should try ? fabien

postgresql - How to calculate bandwidth by SQL query -

i have table this: -----------+------------+------- first | last | bytes -----------+------------+------- 1441013602 | 1441013602 | 10 -----------+------------+------- 1441013602 | 1441013603 | 20 -----------+------------+------- 1441013603 | 1441013605 | 30 -----------+------------+------- 1441013610 | 1441013612 | 30 which 'first' column switching time of first packet of traffic flow 'last' column switching time of last packet of traffic flow 'bytes' volume of traffic flow. how can calculate bandwidth usage each second 1441013602 1441013612 ? i want this: 1441013602 20 b/s 1441013603 20 b/s 1441013604 10 b/s 1441013605 10 b/s 1441013606 0 b/s 1441013607 0 b/s 1441013608 0 b/s 1441013609 0 b/s 1441013610 10 b/s 1441013611 10 b/s 1441013612 10 b/s you can use postgresql's generate_series function this. generate series of rows, 1 each second, since that's want. left join on table of info,

d3.js - Link in D3 bar chart -

i creating d3 bar chart using below code . <head> <style> .axis { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispedges; } </style> </head> <script src="http://d3js.org/d3.v3.min.js"></script> <script> var margin = {top: 20, right: 20, bottom: 70, left: 40}, width = 600 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; var x = d3.scale.ordinal().rangeroundbands([0, width], .05); var y = d3.scale.linear().range([height, 0]); var xaxis = d3.svg.axis() .scale(x) .orient("bottom"); var yaxis = d3.svg.axis() .scale(y) .orient("left") .ticks(10); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate

objective c - How to slowly fill the NSProgressIndicator (Progress Bar) from 0 to 100? -

Image
task : take progress bar (nsprogressindicator) 0 100 smoothly. problem : progress bar getting 0 100 not smoothly. what have done yet: // scan click on prgress should start -(void)scannowclick:(id)sender { // setting initial value of progress bar [progressbar setdoublevalue:0]; // starting timer [nstimer scheduledtimerwithtimeinterval:0.5 target:self selector:@selector(callafter10sec:) userinfo:nil repeats:yes]; } // timer update progress bar -(void)callafter10sec:(nstimer *)time { double value = [progressbar doublevalue]+10; [[progressbar animator] setdoublevalue:value]; if(value >= 100) { [time invalidate]; } } /// layer set you should use cadisplaylink , not nstimer when dealing ui related updates. the link called 60 times per se

python - How does the look up time of nested dictionaries increase? -

can comment on how complexity of dictionaries increases "nest" them further? e.g add element follows: dict_name[a][b][c][d] = 0 i think lookup time should same dictionary (constant time o(1)), change if add elements this? dict_name[a][b][c]....[z] python's dictionary implementation doesn't change nesting, no, algorithmic complexity of lookup not change. far python concerned, each [key] subscription independent object subscribing came from. each lookup still o(1). looking nested element depth times o(1) lookup. since hard-coded depth (by using literal notation), have still o(1) constant multiplier doesn't affect big-o complexity.

javascript - Relative position issue -

an element position: relative; positioned relative normal position. setting top, right, bottom, , left properties of relatively-positioned element cause adjusted away normal position. other content not adjusted fit gap left element. here source: css positioning now,how can make relative position work viewport , adjust accordingly setting height,width etc fixed position. possible in css or not? if not how can do? check fiddle try it: div{ position: relative; top: 450px; left: 651px; width: calc(100% - 651px); float: left; } you can use javascript or jquery it.

mysql - How get MAX(id) for each username? -

Image
i have mysql table: how maximum id each username? like above in image, desire rows username 'mostafa' or 'samsung' max id. i testing lot of query, : select max(id) , latitude, longitude 'users_geo' username = 'mostafa' this returns record max id username mostafa. also test query: select id, latitude, longitude `users_geo` username = 'samsung' having max( id ) limit 0 , 30 this query return wrong result. query return row id=9 while max id user 'samsung' 21 . use mysql group by aggregate (group by) functions namely max in case. select username, max(id) users_geo group username;

gunzip - Unzip files in subdirectories bash -

i have directory called test1 contains multiple directories. in each directory test1/*/ , there *.gz file want unzip. tried writing code doesn't work, appreciated. for folder in test1/*/; find . -name "*.gz" | while read filename; gunzip -d $filename;done ;done gunzip test1/*/*.gz gunzip extract file in directory in.

ruby on rails - how to use the context in the tests? -

please write tests context. model album: class album < activerecord::base validates :title, presence: true, length: { maximum: 50, minimum: 3 }, uniqueness: { case_sensitive: false } validates :description, presence: true, length: { maximum: 600, minimum: 10 } end i wrote tests model album: describe album "has valid factory" expect(factorygirl.create(:album)).to be_valid end "is invalid without title" expect(factorygirl.build(:album, title: nil)).not_to be_valid end "is invalid duplicate title" factorygirl.create(:album, title: 'qwerty') expect(factorygirl.build(:album, title: 'qwerty')).not_to be_valid end "is valid different title" factorygirl.create(:album, title: 'zxcvbn') expect(factorygirl.build(:album, title: 'asdfgh')).to be_valid end end these tests worked ok. need use context: describe album "has valid factory"

creating ROC curve with Sensitivity and 1- specificity in R -

i have created 2x2 contingency table.the contingency table created through following process: plus <- ua.mask + vm.c.m.s; minus <-ua.mask - vm.c.m.s; here, ua.mask , vm.c.m.s raster layers(can considered matrix) cells given values 0 (for non urban areas) , 1(for urban).ua.mask reference map , vm.c.m.s map accuracy want check. m <- matrix(0, nrow=2, ncol=2) m[1,1] <- length(which(plus[]==2)) m[1,2] <- length(which(minus[]==-1)) m[2,1] <- length(which(minus[]==1)) m[2,2] <- length(which(plus[]==0)) so, when add , subtract these raster layers cells have values of 1,-1,0 , 2. means, have 4 possible outcomes 2 =tp, -1 = fp, 1=tp, 0 =tn. at, end 2x2 contingency table looks this: [,1] [,2] [1,] 2 -1 [2,] 1 0 then, calculated sensitivity (tpr) , 1-specificity(fpr). now, plot pairs of sensitivity , 1-specificity create roc curve (sensitivity vs. 1-specificity) cities, can't figure out how this. i went th

javascript - Ext.EventManager is deprecated in ExtJS 5 -

in extjs 5 i'm getting console warning saying [w] ext.eventmanager deprecated. use ext.dom.element#addlistener attach event listener. i using code statement bellow, ext.eventmanager.on(window, 'beforeunload', function() { //code here }); i understand ext.eventmanager deprecated how should replace code statement work in extjs 5 ? use getwin() method , append event handler using on . ext.getwin().on('beforeunload',function(){ //code here }); other possible option use pure javascript. window.onbeforeunload = function(){ //code here };

javascript - Grunt wiredep not injecting font-awesome -

i'm working on project had been started using yeoman . for reason, when run grunt-wiredep dependencies correclty injected in index.html except font-awesome . here's bower.json file: { "name": "watermelon", "version": "0.0.0", "dependencies": { "angular": "^1.3.0", "angular-animate": "^1.3.0", "angular-bootstrap": "~0.13.3", "angular-cookies": "^1.3.0", "angular-google-maps-native": "~2.0.0", "angular-mocks": "~1.3.0", "angular-resource": "^1.3.0", "angular-route": "^1.3.0", "angular-sanitize": "^1.3.0", "angular-scenario": "~1.3.0", "angular-touch": "^1.3.0", "angular-ui-router": "~0.2.15", "bootstrap": "^3.2