Posts

Showing posts from May, 2012

angularjs - Passing directives to Component in Angular 1.5 -

i'm using angular 1.5 library , wants create component simple text box below. component js 'use strict'; angular .module('components') .component('inputbox', { bindings: { label: '@', name: '@', type: '@', classes: '@', placeholder: '@', maxlength: '@' }, controlleras: 'field', templateurl: 'app/components/inputbox.html' }); component template <input type="{{field.type || 'text'}}" class="form-control {{field.classes}}" id="{{field.name}}" name="{{field.name || 'unnamed'}}" maxlength="{{field.maxlength}}" placeholder="{{field.placeholder}}" /> usage in templates. <input-box label="enter account" n...

mysql - Data model. ¿Pluralize or not pluralize the names of the tables? -

hello everyone. whenever start develop new data model application have same question: is convenient pluralize names of tables? where table stored, example, users; call ' users ' or ' user '? i not pluralize , because data model, generated entities orm , seems more correct instantiate new ' user ' new ' users '. i know think it . greetings all! i guess depends on going use database for: i not pluralize, because data model, generated entities orm , seems more correct instantiate new 'user' new 'users'. but don't give information regarding language use besides sql, framework, tools. i best conform standards of framework or orm, instance in .net entity framework tables generated singular notation , class names map these tables singular well, whereas in ruby on rails activerecord generated pluralized in database mapping classes singular. there no better way think but, if data application ever going m...

c# - .NET Code Contracts - ProjectA.exe cannot find ProjectB.Contracts.dll when both are in same solution -

i have c# solution in vs2013, code contracts extension installed. in solution have application project (projecta) , class library project (projectb). projecta references projectb, , of projectb's public members have contracts associated them. i can access of projectb's members projecta without issue, on 1 property getting filenotfoundexception , message "could not load file or assembly 'projectb.contracts, version=....' or 1 of dependencies." here fusion log has say: === pre-bind state information === log: displayname = [solutionname].projectb.contracts, version=1.0.5953.23121, culture=neutral, publickeytoken=null (fully-specified) log: appbase = [solutiondir]/[solutionname].projecta/bin/debug/ log: initial privatepath = null calling assembly : [solutionname].projectc, version=1.0.5953.23122, culture=neutral, publickeytoken=null. xxx log: bind starts in default load context. log: using application configura...

javascript - EmberJS config prod img src url -

ember : 1.13.6 ember data : 1.13.7 i need able set global property , use inside .hbs files. lets production need serve images server developing locally can severed relative project. <img src="{{imgsrc}}/spinner.gif" alt="loading..."/> how can set global property or config , use inside .hbs files? here able come seems work no idea if it's "good idea". config/environment.js - set configurable imgsrc property envs module.exports = function(environment) { var env = { //... app : { imgsrc: '/prod/path/to/assets/' } //... }; if (environment === 'development') { env.app.imgsrc = 'assets/images/'; } app.js - make imgsrc property available within app import ember 'ember'; import resolver 'ember/resolver'; import loadinitializers 'ember/load-initializers'; import config './config/environment'; var app; //... app = ember.appl...

php - Applying restriction to user -

im working on php-based login system user can upload csv file database. user restricted can upload file 5 times per session , cant upload more.can give me idea best way accomplish this? tq. there few things come mind. 1 have session keep track of how many uploads person has made simple counter. when you're processing file uploaded, first check make sure hadn't uploaded five, , increase count. once reach 5, stop displaying upload form. another option, may unnecessarily complicated purpose (but still practice) keep database record of every file user uploads, details. way, know when last uploaded file, how many had in stretch of time, etc.

JQuery DataTables - Prevent sorting on sortable column -

i have jquery datatable checkbox in 1 of column headings: <table id="vehtbl" class="table table-striped table-bordered"> <thead> <tr> ... <th> <input type="checkbox" id="someid" onchange="tickallboxes()" /> publish </th> </tr> </thead> </table> my datatable initialised this: var table = $("#vehtbl").datatable( { ... "aocolumns": [ ... { "mdataprop": "somename", "fnrender": somefunction, "buserendered": false }, ... ] }); so column sortable. need prevent sort event being fired when checkbox clicked (and tickallboxes fired result). sorting should work on column otherwise. what potentially work bind handler "sort...

