Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from stackoverflow.com 2018-02-21T10:21:19Z
Updated: 4 hours 28 min ago

Combining lists into a dataframe more efficiently

Sun, 02/18/2018 - 21:40

I am running multiple chains of a MCMCglmm() model and I am trying to find the most efficient way to synthesize my output.

I am using mclapply() to run 4 chains and then combining each of the 4 chains into a list with lapply().

Here is my model and code to clean up and combine the chains. I am using this helpful tutorial for running the chains: https://github.com/tmalsburg/MCMCglmm-intro

Model:

library(parallel) chains <- mclapply(1:4, function(i) { MCMCglmm(outcome ~ 1 + pretest + race + satisfaction*race, data = data, random = ~ provider, prior = prior.1, verbose = TRUE, family = "gaussian", nitt = 10000, burnin = 5000, thin = 10) }, mc.cores=4)

My cleanup is a little clunky. Is there a way to run a lapply command (or I think what is needed is mapply) on both the fixed and random effects to combine them into the same list and subsequent data frame? In the end, I am hoping to have a data frame so I can add/ subtract posterior distributions and run summary statistics on them.

fixed <- lapply(chains, function(m) m$Sol) # Sol = fixed effects fixed <- do.call(mcmc.list, fixed) summary(fixed) random <- lapply(chains, function(m) m$VCV) # VCV = variance random <- do.call(mcmc.list, random) summary(random) fixed_df <- do.call(rbind, Map(data.frame, fixed)) random_df <- do.call(rbind, Map(data.frame, random)) chains_df <- cbind(fixed_df, random_df)

Ultimately, I am hoping to run one lapply() or mapply() and have a single fixed.random list of lists. I believe I can use the Map(data.frame, fixed.random) on that to create my data frame. My knowledge of the apply function is limited, so I'm hoping to learn more and apply it (no pun intended) to my datasets.

Unfortunately, the models output MCMC objects, so I am unable to create the exact structure. This is the best I can come up with:

list1 <- list(a = rnorm(100, 0, 1), b = rnorm(100, 0, 1)) list2 <- list(a = rnorm(100, 0, 1), b = rnorm(100, 0, 1)) list3 <- list(a = rnorm(100, 0, 1), b = rnorm(100, 0, 1)) list4 <- list(a = rnorm(100, 0, 1), b = rnorm(100, 0, 1)) list5 <- list(d = rnorm(100, 0, 1), e = rnorm(100, 0, 1)) list6 <- list(d = rnorm(100, 0, 1), e = rnorm(100, 0, 1)) list7 <- list(d = rnorm(100, 0, 1), e = rnorm(100, 0, 1)) list8 <- list(d = rnorm(100, 0, 1), e = rnorm(100, 0, 1)) fixed <- list(list1, list2, list3, list4) random <- list(list5, list6, list7, list8)

'undefined' error even after JSON.parse

Sun, 02/18/2018 - 21:36

<!DOCTYPE html> <html> <head> <title>Imagery Gallery</title> </head> <body> <h2>Location List</h2> <!-- image gallery will be displayed in the results <div> --> <div id="results"></div> <!-- JavaScript codes --> <script src="HTTPRequest.js"></script> <script> //Send request to the server to get the JSON dataset showing the list of locations //The URL to request is "http://geopingyin.com/gis/Locations.php" //The request function sendHttpRequest(sURL) is defined in the HTTPRequest.js file sendHttpRequest("http://geopingyin.com/gis/Locations.php"); //When the JSON dataset (JSONData, a text string) is successfully returned to the browser, //The function handleResponseData(JSONData) will be automatically called. //Complete the following function to process the JSON dataset. function handleResponseData(JSONData) { var obj = JSON.parse(JSONData); for (i in obj) { i += obj[i] + "<br>"; document.getElementById("results").innerHTML = i.Locations; } } //place your codes here for the imagery gallery </script> </body> </html>

