Posts

Showing posts from March, 2013

javascript - 3D carousel not working -HTML CSS3 -

Image
i new css3 , trying implement simple 3d carousel. don't understand why it's not working should be. kindly me this. here screenshot of page, html, css, javascript files : var init= function(){ console.log("init function"); var carousel=document.getelementbyid('carousel'), navbuttons=document.queryselectorall('nav button'), panelcount=carousel.children.length, transformprop=modernizr.prefixed('transform'), theta=0, onnavbuttonclick=function(event){ var increment=parseint(event.target.getattribute('data-increment')); theta +=(360/panelcount)*increment* -1; carousel.style[transformprop] ='translatez(-288px) rotatey('+theta+');'; console.log(panelcount); console.log(increment); console.log(theta); console.log(carousel.style); console.log("inside button click"); }; for (var = 0; < 2; i++) { navbuttons[i].addeventlistener('click',onnavbuttonclick,fa

sql server - C# Excel Object reference not set to an instance of an object -

i know there many questions object reference not set instance of object question different gives same error i running script in ssis package inside script task builds , complies fine when ran through visual studio 2013 professional both local or on server (where package deployed). but when run sql job package fails , in log file writes following error formatting file method started.. error occurred ..please see error message :object reference not set instance of object. i unable understand why on server builds when ran in visual studio fails in sql job? using system; using system.data; using microsoft.sqlserver.dts.runtime; using system.windows.forms; using system.io; using system.text; using system.data.sqlclient; using system.diagnostics; using system.reflection; using excel = microsoft.office.interop.excel; using microsoft.csharp; public void formatfile(string sfilename) { microsoft.office.interop.excel.application objexcelapp = new excel

go - Golang project structure in an application versus a package -

my organization uses rails develop app i'm attempting re-write 1 of our back-end processes in golang because it's quicker. i've structure application our company namespace app ( example.co ), , subfolder each of packages within app. each library i've included (e.g. sqlx , etc...) has it's own folder. src/ github.com/ jmoiron/ (sqlx package files) example.co my_app/ (my app package files) model/ (model package files...) however looking @ other packages sqlx , appears scrap directory structure entirely , put files in root directory is because i'm writing application , sqlx package that's meant included in other applications? or difference in preference since there's no real accepted "standard" i did on first project. have since learned: the $gopath/bin/ pkg/ src/ layout constructed go get , similar commands you can organize .go files single flat project dir or subfolders (caveat: .go

java - Using one to many relation in AdditionalCriteria -

entities: post, space , profile. in summary: class post { space space; string text; } class space { list<profile> members; } class profile { string username; list<space> spaces; } how set @additionalcriteria on post return posts belongs spaces current user member of. what have tried far below. #1 - :currentuserprofile in space.members @additionalcriteria(":currentuserprofile in (this.space.members)") profile profile = new profile(); em.setproperty("currentuserprofile", profile); results in: exception [eclipselink-6015] (eclipse persistence services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.queryexception exception description: invalid query key [space] in expression. query: readobjectquery(name="readpost" referenceclass=post ) #2 - :currentuserprofile member of space.members @additionalcriteria(":currentuserprofile member of this.space.members") profile profile = new profile(); em.setpr

Starting Redis on Windows failing -

i'm trying start redis on windows 10. when run redis-server.exe following message though: c:\program files\redis>redis-server.exe [4680] 01 jun 19:57:30.844 # windows version of redis allocates memory mapped heap sharing forked process used persistence operations. in order share memory, windows allocates system paging file portion equal size of redis heap. @ time there insufficient contiguous free space available in system paging file operation (windows error 0x5af). work around may either increase size of system paging file, or decrease size of redis heap --maxheap flag. reboot defragment system paging file sufficiently operation complete successfully. please see documentation included binary distributions more details on --maxheap flag. redis can not continue. exiting. i've tried adding --maxheap value, causes application crash , print out crash dump: c:\program files\redis>redis-server.exe --maxheap 150 [6728] 01 jun 19:57:41.063 # === redis bug report

angular - angular2 submit form by pressing enter without submit button -

is possible submit form not have submit button (by pressing enter) example : <form [ngformmodel]="xxx" (ngsubmit)="xxxx()"> <input [(ngmodel)]="lxxr" ngcontrol="xxxxx"/> </form maybe add keypress or keydown input fields , assign event function submit when enter clicked your template this <form (keydown)="keydownfunction($event)"> <input type="text" /> </form and function inside class this keydownfunction(event) { if(event.keycode == 13) { alert('you clicked enter'); // rest of code } }

javascript - Hidden a list when user select a item in emberjs 2 -

i'm need show list in route , after user selected item show item nested route. example. inside /locals - show list of locals locals/:id - here show local details , hide local list. how in emberjs 2? nested route don't work how expected. you'll use index route underneath locals route, , show list in index route, , redirect individual local route when select local . |locals |____index |____local

Does jQuery work with AJAX created elements in a form? -

i've made form of elements added using ajax (post). press button add elements generated php page. the jquery validation ( https://jqueryvalidation.org/ ) doesn't work on elements have been added using ajax. i've tested page replacing ajax elements regular elements in page , works fine, think it's ajax. here's jquery: $("#editeventformnew").validate ( { rules: { artwork: { filesize: 2097152 }, name: { required: true, minlength: 2, maxlength: 50 }, desc: { required: true, minlength: 2, maxlength: 3000 }, venue2: { required: true }, stadate: { required: true, //greaterthan: "datehigherthantoday" }, enddate: { required: true, greaterthan: "#stadate3" }, cutdate: { required: true, lessthan: &qu

sql server - How to calculate percentages in tsql using a group by query? -

i have table lists results sport , start , end dates , win/loss result. need calculate percentage of wins per sport per season_start. table: table1 ****** id sport won playerid season_start season_end updated_date --- ----- ---- -------- ------------ ------------ ------------ 1 rugby y kato23 2016-01-01 2016-01-31 2016-02-01 2 rugby y king54 2016-01-01 2016-01-31 2016-02-01 3 rugby n robby1 2016-03-01 2016-03-28 2016-04-01 4 rugby y kelly2 2016-03-01 2016-03-28 2016-04-01 5 soccer y kato23 2016-01-01 2016-01-31 2016-02-01 6 soccer y jeri44 2016-01-01 2016-01-31 2016-02-01 7 soccer n matt24 2016-06-01 2016-06-30 2016-07-01 8 tennis y kray43 2016-01-01 2016-01-31 2016-02-01 9 tennis y jeri44 2016-01-01 2016-01-31 2016-02-01 10 tennis n jeri44 2016-01-01 2016-01-

c++ - QThread communicate threadsafe -

i know it's not allowed call function of thread in mainthread. allowed call signal form thread without problems? lets code in mainwindow: thread->movetothread(obj); emit obj->signal(); thank you or way go: obj.h signals: void testsignal(); public slots: void func(); mainwindow.h void testsignal(); mainwindow.cpp thread->movetothread(obj); connect(this,signal(testsignal()),obj,signal(testsignal())); emit testsignal(); obj.cpp connect(this,signa(testsignal()),this,slot(func())); yes! signal can called thread long use default automatic connection signal. such slots/functors execute in context object's thread. can emit signals callbacks 3rd party libraries, example, if these libraries don't use qt. warning : explicitly directly connected slots/functors execute in thread signal invoked.

audio mapping in ffmpeg -

i have video file audio in 1 channel, left. i'd use ffmpeg -map_channel option map audio appears in both l&r channels. what ffmpeg command like? ffmpeg -i input.mov -c:v copy -c:a copy -map_channel 0.1.0 -map_channel 0.1.0 output.mov isn't working. audio still in left channel only. remove -c:a copy . -map_channel way of using pan filter , can't stream copy ( -c:a copy ) , filter @ same time. if want use pan instead: ffmpeg -i input -filter_complex "pan=stereo|fl=c0:fr=c0" -c:v copy output

android - Putting an AdMob native ad in a listView -

i'd use new admob native ad functionality in app. want put native ad within listview, every 20th item or in list ad. possible achieve native express ad? or have use natve advanced ad? well @jagjit has shown right approach. write step step 1. create own custom adapter (by extending baseadapter ) shown listview items 2. create layout resource file showing native ad (design should similar custom adapter created in above step) 3. in getview method follows (for showing ad @ 2nd position) if (position == 1) { rowview = inflater.inflate(r.layout.native_ad_adapter, null); nativeexpressadview adview = (nativeexpressadview)rowview.findviewbyid(r.id.adview); adrequest adrequest = new adrequest.builder().build(); adview.loadad(adrequest); } else { rowview = inflater.inflate(r.layout.my_custom_list, null); textview bigtxt = (textview) rowview.findviewbyid(r.id.txt1); ... ... } here custom adapter my_custom_list see ads loading. there small

html - Javascript - Click outside of element using event.target not working -

this question has answer here: javascript detect click event outside of div 8 answers i have a pop menu has close button works fine. i'm trying close menu when user clicks outside of box too. i have tried using if statement inside closemenu() checks if event.target wasn't button element doesn't seem work. any ideas or direction appreciated. var button = document.createelement('div'); button.classname = "doorselector--familyoption"; var event_func = (parent == null) ? this.closemenu.bind(this, close_container) : this.createmenuoptions.bind(this, parent, null); button.addeventlistener('click', event_func); menu.prototype.closemenu = function(container, event) { event.preventdefault(); event.stoppropagation(); container.classlist.remove('show'); }; the full code can seen here if needed. thanks

visual studio - How can i get my C# application on another computer? -

i have created small c# application on home computer using visual studio 2015 , id use small application on computer @ work. can point me tutorial/video me accomplish this? thanks. offtopic or not. imagine might problem start using programming language. @quantic mentions quickest way copy folder ./release or ./debug computer of choise. can use oneclick https://msdn.microsoft.com/en-us/library/31kztyey.aspx

assembly - x86 Strange printing after console has been scrolled -

i have following function: printrows proc mov cx, 25 printrowsloop: mov si, 0 printsinglerowloop: mov ah, 3 ;save current cursor position @ dx (dh:dl) int 10h push dx ;keep position later mov ah, 2 mov dl, '&' int 21h ; print '&' char in current curser position pop dx ; restore dx add dl, 5 ; increase column of const number (so square) mov ah, 2 int 10h inc si cmp si, 3 ; print 3 '&' in each row jne printsinglerowloop mov dl, 13 ; result of these 3 groups of commands should 2 new lines mov ah, 2 int 21h mov dl, 10 ;mov ah, 2 ; ah alredy 2 int 21h ;mov dl, 10 ; dl 10 ;mov ah,2 ; ah 2 int 21h loop printrowsloop ; print (cx) lines ret printrows endp the

javascript - Getting stuck in a loop on .change - Select2 Drop Down Lists -

i have 2 drop down lists. 1 people , 1 businesses. if select person list automatically query database , select correct corresponding business associated person. if select business, automatically query database people associated company. clears current list of people , appends associated people. this works great...until wanted use select2 make drop down lists searchable. stuck in infinite loop because select2 uses .val().trigger('change') method select value want. when that's triggered triggers .change function runs queries , populates fields. what can fix this? here code: $('#personnamefield').select2(); $('#businessnamefield').select2(); /* when business selected pulls associated customers , puts them customer name drop down list */ $("#businessnamefield").change(function getassociatedpeople() { var sitepath = sitepath.sitepath; var business_id = $("#businessnamefield").val(); if (business_id == 'choose compa

php - Need to change the routes on every route used in an app but don't want use to find/replace -

i'm working on modifying web-app.i not part of original development team (the ones made app), donated us. bureaucracy reasons cannot make virtual host on server (the server ubuntu server (v15.*) using apache2) , bind subdomain (specially because don't own server on app runs). reason need make app run on folder within webroot folder (/var/www in case). problem this: completely , abosolutly routes used in app's code made assuming put directly in webroot directory example: include 'includes/header.phhp'; include_once 'includes/encode.php'; that in php. involves html sources like: <link rel='icon' href="imagenes/favicon.png" type="image/png" /> and inside javascript code: url: '/js/reservas/src/php/wizardsubmit.php', as expected server try find resources within root directory so: http:address.com/imagenes/favicon.png (using html image source shown above) , fail so, because there intermediate director

c# - DateTime.Now inside object initialiser -

if do: var foo = new foo { created = datetime.now, modified = datetime.now }; is there chance compiler optimisation going on ensures 2 date properties equal, or must read now temporary variable first myself? the compiler not supposed omit datetime.now , regardless of optimization. ensure fields initialized same value, consider this: struct foo { public datetime created; public datetime modified; public foo(datetime dt) { created = modified = dt; } } var foo = new foo(datetime.now); the probability created != modified , if initialized separately, rather high. following loops on system (in debug , release ) never makes more few sousand iterations. for (int = 0; < 1000000000; i++) { var foo = new foo { created = datetime.now, modified = datetime.now }; if (foo.created != foo.modified) { console.writeline("{0} {1} {2}", foo.created.ticks, foo.modified.ticks, i); br

c# - Is it possible to create an interface this general? -

i'm going creating lot of classes like public static class m2sa { // median of 2 sorted arrays public static int method ( int[] a, int[] b ) { int m = a.length, n = b.length; if((m | n) == 0) throw new argumentexception("a , b cannot both empty"); int = 0, j = 0, k = (m + n)/2; while((i + j) < k) { if(i == m) ++j; else if(j == n || a[i] <= b[j]) ++i; else ++j; } if(i == m) return b[j]; else if(j == n) return a[i]; else return math.min(a[i],b[j]); } public static int alternative ( int[] a, int[] b ) { if ((a.length | b.length) == 0) throw new argumentexception("a , b cannot both empty"); int[] mergedandsorted = a.concat(b).orderby(x => x).toarray(); return mergedandsorted[mergedandsorted.length / 2]; } public static bool test () { return false;//p

c# - TDD nUnit multiple asserts for one method -

using tdd first time in life today. using nunit. i have 1 method, can insert multiple different inputs , check if result works. i read multiple asserts in 1 test not problem, , don't want write new test each input. example multiple asserts: [testfixture] public class testclass { public program test; [setup] public void init() { test = new program(); } [test] public void parse_simplevalues_calculated() { assert.areequal(25, test.parsecalculationstring("5*5")); assert.areequal(125, test.parsecalculationstring("5*5*5")); assert.areequal(10, test.parsecalculationstring("5+5")); assert.areequal(15, test.parsecalculationstring("5+5+5")); assert.areequal(50, test.parsecalculationstring("5*5+5*5")); assert.areequal(3, test.parsecalculationstring("5-1*2")); assert.areequal(7, test.parsecalculationstring("7+1-1&quo

jquery - can someone help me find the error making a slider not slide? -

this code slider on www.croquetero.com slider not sliding of sudden. working code , not. appreciate me pinpoint problem {{ 'nivodefault.css' | asset_url | stylesheet_tag }} {{ 'nivo-slider.css' | asset_url | stylesheet_tag }} <div id="wrapper"> <div class="slider-wrapper theme-default"> <div id="slider" class="nivoslider"> <a href="http://croquetero.com/pages/hot-sale"><img src="//cdn.shopify.com/s/files/1/0740/0383/files/banner-hot-sale-web_1024x1024.png?12813352639418963988" alt="hot sale" /></a> <a href="http://croquetero.com/pages/programa-y-ahorra?utm_source=homepage&utm_medium=banner&utm_campaign=bannerprogramayahorra280116"><img src="//cdn.shopify.com/s/files/1/0740/0383/files/programayahorrahome_1.png?10630346986431682724" alt="vive la experiencia programa y ahorra"/></a> </div

heroku - Rails Paperclip S3 hide url of attached file -

i using paperclip upload files directly aws s3 (following guide: https://devcenter.heroku.com/articles/paperclip-s3 ). as shown below, user can view file in browser using "attachment.file.url" method. security vulnerability display s3 url user? if so, there way hide url without streaming file app first or "download_file" controller action? production.rb rails.application.configure config.paperclip_defaults = { storage: :s3, s3_credentials: { bucket: env.fetch('s3_bucket_name'), access_key_id: env.fetch('aws_access_key_id'), secret_access_key: env.fetch('aws_secret_access_key'), s3_region: env.fetch('aws_region'), } } end attachment.rb class attachment < activerecord::base belongs_to :upload, polymorphic: true has_attached_file :file validates_attachment :file, content_type: { content_type: ["image/jpeg", "image/gif", "image/png", "applic

reactjs - Confusion after setting a property of a Map -

i'm reading , practicing tutorial: http://teropa.info/blog/2015/09/10/full-stack-redux-tutorial.html couldn't reducer tests passed. made new test find out reason. here's test.js(mocha chai): import {expect} 'chai'; import {list, map, fromjs} 'immutable'; describe('set', () => { it('sets map\'s property', () => { const state = map(); const action = {type: 'set_entries', entries: ['trainspotting']}; const nextstate = state.set('entries', action.entries); /* expect(nextstate).to.equal(map({ entries: ['trainspotting'] })); */ expect(nextstate).to.equal(fromjs({ entries: ['trainspotting'] })); }); }); either use map or fromjs, test doesn't pass if choose "map", shows: assertionerror: expected 'map { "entries": trainspotting }' equal 'map { "entries": trainspotting }' + expected

c# - How to sort a list<string> / array of string version number? -

Image
i have list of strings of version (see photo), , i'd sort them in descending order. i've seen few solutions using version class compare them, can't think of solution sort whole list this. least complicated way achieve this? what wrong simple implementation? using system; using system.collections.generic; namespace consoleapplication1 { class program { static void main(string[] args) { var ver = new list<version>(); ver.add(new version("3.5")); ver.add(new version("3.15")); ver.add(new version("3.10")); ver.add(new version("3.1")); ver.sort(); ver.reverse(); } } }

java - How can I handle file uploading to other apps and sites? Android -

i working on simple android file manager. problem facing getting app upload files app or site when wants send files , such. tried reading through developer docs, bit confusing. how can set mainactivity(if place put this) handle , allow uploading of files? here have in manifest... <activity android:name="com.myapp.mainactivity" android:label="@string/app_name" android:configchanges="keyboardhidden|screensize|orientation"> <intent-filter> <action android:name="android.intent.action.main"/> <category android:name="android.intent.category.launcher"/> </intent-filter> <intent-filter> <action android:name="android.intent.action.get_content"/> <category android:name="android.intent.category.openable"/> <category android:name="andro

How do I open all files in a directory in python? -

this question has answer here: can't open files directory in python 1 answer i have code import os def load(): filename in os.listdir("directorypath"): content = open(filename, "r") load() and know how load files filename returns, @ moment error saying filenotfounderror: [errno 2] no such file or directory: 'adjectives.txt' os.listdir() returns filename, not full path. need pass whole path open . can use os.path.join combine directory , filename: content = open(os.path.join('directorypath', filename), 'r')

Displaying specific fields in the datagrid from a MySQL search result in VB.NET -

i design (php) db editors in gaming world past time. took challenge of doing same thing, time vb (originally 6, mysql tricky) i'm working 2008. one of tables has massive amount of info , need display 4 or 5 fields search result (there on 100+ fields) i know how populate grid whole table, not know how via specific fields without going long way around it. this first time vb6 vb.net - sadly not impressed (looks (m$) have deviated "basic" , went c++ engine format - super ugly (but digress). try conn.open() da = new mysqldataadapter(sqlqry, conn) dim cb mysqlcommandbuilder = new mysqlcommandbuilder(da) da.fill(ds, "big_table") datagridview1.datasource = ds datagridview1.datamember = "big_table" catch ex common.dbexception msgbox(ex.tostring) conn.close() end try the above works fine, not not need 100+ fields displaying. want player name, level, if online , few other fields show - here can sel

nlp - How to deal with length variations for text classification using CNN (Keras) -

it has been proved cnn (convolutional neural network) quite useful text/document classification. wonder how deal length differences lengths of articles different in cases. there examples in keras? thanks!! here 3 options: crop longer articles. pad shorter articles. use recurrent neural network, naturally supports variable-length inputs.

Return to the main Form, and close the others, from a form that has other forms opened (C#)? -

my problem it´s have form1, opens form2, , opens form, want make button on last form returns main form , closes other. here´s how programmed forms openings: form2 popup= new form2(); this.hide(); popup.showdialog(); this.show(); and did same other form, tried doing this: form1 main= new form1(); this.close(); main.show(); but leaves other forms opened. thanks! you can list of open forms in application using application.openforms . can loop through them , close ones don't want. this: foreach (form f in application.openforms) { if (f.name != this.name) f.close(); } form1 main= new form1(); this.close(); main.show(); i have no means test code right now, can close current form others in loop, code can reduced to: foreach (form f in application.openforms) { f.close(); } form1 main= new form1(); main.show();

ios - KVO or custom accessor methods? -

i got few entities for ios app linked relations. make simple example, lets assume got relation (one-to-many): company <--->> person i'm using xcode 4.6 , core data modelling tool model generation, end //company.h @class person; @interface company : nsmanagedobject @property (nonatomic, retain) nsstring * company_name; @property (nonatomic, retain) nsnumber *has_changed; @property (nonatomic, retain) nsset *person; @end @interface company (coredatageneratedaccessors) - (void)addpersonobject:(person *)value; - (void)removepersonobject:(person *)value; - (void)addperson:(nsset *)values; - (void)removeperson:(nsset *)values; @end //company.m #import "company.h" #import "person.h" @implementation company @dynamic company_name; @dynamic has_changed; @dynamic person; @end and //person.h @class company; @interface person : nsmanagedobject @property (nonatomic, retain) nsstring * first_name; @property (nonatomic, retain) nsstring * last_name;

javascript - How to return the response from an asynchronous call? -

i have function foo makes ajax request. how can return response foo ? i tried return value success callback assigning response local variable inside function , return one, none of ways return response. function foo() { var result; $.ajax({ url: '...', success: function(response) { result = response; // return response; // <- tried 1 } }); return result; } var result = foo(); // ends being `undefined`. -> more general explanation of async behavior different examples, please see why variable unaltered after modify inside of function? - asynchronous code reference -> if understand problem, skip possible solutions below. the problem the a in ajax stands asynchronous . means sending request (or rather receiving response) taken out of normal execution flow. in example, $.ajax returns , next statement, return result; , executed before function passed success callback

html - Text not aligning to the center in the li ul -

in following code, through trying understand drop down menu. if see output, can notice li texts first second , fourth not equally horizontally aligned equal spaces between each other.for instance there more horizontal space on right side of fourth. whats best possible way align text in middle (horizontally) without manually giving values of margin, padding etc. there should way using text-align:center or margin:auto auto can align text in center automatically irrespective of length of text or font size. ul{ width:350px; height:50px; padding-left:0; margin:0; background:#cccccc; } ul > li{ list-style: none; display: inline; font-size: 24px; float: left; width: 106.66px; margin-right: auto; text-align: center; margin-left: auto; } ul > li > ul{ margin:10px 0px; padding-left:0; width:80px; height:40px; visibility: hidden; } ul > li > ul >

ios - Set height UILabel to 0 -

Image
is there anyway set height of uilabel programmatically? i've added bunch of constraints .xib files every other label dependent upon 1 above or below it's positioning. it'd make life easier if use: namelabel.height = 0 my .xib looks this: plz take iboutlet of constraint height , set height want

node.js - Incorrect TypeScript definition for request / request-promise: option "time" is missing -

on nodejs typescript , using npm request-promise (which wraps npm request). i want use "time" option time round-trip documented here "time - if true, request-response cycle (including redirects) timed @ millisecond resolution, , result provided on response's elapsedtime property" , available within npm evidenced here if (options.time) { self.timing = true self.elapsedtime = self.elapsedtime || 0 } but option doesn't appear supported in of request definitions can find. so first question - reading things wrong? if not, second question - there reason it's not there? finally, if should there - can modify local copy of definitions but, of course, better way repository definitions fixed , i'm not sure best way go doing that, can point me in right direction? the definition time option missing typings definition of request package: https://github.com/louy/typed-request/blob/master/index.d.ts the typings definition versi

arrays - Working with multiple subs in VBA -

i cant seem code display date stock @ waltech exceeded searched price. (the dates listed in column , prices listed in column b) right code giving me problem message box. can me? sub records() dim searchprice currency 'get price call other sub searchprice = inputbox("enter price") call recordhigh1 end sub sub recordhigh1() dim stocks() string dim dt() string dim nstock integer dim integer 'capture stocks , dates , put them in 2 seperate arrays wsdata.range("a2") nstock = range(.offset(1, 0), .end(xldown)).rows.count redim stocks(1 nstock) redim dt(1 nstock) = 1 nstock stocks(i) = .offset(i, 0).value dt(i) = .offset(i, 1).value next end 'loop through arrays find date stock exceeds searchprice range("a2") = 1 nstocks if .offset(i, 1).value > searchprice msgbox "the first date waltech stock price exceeded " & stocks(i).value & " " & dt(i).value

Optionals in designing Swift API -

i'm creating new api use in app. swift api guidelines have no mention of optionals. i have structured api accept data in 1 format , return in format use in creation. i.e. func createmydatafromyourdata(data: yourdata?) -> mydata? {} the function checks see if data nil, , proceeds appropriately. after writing occurred me api should deal non-optionals , user should checking nil before passing. have decided on rule yet? there's not "rule" this. it's dependent on how app work. in case, you're trying create mydata object, suggest instead do: class mydata { convenience init?(data: yourdata?) { guard let data = data else { return nil } self.init() // whatever data } } that way it's obvious you're creating new object when call so: let obj = mydata(data: yourdataobject) obj nullable object itself. it's possible still create mydata object if yourdata nil, , in case you'd not make nullable.