Posts

Showing posts from May, 2014

group by - How to make zero counts show in LINQ query when getting daily counts? -

i have database table datetime column , want count how many records per day going 3 months. using query: var mindate = datetime.now.addmonths(-3); var stats = t in teststats t.date > mindate group t entityfunctions.truncatetime(t.date) g orderby g.key select new { date = g.key, count = g.count() }; that works fine, problem if there no records day day not in results @ all. example: 3/21/2008 = 5 3/22/2008 = 2 3/24/2008 = 7 in short example want make 3/23/2008 = 0 . in real query zeros should show between 3 months ago , today. fabricating missing data not straightforward in sql. recommend getting data is in sql, joining in-memory list of relevant dates: var stats = (from t in teststats t.date > mindate group t entityfunctions.truncatetime(t.date) g orderby g.key select new { date = g.key, count = g.count() }).tolist(); // hydrate query db once var firstdate = stats.min(s => s.date); var lastdate = stats.max(s => s.date); var alldates =

Monitoring Status of Message Sent to RabbitMQ via Web-Stomp web-socket -

using web-stomp rabbitmq , web-socket (sockjs not used), after sending message queue, how can consumer notified broker or monitor sent message has been consumed? i've experimented subscribing queue makes client consumer , goal not receive message processing, know when consumer elsewhere has picked up, acknowledged message , no longer in queue. in retrospect, believe i'm breaking spirit of "send , forget it" question's approach. the better approach subscribe queue receive "finished processing" message sent processor. client can take appropriate actions there.

tsql - Tableau-Generated Query Not Hitting the Optimal Table Index -