This code is giving me an 'undefined' answer whenever I run it. After lots of research it seems like most people have issues with 'undefined' because they are using strings and not objects. However in my code I used a JSON.parse in order to create an object off of the original string, and it still comes up as undefined. I wish to use JSON.parse in order to change my array into objects and then loop through and display each one, yet I can not seem to figure out how to go about this. Any help would be greatly appreciated!

Also here is my HTTPRequest.js code just in case

var xmlHttp = createHttpRequestObj(); //Http request object //Create HTTP request object function createHttpRequestObj() { var xmlHttpObj; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari try { xmlHttpObj = new XMLHttpRequest(); } catch (e) { xmlHttpObj = false; } } else { // code for IE6, IE5 try { xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { xmlHttpObj = false; } } if (!xmlHttpObj) alert("Cannot create the Http request object"); else { return xmlHttpObj; } } //Send HTTP request with the URL //Function handleServerResponse() will be used to interpret the response function sendHttpRequest(sURL) { if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) { xmlHttp.open("GET", sURL, true); xmlHttp.onreadystatechange = handleServerResponse; xmlHttp.send(); } else { setTimeout(function() { sendHttpRequest(sURL); }, 1000); } } //Handel HTTP response function handleServerResponse() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { xmlResponse = xmlHttp.responseText; //Handle the xmlResponse handleResponseData(xmlResponse); } } }

THANK YOU!

Combine an array with other arrays, push each combination Javascript

Sun, 02/18/2018 - 21:30

I'm trying to take an array, and compare each value of that array to the next value in the array. When I run my code, components that should match with more than one array only return one match, instead of all of them. I'm probably doing something wrong somewhere, but for the life of my I don't seem to be able to figure it out.

This is my code:

INPUT

minterms = [["4",[0,1,0,0]], ["8",[1,0,0,0]], ["9",[1,0,0,1]], ["10",[1,0,1,0]], ["12",[1,1,0,0]], ["11",[1,0,1,1]], ["14",[1,1,1,0]], ["15",[1,1,1,1]]];

Function

function combineMinterms(minterms) { var match = 0; var count; var loc; var newMin = []; var newMiny = []; var used = new Array(minterms.length); //First Component for (x = 0; x < minterms.length; x++) { if(minterms[x][1][minterms[x][1].length - 1] == "*") { newMin.push(minterms[x].slice()); continue; }; //Second Component for (y = x + 1; y < minterms.length; y++) { count = 0; //Compare each value for (h = 0; h < minterms[x][1].length; h++) { if (minterms[x][1][h] != minterms[y][1][h]) { count++; loc = h; } if (count >= 2) {break; }; } //If only one difference, push to new if (count === 1) { newMin.push(minterms[x].slice()); newMiny = minterms[y].slice(); newMin[match][1][loc] = "-"; while(newMin[match][0].charAt(0) === 'd') { newMin[match][0] = newMin[match][0].substr(1); } while(newMiny[0].charAt(0) === 'd') { newMiny[0] = newMiny[0].substr(1); } newMin[match][0] += "," + newMiny[0]; used[x] = 1; used[y] = 1; match++; continue; } } //If never used, push to new if(used[x] != 1) { newMin.push(minterms[x].slice()); newMin[match][1].push("*"); match++; } } return newMin; }

Desired Output

newMin = [["4,12",[-,1,0,0]], ["8,9",[1,0,0,-]], ["8,10",[1,0,-,0]], ["8,12",[1,-,0,0]], ["9,11",[1,0,-,1]], ["10,11",[1,0,1,-]], ["10,14",[1,-,1,0]], ["12,14",[1,1,-,0]], ["11,15",[1,-,1,1]], ["14,15",[1,1,1,-]]];

It will combine term 8, with 9 but won't continue to combine term 8 with 10, 12

Thanks in advance for the help.

Change Foreground in ListViewItem

Sun, 02/18/2018 - 21:08

I have a collection of the class's objects UrlCount:

public ObservableCollection<UrlCount> URLsCount { get; set; } public class UrlCount { public string Url { get; set; } public int Count { get; set; } }

This collection is are ItemSsource of one ListView :

<ListView Margin="10" Name="ListUrlView" ItemsSource="{Binding URLsCount}"> <ListView.ItemTemplate> <DataTemplate> <TextBlock> <Run Text="{Binding Url}"/> <Run Text=" : "/> <Run Text="{Binding Count}"/> </TextBlock> </DataTemplate> </ListView.ItemTemplate>

I need to Change Foreground in ListViewItem if Count = -1. I try this :

<ListView.Resources> <Style TargetType="ListViewItem"> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=ListUrlView, Path=ItemsSource.Count}" Value="-1"> <Setter Property="Foreground" Value="Red"/> </DataTrigger> </Style.Triggers> </Style> </ListView.Resources> </ListView>