php - pyrocms assign count to variable -

i check if last post loop. using pyrocms. problem if using helper:count 2 times not working correctly. how can assign helper:count variable , use later variable. possible? {{ blog:posts limit="5" order-by="title" order-dir="desc" }} {{ if { helper:count mode="subtract" } == blog:all_posts}} <li> <a href="{{ url }}" title="read more about: {{ title }}"> <span class="naslovna_datum_novice">{{ helper:date format="d.m.y" timestamp=created_on }} - </span> {{ title }} </a> </li> {{ elseif { helper:count mode="subtract" } == 5 }} <li> <a href="{{ url }}" title="read more about: {{ title }}"> <span class="naslovna_datum_novice"...

Why are javascript promises asynchronous when calling only synchronous functions? -

in testing i've found javascript promises always asynchronous regardless of whether or not contain asynchronous functions in chain. here code shows order of operations in console. if run see though every function synchronous output shows both of apromise() calls being run in parallel, , "surprisingly happens after run 2 finishes" not happening before run 2 finishes. function apromise() { return new promise(function(resolve, reject) { console.log("making promise a") resolve(bpromise()); console.log("promise resolved") }); } function bpromise() { return new promise(function(resolve, reject) { console.log("making , resolving promise b") resolve(); }); } apromise().then(function() { console.log("finish run 1"); }).then(function() { console.log("surprisingly happens after run 2 finishes"); }); apromise().then(function() { console.log("finish run 2...

list - How can I implement this code in ocaml? -

let rec list_add l = match l [] -> [i] | h::t -> h::(list_add t i) list add adding each pair of integers 2 lists (type) list add : int list -> int list -> int list (description) list add [a; b; c; ...] [x; y; z; ...] returns [a + x; b + y; c + z; ...] . if 1 list longer other, remaining list of elements appended result. (example) list add [1; 2] [3; 4; 5] returns [4; 6; 5] . let rec add l1 l2 = match l1 [] -> l2 |h::t -> (*you can rest*) ;;

c# - How Can i Read a unread SMS on uwp? -

i need help. have code: windows.applicationmodel.chat.chatmessagestore store = await windows.applicationmodel.chat.chatmessagemanager.requeststoreasync(); var msglist = store.getmessagereader(); ireadonlylist<windows.applicationmodel.chat.chatmessage> = await msglist.readbatchasync() and read sms this foreach (var item in a) { system.diagnostics.debug.writeline(item.body); } how can read unread sms? mean read new sms , afterwards change status 'read'. question uwp win 10.. take @ chatmessage class isread property read-only. mean can check message readed. can't set message been readed or unreaded foreach (windows.applicationmodel.chat.chatmessage item in a) { if (item.isread) system.diagnostics.debug.writeline(item.body); }

linux - Finding the Number of strings in a File -

i'm trying write small program check number of sub strings in large text file. count first 2000 lines of text file, find "ttt" sub-strings, count them, , set variable total. i'm bit new shell, amazingly appreciated! #!/bin/bash $counter=(head -2000 [file name] | grep ttt | grep -o ttt | wc -l) echo $counter for it's worth might awk better suited task: awk -f"ttt" '{j=(nf-1)+j}end{print j}' filename this split each record in file delimiter "ttt". counts number of fields, subtracts one, , adds total. a file like: ttt tttttt 1 5 ttt tt 1 more ttt record would split (visualizing pipe delim) like: | || 1 5 | tt 1 more | record counting number of fields per record: 4 2 1 2 subtracting 1 that: 3 1 0 1 which totals 5, how many "ttt" substrings present. to incorporate script (and fixing other issue): #!/bin/bash counter=$(awk -f"ttt" '{j=(nf-1)+j}end{print j}' filename) ech...

asp.net - XDocument: Could not find file 'C:\Program Files (x86)\IIS Express\myfile -

here's code dim doc = xdocument.load("web.sitemap") i'm trying load xml file can manipulate it. i'm getting error saying file cannot found in iis express directory. file located in root directory of project. i've changed copy output directory property copy always , i'm still getting same error. there reason? thanks helping i'm getting error saying file cannot found in iis express directory. yes, because you're loading relative path name, means "relative current working directory"... in case iis. you either embed data within assembly, or use httpserverutility.mappath map relative path 1 within directory containing web site.

