Posts

Showing posts from September, 2014

c# - Linq query with grouping to fetch youngest date -

Image
my case, see below image: i designed query , added grouping grouping not reduce records youngest contractenddate. appears have no effect on result. public iqueryable<soonobsoletecontractsviewmodel> get() { var countries = unitofwork.getall<country>(); var companies = unitofwork.getall<company>(); var contracts = unitofwork.getall<contract>(); var query = country in countries join company in companies on country.id equals company.countryid join contract in contracts on company.id equals contract.companyid select new soonobsoletecontractsviewmodel { countryname = contry.name, companyname = company.name, companyid = company.companyid contractbegindate = contract.begin, contractenddate = contract.end, contractid = contract.id }; query.groupby(c => c.companyid, (key, e) => e.order

user defined functions - Return Row Type In Presto Udf -

i want implement udf returns me row. i searched on net, there no example. in source of presto saw methods this takes row data type parameter. there no sample how create row. thanks. define output function this: @outputfunction("row(name double,some double)") public static void output(somestate state, blockbuilder out){ blockbuilder blockbuilder = doubletype.double.createblockbuilder(new blockbuilderstatus(), 1); doubletype.double.writedouble(blockbuilder, 1.0); doubletype.double.writedouble(blockbuilder, 2.0); block block = blockbuilder.build(); out.writeobject(block); out.closeentry(); } here, define parameter types row(name type) wiki

javascripts/jquery countdown giving wrong hours on mobile -

i'm counting down eclipse using jquery countdown.js. counts correctly on desktop. on mobile (android), countdown 1 hour ahead. on other people's mobile, countdown shows 0 hours. doing wrong? not accounting timezone? should matter? countdown eclipse (less 4 hours now), use quickly! var date = new date("2017-08-21t13:18:00"); //1:18 p.m. est $("#dayelem") .countdown(date, function(event) { if (event.strftime('%-d') < 10) { $(this).text('0' + event.strftime('%-d') ); } else { $(this).text( event.strftime('%-d') ); } }); $("#hourelem") .countdown(date, function(event) { if (event.strftime('%-h') < 10) { $(this).text('0' + event.strftime('%-h') ); } else { $(this).text( event.strftime('%-h') ); } }); $("#minuteelem") .

php - Extend Model class for Price Filter Layered Navigation in Magento2 -

i have created custom module thought override function handles pricerender price filter (layered navigation). for example, instead of showing price filters such 0 - 99.99, 100 - 199.99, show 0 - 100, 100 - 200 , forth. my module stands... di.xml: <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:nonamespaceschemalocation="urn:magento:framework:objectmanager/etc/config.xsd"> <preference for="magento\catalog\model\layer\filter\price" type="rf\roundpricefilter\model\layer\filter\price" /> </config> and module.xml file is: <?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:nonamespaceschemalocation="../../../../../lib/internal/magento/framework/module/etc/module.xsd"> <module name="rf_roundpricefilter" setup_version="1.0.0"</module> </config> and in

php - Codeigniter: How do I display the value returned by a model function on a view textbox during data entry -

this question based on following tables. procedures - id | procedure_name |cost visits - id | visit_date | patient_id | notes | staff_id visits_procedures - id | visit_id | procedure_id | quantity payments - id | visit_id | payment_date | amount | payment_method_id | transanction_id | payment_status_id the payments table records total amount paid during visit based on number of procedures performed. visits_procedures table tracks number of procedures performed during visit. trying populate amount textbox value returned get_visit_amount() function in model when creating new payment. getting error 'undefined variable: amount'. appreciate ideas on how make work. below code snippets. payment model public function get_visit_amount(){ $this->db->select_max('id'); $result= $this->db->get('visits')->row_array(); $answer = $result['id']; $this->db->select('sum(procedures.cost * visits_proc

How to insert a video player inside a tkinter window with Python 3? -

i want build video player python, application have more buttons play/pause, need insert video inside window. i have code until now: import tkinter import os import gi gi.require_version('gst', '1.0') gi.repository import gobject, gst def set_frame_handle(bus, message, frame_id): if not message.get_structure() none: if message.get_structure().get_name() == 'prepare-window-handle': display_frame = message.src display_frame.set_property('force-aspect-ratio', true) display_frame.set_window_handle(frame_id) root = tkinter.tk() w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.geometry("%dx%d+0+0" % (w, h)) gst.init(none) gobject.threads_init() video = tkinter.frame(root, bg='#000000') video.grid(row=0, column=0, sticky="nsew") frame_id = video.winfo_id() player = gst.elementfactory.make('playbin', none) player.set_property('video-sink', non

python - kubernetes set value of service/status/loadBalance/ingress- ip -

i'm looking way set service/status/loadbalance/ingress-ip after creating k8s service of type=loadbalancer (as appears in 'type loadbalancer' section @ next link https://kubernetes.io/docs/concepts/services-networking/service/ ). my problem similiar issue described in following link ( is possible update kubernetes service 'external ip' while watching service? ) couldn't find answer. thanks in advance there's 2 ways this. json patch or merge patch. here's how latter: [centos@ost-controller ~]$ cat patch.json { "status": { "loadbalancer": { "ingress": [ {"ip": "8.3.2.1"} ] } } } now, here can see merge patches, have make dictionary containing object tree (begins @ status) need change merged. if wanted replace something, you'd have use json patch strategy. once have file send request , if goes well, we'll rece

javascript - Does a GraphQL Interface definition bind its implementing types to using the same input argument "signature"? -

for example, github api declares type called actor : interface actor { avatarurl(size: int): uri! login: string! resourcepath: uri! url: uri! } is safe assume each type implements actor takes int input argument field avatarurl ? can subtype of actor declare more input arguments on avatarurl field? this transpiler schema language (client implementation), don't want make assumptions can fail @ runtime. as far graphql.js concerned: yes, type implements actor interface need include size argument on avatarurl field in type definition. to clear, if argument not-nonnull, client still leave off inside query. however, need included in type definition or graphql complain. yes, type implementing actor declare additional arguments on field beyond interface mandates. imagine of edge case, these arguments not usable on queries returning interface. query returning specific type, not interface, technically utilize additional arguments.

html - Require php line of code not working -

very new of , having issues using line of code. all trying have html file have require statement pulls php file not working. please help. <?php require 'localhost/php/loginscreen.php'; ?> "all trying have html file have require statement pulls php file not working" . that me suggests you're using .html file base file pull in .php file. unless you've instructed server treat .html files php, need rename file .php extension. edit. consult following q&a on stack on how this: using .htaccess make .html pages run .php files? your syntax require 'localhost/php/loginscreen.php'; incorrect. you need either use full system path: (as example, replace system path). require '/var/usr/public/php/loginscreen.php'; or relative path: require 'php/loginscreen.php'; and using http://localhost rather possible file:/// url in browser. "strange there no error. refresh html file nothing hap

node.js - Response not ending -

i'm creating frontend application 1 of our projects user, cluster, (single) node management, etc. i've decided create frontend using html , javascript, , nodejs server-side functionality. i've created webserver, can handle both defined routes , files; , i've decided split operations in functions. i've gathered javascript, parameters called value if they're not objects, , reference if objects? if case, why can not end() request external function? , if can, how go this? thanks! code below reference. // define server functionality if (request.method === "get") { // functions/routes go here if (routes[request.url]) { // route found! // execute handler function routes[request.url](request, response); } else { // no such route found in hashtable // check if it's file var filepath = __dirname + request.url; if (fs.existssync(file

how to generate logs using log4js-protractor-appender in angular/cli project using typescript -

i have tried using log4js-protractor-appender e2e testing using protractor in angular cli project following link writing log file protractor/jasmine tests without using command line i think should use jasmine or mocha reporting test results. hope you. how can save protractor test results wiki

python - How to use dropna on dataframes with dtype=str? -

when have dataframe this: import pandas pd import numpy np df = pd.dataframe(np.nan, index=list('abc'), columns=list('def'), dtype=float) df.set_value('a', 'd', 4.0) df.set_value('b', 'e', 10.0) d e f 4.0 nan nan b nan 10.0 nan c nan nan nan i can rid of rows contain nans calling: df = df.dropna(how='all') which yields d e f 4.0 nan nan b nan 10.0 nan how 1 same on dataframe initialized dtype=str ? following not work: df2 = pd.dataframe(np.nan, index=list('abc'), columns=list('def'), dtype='str') df2.set_value('a', 'd', 'foo') df2.set_value('b', 'e', 'bar') d e f foo n n b n bar n c n n n then command df2 = df2.dropna(how='all') returns unmodified dataframe. call df.replace first, , df.dropna : in [1576]: df2.replace('n', np.nan).dropna(how=

selenium - Dynamically create autoload command from filenames in Ruby -

i testing web application ruby, rspec, capybara , selenium , ran uninitialized constant activeadminloginpage exception don't know how solve. in spec_helper.rb requiring following: dir[file.join(dir.pwd, 'spec/page_objects/**/*.rb')].each { |f| require f } i have 2 classes spec/page_objects/products/active_admin_login_page.rb module products class activeadminloginpage < ::activeadminloginpage ... end end inherits from spec/page_objects/active_admin_login_page.rb unfortunately sub class loaded before parent class. how create autoload command dynamically filenames in directory? replace command: dir[file.join(dir.pwd, 'spec/page_objects/**/*.rb')].each { |f| require f } with autoload command. how use require load dependency in file needs it? require loads file once, shouldn't encounter side effects. or, better, can use auto_load , uses require under hood, in smarter way autoload :activeadminloginpage, 'ac

Issue in accessing facebook page using selenium chrome browser -

i trying facebook profile data using selenium. have used chrome driver access facebook page. when run selenium code chrome browser opening properly. after logging facebook, page faded out in black color. not perform click event on page. hence code fails data page. wiki

assembly - Call of statically link function crash everytimes on windows 8/10 but not 7 -

the issue : i have build https://github.com/reorg/pg_repack project generate binary. binary linked postgres 9.6 redistributable (i use delievered entreprisedb). works fine on windows 7. have no issue during build or during runtime. on windows 8 or 10, application crashs following sequences. binary generated c sources visual studio 2013, on windows 7 (i have tried version generated on windows 10 doesn't change anythings), on x64 system, x64 application , optimisation disabled , use dynamic base. sure use right binaries, have copy redistributable binaries folder of application. assembly details on windows 7 (working case) : few lines after main, application calls function set_pglocale_pgservice set_pglocale_pgservice(argv[0], "pgscripts"); 00007ff6e4b39c85 mov eax,8 00007ff6e4b39c8a imul rax,rax,0 00007ff6e4b39c8e lea rdx,[default_options+120h (07ff6e4b43b10h)] 00007ff6e4b39c95 mov rcx,qword ptr [argv] 00007ff6e4b39c9a

php - How do I track the activity of logged in users? -

i have larval application , have many members. want track activity of logged in users on website. there way can see links of pages logged in user go within website , store them on database? you can create user meta field in database holds json data, can keep track of url using request object such as // full url, query string $request->fullurl() // path part of url $request->path() // root (protocol , domain) part of url) $request->root() now can update database field using let $dbval value of column used store tracking data json array. $newfield=json_encode(array_push(json_decode($dbval),$request->path())) here in way can maintain records multiple users. wiki

Why is this Fortran DLL not being read by my VB.NET application? -

i trying link fortran dynamic-link-library (dll) vb.net application. subroutine contained in dll supposed modify value c provided in vb side, not doing it: keeps c is. here fortran code: subroutine prueba_int(m,n,p) !dec$ attributes dllexport, decorate, alias : "prueba_int" :: prueba_int !dec$ attributes reference :: m,n implicit none integer, intent(in) :: m,n integer,intent(out) :: p p=m*n end subroutine and here vb.net section: public class form1 public declare sub prueba_int lib "dll2.dll path" (byref m integer, byref n integer, byref p integer) private sub btn1_click(sender object, e eventargs) handles btn1.click ofd.filter = "(*txt)|*.txt" if (ofd.showdialog() = dialogresult.ok) txtarray.text = ofd.filename end if end sub private sub btncalc_click(sender object, e eventargs) handles btncalc.click dim a, b, c integer = cint(txt1.text) b = cint(txt2.text) c = 1 call prueba_int(a, b, c) msgbox

file - C# relative Filepath encrypt -

i want encrypt file relative file. use code encryption. private void encryptfile(string inputfile, string outputfile) { try { string password = @"cortex98"; unicodeencoding ue = new unicodeencoding(); byte[] key = ue.getbytes(password); string cryptfile = outputfile; filestream fscrypt = new filestream(cryptfile, filemode.create); rijndaelmanaged rmcrypto = new rijndaelmanaged(); cryptostream cs = new cryptostream(fscrypt, rmcrypto.createencryptor(key, key), cryptostreammode.write); filestream fsin = new filestream(inputfile, filemode.open); int data; while ((data = fsin.readbyte()) != -1) cs.writebyte((byte)data); fsin.close(); cs.close(); fscrypt.close(); } catch { messagebox.show("encryption failed!", "error"); } } when use absolute path like: encryptfile(@"c:\mo

html - How can I make screen reader (esp using NVDA) not read an element when focused? -

i working on highly accessible website. how can make screen reader not read (1) associated labels, (2) not indicate if checked or not, focused checkbox? when focus checkbox screen reader not read anything. i tried adding class .dontread it's not working. can suggest other methods? .dontread { speak: none; } you can't , shouldn't that. if site not highly, accessible, in no way should prevent screen reader reading element in focus, being strictly against accessibility recommendations. , preventing reading checked state of check box worse. if want that, replace native controls check boxes images no alt . please, heaven's sake, don't in way, drop accessibility level many points @ once. if misunderstood you, please reword question or (better) add clear things bit more. wiki

ruby - How to test rake task callbacks -

i create test code rspec. want test callback executed or not. task main: [:callback] means run callback before main , doesn't it? but test failed. looks callback not executed. why? require 'rails_helper' require 'rake' rspec.describe 'rake::task' before(:all) @rake = rake::application.new rake.application = @rake rake.application.rake_require('rspec_before', ["#{rails.root}/lib/tasks"]) end subject { @rake['rspec_before:main'].execute } "expects run callback before main task" expect{ subject }.to output(/hello, world/).to_stdout end end my rake task below. namespace :rspec_before task :callback @greeting = "hello, world" end # case 1 # in case, `callback` not executed in rspec # in console, `callback` executed !!!! desc "main task" task main: [:callback] puts @greeting end # case 2 # in case, `callback` executed in rspec # task

webstorm - IntelliJ JSDoc block + ESLint valid-jsdoc -

here simple function auto-generated docblock webstorm: /** * * @param * @param b * @returns {string} */ function foo(a, b) { return "ad"; } this considered "invalid" eslint valid-jsdoc because @param don't have type, i.e. should have been: /** * * @param {some-type} * @param {some-type} b * @returns {string} */ function foo(a, b) { return "ad"; } i cannot figure out how fix this. appreciated wiki

c++ - C++11 default class member initialization with initializer list , simultaneously -

can point me please, corresponding paragraph of c++ standard, or maybe can provide explanation why code not compile if uncomment text ({123}) ? generally speaking understand wrong usage of default member initialization , initialization via initializer list, can't refer exact reasons. enum class my: int { = 1 }; struct abc { int a;/*{123};*/ //compilation failed if uncommented m; }; abc = {1, my::a}; compiler error, in case of uncommented text: error: not convert ‘{1, a}’ ‘<brace-enclosed initializer list>’ ‘abc’ the below syntax: abc = {1, my::a}; is list-initialization may perform differently depending on type being initialized. without non-static data member initializer ( /*{123};*/ ), struct aggregate , case falls under [dcl.init.list]/p3 : otherwise, if t aggregate, aggregate initialization performed. however, aggregate type, following conditions must met in c++11: an aggregate array or class (clause 9) no us

node.js - Mongodb collection intersection -

i'm new mongodb , need faster way write following script: db.lth1.find().foreach( function(mydoc) { db.corpus.find({ 'p': mydoc._id.p, 's': mydoc._id.s, 'o': mydoc._id.o }).foreach(function(newdoc){ db.newdb1.insertone(newdoc, function(err, res) { if (err) throw err; console.log("1 document inserted"); }) } ); } ) wiki

html - Font Awesome icons not working in Firefox -

i trying understand going on, using font-awesome , 2 icons not load @ in firefox, can guys me solve it? if open jsfiddle see works on chrome not in firefox. icons not working are: fa-user-circle-o fa-calendar-plus-o icon working: fa fa-pencil-square-o tested in: firefox 55.0.2 (64-bit) ubuntu chrome version 58.0.3029.96 (64-bit) ubuntu jsfiddle: https://jsfiddle.net/s15dxabc/4/ <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <br><br> <i class="fa-calendar-plus-o"></i> <br><br> <i class="fa-user-circle-o"></i> <br><br> <i class="fa fa-pencil-square-o"></i> here updated js fiddle https://jsfiddle.net/s15dxabc/6/ forgot add .fa class <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="styl

javascript - How do I make CSS accordions collapse when different tab is selected? -

i have combined pure css tab pure css accordion. here sources: accordion: https://codepen.io/raubaca/pen/pzzpve tabs: https://css-tricks.com/css3-tabs/ i have pure css accordion on first tab. problem when accordions opened in first tab , tab selected, user can see opened accordion underneath. how collapse accordions when tab selected? https://jsfiddle.net/lance_bitner/ybtqm1hq/ <div class="w3c"> <div id="tab16"> <a href="#tab16">tab 16</a> <div> <div class="tab"> <input id="tab-one" type="checkbox" name="tabs"> <label for="tab-one">introduction sharepoint</label> <div class="tab-content"> <div> <div class="column2"> <a href=""><img src="../images/classroom1.png"></a> <a href=""><img src

where does the python start the code execution from? -

i trying understand when execute .py file, part of code python start execution from? e.g.when execute java program, "public static void main(string[] args)" location java start code execution. so, when talk python, how work? know there python main function (__name__ = "__main__") , have gone through article in , out of stackoverflow, loads python module, , python udfs etc. so, per understanding, location executed first thing. please correct me, or guide me web links query. if python code in method, no code executed unless explicitly call method (e.g. after checking __name__ == '__main__' ). convention call main method, can call method starting point of execution. if python code not in method, code executed anytime run or import file. wiki

ios - Custom camera , video is not playing with Audio in swift -

i new in swift stake overflow. advanced thank's attention. trying build custom camera record video audio. means video play sound when play video. las few days try build custom camera. followed tutorial still missing camera. try per custom camera recording video. maybe not recording audio. don't understand. searching answer, not find appropriate answer this. here did import uikit import avfoundation import svprogresshud import mediaplayer import mobilecoreservices import avkit var videourl = [anyobject]() class testviewcontroller: uiviewcontroller { @iboutlet var viewvidioplayer: uiview! @iboutlet weak var myview: uiview! var session: avcapturesession? var userreponsevideodata = nsdata() var userreponsethumbimagedata = nsdata() override func viewdidload() { super.viewdidload() } override func viewdidappear(_ animated: bool) { super.viewdidappear(animated) } // here create session func createsession() { var input: avcapturedeviceinput? l

format - How to print roman numerals greater than 3,999? -

i want print several numbers roman numerals but (format t "~@r~%" 4000) leads following error in sbcl 1.3.20 , similar 1 using ccl: number large print in roman numerals: 4,000 [condition of type simple-error] restarts: 0: [retry] retry slime repl evaluation request. 1: [*abort] return slime's top level. 2: [abort] abort thread (#<thread "new-repl-thread" running {100503d2b3}>) i did not find information limit in hyperspec , wasn't aware romans had numbers unto 3,999. is there ready-to-use solution print numbers greater 3,999 roman numerals? there no consensus among romans on large number representation . cl implementors demurred on resolving controversy, since both approaches used romans ("apostrophus" , "vinculum") unsuitable representation in ascii on tty. ps. 3.999 can approximated iv ;-) wiki

r - gWidgets - ginput() function error -

i'm having problem launching ginput pop-up gwidgets. this error: loading required package: gwidgetstcltk error in (function (classes, fdef, mtable) : unable find inherited method function ‘.ginput’ signature ‘"guiwidgetstoolkittcltk"’ in addition: warning message: in library(package, lib.loc = lib.loc, character.only = true, logical.return = true, : there no package called ‘gwidgetstcltk’ i use popup type number assign variable. code snippet follows: options(guitoolkit = "tcltk") # tool kit dependency gwidgets. library(gwidgets) # package required launch ginput gui. width.var <- as.numeric(ginput("enter value - width ", title = "png dimensions", icon = "info")) supplementary info : i updated r version 3.2.5 3.4.1 installing latest rstudio version. i've run code section before on r3.4.1 on different computer without is

java - How can I run a standard jar application and stop it in a web application on Glassfish using the web interface? -

there standard application (with main (string args []) ). consists of following components: jdbc; telegram-bot (library java); http-server (accepts get-requests server) com.sun.net.httpserver.httpserver ; read property file (at startup). the application works @ start-up in terminal ( java -jar jarname.jar ). web application needed edit property file using web interface. changing properties causes restart of jar application. how , run application in web application , stop it? wiki

enums - Scala: give a constructor an enumeration and a function that takes that enumeration as a parameter -

i'm wondering if there way write following in scala: class test(enumeration:enumeration, f:enumeration.value=>string){ // add fields here } class test[a <: enumeration](val enumeration: a, f: a#value => string) { // class body } wiki

python 3.x - Django Allauth replace labels -

i have following form account_signup_form_class pointing to class signupform(forms.form): def __init__(self, *args, **kwargs): super(signupform, self).__init__(*args, **kwargs) field_name in self.fields.keys(): print(field_name, self.fields[field_name].label) i'm trying replace labels each of following fields: username , email , password1 , password2 . when form initiated, following printed. username username email none but rendered form in browsers shows of fields labels username* e-mail* password* password (again)* why username , email being printed, , why email field label none yet shows fine when rendered. how able change labels of 4 fields? you can't on form that's set on account_signup_form_class . form used base class signupform allauth. can't change field because doesn't exist on form (only on subclass). want have subclass signupform django allauth , use real signup form can set this:

bufferedreader - How can i edit line 2 in filereader and buffered reader - Java -

i have code when press button edit first line in txt file: string editn = jtextfield13.gettext(); if (jtextfield18.gettext().equals("1")) { try { string verify, putdata; file file = new file("name.txt"); filewriter fw = new filewriter(file); bufferedwriter bw = new bufferedwriter(fw); bw.write(editn); filereader fr = new filereader(file); bufferedreader br = new bufferedreader(fr); while ((verify = br.readline()) != null) { if (verify != null) { putdata = verify.replaceall("here", "there"); bw.write(putdata); } } br.close(); bw.close(); filereader fr2 = new filereader(file); bufferedreader br2 = new bufferedreader(fr2); string line1 = br2.readline(); br2.close(); worker1.settext("1. " + line1); editworker.setvisible(false); w

javascript - Discord.js reply to message then wait for reply -

right want bot wait message user "!spec" when gets message want respond "see or change?" wait type "see" or "change" cant work, docs arent clear me , im not sure on how it. this has able work in pm dont want spam discord plan do. i have tried this: if (command === 'spec'){ message.author.send("see or change?"); const collector = new discord.messagecollector(message.channel, m => m.author.id === message.author.id, { time: 10000 }); console.log(collector) collector.on('collect', message => { if (message.content === "see") { message.channel.send("you want see someones spec ok!"); } else if (message.content === "change") { message.channel.send("you want change spec ok!"); } }) i may writing wrong im not used library. compare == , try. if (command ===

bash - Print a value from a URL string using shell commands -

i have url string (such http://10.58.206.10:20002/job-cache/job/548 ) in file. string need print ip address value (i.e, 10.58.206.10 ). this ip address vary often, need "the value coming after http:// , before :20002 ". using grep , sed below, wasn't able exact value. grep -i "result url:" taf.log | sed 's/^.*http://' you can avoid grep use single sed : sed -e '/result url:/s~.*http://([^:]+):.*~\1~' taf.log wiki

Error 429, quota exceeded for Google Pagespeed API -

the google pagespeed api docs show quota limit of 100 queries per 100 seconds, or 25k per day. yet, error 429 when i've run less 5 queries week, , no closer 20 seconds. any ideas? i've emailed google 6 times of course no response. i have timeouts of 20 seconds between calls , still quota limit exceeded errors every 4 calls. wiki

angular - Convert String type to Class type -

this question has answer here: dynamically loading typescript class (reflection typescript) 5 answers in java use this: class<?> classtype = class.forname(classname); how can achieve same goal angular? in case it's object , can convert this let = 'object string';let jsobj = json.parse(a);console.log(jsobj); wiki

php - Laravel 5.4 - Return single row from joined table -

i have model album (table albums) , model photo (table photos). when i'm fetching albums page, display first photo each album album image. album model: public function photos() { return $this->hasmany('app\photo'); } photo model: public function album() { return $this->belongsto('app\album'); } query: public function getalbums() { return db::table('albums') ->join('photos', 'albums.id', '=', 'photos.album_id') ->select('photos.title', 'albums.title album_title', 'albums.slug album_slug') ->get(); } it returns photos album title. how modify query return first photo each album? how use limit 1 in joined table? or there way this? thanx. reslut why not things laravel way instead of raw db queries? there's trick doing this. first in album model, add method (i use latest() maybe want oldest() , or other limit described in do

Change response URL on Rails server -

i trying change response url redirect (without redirect) custom subdomain. using devise , apartment , trying use user's subdomain after successful request. before_action :authenticate_user! after_action :switch_tenant_response def switch_tenant_response response.headers["server_name"] = 'tenant_name.lvh.me' # not work end i request being sent lvh.me (domain name localhost) redirected tenant_name.lvh.me . avoid doing in middleware (but if there way please let me know) since on rails app have access devise's current_user . i don't quite question, you're looking for? redirect_to some_path(subdomain: false) #redirect localhost or whatever host without subdomain , redirect_to some_path(subdomain: tenant_subdomain_from_a_variable) #redirects provided subdomain wiki

mysql - PHP & JSON Show column data by user -

i'm in process of relaying data column called "followers_count", in table called "tbl_users". site has several users each own page. on pages person can click follow button , follow count displayed, using json. code works far except shows/updates data of "followers_count" first "userid" in table. question is, how alter code knows each user's page display followers_count? in changes.php: <?php require_once 'class.channel.php'; $user_change = new user(); $seqfollows = $user_change->runquery("select followers_count tbl_users"); $seqfollows->execute(); $row = $seqfollows->fetch(pdo::fetch_assoc); $follow_count = $row['followers_count']; header('content-type: application/json'); $array = array('followers_count'=>$follow_count); echo json_encode($array); ?> in index.php?id= (the user page template): <div> channel adds: <div id="follow_count" style=&q

Arduino variable syntax error -

what's wrong follow syntax? void draw() { int dword; dword = serial.read(); u8g.setfont(u8g_font_gdr25); u8g.drawstr( 5, 60, dword); } i error: call of overloaded 'drawstr(int, int, int&)' ambiguous if @ source code : u8g_uint_t drawstr(u8g_uint_t x, u8g_uint_t y, const char *s) { return u8g_drawstr(&u8g, x, y, s); } it receives parameter variable of type const char * , must convert integer type of variable, example can use itoa function: int dword = 321; char str_dword[5]; # replace 5 number of digits think number has. itoa(dword, str_dword, 10); u8g.drawstr( 5, 60, str_dword); wiki

wordpress - User submitted cf7 -

i new contact form 7 on wordpress , create option login users can see submitted cf7 forms on allocated content page. the idea here have participants send form , able view had sent , avoid case other users see others form submission data. i want in user allocated pages , not on backend dashboard wiki

Search for color string in powershell -

i have powershell code. how can search characters within richtextbox have color formatting? or color @ all? let's red background example. have highlighted portion of text , find characters. currently, have search text only. code example: function example-search { $index = $resultbox.find($searchtext, $resultbox.selectionstart + $resultbox.selectedtext.length, [system.windows.forms.richtextboxfinds]::none) if($index -ge 0) { $resultbox.select($index, $searchtext.length) $resultbox.scrolltocaret() } else { $index = $resultbox.find($searchtext, 0, $resultbox.selectionstart , [system.windows.forms.richtextboxfinds]::none) } if($index -ge 0) { $resultbox.select($index, $searchtext.length) $resultbox.scrolltocaret() } else { $resultbox.selectionstart = 0 } } here way it, goes through each character in richbox , checks color name. can rearrange needs funct

How to calculate the average of a value in R in a loop -

i have dataset one: date_a date_b type price 2345 2400 120 1115 1230 b 226 930 945 c 90 1050 1100 157 and want print values type column values of date_a less date_b. part did following code: for(i in 1:length(list)){ if(`date_a`[i]<`date_b`[i]){ print(type[i]) } } this code works fine. want calculate total average of price column type values printed before type's date_a < date_b. thought of doing like: for(i in 1:length(list)){ if(`date_a`[i]<`date_b`[i]){ print(type[i]) price_average[i] <- mean(price) } however gives me total mean of whole dataset , want mean of price date_a < date_b. trying figure out how calculate using loops since practicing loops in r. i'm not sure understand want. try this: mean(price[date_a < date_b]) wiki

java - Can't get Stdlib.jar to work in terminal -

i'm coding java , using intellij. have imported stdlib.jar library using instructions here https://stackoverflow.com/a/29640488/8304687 , works fine in intellij. but, when run code in terminal "cannot find symbol" errors methods i'm using stdlib.jar. i've tried copying of methods src file project i'm working on, , copying main file (directory?) of project, none of things have worked. wiki

Jupyterhub and nginx reverse proxy configuration -

i trying configure jupyterhub proxy route content going my-host-ip/notebook cannot figure out solution. i using following nginx configuration: server { listen 80; server_name localhost; location /notebook { proxy_pass http://localhost:8000; # proxy_set_header x-real-ip $remote_addr; # proxy_set_header host $http_host; # proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; } location ~* /(user[-/][a-za-z0-9]*)/(api/kernels/[^/]+/(channels|iopub|shell|stdin)|terminals/websocket)/? { proxy_pass http://localhost:8000; # proxy_set_header x-real-ip $remote_addr; # proxy_set_header host $http_host; # proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; # websocket support proxy_http_version 1.1; proxy_set_header upgrade $http_upgrade; proxy_set_header connection "upgrade"

language agnostic - SPOJ query- PRIME1 - Prime Generator -

i tried solve question prime generator . people told me first spend sometime problem , go searching or so. when searched google showed me use algorithm called sieve of eranthoses. didn't know how supposed solve question or in wasting time solving question. thanks question. better try solving problem while. when trying , searching solution brain trains itself. so, sticking problem good. when you'll fail find solution, ask friend little hint. or may try searching in web hint. if familiar algorithm, must try yourself. otherwise searching tutorial on algorithm might you. however, sieve of eratosthenes known algorithm finding primes given range. can find information , tutorials here , here . wiki

osx - MySQL service inside docker container not working in macOS Sierra 10.12.6 -

i forced reinstall macos sierra because in beta program high sierra , serious crash downgraded system. this dockerfile working in high sierra before sudden crash of system. from ubuntu:16.04 maintainer xxx version 0.0.1 # prepare debian environment env debian_frontend noninteractive # don't need apt cache in container run echo "acquire::http {no-cache=true;};" > /etc/apt/apt.conf.d/no-cache # ---------------------------- # configure supervisor # ---------------------------- run apt-get update > /dev/null 2>&1 && apt-get install -y supervisor > /dev/null 2>&1 run mkdir -p /var/log/supervisor copy files/supervisord.conf /etc/supervisor/conf.d/supervisord.conf ## mysql run apt-get install -y mysql-client > /dev/null 2>&1 #run debconf-set-selections <<< 'mysql-server mysql-server/root_password password 1234' #run debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password

sql - How to merge last two events into one row -

i have table below. date id event keyword val pattern_id() 2017-08-01 001 triggerx abc (null) 1 2017-08-01 001 triggery (null) 3 1 2017-08-01 009 triggerx cde (null) 2 2017-08-01 010 triggerx ghi (null) 3 2017-08-01 010 triggerx ghi (null) 3 2017-08-01 010 triggerx ghi (null) 3 2017-08-01 010 triggery (null) 1 3 (list continues..) event triggerx followed triggery (not vice versa). there chance there triggerx (no triggery) id 009. however, there no chance triggery only. what i'd following. for example of id 001, i'd merge triggerx keyword column , triggery val column 1 row. for example of id 010. has 4 events, need last 2 events (last triggerx , y) , merge keyword column , val column. give me below. date id keyword val 2017-08-01 001 abc 3 2017-08-01 010 ghi 1 could me figure out how construct sql result above?

maven - Grails Download zip file as dependency -

i have standalone custom code packed zip file(custom-1.0.zip) using maven-shade-plugin –uploaded company's artifactory <dependency> <groupid>com/mypackage/domain</groupid> <artifactid>custom</artifactid> <version>1.0</version> <type>zip</type> </dependency> i want use zip file in grails 2.3.5 project configured use maven resolving dependencies. believe need following: download zip file artifactory local maven repository copy zip file local maven repository web-app/resources folder of project i added following build.groovy download zip file: grails.project.dependency.resolver = "maven" dependencies { compile ("com.mypackage.domain:custom:1.0") } … .. plugins { compile ("com.mypackage.domain:custom:1.0") } above code downloads jar, pom , zip file local maven repository , fails loading grails 2.3.5 |configuring classpath |downloading: com.mypa

ios - how to make cameraOverlayView along the y axis (swift3) -

Image
i making photo app want imagepicker screen have blocks of red pre mask photo before crops. following code gets roadblock on top x axis. place red box along entire y axis yellow rectangle is. let blockview = uiview.init(frame: cgrect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 150)) blockview.backgroundcolor = uicolor.red imagepicker.cameraoverlayview = blockview please try following : let mainview = uiview.init(frame: cgrect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height-150)) let blockview = uiview.init(frame: cgrect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 150)) blockview.backgroundcolor = uicolor.red let blockview1 = uiview.init(frame: cgrect.init(x: 0, y: 170, width: 100, height: self.view.frame.size.height-320)) blockview1.backgroundcolor = uicolor.green mainview.addsubview(blockview) mainview.addsubview(blockview1) imagepicker.cameraoverlayview = mainview