But none of the ListViewItems are not changed his Foreground. I haven't any Idea, how to fix it.

Serial to send data to ardiuno from C# APP

Sun, 02/18/2018 - 19:54

I have trouble with application with sending data(two trackbars positions) to set PWM frequency and Voltage. I wrote this in arduino:

#include <PWM.h> #include <Servo.h> int led = 9; int32_t frequency = 100; void setup() { InitTimersSafe(); bool success = SetPinFrequencySafe(led, frequency); } void loop() { //pwmWrite(led, 124); int channel; int freq; int Pwm; pwmWrite(led, Pwm); channel = Serial.readStringUntil(':').toInt(); if (channel = 1) { Pwm = Serial.readStringUntil('*').toInt(); pwmWrite(led,Pwm); } else if (channel = 2) { freq = Serial.readStringUntil('*').toInt(); frequency = freq; pwmWrite(led,Pwm); } }

I've seacrhed milion websites, rode serial references and still it doesn't work.

The C# app has connection (COM3) and i see the data transfer when I moving the trackbar.

the C# code:

private void trackBar2_Scroll(object sender, EventArgs e) { string bar2 = trackBar2.Value.ToString(); label2.Text = bar2; int freq = trackBar2.Value; //port.WriteLine(trackBar2.Value.ToString()); SendFrequencyInfo(1, freq); } private void SendFrequencyInfo(int frequency, int trackBar2Pos) { string message = frequency.ToString() + ':' + trackBar2Pos.ToString() + '*'; try { port.Write(message); } catch { } }

The question is: How to send two values via Serial connection (two trackbar values) to setup frequency and PWM voltage? Did I miss something, I don't really. Please help me :)

Predicting binary response probabilities from gamlss R object

Sun, 02/18/2018 - 18:30

I want to predict binary class probabilities/class labels from gamlss R function, how can the predict function be used to get them?

I have the following sample code

library(gamlss) X1 <- rnorm(500) X2 <- sample(c("A","C","D","E"),500, replace = TRUE) Y <- ifelse(X1>0.2& X2=="A",1,0) n <- 500 training <- sample(1:n, 400) testing <- (1:n)[-training] fit <- gamlss(Y[training]~pcat(X2[training],Lp=1)+ri(X1[training],Lp=1),family=BI()) pred <- predict(fit,newdata = data.frame(X1,X2)[testing,],type = "response")

Error in predict.gamlss(fit, newdata = data.frame(X1, X2)[testing, ], : define the original data using the option data

Any idea?

LibGDX - Activate accelerometer in runtime

Sun, 02/18/2018 - 15:49

I have an application which uses the accelerometer, but only occasionally under rare circumstances. I'd like to preserve battery by having it disabled by default and only turn it on when needed.

Only thing I've found is setting configurations when initializing the app from this site

@Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); config.useCompass = false; config.useAccelerometer = false; MyGame myGame = new MyGame(new AndroidPlatform(this, config)); initialize(myGame , config); }