web - 3-tier architecture business logic layer without logic -

hello working on school project in making web application. have pretty understanding 3-tier architecture, in business logic layer (bll) have no logic. using of raw data retrieve data access layer (dal) display in presentation layer (pl). in controller classes, i'm calling mapper facade classes methods without doing further. question is: is right way it, know dal must never speak directly pl , vise versa, or should call controllers else more describing? furthermore have made controller class each entity, if have methods in between 2 entities meaning access both entity classes. it pretty rare in real application database maps 1-1 presentation layer. there normalization sql databases, or denormalization nosql dbs. also, business layer needs user identity security , such doesn't map directly database representation. the last point made single controller knowing 2 entities fine. why not directly using entities in presentation layer. can mash entities ui can m...

javascript - Consume crossdomain WebAPI with Jquery -

i'm trying consume mongolab webapi jquery v1.9 $.ajax this $.ajax({ url: "https://api.mongolab.com/api/1/databases/my-db/collections/my-coll?apikey=myapikey", type: "get", contenttype: "application/json" }); and thought crossdomain request, , contenttype should application/javascript , datatype should jsonp , surprisingly, return json result contenttype 'application/json' . i'm quite confuse if jquery encapsulate ajax call , automatically call server application/javascript . could give me explanation although may looks rookie question? when try run code in safari jsfiddle.net, get: failed load resource: origin http://fiddle.jshell.net not allowed access-control-allow-origin. this means safari asked api.mongolab.com if fiddle.jshell.net allowed access via ajax call, , mongolab.com either did not respond or responded "no, don't allow it". perhaps if domain name localhost or if registered mongolab...

.net - Difference between datacontext and normal object creation in C# -

i have seen video @ different windows, presenter follows different styles. for instance: in 1 window, uses below: employeeviewmodel evm = (employeeviewmodel)this.datacontext; evm.display(); in another, uses like: employeeviewmodel evm = new employeeviewmodel(); evm.display(); whats difference technically , best way use ? please me understand difference. the first code fragment retrieves displayed viewmodel. (it should null-check) the second code fragment creates new instance of viewmodel. because not clear display() does, hard explain difference between effect of 2 fragments second fragment (unit)test of viewmodel ignores view. there no best way far can see because both fragments serve different purpose.

How do I write this equation in Python? -

Image
i don't know how write correctly. how tried: def is_cardano_triplet(a, b, c): f = lambda x: x ** 1. / 2 g = lambda x: x ** 1. / 3 return g(a + b*f(c)) + g(a - b*f(c)) == 1 print is_cardano_triplet(2,1,5) # should true i should true 2, 1, 5 , i'm not. what's wrong function? doing bit of research and calculations, solving equation variable c , i found out that and therefore now, due floating point arithmetic being imprecise on binary-based systems known reasons , first formula pretty hard compute precisely. however, the second 1 easier compute without floating point precision errors since doesn't involve irrational functions , a , b , c integers. here's smart solution: def is_cardano_triplet(a, b, c): return (a + 1)**2 * (8*a - 1) - 27*b**2*c == 0 >>> is_cardano_triplet(2, 1, 5) true

entity framework - ASP.NET Core 1 EF - migrations update to latest -

Image
i have 2 migrations in asp.net core 1 mvc project follows: the v1 migration initial migration 1 table, restaurants. i added v2 migration now, after added asp.net identity project, , want update db latest migration, getting error table exists. the restaurant table exist, thought drop-create , add new tables well. none of new tables exist. used following commands create: dnx ef migrations add v2 , update: dnx ef database update , tried specifying v2 keeps trying migrate initial version only. how second migration update existing database? update: added third migration, deleted database , reran update migrations command - time v1 , v2 ran, v3 did not. gives? you need check "dbo.__migrationhistory" table if exists there in database. if not there, delete existing migrations. add new migration , update database. create , sync database model. if deleting database delete existing migrations. , add new migration. still facing same issue open migration c...

android - Camera.open() occur error (using MediaRecorder) -