i have tableau-generated query looks like: select (((datepart(year,(case when 0 = isdate(cast([table1].[m_date] varchar)) null else dateadd(day, datediff(day, 0, cast(cast([table1].[m_date] varchar) datetime)), 0) end)) * 10000) + (datepart(month,(case when 0 = isdate(cast([table1].[m_date] varchar)) null else dateadd(day, datediff(day, 0, cast(cast([table1].[m_date] varchar) datetime)), 0) end)) * 100)) + datepart(day,(case when 0 = isdate(cast([table1].[m_date] varchar)) null else dateadd(day, datediff(day, 0, cast(cast([table1].[m_date] varchar) datetime)), 0) end))) [md:m_date:ok] [tbl].[table] [table1] group (((datepart(year,(case when 0 = isdate(cast([table1].[m_date] varchar)) null else dateadd(day, datediff(day, 0, cast(cast([table1].[m_date] varchar) datetime)), 0) end)) * 10000) + (datepart(month,(case when 0 = isdate(cast([table1].[m_date] varchar)) null else dateadd(day, datediff(day, 0, cast(cast([table1].[m_date] varchar) datetime)), 0) end)) * 100)) + datepart(day,

node.js - Share a database connection pool between sequelize and pg -

i have server i've written using express , node-postgres (pg). creates own db pool: const dbpool = new pg.pool(dbconfig); and runs sql queries directly using connection. now i'm adding new table , corresponding rest api. i'd use sequelize , epilogue reduce boilerplate. unfortunately, sequelize wants create own database connection pool: const sequelize = new sequelize(database, user, password, config); is possible re-use existing connection pool or otherwise share between existing pg code , new sequelize code?

C++ reading 2d array from file -

i have small problem. trying read file, , output read data 2d array in c++. i've created .txt file , been fixing code not find out problem is. my code following: #include <iostream> #include <fstream> // file handleing using namespace std; int sudoku[9][9]; int main() { ifstream fp("sudoku.txt"); // reading , opening existing file sudoku.txt for(int row = 0; row < 9; row++){ for(int column = 0; column < 9; column++){ fp >> sudoku[row][column]; // fp read characters } } for(int row = 0; row < 9; row++){ for(int column = 0; column < 9; column++){ cout << sudoku[row][column] << " "; } cout << endl; } fp.close(); return 0; my text file looks this: 6 4 0 0 0 0 8 0 1 5 0 0 7 0 0 0 2 0 2 7 0 4 9 0 0 0 0 0 3 6 5 1 8 0 9 0 0 0 0 3 0 2 0 0 0 0 5 0 9 6 7 1 4 0 0 0 0 0 7 4 0 8 6 0 8 0 0 0 9 0 0 2 7 0 1 0 0

apache camel - How do I set an exchange header to the result of a route? -

i have camel route has step calls subroute convert text portion of body pdf. unfortunately camel-pdf not preserve headers. there way can value of subroute without losing current exchange? sub route from("seda:generate-pdf") // original in header .setheader("original", body()) // create pdf .to("pdf:create?textprocessingfactory=autoformatting") // uhoh! headers gone :( // set pdf header doc server .setheader("pdf", body()) // move indicator body .setbody(header("original")) // <-- no longer exists main route // snip // unmarshal java .unmarshal().json(jsonlibrary.gson, myreportcontainingtext.class) // call sub-route generate pdf .inout("seda:generate-pdf") // uhoh! headers gone :( // snip instead of saving stuff in headers can removed when pass 1 route save them exchange properties. example: .setproperty("pdf", body()) .setproperty("pdf", simple("${body}") excha

ios - Swift: Hide button in UICollectionView cell -

i programmatically creating cells , adding delete button each 1 of them. problem i'd toggle .hidden state. idea have edit button toggles of button's state @ same time. maybe going wrong way? func collectionview(collectionview: uicollectionview, cellforitematindexpath indexpath: nsindexpath) -> uicollectionviewcell { let cell = collectionview.dequeuereusablecellwithreuseidentifier("verticalcell", forindexpath: indexpath) as! racollectionviewcell let slide = panelslides[indexpath.row] cell.slidedata = slide cell.slideimageview.setimagewithurl(nsurl(string: image_url + slide.imagename + ".jpg")!) cell.setneedslayout() let image = uiimage(named: "ic_close") uiimage? var deletebutton = uibutton(type: uibuttontype.custom) uibutton deletebutton.frame = cgrectmake(-25, -25, 100, 100) deletebutton.setimage(image, forstate: .normal) deletebutton.addtarget(self,action:#selector(deletecell), forcontrolevents:.t

sql checkboxes php form -

can please me? wanted little "system" when click on checkbox sql statement executed. example statement : select * customers id = 6; if can me great. i ajax html <input type='checkbox' onclick'clicked();'> javascript +jquery function clicked(){ $.ajax({ type: "get", url: "phpfile.php", data:{checked:$("checkboxselector")[0].checked} }) } php //phpfile.php $checked = isset($_get['checked']) && $_get['checked'] == "true" ?1:0; if($checked){ $query = "select * customers id = ''"; // execute query }

python - How to stop automatic resizing of frames -

Image
i have 3 frames, when new label appears frames automatically readjust new size. how stop readjustment , have size of each frame set , immutable. #import tkinter make gui tkinter import * tkinter import ttk import codecs #program results when user attempts log in def login(*args): file = open("rot13.txt", "r") lines = file.readlines() uname = user.get() pword = pw.get() in lines: x = i.split() if codecs.encode(uname,'rot13') == x[0] , codecs.encode(pword,'rot13') == x[1]: result.set("successful") break; else: result.set("access denied") root = tk() root.title("login") #configures column , row settings , sets padding mainframe = ttk.frame(root, padding="3 3 12 12") mainframe['borderwidth'] = 5 mainframe['relief'] = "solid" mainframe.grid(column=1, row=1, columnspan=3, rowspan=2) mainframe.columnconf

jquery - How to return HTML from a AJAX call in Rails and fire the ajax:success event? -

i have form remote: true set. here's relevant coffeescript: document.addeventlistener 'turbolinks:load', -> $(document).on 'ajax:success', "form.new_carrier.specific", (event, data) -> console.log data console.log data.responsetext i have following in create method of controller: respond_to |format| format.html { redirect_to_user } format.js render partial: 'carriers/for_order', layout: false end end i want return html partial, correctly doing. jquery expecting json response, not html, ajax:success event never gets called (though can use ajax:complete ). how can make above return response ajax:success event called?

ruby on rails - Delayed Job Gem: Undefined Method 'perform' for Class -

i successful integration delayed_job mailer (app > mailers > notification_mailer.rb), has single method: class notificationmailer < actionmailer::base default from: env["gmail_username"] def notification_message(activity, user) @user = user @activity = activity if @activity.is_comment? subject = @activity.trackable.user.username + ' commented on ' + @activity.trackable.commentable.project.title @type = "comment" end mail(to: @user.email, subject: subject) end end i call in controller, example: notificationmailer.delay.notification_message(@activity, user) however, i'm having issues using delayed_job non mailer jobs. created folder in app > jobs i've placed classes, such as: class carrierwaveimageuploader def execute(image_id, s3_url) if image.exists?(image_id) @image = image.find(image_id) @image.remote_image_path_url = s3_url @imag

swift - Identify Duplicates In Array -

Image
i have array of custom objects , want know how identify objects duplicates. know how remove duplicates not functionality i'm after. im using swift 2. example: var movies: [movie] = ["batman v superman: dawn of justice", "batman v superman: dawn of justice", "deadpool"," "deadpool", "hardcore henry", "jason bourne", "jurassic world"] so want show table view list of movies above "batman" , "deadpool" highlighted. for more clarity on i'm trying achieve @ screenshot. have list of movies 2 users select in previous view controller. want display selected movies in table view. want show if there movies both people selected. based on comment have made simple example string arrays, can converted movie type: let movies = ["batman","batman","flash","avengers"] var moviecounts:[string:int] = [:] movie in movies { moviecounts[mov

swift2 - How to hide / disable tab bar item in swift -

i have 5 tab, tab bar controller in app, , want show 5th item if manager logged app (instead of employee). i have code disables 5th item can still see (its grayed out , not clickable). self.tabbarcontroller!.tabbar.items![4].enabled = false is there way show first 4 items , evenly space them if non manager logged in?

jpa - (JAVA EE) Method not working without throwing any error -

i'm developping airline management web application java ee, ejb & jpa (eclipselink) i'm having trouble when i'm calling method in service layer servlet : method don't expected without having error. the method addpassengertoflight trying add passenger passengers list have in flight entity manytomany relationship. this structure of priject. this flight , passenger entities whitout getters , setters: flight: public class flight implements serializable { @id @generatedvalue( strategy = generationtype.auto ) private integer id; @enumerated( enumtype.string ) private cities depart; @enumerated( enumtype.string ) private cities destination; private string prix; @temporal( temporaltype.timestamp ) private date date; @manytomany( cascade = { cascadetype.merge, cascadetype.persist, cascadetype.refresh } ) @jointable( name = "f_p_join", joincolumns = @

performance - Improve speed on MySQL JOIN with big data -

below 2 tables want fetch data (note these dummy databases don't pay attention data i'm pulling) > describe bigdata; +----------------+----------------------+------+-----+---------+-------+ | field | type | null | key | default | | +----------------+----------------------+------+-----+---------+-------+ | galaxy | int(2) | no | pri | 0 | | | system | int(3) | no | pri | 0 | | | planet | int(2) | no | pri | 0 | | | ogame_playerid | int(11) unsigned | no | mul | 0 | | | moon | enum('true','false') | no | | false | | | moonsize | smallint(5) unsigned | no | | 0 | | | metal | int(10) unsigned | no | | 0 | | | crystal | int(10) unsigned | no | | 0 | | | planetname | varchar(40) | no |

javascript - Difference between angular.merge and angular.extend? -

can 1 please explain me difference between angular.merge , angular.extend..and deep copy means , when should used ? extend : shallow copy properties of source objects right left, way destination object. example: extend person , job objects , vise versa. //------------------------------------extend-------------------------- $scope.extendpersontojob = function () { var person = { 'name': 'monica', 'age': '25', 'skills': { 'name': 'travelling', 'place': 'queenstown' } }; var job = { 'title': 'programmer', 'experience': '5', 'skills': { 'name': 'designing', 'experience': '2', 'certified': 'true' } }; // extend person job $scope.persontojob = angular.extend(person, job); //output : {{ 'name': 'monica', 'age': '2

python with open invalid argument windows -

import datetime import os import sys import time if "zlog_file" not in globals(): global zlog_file script_dir = os.path.realpath(sys.argv[0]).replace(sys.argv[0], "") zlog_file = os.path.join(script_dir, "log", datetime.datetime.fromtimestamp(time.time()).strftime("%m-%d-%y %h:%m:%s")) open(zlog_file, "w"): pass def log(level, msg): open(zlog_file, "a") f: # fix colors if level == "info": msg = "esc[37m[info] " + msg elif level == "warn": msg = "esc[33m[warn] " + msg elif level == "error": msg = "esc[31m[error] " + msg if level != "error": print(msg) else: sys.stderr.write(msg) f.write(msg) i made simple logging library on first import makes new file current time , date in log directory in same location m

javascript - json last error returns 4 -

Image
i trying send array js php through ajax call.to achieve first converted string json using json.stringify() , @ other end used json_decode() decode, didn't work out. using json_last_error() found error 4. js code looks this var form_data = $(this).serialize(); form_data+='&extraitems='+json.stringify(extraitems); var button_content = $(this).find('button[type=submit]'); form_data=form_data+'&landtype='+landtype; button_content.html('adding...'); //loading button text $.ajax({ //make ajax request cart_process.php url: "/cart/cart_process.php", type: "post", datatype: "json", //expect json value server data: form_data }).done(function (data) { //on ajax success $("#cart-info").html(data.items); //total items in cart-info element button_content.html('add cart')

Where is tomcat configuration in Cpanel? -

i have tomcat 7 installed on linux vps under cpanel using easyapache 3. it appears working - can upload war file , service execute. however, need make configuration changes such defining java.library.path. there excellent description of @ [ how add native library in tomcat? . says create setenv.sh file in configuration folder, contains catalina.sh. however, cannot find folder catalina.sh on cpanel server. have done find on entire file system, , not there. tomcat configuration files can find in folder /usr/local/easy/etc/easy-tomcat7 drwxr-xr-x 3 root nobody 4096 sep 9 03:54 ./ drwxrwxr-x 3 root wheel 4096 jul 27 13:42 ../ drwxrwxr-x 4 root nobody 4096 sep 9 03:54 catalina/ -rw-rw-r-- 1 tomcat nobody 11893 jan 27 2015 catalina.policy -rw-rw-r-- 1 tomcat nobody 5946 jan 27 2015 catalina.properties -rw-rw-r-- 1 tomcat nobody 1394 jan 27 2015 context.xml -rw-rw-r-- 1 root nobody 144 jan 27 2015 easy-tomcat7-chkserv -rw-r--r-- 1 root root 5

windows - I need to create/rewrite a driver on Win10 to change the behavior of a button on my camera -

i got lost thing. my girlfriend studying odontology (you know, doctor takes care of teeth) , i'm going give camera intraoral photos, since know lot (and i, because using mirrors , big cameras in mouth not thing practice subject me). here's problem professional cameras expensive , found 1 affordable me, ... yeah there's ... buton camera have when pressed changes de color of image! need take photo instead ... or send signal (enter or that) pc take picture. i'm reading how create drivers windows, i'm lost. amazing if guys me. or if there's way love know. if need anymore information please let me know! the camera - http://produto.mercadolivre.com.br/mlb-711313907-cmera-intra-oral-usb-pronta-entrega-dente-_jm

c# - Will assigning a static object to another (non-static) variable make a copy of that object? -

i have static class holds static textures use throughout game. public static class assetmanager { public static texture2d sometexture; .... } my question is, if assign static texture variable in class, this: texture2d classtexture = assetmanager.sometexture; would creating copy of texture? i'm not thinking , reading it, don't think thats how static variable should work. tried out , checked hashcode of each , seemed same. i'm not sure if thats correct way checking , don't want run problem later on i'm creating bunch of new textures don't need. c# never makes implicit copies of objects. it kind of sounds caution may coming c++ background, in case can think of objects in c# being pointer.

clojure - Extend "name" for custom record type -

i have record includes :name . there way tell clojure.core/name how extract :name out of record? if you're able change defrecord declaration, implement clojure.lang.named interface there. (defrecord myrecord [name] clojure.lang.named (getname [this] (:name this))) (name (myrecord. "dan")) ;;=> "dan""

How Does Apache Shiro Hash Salted Passwords? -

if use apache shiro command line tool generate password java -jar shiro-tools-hasher-1.3.1-cli.jar -p -a sha-512 and use password password $shiro1$sha-512$500000$wnjbm5pwpwn5784aq7i7qa==$iqj6xdwuktcnqjcu982czr6b4a3lngp2f/wd8tmwvc7sanogeuugtbbj/ki9fqiibx/ngf9rjd+5iy971d88cg== the documentation says hashing salted default , defaults 500k iterations , testing results in different password each time assume is. i can log in without specifying salt anywhere though subject currentuser = securityutils.getsubject(); usernamepasswordtoken token = new usernamepasswordtoken("jsmith", "password"); token.setrememberme(true); currentuser.login(token); the place can see must in hash. if can see sections: $shiro1 shows shiro hashed password $sha-512 shows algorithm used $500000 shows number of iterations the salt after section or @ end. is dangerous approach? are apache shiro exposing information here , making easier create attack?

ruby on rails - When building an index of items, how to show which a user has liked/starred -

in rails 4/5, i'm trying show list of items, , if searching user has liked or saved of these items, display somewhere on index. similar social networks showing feed of posts , allowing me see whether i've liked post, or showing list of items , marking whether i've saved of items on list. for simple example, imagine have user , post , , likedpost join model. users can create posts, , other users can posts. user, can through posts , see if i've liked 1 of posts. in theory, should work: @posts = post.includes(:liked_posts) .where('liked_posts.user_id = ?', current_user.id) .references(:liked_posts) but performs query only shows me posts i've liked. other posts filtered out. i'm having strangely hard time finding relevant online, , able find comes down 'you'll need write sql.' tips/advice? ok, on index page have list of posts right? , each post... display name or something? why not have like: &

.net - C# JSON.NET - Deserialize response that uses an unusual data structure -

i having trouble figuring out clean (as possible) way deserialize json data in particular format. want deserialize data typed data object classes, pretty flexible regarding specifics of this. here example of data looks like: { "timestamp": 1473730993, "total_players": 945, "max_score": 8961474, "players": { "player1username": [ 121, "somestring", 679900, 5, 4497, "anotherstring", "thirdstring", "fourthstring", 123, 22, "yetanotherstring"], "player2username": [ 886, "stillastring", 1677, 1, 9876, "alwaysastring", "thirdstring", "fourthstring", 876,

html - why css use inline-block must be add pseudo element (let vertical-align:middle work) -

.pseudo{ width:100%; height:100px; border:1px solid blue; text-align:center; } .pseudo:before{ content:""; display:inline-block; vertical-align:middle; height:100%; } .pseudo p{ display:inline-block; } <div class="pseudo"> <p>hello</p> </div> this html & css code. question why must use pseudo element vertical-align:middle can work . it's not work(vertical-align:middle) if write .pseudo{ width:100%; height:100px; border:1px solid blue; text-align:center; display:inline-block; vertical-align:middle; } the vertical-align property applies element of text line (unless apply display:table-cell ), keywords center , top , , bottom calculated height of text line (the called line box ). height of line box calculated heights of inline elements make line (texts, images, inli

MongoDB Aggregation Sum on Objects in Array -

i've seen lot of answers on how sum properties of objects in arrays within array, i'm trying sum individual properties on object in array across documents. example, given document structure: { "id": 1, "stats": [ { "number": 100, "year": 2014 }, { "number": 200, "year": 2015 } ] }, { "id": 2, "stats": [ { "number": 50, "year": 2014 }, { "number": 75, "year": 2015 } ] } the desired output be: { "stats": [ { "number": 150, "year": 2014 }, { "number": 275, "year": 2015 } } i don't want sum number property of 2014 , 2015, want sum across 2014 both documents. db.test.aggregate([ { $unwind: "$stats" }, { $gro

html - Can someone explain this sample PHP code for me? -

i doing independent study on php , html in w3school , don't understand following codes: (copied w3school) 1 <!doctype html> 2 <html> 3 <body> 4 5 <form method="post" action="<?php echo $_server['php_self'];?>"> 6 name: <input type="text" name="fname"> 7 <input type="submit"> 8 </form> 9 10 <?php 11 if ($_server["request_method"] == "post") { 12 // collect value of input field 13 $name = $_post['fname']; 14 if (empty($name)) { 15 echo "name empty"; 16 } else { 17 echo $name; 18 } 19 } 20 ?> 21 22 </body> 23 </html> q1: why can i, , how should insert php code in middle of bunch of html codes sample did in line 5? topic should @ learn more kind of operation? q2: in php codes after line 10, why want include if statement decide if request method "post"? can

ssas - Function to apply member function to set -

Image
is there mdx function takes set argument , member function separate argument , returns set function applies members? i have set of selected dates, , want return set same dates less 1 year, need use parallelperiod on each member. this approach seems work ok: with set [fewdays] [date].[calendar].[date].&[20070121] : [date].[calendar].[date].&[20070127] set [thedates] generate ( [fewdays] s ,{parallelperiod ( [date].[calendar].[calendar year] ,1 ,s.currentmember )} ) select {} on 0 ,[thedates] on 1 [adventure works]; i think prettier , avoids generate may faster: with set [fewdays] [date].[calendar].[date].&[20070121] : [date].[calendar].[date].&[20070127] member [measures].[cntmembers] [fewdays].count set [lastmemlastyear] { parallelperiod ( [date].[calendar].[calendar year] ,1 ,tail([fewdays

c# - MVC 4 Entity Framework Cannot Connect to Dynamically Created Database from IIS Server -

Image
after hosted apps in localhost iis, system gives me error: cannot open database "alvincms" requested login. login failed. login failed user 'nt authority\system'. the database alvincms created @ runtime. system has no problem when in debug mode. here global.asax: public class mvcapplication : system.web.httpapplication { protected void application_start() { //check , init database alvin_cms.app_start.databaseconfig.initialize(); ...... this initialization: public static void initialize() { alvin_cms.models.alvincmsmigrationdbcontext migrationdb = new models.alvincmsmigrationdbcontext(); try { if (!migrationdb.database.exists()) { migrationdb.database.initialize(false); //this creates database alvincmsextension.models.accountdbcontext accountdb = new alvincmsextension.models.accountdbcontext(); accountdb.database.initialize(false); setdefaul

apache spark - need term frequency in new column of dataframe // scala -

i have dataframe : +----------+--------+---------+-------------+----+ |article_id| sen| token| ner| pos| +----------+--------+---------+-------------+----+ | 1|example1|standford| organisation| nnp| | 1|example1| is| o| vp| | 1|example1| is| location| adp| | 2|example2|standford|organisation2|nnp2| | 2|example2| is| o2| vp2| | 2|example2| good| location2|adp2| +----------+--------+---------+-------------+----+ i need new column called "term_frequency" gives me: 2 in front of is and 1 in front of stanford as need map them number of times occur in article_id . i guess like: df2.withcolumn("termfrequency",'token.map(s => (s,1).reducebykey(_ + _))) or creating new udf. dataframe schema follows: root |-- article_id: long (nullable = true) |-- sen: string (nullable = true) |-- token: string (nullable = true) |-- ner: string

multithreading - Best Way to handle Bulk Mail in C# -

what best method send bulk emails lists. e.g. user request service service category. 200-20000 matching emails users criteria , send users request recipients. i have done research not sure best solution task. method 1, use multiple threads enable multiple smtp clients send mails (not sure if send massive amount of recipients if kill server threads) http://www.aspsnippets.com/articles/send-bulk-mass-email-in-aspnet-using-c-and-vbnet.aspx method 2, use service sendgrid manage emails. (i see in marketing campaigns can manage lists/contacts. not sure if can dynamically generate content template , send list) https://sendgrid.com/docs/api_reference/web_api_v3/marketing_campaigns/contactdb.html any advice appreciated!! you have many different ways the first way, use , in opinion best, need use database store data , write code executed: create table "emaillogs" following fields profilename, body, subject, [to],cc,bcc,isactive,queuedon,senton write

sql - How to reuse query of IN sub query? -

i have below query select a.id, a.user_id, a.approver_id, a.second_approver_id tbl_approve_master user_id in (select id tbl_user name '%john%') or approver_id in (select id tbl_user name '%john%') or second_approver_id in (select id tbl_user name '%john%') how reuse query statement of in ? tried accept answer of how reuse sub query in sql? as with cte (select id tbl_user name '%john%') select a.id, a.user_id, a.approver_id, a.second_approver_id tbl_approve_master user_id in cte or approver_id in cte or second_approver_id in cte but not ok. how can achieve ? try this: select a.id, a.user_id, a.approver_id, a.second_approver_id tbl_approve_master exists ( select * tbl_user u u.name '%john%' , u.id in (a.user_id, a.approver_id, a.second_approver_id) )

scala - Find aggregated sum of repetition spark -

input : name1    name2 arjun       deshwal nikhil       choubey anshul     pandyal arjun       deshwal arjun       deshwal deshwal    arjun code used in scala val df = sqlcontext.read.format("com.databricks.spark.csv") .option("header", "true") .load(file_path) val result = df.groupby("name1", "name2") .agg(count(lit(1)) .alias("cnt")) getting output : nikhil   choubey    1 anshul   pandyal   1 deshwal    arjun    1 arjun    deshwal    3 required output : nikhil     choubey   1 anshul   pandyal    1 deshwal   arjun      4 or nikhil   choubey   1 anshul   pandyal   1 arjun   deshwal   4 i approach using set, not contain order , therefore compares on content of set: scala> val data = array( | ("arjun", "deshwal"), | ("nikhil", "choubey"),

ruby on rails - Failure in create.js file -

i had made create file in view in ruby on rails when trying create showing following error: rendered issue_tracker_accesses/_form.html.erb (21.0ms) rendered issue_tracker_accesses/create.js.erb (24.9ms) completed 200 ok in 46ms (views: 33.1ms | activerecord: 2.6ms) controller code: def create @issue_tracker_access = issuetrackeraccess.new(issue_tracker_access_params) @issue_tracker_accesses = issuetrackeraccess.all respond_to |format| if @issue_tracker_access.save @issue_tracker_access = issuetrackeraccess.new format.js { @flag = true } else flash.now[:alert] = 'access exist.' format.js { @flag = false } end end end you have write create method in controller write creation logic in controller & render create.js.erb fields or data want display. also, need set remote:true in form. follow steps writen in example http://guides.rubyonrails.org/working_with_javascript_in_rails.html#a-simple-example

javascript - How to remove border from stacked column chart in Chartkick - Chart.js -

Image
i using chart.js throug chartkick gem. = column_chart [{"name":"a","data":[["2016-07-01",1],["2016-08-01",0],["2016-09-01",0]]},{"name":"b","data":[["2016-07-01",1],["2016-08-01",0],["2016-09-01",0]]}], xtitle: "date range", ytitle: "counts", stacked: true, height: "600px" i getting following chart: i don't want border around stacked blocks. want set border 0. how can achieve using chartkick gem? i tried adding on page load in application.js. chart.defaults.global.elements.rectangle.borderwidth = 0; but not working.

in jqwidgets jquery framework bootstrap integration is my issue for a dropdown -

in jqwidgets jquery framework bootstrap integration not working..kindly give steps the plugin : <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="jqwidgets/styles/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="jqwidgets/jqwidgets/styles/jqx.base.css" rel="stylesheet" type="text/css" /> <script src="jqwidgets/scripts/jquery-1.11.1.min.js" type="text/javascript"></script> <script src="bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="jqwidgets/scripts/demos.js" type="text/javascript"></script> <script src="jqwidgets/jqwidgets/jqxbuttons.js" type="text/javascript"></script> <script src="jqwidgets/jqwidgets/jqxcore.js" type="text/javascript&quo

android - how to use arrayadapter.getview method -

here defined siteadapter , extends arrayadapter : public class siteadapter extends arrayadapter<site> { private int resourceid; private list<site> sites = null; private context context; public siteadapter(context context, int resource, list<site> objects) { super(context, resource, objects); this.context = context; this.resourceid = resource; this.sites = objects; } @override public site getitem(int position) { return sites.get(position); } @override public int getcount() { return sites.size(); } //get viewpage inflate site_layout.xml file @override public view getview(int position, view convertview, viewgroup parent) { site site = getitem(position); view view = convertview; if (view == null) { layoutinflater vi = (layoutinflater) context.getsystemservice(context.layout_inflater_service); view = vi.inflate(resourceid, null); } //this place need whole widget in site_layout.xml file imageview i1 =

ios - NSPredicate with ANY and "=nil" doesn't work -

this condition works nspredicate *predicate = [nspredicate predicatewithformat: @"any region.beacons.major = %d",rangedbeacon.major.intvalue]; but not nspredicate *predicate = [nspredicate predicatewithformat: @"any region.beacons.minor = nil"]; beacons list inside region object. major , minor have type nsnumber you may try this: nspredicate *predicate = [nspredicate predicatewithformat:@"any region.beacons.minor = $minor"]; predicate = [predicate predicatewithsubstitutionvariables: [nsdictionary dictionarywithobject:[nsnull null] forkey: @"minor"]];

javascript - Dynamic file path in require with webpack? -

this works fine when manually request file using require , moment use exact same request, change string it's split variables fails. this works great: module.exports = (function() { var $svg = require('svg-inline!../../assets/svgs/global/connected.svg'); console.log($svg); }()); however if this: module.exports = (function() { var $path = '../../assets/svgs/global/'; var $svg = require('svg-inline!'+$path+'connected.svg'); console.log($svg); }()); it fails , says inside console: uncaught error: cannot find module "." i guess question why can't concatenate strings have here? i think have webpack context . when try require contains expression, webpack create context. expression treated regular expression , doesn't work may expect.

javascript - Canvas rectangle background image -

i want set background image rectangle in canvas. far i've done this. var img = new image() img.src = //source of image. var newpattern = ctx.createpattern(img, "no-repeat"); ctx.fillstyle = newpattern; and works, problem is, applies image canvas, not rectangle. and whenever change position of rectangle, image remains in same position. can suggest how fix this, image'd attached rectangle. if want draw image within specified rectangle can this. context.rect(x, y, width, height); context.clip(); context.drawimage(img, 0, 0); this creates rectangle @ (x, y) size (width, height) used future calls context. if want stop clipping need add a context.save(); before code above , a context.restore(); after have drawn image. jsfiddle edit: updated rect

javascript - Canvas context drawing frame rate too fast -

i trying display scrolling home screen asteroids game keeps redrawing background until user presses 'enter', after which, execute methods necessary start game. the frame rate normal on home screen, when press enter, game renders, moves fast animation lags , game unplayable. i feel must have 'speed' variable being out of control, have tried resetting it. if remove first call of requestanimationframe , home screen not scroll, (obviously, because 'speed' never increases, background static), game play @ it's normal frame rate. have tried calling this.game.draw(this.ctx, speed) speed 0, no avail. note dim_y , dim_x constants defined out of scope. gameview.prototype.animate = function(time) { speed += 1; if (speed >= 605) { speed = 0; }; if (this.onhomescreen) { console.log("asf") let = this; img.onload = function () { that.ctx.drawimage(img, 0, 0) }; img.src = 'space_background.

java.util.ArrayList cannot be cast to android.os.Parcelable. key expected Parcelable but value was a java.util.ArrayList -

what reason of below error key object_list expected parcelable value java.util.arraylist. default value <null> returned. this full code public class singleobjectactivity extends activity { public static final string object_list = "object_list"; private arraylist<listitem> objects; public imageview imgview; private listitem listobjects; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.singleobject); bundle extras = getintent().getextras(); imgview = (imageview) findviewbyid(r.id.funnyimage); if (extras.containskey(object_list)) { this.listobjects = extras.getparcelable(object_list); } else { this.listobjects = null; } if (listobjects != null) { picasso. with(getapplicationcontext()). load(listobjects.geturl())

java - Jackson JSON Schema generator for Joda date time -

i using jackson json schema module version 2.7.4 generate json schema of classes. in classes, have used joda datetime object. schema object generated it's properties exploded (as shown below). possible convert date_time ? "createddate":{ "type":"object", "id":"urn:jsonschema:org:joda:time:datetime", "properties":{ "weekofweekyear":{ "type":"integer" }, "weekyear":{ "type":"integer" }, "yearofera":{ "type":"integer" }, "secondofday":{ "type":"integer" }, "minuteofday":{ "type":"integer" }, "yearofcentury":{ "type":"integer" }, "centuryof

java - Error loading SQLite file on Tomcat war app -

i trying use , embedded sqlite.db file on tomcat app. working on netbeans , deploying on local server through netbean's play button. far good. however, facing problem when build war file , deploy on raspberry pi tomcat. attach error below. for som reason, same code works locally, won't work on tomcat server installed on raspberry. ideas? thank you! ==== code ==== contextservice.java public class contexservice implements servletcontextlistener { /** * * @param sce */ @override public void contextinitialized(servletcontextevent sce) { system.out.println("== context initialized =="); sqlitetest.getinstance().start(); sqlitetest.getinstance().stop(); } /** * * @param sce */ @override public void contextdestroyed(servletcontextevent sce) { system.out.println("== context destroyed =="); sqlitetest.getinstance().stop(); } } sqlitemanager.