But I can't find a way to enable/disable it while the app is running. Anyone have an idea?

EDIT:

In the above example AndroidPlatform is implementing a Platform interface in the core project. I tried out Zoe's idea of passing the config to platform implementation and changing it follows:

@Override public void enableAccelerometer(boolean enable) { config.useCompass = enable; config.useAccelerometer = enable; }

and then in the core project when the accelerometer should be enabled:

private void startInclineMonitoring() { System.out.println("Before:"); System.out.println(Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer)); System.out.println(Gdx.input.isPeripheralAvailable(Input.Peripheral.Compass)); platform.enableAccelerometer(true); System.out.println("After:"); System.out.println(Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer)); System.out.println(Gdx.input.isPeripheralAvailable(Input.Peripheral.Compass)); }

Unfortunately this outputs:

I/System.out: Before: I/System.out: false I/System.out: false I/System.out: After: I/System.out: false I/System.out: false

So, no luck there.

Cannot access C shared library methods from C++ code

Sun, 02/18/2018 - 12:22

I'm trying to include a C library in my C++ code.

The C code has been compiled in to a C library. The C part is below:

This is the Android.mk file from the C component:

LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES:= logger.c LOCAL_C_INCLUDES += $(LOCAL_PATH) LOCAL_CFLAGS += -Wall -Wno-unused-parameter -std=gnu99 LOCAL_SHARED_LIBRARIES := libcutils libsysutils LOCAL_LDLIBS := -llog LOCAL_MODULE_OWNER := company_name LOCAL_PROPRIETARY_MODULE := true LOCAL_MODULE := liblogger LOCAL_MODULE_SUFFIX := .so LOCAL_MODULE_TAGS := optional include $(BUILD_SHARED_LIBRARY)

The header file (logger.h) from the C layer is below:

#if defined (__cplusplus) extern "C" { #endif // __cplusplus int logger_init (); #if defined (__cplusplus) } #endif // __cplusplus

The logger.c implementations is below:

