Posts

Showing posts from April, 2011

node.js - retrieving json properties from databse using express -

i new express. have created api crud app in express access cloudant db. now want parse properties json files have on db , put them properties. i have tried " request ( url, function(error, response, data) { body = data; } didn't work. body undefined. var express = require('express'); var http = require('http'); var app = express(); var bodyparser = require('body-parser'); var request = require("request"); var body; var cloudant = require('cloudant'); app.set('port', process.env.port || 3000); app.set('json spaces', 2); app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: true })); //==== configure database ======================================// var services = json.parse(process.env.vcap_services || "{}"); var cloudantcreds = {}; (var servicename in services) { if (servicename.indexof("cloudantnosqldb") > -1) { cloudantcreds = servic...

javascript - What is the current bandwidth or quality of an audio MediaStream in a browser? (WebRTC) -

i'm building webrtc application , want gather statistics in order rate solution. 1 metric i'm interested in current bandwidth of received audio (and video) stream. able find used codec @ chrome://webrtc-internals/ (opus), wasn't able find numbers current quality/bandwidth of stream (e.g. 128kbit/s). i searched rtcpeerconnection object such numbers, haven't found some. xxx.rtcconnection.getremotestreams()[0].getaudiotracks()[0].getconstraints() returns { deviceid: {}, echocancellation: {}, facingmode: {}, framerate: {}, height: {}, mediasource: "camera", mozautogaincontrol: {}, moznoisesuppression: {}, viewportheight: {}, viewportoffsetx: {}, ... } that contains information video stream (funnily requested audio stream) , no bandwidth details. there no other streams arrays in example above. know need current quality/bandwidth of mediastream? you need use rtcpeerconnection.getstats() api, search bytesreceived ...

Using a shared python library in Visual Studio -