Image
my action flow: camera.open() camera.unlock() recorder = new mediarecorder(); recorder.setcamera(), , then.. more setting. (click start button) recorder.start() (click stop button) recorder.stop() recorder.release() recorder = null; (save recorded video file) camera.open() <= occur error step 9 recording again more video. but, step occur error. it's logcat : it's source : public class talk extends activity implements surfaceholder.callback{ context context; surfaceview sfv_preview; progressbar progressbar; private surfaceholder holder; private mediarecorder recorder = null; camera camera; boolean recording = false; private static final string output_file = "/sdcard/vitalk/temp.mp4"; private static final string output_file_name = "temp.mp4"; private static final int recording_time = 10000; //uri fileuri; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); ...

python - Mask minimum values in matrix rows -

i have 3x3 matrix: a=array([[ 1, 11, 5], [ 3, 9, 9], [ 5, 7, -3]]) i need mask minimum values in each row in order calculate mean of each row discarding minimum values. there general solution? have tried a_masked=np.ma.masked_where(a==np.ma.min(a,axis=1),a) which masks minimum value in first , third row, not second row? i appreciate help. thanks! the issue because comparison a == a.min(axis=1) comparing each column minimum value of each row rather comparing each row minimum values. because a.min(axis=1) returns vector rather matrix behaves nx1 array. such, when broadcasting, == operator performs operation in column-wise fashion match dimensions. a == a.min(axis=1) # array([[ true, false, false], # [false, false, false], # [false, false, true]], dtype=bool) one potential way fix resize result of a.min(axis=1) column vector (e.g. 3 x 1 2d array). a == np.resize(a.min(axis=1), [a.shape[0],1]) # array([[ true, false, false], #...

android - How to automatically load data from json file on startup with kivy -

i making android app python , kivy keeps track of diabetes entries , has basic profile page. figured out how save input textinput widgets json file works fine. cannot figure out how automatically load information textinput widets on startup. loading labels work sloppier. know there on_start module, have no idea how use it. suggestions appreciated. .kv file <phone>: result: _result h: _h w: _w n: name_input g: gender_input t: _type ti: _times m: _meds anchorlayout: anchor_x: 'center' anchor_y: 'top' screenmanager: size_hint: 1, .9 id: _screen_manager screen: name: 'home' canvas.before: rectangle: pos: self.pos size: self.size source: "/home/aaron/desktop/main.png" label: markup: true text: '[size=100][color=ff3333]welcome [color=ff3333]diabetes manage...

opencv - How do I successfully convert a 32b image to 8b? -

i have input image of type cv_32uc3 rgb mat convert cv_8uc3. have tried using convertto method follows: img.convertto(dst, cv_8uc3, 0.00390625) however, resulting image black. my question is, how convert 32b 3 channel image 8b? i believe scale backwards. if want scale floating point image (0-1 values) 8 bit need use 255 scale factor.

javascript - Get the files chosen using the input type file (multiple) and store them in an array -

in html select multiple files. <input type="file" id="img" multiple> i want store each element in array can print file source. i have done in javascript not work. function loadfiles() { var x=document.getelementbyid("img"); (var i=0;i<x.length;i++) { document.write(x.elements[i].src); } } the property files gets array of files selected file input. loadfiles function should modified following: function loadfiles() { var imagefiles = document.getelementbyid("img"), fileslength = imagefiles.files.length; (var = 0; < fileslength; i++) { document.write(imagefiles.files[i].name); } }

Rails - Pass multiple checkbox values through params -

i using smart listing gem real time filtering. following simple form without submit , url. <%= smart_listing_controls_for(:search) %> <%= simple_form_for :search |f| %> <%= f.input :certificates, collection: certificate.all, :as => :check_boxes, include_hidden: false, :input_html => {:multiple => true} %> <% end> <% end> the above code generates multiple check-boxes 'certificate id's values. 1 of check-boxes checked, smart listing sends request controller params. parameters: {"utf8"=>"✓", "search_smart_listing"=>{"_"=>"1", "page"=>"", "per_page"=>"10"}, "authenticity_token"=>"z25rulu5jeewcezdpsy0+bz7ojfdwpmxrvgnzpvdg0cjm0ufpc3ydb9+5gywdqkumcm6rgjnf0c4yrd0swpj6g==", "search"=>{ "certificates"=>["6"]}} the problem when select multiple check-boxes, certificates...

adal - Azure B2C - Failed to acquire token silently -

i'm building application asp.net mvc , webapi using template : azure ad b2c webapp / wepapi . i've configured azure b2c ad through web.config files , when click "sign in" see identity providers. login works far (i see username on top right corner) , i'm able execute "to-do list"-action. but stop debugger , restart application pressing f5, error when click on "to-do list"-action again. failed acquire token silently. call method acquiretoken text --> code this happens, cause user still authenticated, naivesessioncache empty after applications restart. possible solution be, store token in onauthorizationcodereceived handler, looks little bit weird me private async task onauthorizationcodereceived(authorizationcodereceivednotification notification) { string userobjectid = notification.authenticationticket.identity.findfirst("http://schemas.microsoft.com/identity/claims/objectidentifier").value; st...

c# - How to insert comment in xml generated by serializer? -

this question has answer here: how write comment xml file when using xmlserializer? 3 answers i have class, example: public class myclass public property myproperty integer = 1 end class serializer (xml.serialization.xmlserializer) creates xml: <?xml version="1.0" encoding="utf-8"?> <myclass xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema"> <myproperty>1</myproperty> </myclass> how can serializer somthing this: <?xml version="1.0" encoding="utf-8"?> <myclass xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema"> <!-- use positive values less 10 --> <myproperty>1</myproperty> </myclass> thanks! t...

amazon web services - dynamodb table design for SET like scenario -

moving rdbms , not sure how best design below scenario i have table around 200,000 questions question id partition key. users view questions , not wish show viewed question again user. 1 better option? have table question id partition key , set of user ids attribute have table user id partition key , set of question ids have viewed attribute have table question id partition key , user id sort key. once user has viewed question, add row table 1 , 2 might have problem 400 kb size limit item. third seems better option though end 100 million items there 1 row per user per question viewed. assume not problem dynamo? another problem how 10 random questions not viewed user. generate 10 random numbers between 1 , 200,000 (the number of questions) , check if not in table mentioned in point 3 above? i not go option 1 or 2 reason mentioned: limiting scalability 400kb limit. uuid of 128 bits, limited 250 users per question. option 3 way go dynamodb, need consider part...

python - Retrieve files with date between date1 and date2 -

problem: retrieve files particular "path" satisfy below criteria: should file date falls in between 'startdate' , 'enddate' example: fetch(path,startdate,enddate): path-> path of directory startdate-> date listed in ls (jun 27) enddate-> date listed in ls and also, not able store o/p of 'ls -lrt' check particular pattern. can me !!! this function might you: from datetime import datetime os import path glob import glob time import time current_time def get_files(pattern, start=0, end=none): """ returns list of files in pattern files creation date between start , end pattern = pattern retrieve files using glob start = start date in seconds since epoch (default: 0) end = end date in seconds since epoch (default: now) """ start = datetime.fromtimestamp(start) end = datetime.fromtimestamp(current_time() if end none else end) result = [] file_path ...

javascript - Show all filter on Aurelia value converter -

at moment app displays exercises , filters them muscle group using select option. i'm struggling understand how display of them. as app loaded filtered muscle group, or if filtered value of 'all' doesn't display not specified muscle group in json. organised in following way: select option call filter (muscle filters array off muscle groups) <div class="form-group"> <label for="muscle">show:</label> <select id="muscle" ref="muscle"> <option value="all">all</option> <option repeat.for="muscle of musclefilters" value.bind="muscle">${muscle}</option> </select> </div> display <div class="col-sm-6 col-md-3" repeat.for="exercise of exercises | sortmuscle:muscle.value"> ${exercise.title} </div> sorting function export class sortmusclevalueconverter { toview(array, propertynam...

java - How to Parse this json object nested in json array -

i using code private void parsedata(jsonarray array){ log.d(tag, "parsing array"); for(int = 0; i<array.length(); i++) { bookitems bookitem = new bookitems(); jsonobject jsonobject = null; try { jsonobject = array.getjsonobject(i); jsonobject bookchapter = jsonobject.getjsonobject("chapter"); bookitem.setbook_subtitle(bookchapter.getstring("subtitle")); jsonobject chapverses = jsonobject.getjsonobject("verses"); jsonarray versereaders = chapverses.getjsonarray("readers"); jsonobject readersnum = versereaders.getjsonobject("number"); versereadnum = readersnum; } catch (jsonexception w) { w.printstacktrace(); } mbookitemslist.add(bookitem); } } to parse json. [ { "chapter...

python - Accessing SQLAlchemy table column names with variables -

i have dictionary of sort {'category_id': 'women_shoes', 'product_id': 486778462l} here category_id table name in mysql database. trying specified product_id table women_shoes. able achieve through code class_name = globals()[each_itemset["category_id"].capitalize()] table_values = session.query(class_name).filter(class_name.product_id == each_itemset["product_id"]) each in table_values: print each.brand_name name = "brand_name" up til here things work fine , able brand_name of product. want instead of giving statement print each.brand_name i want name = "brand_name" print each.name because don't want specify exact table name myself. want table column names class_name. table .columns.keys(), , iterate on each column name , supply name 1 one. i following error when this traceback (most recent call last): file "main_site.py", line 14, in <module...

Using enums correctly -

wondering why can't use following code. enum player_state { fast, slow, focus, bust, out}; if (score >= 100) player_state = fast; else if (score > 50) player_state = slow; else if ((score <= 50) && (score > 1)) player_state = focus; else if ((score == 1) || (score < 0)) player_state = bust; else player_state = out; i error @ assignment's (=). any tips? thought this, if not this. an enum type declaration. have make variable uses type. instance enum player_states { fast, slow, focus, bust, out}; player_states playerstate = fast;

google apps script - BigQuery Functions Not Working -

the bigquery functions in our apps script had been working fine along 18/06/2013 onwards setprojectid() , setquery() , other bigquery functions have stopped working. on using these functions, variables remain undefined when should ideally populated. a small sample script reproduces issue: var newjobreference = bigquery.newjobreference().setprojectid(yourprojectid); var jobconfig = bigquery.newjobconfiguration().setquery(yourjobqueryconfiguration); anyone facing same issue? might causing this? issue resolved when use: var newjobreference = bigquery.newjobreference(); newjobreference.setprojectid(yourprojectid); instead of: var newjobreference = bigquery.newjobreference().setprojectid(yourprojectid);

How to use the cookie got from Javascript's document.cookie in Ruby mechanize? -

i'm automate login process using ruby mechanize. because it's complex recreate process in mechanize, choose use existing cookies grabbed browser document.cookie . want know how can use string in ruby mechanize. thanks. i dont think mechanize runs javascript, you'll have use selenium that. with selenium, can run arbitrary scripts. example: driver = selenium::webdriver.for :firefox driver.get("http://some.url") driver.execute_script("console.log('javascript')") driver.close

java - Clicking an ImageButton to change to a different image everytime -

i have imagebutton , false appears gray image , while true appears green image . if use state_pressed="true" , state_pressed="false" function work, need hold left-click button button change true . p.s: believe using wrong state have tried others didn't work. my question is : how keep image true clicking once on imagebutton ? code: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/green_clock" android:state_selected= "true"> </item> <item android:drawable="@drawable/grey_clock" android:state_selected="false"> </item> </selector> java file: public void onclickclock(view v) { imagebutton clockbtn = (imagebutton)findviewbyid(r.id.clock); clockbtn.setimageresource(r.drawable.clock); } activity.xml: <imagebutton and...

ios - dynamically created method not being called -

after dynamically creating method in appdelegate using class_addmethod class, never gets called when should. the method create on runtime is: -(bool)application:(uiapplication *)application openurl:(nsurl *)url { //do something... return yes; } the code used create previous method dynamically is: { uiapplication* app = [[uiapplication sharedapplication] delegate]; class_addmethod([app class], @selector(application:openurl:), (imp)mymethodimp, @"b@:"); } along imp function: bool mymethodimp(id self, sel _cmd, uiapplication *application, nsurl *url) { [self application: application openurl:url]; //do something... return yes; } i have verified indeed created on app delegate using class_getinstancemethod method am missing something? @bbum right, uiapplication cache delegate dones not respond method, can this @interface uiapplication (mbshare) @end @implementation uiapplication (...

c# - IQueryable.Distinct() vs List.Distinct() -

i have linq query using distinct() on. if call distinct() without converting list not return distinct list - still contains duplicates. however if convert list , then call distinct() - works expected , unique objects. i'm using telerik orm , objects being returned class representing 1 of tables in database. var uniqueusers = (from u in database.users select u).distinct(); the code above not produce distinct results, when convert list , call distinct - does: var uniqueusers = (from u in database.users select u).tolist().distinct(); i suspect has collection before being converted list, comparing references objects rather object data not understand going on - why fist code example not produce unique results , happens collection when using .tolist() makes work? [edit] i've simplified above queries, in real world query has several joins generates non-unique results, returning user objects. i tried overriding equals ...

html - Css Dropdown Button in a navbar -

okay i'm trying learn css , i'm trying insert dropdown button in navbar. what's happening when hover button whole navbar expanding instead of content of button. doing wrong? thanks! ul { list-style-type: none; margin-left:8%; margin-right: 8%; padding-left: 0; padding-right: 0; overflow: hidden; background-color: #f3f3f3; } .right{ float: right; } li { float: left; display: block; color: #6f6f6f; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover { background-color: #e0e0e0; } p { color: red; margin-left: 8%; margin-right: 8%; } body{ font-family:arial; background-color:#f9f9f9; } .dropbtn { background-color: #f3f3f3; color: #6f6f6f; padding: 14px 16px; font-size: 16px; border: none; cursor: pointer; } /* container <div> - needed position dropdown content */ .dropdown { position: relative; display: block; } /* drop...

Android TextView Multiline Formatting -

Image
these 2 line logcat strings formatted string.fortmat() 04-19 13:57:44.918 26962-26962/ts.kiosk.app.checkout e/java.lang.stacktraceelement: "tendered amount: rs. 0.00" 04-19 13:57:44.919 26962-26962/ts.kiosk.app.checkout e/java.lang.stacktraceelement: "change due: rs. 0.00" you can see both line same exact length in text view string not formatted be: string.format("%-25s rs. %2$8.2f", "tendered amount:", formatcentstocurrency(checkoutbasket.tenderedamount)); string.format("%-25s rs. %2$8.2f", "change due:", formatcentstocurrency(checkoutbasket.changedue)); so how aligned in textview: "tendered amount: rs. 0.00" "change due: rs. 0.00" i'm thinking textview messing formatting somewhow: <textview android:id="@+id/text_receipt"...

php - How to capture exact text input in textarea and display it in a table? -

Image
i creating programming forum , having trouble containing retrieved text database. textarea looks this <textarea name = "posttext" style = "width: 90%; height:480px; resize:none; direction: ltr; unicode-bidi: bidi-override;text-align:left;"required> </textarea> unicode-bidi: bidi-override captures code how entered can not make word-wrap function correctly when using them both. first question how can capture exact text in textarea , and display in table. td tag looks this <td style = "margin:0 auto; text-align:left;"><pre>'.htmlspecialchars($post_).'</pre></td> the pre tag displays text how entered not wrap correctly , overflows container. how capture exact text input in textarea , display in table? i'd recommend storing store (just insert table is), , when display text got database, output this: <td style = "margin:0 auto; text-align:left;">'.nl2br($post_).'<...

python - SQLAlchemy ORM Event hook for attribute persisted -

i working on finding way in sqlalchemy events call external api upon attribute gets updated , persisted database. here context: an user model attribute named birthday . when instance of user model gets updated , saved, want call external api update user's birthday accordingly. i've tried attribute events , however, generates many hits , there no way guarantee set / remove attribute event persisted (auto commit set false , transaction gets rolled when errors occurred.) session events not work either because requires session/sessionfactory parameter , there many places in code based sessions have been used. i have been looking @ possible sqlalchemy orm event hooks in official documentation couldn't find 1 of them satisfy requirement. i wonder if else has insight how implement kind of combination event trigger in sqlalchemy. thanks. you can combining multiple events. specific events need use depend on particular application, basic idea this: ...