int combilog_init () { // logic return 0; }

Im my CPP code, Android.mk, I've included this C library in "LOCAL_SHARED_LIBRARIES":

LOCAL_SHARED_LIBRARIES := liblogger

Then I'm accessing it in my CPP code as:

int ret = init();

While compiling, I'm seeing the following error:

In file included from xxxx/Logger.cpp:20: XXXX/CPP_Logger.h:26:10: fatal error: 'logger.h' file not found

Any help here would be greatly appreciated.

Function returns without waiting for-loop

Sun, 02/18/2018 - 10:04

I'm unable to retrieve results from the anonymouse function used inside the object "tilemap" given below. I believe the onload function creates some sort of asynchronized callback but I'm not sure how could I fix it.

Thanks in advance...

function generateTileMap(imageLocation, w, h, name = "Tilemap") { var image = new Image(); image.src= imageLocation; return (image.onload = function () { if (image.naturalWidth % w > 0) { return false; //if width is out of scope } if (image.naturalHeight % h > 0) { return false; //if height is out of scope } var tilemap = { conf: { name: name, width: w, height: h, image: image }, frames: (function () { //Unable to return frames. Async? var frames = []; for (var i = 0; i < image.naturalHeight / h; i++) { for (var j = 0; j < image.naturalWidth / w; j++) { frames.push({ x: j, y: i }); } } return frames; })() }; return tilemap; })(); }

I can't upload video file to server.

Sun, 02/18/2018 - 10:04

I have a problem with uploading video files (.avi, .mp4) to server.

I'm working with OSX and Linux servers with PHP 7 on board. In both cases the same behaviors.

First of all, I try it at Yii2, but get empty response ($_FILES[] is empty), but when I try to upload any other types of files (like .doc. mp3, jpeg, zip-archive with size about 80 mb...) - it's working great.

My second attempt - use some pretty easy and clean script on PHP for that. Source code I'm get from here GitHub As result - the same behavior. $_FILES[] is empty, and nothing to put to destination directory.

I try files with size more than 20 mb, and also small files - about 2-3 mb. I try to change names of files - from difficult with special charset, to something like 'a.mp4' - nothing.

But, all working fine on Windows 7 x64 web server.

I try to set 777 permissions to all folder (just for testing purposes) - the same (nothing).

The final think - it's a problem with configuration of server in php.ini

Could you, please, to see at my phpinfo(), and say, maybe some configs is wrong. Or maybe I doing wrong in some other things. Thank you.

PHPINFO

How to print a binary tree in as a structure of nodes in Python

Sun, 02/18/2018 - 10:03

I have a python code to convert a string mathematical expression into a binary tree and order the nodes of the tree so the left child will be always smaller than the right child. I want to print the binary tree in the following order.

For example consider the mathematical expression ((2 * 75) / 4). buildParseTree() converts the string expression into a tree and printNodeInLevels() rearranges the nodes so left child is smaller than the right right child at each level. Operands < operators and operators are orders as '+' < '-' < '*' < '/'. If the structure of the tree is like this

+ /\ 4 * /\ 2 75

I want to print it as follows. How should I go about this? Because the length of the mathematical expressions vary all the time e.g (24 * 2), ((5 - 1) * (2 / 3)), (20 - (5 + 4)) etc

Node("+") #root .addkid(Node("*") #right child at level 1 .addkid(Node("75")) #right child at level 2 .addkid(Node("2")) #left child at level 2 ) .addkid(Node("4")) #left child at level 1

I have worked out the method to print nodes by their levels as in an in-order traversal pattern.If I call the method as follows it will print the following:

pt = buildParseTree("( ( 2 * 74 ) / 4 )") printNodesInLevels(pt)

output:

/ 4 * 2 74

Is it possible to split the envelope of a multiple recipient message using sendmail and apply separate deferral conditions per recipient?

Sun, 02/18/2018 - 10:03

I'm a bit new to sendmail and hope someone can help me out. I'd like to be able to create separate rules for different recipients for deferring delivery of a message under certain conditions. Also, when doing this, is it possible to alert the sender when an email is deferred for a particular recipient of a message?

Thanks a lot.

using localStorage with a for in loop

Sun, 02/18/2018 - 10:03

This is my first post on stackOverflow although I have been lingering around the forums when I have needed help. However, I was unable to find an answer for my current problem so thought it was best I made an account and asked.

It is a workout application with 3 pages - page 1: user selects what gym equipment (bike, rower or x trainer) they wish to use and what difficulty, page 2: All workouts available specific to the options selected. page 3: the actual workout to complete.

Basically, I am trying (if possible), to store certain data in a localStorage object depending on what link the user clicks on, but what keeps happening is the last value in the for in loop keeps storing no matter which link is clicked. Please see below and hopefully you can see what I mean:

PAGE 1: (there are 2 dropdown menus, the first the user selects what equipment they wish to use, and the second option they choose the difficulty of the workout):

//constructor function - create workouts with instances of this function function Workout(name, desc, loc, work_rest, res, intensity){ this.name = name; this.desc = desc; this.loc = loc; this.work_rest = work_rest; this.res = res; this.intensity = intensity; } //CREATE WORKOUTS var bike = { easy: [ {workout_1: new Workout('Tabata', 'This is a tabata style workout', '../Workout_page_example/index.html', [20, 10, 20, 10, 20, 10, 20, 10, 20, 10, 20, 10, 20, 10, 20, 10], [8,2,8,2,8,2,8,2,8,2,8,2,8,2,8,2], [120,60,120,60,120,60,120,60,120,60,120,60,120,60,120,60])}, {workout_2: new Workout('Classic_HIIT', 'This is a HIIT session', '../Workout_page_example/index.html',[60,30,60,30],[7,3,7,3],[100, 70, 100, 70])}, {workout_3: new Workout('Clock_Face', 'Beat the clock', '../Workout_page_example/index.html',[120, 60, 110, 60, 100, 60], [7,4,7,4,7,4],[120, 60, 120, 60, 120, 60])} ], int:[ ], adv:[ ] }; btn.addEventListener('click', function() { //dependant on options - send storage information to 'choose a workout page' if(equipment.value === "bike"){ if(difficulty.value === "easy"){ localStorage.setItem('get_info', JSON.stringify(bike.easy)); }else if(difficulty.value === "int"){ localStorage.setItem('get_info', JSON.stringify(bike.int)); }else if(difficulty.value === "adv"){ localStorage.setItem('get_info', JSON.stringify(bike.adv)); } } //send storage information for specific workout to this page location.href = 'workouts/index.html'; })

so this above page is fine - Sorry if it appears a bit blocky, I only showed the relevant parts as it is a fairly big script, hopefully you can figure out what each variable is in relation to the DOM as they are pretty straight forward. So the problem appears on page 2, this page displays all the workouts available for the equipment and difficulty selected by the user, which is as follows:

PAGE 2: (This page displays all workouts of the equipment and difficulty selected)

window.addEventListener('load', function(){ var getInfo = JSON.parse(localStorage.getItem('get_info')); var dom = document.getElementById('section'); for(var key in getInfo){ var obj = getInfo[key]; for(var prop in obj){ dom.innerHTML += "<hr/><div class ='workout_title'> <h1>"+obj[prop].name.replace('_',' ')+"</h1></div>"; //replace underscore with space in workout names with more than one word - display name dom.innerHTML += "<div class='workout_desc'><h4>"+obj[prop].desc+"</h4></div>"; //display description localStorage.setItem('work_rest', JSON.stringify(obj[prop].work_rest)); localStorage.setItem('resistance', JSON.stringify(obj[prop].res)); localStorage.setItem('intensity', JSON.stringify(obj[prop].intensity)); dom.innerHTML += "<div class='workout_link'><a href='"+ obj[prop].loc +"' id='"+obj[prop].name+"'>START >></a></div>"; } } })

When the user clicks on one of the links - the localStorage obj only stores the last of the object instances passed in. So in this example the data for the instance with the name 'clock_face'. I can understand why it is happening, but I am unsure as to how to correct this.

If statement not working (Javscript)

Sun, 02/18/2018 - 10:03

So I have a code that classifies a point 1 if it's above the line y=x, and -1 if it's below the line y=x. So I draw the line in canvas of y=x(Since the y axis is inverted in canvas it looks like y=-x). Then I draw each point, and if it's 1 I paint it green, if it's -1 I paint it red. So I would expect to see a straight line with one side being green and one side being red. I ran the code and I got a weird result.

Here's the code for how I label my points:

function Point(x, y){ this.x = x; this.y = y; this.label = 0; if(this.y >= this.x){ this.label = 1; console.log(x, y, "UP"); }else if(this.y < this.x){ this.label = -1; console.log(x, y, "Down"); } }

Here's the code to paint the points:

function draw(){ ctx.clearRect(0, 0, can1.width, can1.height); ctx.strokeStyle = "yellow"; ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(can1.width, can1.height); ctx.stroke(); ctx.closePath(); for(var i = 0; i < points.length; i++){ var x = points[i].x; var y = points[i].y; if(points[i].label == 1){ var color = "Chartreuse"; }else{ var color = "red"; } ctx.fillStyle = color; ctx.beginPath(); ctx.arc(x, y, 5, 0, Math.PI * 2, false); ctx.fill(); ctx.closePath(); }

}

So I then run it in the browser and I get this:

It seems to be kinda working, but not fully?

Please help and thanks!

Edit: The x and y values are assigned randomly in other parts of the code.

Query different field than defined in return for a ManyToMany field option

Sun, 02/18/2018 - 10:03

I am new to Django and have a problem that I am trying to fix. In my application I have a model Asset which has multiple choice answer from AFF. Here is the code:

class Rtype(models.Model): rtype_name = models.CharField(max_length=10, verbose_name="Type", default = "") rtype_score = models.CharField(max_length=10, verbose_name="Score", default = "") def __str__(self): return self.rtype_name class AFF(models.Model): ff = models.CharField(max_length=100, verbose_name="FF", default = "") ff_score = models.ForeignKey(Rtype, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Score", default = "") def __str__(self): return self.ff class Asset(models.Model): fjam = models.ManyToManyField(AFF, verbose_name="Fjam", default = "", blank=True) def __str__(self): return self.fjam

Let's say there are following entries in the database:

rtype_name = Critical

rtype_score = 5

rtype_name = Medium

rtype_score = 3

ff = Direct

ff_score = Critical

ff = Indirect

ff_score = Medium

If user chooses in Asset form, both Direct and Indirect, how can I save 3 + 5 in the database when they submit the form instead of rtype_names by keeping return self.rtype_name in Rtype (useful for showing user a name rather then a score).

check if label.text have had the same text for x amount of seconds?

Sun, 02/18/2018 - 10:02

Is there a way to check if label.text have had the same text for like 5 seconds? I have a label that is changing its text between "speech" & "silence" depending if the microphone pics up anythinf or not.

for example

if(label.text == "silence" for 5 seconds { //do whatever }

Logcat in Android Studio shows nothing in mac OS X, any suggestions?

Sun, 02/18/2018 - 09:57

When I run my code,logcat shows nothing but empty. I tried restarting android studio still nothing happened. Any suggestions?

Latest version of Wokrbench requires old Mysql version when trying to export a DB, but couldn't downgrade Mysql (Wampserver)

Sun, 02/18/2018 - 09:51

When I try to export a DB in workbench, it tells me error as in the screenshot below:

As I understood, it wants me to downgrade MySQL, which is currently v5.7.19 came with the wampserver. But when I went to wampserver website I didn't find such MySQL version in older wampserver versions.

Also, when I check updates fro workbench, I am told it is latest version.

If the solution to this problem not by going that way, Please tell me. In all cases, please help me to solve the problem showed in the screenshot.

Scroll fixed div beyond viewport?

Sun, 02/18/2018 - 09:51

CSS

.menu{ position: fixed; width: 150px; height: auto; right: 36px; } .menu-button{ position: relative; width: 150px; height: 150px; margin-bottom: 12px; cursor: pointer; float: left; box-sizing: border-box; }

HTML

<html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div class="menu"> <div class="menu-button">ELEMENT 1</div> <div class="menu-button">ELEMENT 2</div> <div class="menu-button">ELEMENT 3</div> <div class="menu-button">ELEMENT 4</div> <div class="menu-button">ELEMENT 5</div> <div class="menu-button">ELEMENT 6</div> <div class="menu-button">ELEMENT 7</div> <div class="menu-button">ELEMENT 8</div> <div class="menu-button">ELEMENT 9</div> </div> </body> </html>

As you see in this picture, i do have a fixed div which height goes beyond the viewport of the browser. The problem i am having right now is that i do not have a scrollbar so that i can scroll down and see the last menu element(element 9). How do i get a scrollbar so i can scroll the whole page down?

What is the difference between combining array by using reduce or joined?

Sun, 02/18/2018 - 09:44

Consider the following array -of strings-:

let arrayStrings = ["H", "e", "l", "l", "o"]

For combining its elements (to get "Hello" as single String), we could:

reduce it:

let reducedString = arrayStrings.reduce("", { $0 + $1 }) // "Hello"

Or join it:

let joinedString = arrayStrings.joined() // "Hello"

Both would return "Hello" String as output.

However, what is the logic to keep in mind to determine what is the better choice for such a process? What is the difference when comparing based on the performance?

Pages