we have python library needs shared among many projects , we're trying find way organize , link shared library specific projects want use it. it needs work without visual studio, meaning if whole project moved different machine, still work , use "shared library", means linked library needs placed statically in every project use (and of course each time it's updated, library directory updated in each project) is there anyway can done? the directory structure looks this: project1 main.py <--- (one of projects uses library) ... libs pylib <--- (this shared library) __init__.py ps_lib.py another.py cwinlib cnixlib some ways i've tested are: working linked files - problem doesn't copy whole package project (which means doesn't work outside of visual studio) adding search path - same problem before, doesn't work outside of visual studio using sys.path.append - means we'll need copy exact d...

ruby on rails - Mongoid access nested attributes with attributes.values_at? -

given following document (snippet): { udid: "0e321dd8-1983-4502-b214-97d6fb046746", person: { "firstname": "jacob", "lastname": "prince" } } i'n console can do: mycollection.first.attributes.values_at("udid", "person") this returns person hash . now want single field. these doesn't work (person.firstname): mycollection.first.attributes.values_at("udid", "person.firstname") mycollection.first.attributes.values_at("udid", "person[:firstname]") mycollection.first.attributes.values_at("udid", "person['firstname']") how how access person child-document? i'm in need have users select fieds want export. thinking along lines of doing this: class foo include mongoid::document # fields definitions embeds_one :person # 2 fields: firstname, lastname def to_csv *columns a...

excel - Sending commands across VBA -

i writing script in vba creates drawing in coreldraw. having trouble centering text. here code works in coreldraw's macro editor: dim s2 object dim txt object dim test string dim returntest string returntest = "test~test1234~test56~test789" test = replace(returntest, "~", chr(13)) set s2 = corelapp.activelayer.createartistictext(-7.75, (1 - 0.5) / 2, test) set txt = s2.text txt.story.font = "swis721 bt" txt.story.size = 20 txt.story.linespacing = 75 txt.story.alignment = cdrcenteralignment s2.fill.uniformcolor.cmykassign 0, 0, 0, 100 s2.outline.setnooutline s2.centerx = s1.centerx s2.centery = s1.centery s1 rectangle defined. problem "cdrcenteralignment". vba not recognize valid argument because referencing exists within coreldraw. "cdrcenteralignment variable not defined" or "type mismatch" if call string. how, if possible, can send command/argument corel...

c# - How to build a table row cell by cell in Angular 2 -

let's say, i've table: +--------+----------+---- | device | serial # | +--------+----------+---- | cam1 | ab123 | +--------+----------+---- since don't know in advance columns that'll displayed, construct table sending pair of key/vale each cell. this how i'm getting data in c# code. list<list<keyvalue>> mytable = devicerepository.getkeyvalues(int facilityid); once set client side, data in mytable of following structure: mytable = [ [ { key: "devicename", value: "device"}, { key: "serialnumber", value: "serial #"}, ..], [ { key: "devicename", value: "cam1"}, { key: "serialnumber", value: "ab123"}, ..], ... ] in razor, i'd have loop through list. @foreach(var row in model) { <tr> @foreach(var cell in row) { <td>@cell.value</td> } </tr> } in angular, don't see how direc...

javascript - Implementing twitter posts synchronously -

hi using code here embed twitter posts in website. works fine on pages code used (in forums, example), however, when browsing through user profiles page, post history of each user generated using ajax because there other sections user activities on website , problems start here. in console following error message: failed execute 'write' on 'document': isn't possible write document asynchronously-loaded external script unless explicitly opened. this causing twitter posts not displayed. any ideas how embed twitter posts synchronously ? looked through twitter documentation, couldn't find solution. youve found wrong solution. never ever stuff synchronously. , never ever use document.write. can append bodys inner content (even after page loaded , twitter request finished): document.body.innerhtml += "some twitter stuff";

android - how add Adapter get view into another parent layout -

i using adapter show auto suggestion dropdown box flowlayout eg. <flowlayout> <textview1> <textview2> <textview3> </flowlayout> but out put using adapter looks like <flowlayout> <textview1> </flowlayout> <flowlayout> <textview2> </flowlayout> <flowlayout> <textview3> </flowlayout> how can solve my code below: java: public class tagfilteradapter extends baseadapter implements filterable { private static final int max_results = 10; private context mcontext; private jsonarray tags; private float scale; private arraylist<pair<integer,string>> resultlist = new arraylist<pair<integer, string>>(); public tagfilteradapter(context context) { mcontext = context; } @override public int getcount() { return resultlist.size(); } @override public string getitem(int index) { // re...

javascript - How to show "Loading..." when i refresh the table with new parameters in Datatable Jquery? -

Image
i want refresh datatable when choose new parameter send database query it. done it, how show "loading.." when refresh datatable loaded @ first time : this script <script type="text/javascript"> $(document).ready(function() { var otable = $('#tabelspta').datatable({ "processing": true "deferrender": false, "footercallback": function (tfoot, data, start, end, display) { var api = this.api(); var intval = function ( ) { return typeof === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof === 'number' ? : 0; }; var p = api.column(10).data().reduce(function (c, d) { //mengatur penjumlahan total akhir di kolom ke-4 (kolom to...

c# - Returning custom object from Core Web API -

i have following basic controller in c# web api core 1.1. [produces("application/json")] [route("api/[controller]")] public class testresultscontroller : controller { // get: api/testresults [httpget] public ienumerable<string> get() { return new string[] { "test1", "test2" }; } [httpget("getresults")] public iactionresult getresults() { try { var output = new groupresult { name = "test", number = 1 }; // ienumerable<groupresult> output = testqueries.gettestresults(); return ok(output); } catch (exception ex) { return notfound("invalid result: " + ex.message); } } // get: api/testresults/5 [httpget("{id}", name = "get")] public string get(int id) { return ...

How to integrate Vue.js with ASP.NET Core? -

i need develop application in asp.net mvc core vue.js views. how should setup application work both technologies? regards assuming want beginner level approach , develop vue spa application, suggest on using following boilerplate. npm install -g yo generator-aspnetcore-spa cd some-empty-directory yo aspnetcore-spa select vue list

makefile - GNU Make on Windows cannot see some executables -

part of deployment run target on makefile on windows called "deploy" runs, among other things, taskkill.exe , psexec.exe. both in c:\windows\system32 in %path% . when try make target, message psexec can't found. taskkill works expected. as test, tried dir c:\windows\system32\psexec.exe , makefile, "file not found". in same shell, however, can run same dir command , positive response. why can't make see file exists, less run it? here example makefile target: exetest: @echo ------------------------------ -dir /b c:\windows\system32\psexec.exe @echo ------------------------------ -dir /b c:\windows\system32\taskkill.exe and happens in command prompt: c:\users\owner\documents\github>make exetest ------------------------------ dir /b c:\windows\system32\psexec.exe file not found make: [exetest] error 1 (ignored) ------------------------------ dir /b c:\windows\system32\taskkill.exe taskkill.exe c:\users\owner\documents\gith...

Multi-dataframe For Loop Analysis Python -

i have data looks following: data#1 class1: name1 name2 name3 name4 class2: name5 name6 name7 class3: name8 name9 name10 name11 name12 name13 … class500: namex namey where above has 500 classes school given names corresponding class next, have data set has of names (some not included in classes) looks following (pairwise correlation coefficients): data#2 name1 name2 name3 …………………………………….. name4000 name1: 1 .96 .5 name2: 0.5 1 -.6 name3: 0.40 -.45 1 ………………………………………………………………………………………………. name4000: -.24 .08 .9 ……………………………………….. 1 my goal take data dataframe1 , analyze each classes genes data 2. meaning; might this: class1df: name1 name2 name3 name4 name1 1 .5 .96 .5 name2 0.5 1 -.6 .8 name3 0.4 -.45 1 0.03 name4 .7 .76 .4 1 and build dataf...

r - RStudio 'Run App' opens Shiny app inside frame -

when start shiny app executing shinyapp(...) line displayed in full mode, single frame covers entire screen. however, if started using 'run app' button in rstudio, browser displays app inside frame approximately half of screen. required pass options show in full-mode ?

php - Foreach comes back as Array Array -

not sure i'm doing wrong one, when attempt foreach loop variable, comes array array . php code: <?php foreach ($thing $t) : ?> <?php $thisstuff = $t[stuff]; ?> <?php echo $thisstuff; ?> <?php endforeach; ?> output: array array could possibly there array within $thisstuff ? if loop through data? if have multidimensional array you'll need use recursive function. an example might this function unfoldarray($array,$output = array()) { if(is_object($array)) { $array = (array)$array; } foreach($array $key => $value) { if(is_array($value) || is_object($value)) { //$output[] = $key; $output = unfoldarray($value,$output); } else { $output[] = $value; } } return $output; } the above function, given array like $array = array( "one", "two", "three" => array("a","b",...

sql - Combining similar names and counting distinct from a single column -

i attempting combine rows similar names within single column. data using has clients listed same name: | client_column | address | | xyz isd | 1 drive | | xyz isd | 2 drive | | xyz isd | 3 drive | however, there records same client has distinct, similar name alternate address: | client_column | address | | abc inc. | 101 lane | | abc inc. - p1 | 102 lane | | abc inc. - p2 | 103 lane | i count total number of distinct addresses each client in table. in example, xyz isd , abc inc. each have 3 unique addresses. how can adjust script can achieve result? i think need use sum aggregate total, not sure how. able count addresses clients exact same name accuracy, ones similar names display single record addresscount. here script: select clientname, count(address) addresscount tablea group clientname order addresscount result: | client_column | addresscount | | blue llc | 15 | | psc parts | 14 | | abc inc. ...

c++ - Reflection + function pointers vs Observer pattern -

i have got program gets commands via network , allocates these specific function. , want implement plugin feature can add .dll file in folder. next step invoke methods in dll based on command. i have 2 ideas how solve problem not know of these better/more performant: initializing methods + commands dll reflection , store them in std::map<std::string, void(*func)(args...)> . when program receives command looks associated function in map , invokes it. load dll runtime , create interface hands on std::string arguments dll's have implemented it. method in dll uses if statements check command can processed in there. (observer pattern) if there better options have not mentioned let me know. although using incorrect terminology describe want, option 2 "cleaner" forcing singular interface implemented plug-in dlls best-practice way of establishing sort of dependency injection you're seeking, in opinion.

bash - Completely removing Node.js: automatic vs manual -

recently used following list of files associated node removing on linux mint 18.1: sudo rm -rf /usr/local/lib/node* /usr/local/include/node* ~/.local/node* ~/.lib/node* ~/.include/node* /usr/local/bin/node* on other hand there solution uses apt-get : sudo apt-get purge --auto-remove nodejs is there difference in them in context of full , total removing nodejs local machine? 1 more correct/safe/complete? thanks in advance! it's safer , more reliable use apt-get purge that. otherwise have know of package files located. includes not limited to: configuration files, man pages, libraries, etc. in addition, package structure may change during time (like new files added or directories changed). apt-get utility execute set of post-removal scripts in /var/lib/dpkg/info . if keep removing files manually, system cluttered , may end in inconsistent state. here visual example (for ubuntu): root@ubuntu-xenial:~# rm -rf /usr/lib/node* /usr/include/node* /usr/bin/no...

python - ImportError raised when trying to load 'material.admin.templatetags.material_admin': cannot import name Layout -

traceback (most recent call last): file "/home/jeremie/.virtualenvs/venv/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) file "/home/jeremie/.virtualenvs/venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ response = self.get_response(request) file "/home/jeremie/.virtualenvs/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) file "/home/jeremie/.virtualenvs/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = response_for_exception(request, exc) ... file "/home/jeremie/.virtualenvs/venv/lib/python2.7/site-packages/django/template/backends/django.py", line 30, in __init__ options['libraries'] = self.get_templatetag_libraries(libraries) file ...

c++ - Is it faster to read the first element of an array, or the 4000th? -

is there speed difference when reading first element of array rather 4000th? same goes other element in array. mostly asking c++ language alright. as array, array of integers. if calling element in array , know exact position in array of element need retrieve, there no difference in speed. however, if there loop involved, or type of functionality searches through array specific value, speed impacted.

lighting - How to set material for metal(like silver) in OpenGL? -

how set material metal(like silver) in opengl? knows? how set material metal(like silver) in opengl? knows? if want material "kinda" metal, need set corresponding diffuse, ambient, specular , "shininess" parameters. investigate existing material libraries 3d editors blender , see how it. that's cheap, cheap. material low gl_shininess value (3..12, think?) "kinda" metallic surface. if want material more metal, under lighting condition, you'll need write pixel shader use photorealistic texture of silver, additional texture map controls specular color , strength. texture allows away horrible , easy shader, long lighting conditions selected. requires programmer glsl knowledge , artist make texture, , artist more important - non-metallic shader per-pixel phong can fine-tuned hand want (precess might boring , tedious). shader requires per-pixel lighting specular (any specular), normalmapping support , environmental reflection mappin...

javascript - Filter a DataTable using input texts client side -

i have html page script inside head, , have datatable id=example, , button id="btnfilter" supposed filter data in datatable based on user typed inside others "input texts tags". i've tried lot of variations found on internet i'm not being able can want. here html have input , label tags, user type text wants filter: <table id="filterlog" class="table table-striped"> <thead> <h4>table</h4> </thead> <tfoot> <th> </th> </tfoot> <tbody> <tr> <td><label class="input-group">from:</label></td> <td><label class="input-group">to:</label></td> <td><label class="input-group">created:</label></td...

R lapply and unique -

i have list of dataframes called test , trying lowest ranking of month per accountid using lapply , unique. current code looks this, throwing error. causing problem? test_1 <- lapply(test, function(x) unique(x[,list(x$ranking = min(x$ranking), x$month), = x$accountid])) when working 1 datatable (one datable 1 month), code below worked fine. best_rank_mar <- unique(rank_mar[,list(ranking=min(ranking), month), = accountid])

python - Asking the user for input until they give a valid response -

i writing program must accept input user. #note: python 2.7 users should use `raw_input`, equivalent of 3.x's `input` age = int(input("please enter age: ")) if age >= 18: print("you able vote in united states!") else: print("you not able vote in united states.") this works expected if user enters sensible data. c:\python\projects> canyouvote.py please enter age: 23 able vote in united states! but if make mistake, crashes: c:\python\projects> canyouvote.py please enter age: dickety 6 traceback (most recent call last): file "canyouvote.py", line 1, in <module> age = int(input("please enter age: ")) valueerror: invalid literal int() base 10: 'dickety six' instead of crashing, try getting input again. this: c:\python\projects> canyouvote.py please enter age: dickety 6 sorry, didn't understand that. please enter age: 26 able vote in united states! how can accomplish this? i...

python - Python3, create multiple objects of a class at once -

i want create multiple objects diferent names @ once. for example class car: def __init__(self, color): self.color = color and need create n objects when program first run car_1 = car("blue") car_2 = car("red") #... car_n = car("color_n") is there way in python3? things i've tried create 1 object , change name or overwhite objects information o fails @ running. can't use exec() or eval() thanks extra: need thing before because need store n client's information whenever run program work (that info stored in .csv file). need thing mentioned before or there way deal kind of data management? you can create list of cars objects, list comprehension class car: def __init__(self, color): self.color = color def __repr__(self): return '{}({!r})'.format(self.__class__.__name__, self.color) colors=['red', 'blue', 'green',] cars_objects = [car(color) color...

html - Making Image Overlay more responsive? -

is there way of making overlay more responsive? in, making overlay not cut off words, or go outside image when resolution changes? to further clarify: having 3 images next each other in row, per w3css framework using, 3 images under that, etc. each image has overlay text links direct other pages, shown in example below. issue responsiveness. want images, , overlays, responsive screen size changes , resolution. thank you! .container { position: relative; width: 50%; } .image { display: block; width: 100%; height: auto; } .overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; width: 100%; opacity: 0; transition: .5s ease; background-color: #008cba; } .container:hover .overlay { opacity: 1; } .text { color: white; font-size: 15px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); } <link href="https://www.w3school...

backup - Backing up data for android app -

i making note taking android app in users can create notes, edit notes etc. want backup whole notes in cloud notes safe if user's device crashed. best way it? i'm planning have amazon s3 databse table - (user id, note id, note text) whenever user finishes writing note , hits save, i'll connect db , update corresponding row/add new row. also, whenever user opens app, i'll connect db , fetch notes particular user. are there better approaches here?

ios - Initializing a Struct in Swift Error: Generic parameter could not be inferred -

i'm trying declare struct in class without providing parameters. struct need initialized function should visible entire class. normally, i'm able var mystruct : mystruct? time it's giving me error. generic parameter 'type' not inferred am initializing struct incorrectly? how i'm using it: class myclass: { static let sharedinstance = myclass() private override init() {} let mystruct = mystruct? // <-- above error occurs here. // let mystruct = mystruct<int>? // <-- error: expected member name or constructor call after type name // let mystruct = mystruct<int>?() // <-- error: cannot invoke initializer type 'mystruct<double>?' no arguments func runfunction(a: int, b: int) { mystruct(var1: a, var2: b) // <-- need initialize here. } func otherfunction() { mystruct.dostuff() // <-- , have access in other functions } code struct: public struct mystruct<ty...

How to I GET an XML page and parse it into a Ruby hash in Rails? -

assuming xml response @ example.com/query , how parse ruby hash without using external dependencies nokogiri? also, , not part of question, why use xml? this trivial: require 'open-uri' url = 'example.com/query' h = hash.from_xml(open url) this example needs hash#from_xml rail's active_support/core_ext/hash , not work vanilla ruby.

calling a python function from flask app -

i developing app runs (always - controller heat pump system) in python , use flask provide user interface controll app. the flask app has different control items, instance buttons turn system on or off. i trying execute specific function python module in response "click" on button (the final goal change value in mmap resource read in module change state of system). in flask app have like: @app.route('/cntr_hpauto',methods=['get','post']) @basic_auth.required def cntr_hpauto(): manage_globals.set_from_web() return render_template('control.html',cur_hp_mode="auto") however, generates "internal server error' the complete flask app (manage_globals *.py file want import , contains function want call): from flask import flask, request, render_template flask_basicauth import basicauth import sys import os import mmap import manage_globals app = flask(__name__) app.config['basic_au...

c# - What is a NullReferenceException, and how do I fix it? -

i have code , when executes, throws nullreferenceexception , saying: object reference not set instance of object. what mean, , can fix error? what cause? bottom line you trying use null (or nothing in vb.net). means either set null , or never set @ all. like else, null gets passed around. if null in method "a", method "b" passed null to method "a". the rest of article goes more detail , shows mistakes many programmers make can lead nullreferenceexception . more specifically the runtime throwing nullreferenceexception always means same thing: trying use reference, , reference not initialized (or once initialized, no longer initialized). this means reference null , , cannot access members (such methods) through null reference. simplest case: string foo = null; foo.toupper(); this throw nullreferenceexception @ second line because can't call instance method toupper() on string reference pointing null ....

r - Hyper-parameter optimization in SVM using Bayesian Optimization -

i trying search optimal values of c , gamma in svm (with gaussian kernel) using bayesian optimization (instead of grid-search) technique. end, using svm_opt function in r (details of function usage can found here ): svm_opt(train_data, train_label, test_data, test_label, gamma_range = c(10^(-5), 10^5), c_range = c(10^(-2), 10^2), init_points = 20, n_iter = 1, acq = "ucb", kappa = 2.576, eps = 0, kernel = list(type = "exponential", power = 2), init_points=21) however, running following error: error in gp_deviance(param_init_200d[i, ], x, y, nug_thres, corr = corr) : infinite values of deviance function, unable find optimum parameters it error related gp_deviance have tried overcome tweaking the: search range (by setting gamma_range = c(2^(-3), 2^3) , c_range = c(2^(-3), 2^3) ), tunable parameters eps , kappa (gp upper confidence bound , expected improvement respectively) determine trade-off between exploration , exploitation, acquisitio...

c# - How to call functions from data structure? -

i able describe actions function calls represented in datastructure. able loop through data structure , call functions. this pseudo-code describes achieve: static void main(string[] args) { action[] actions = new action[] { new action(doaction1(5)), new action(doaction1(7)), new action(doaction2("100201")), }; foreach (action action in actions) { action.<run action function>; } } public static void doaction1(int x) { } public static void doaction2(string x) { } it kind of looks delegates, not quite. any ideas on how achieve this? this you're looking for? action[] actions = new action[] { new action(()=>doaction1(5)), new action(()=>doaction1(7)), new action(()=>doaction2("100201")) }; foreach (action action in actions) { action(); }

javascript - Need help updating input field on selecting dropdown option -

i'm building currency exchange app , i've got basic functionality done problem if change target currency while not changing base currency input value, target currency doesn't update. i'd when change value in second element automatically recalculates rate based on in base input. this first time asking question on so gentle. thank you. you can find project here: https://codepen.io/azdravkovski/pen/bddleq?editors=0010 $(document).ready(function () { //first ajax call populates dropdown $.ajax({ url: 'https://api.fixer.io/latest?', success: function(data) { var currencynobase = object.keys(data.rates); var currencywithbase = currencynobase.concat(data.base).sort(); //populate dropdown lists currency names $.each(currencywithbase, function (val, text) { $('.currencies').append($('<option />').val(val).html(text)); }); ...

raspberry pi - Python: Make a boolean change from True to False after a few seconds -

i have code i'm working on basketball game (sort of arcade style basketball game using vibration sensor , hc-sr04 detecting backboard hits , scored shots). i'm trying figure out how have global boolean change true false after few seconds has passed. so example, ball hits backboard--which sets gobal backboard true--from there stay true few seconds more see if ball bounced backboard net. if backboard variable still true when ball goes through net know off backboard shot , play special sound effect of other cool things. right in callback function backboard variable set true when ball hits backboard, stay true until player scores instead of changing false after few seconds. here code: import rpi.gpio gpio gpiozero import distancesensor import pygame import time ultrasonic = distancesensor(echo=17, trigger=4) ultrasonic.threshold_distance = 0.3 pygame.init() #global backboard = false #gpio setup channel = 22 gpio.setmode(gpio.bcm) gpio.setup(channel, gpio.in) #m...

swift - How to structure data for saving user comments? -

i using xcode program ios app. want set section in app users can leave comments. bit confused on how should go storing set of comments particular post. need save 3 things per comment. user's id, comment itself, , number of comment (ie first comment posted post, or second, third, etc...) not know how best save database. using parse-server primary database , issue while database can store multiple qualities objects, saving dictionary not possible. (i have wanted save info as): desired strategy (but won't work) var commentcount = 5 //will hold value of number of comments post var commentstring = "hello" var commenterid = "e1das312" var commentsavingdict = [int: [string]]() func addcomment(){ commentcount = commentcount + 1 commentsavingdict[commentcount] = [commenterid, commentstring] } the issue in parse-dashboard arrays can saved, not dictionaries commentsavingdict is. considered merely saving string so: 2nd strategy var comment...

Generating a power-law distribution in C and testing it with python -

i know that, given rng generates random numbers uniformly distributed, way obtain power-like data is, following wolfram mathworld following: let y random variable uniformly distributed in (0,1) , x random variable distributed p(x) = c*x**n (for x in (xmin,xmax)). have that x=[ (xmax**(n+1) - xmin**(n-1))y+xmin**(n+1) ]**(1/(n+1)) so made program in c generates 50k numbers 1 100 should distributed x^(-2) , prints frequency of outcomes on file data.txt: void random_powerlike(int *k, int dim, double degree, int xmin, int xmax, unsigned int *seed) { int i; double aux; for(i=0; i<dim; i++) { aux=(powq(xmax, degree +1 ) - powq(xmin, degree +1 ))*((double)rand_r(seed)/rand_max)+ powq(xmin, degree +1); k[i]=(int) powq(aux, 1/(degree+1)); } } int main() { unsigned int seed = 1934123471792583; file *tmp; char stringa[50]; sprintf(stringa, "data.txt"); tmp=fopen(stringa, "w"); int dim=50000; int *k; k= (in...