Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from stackoverflow.com 2017-09-23T21:24:57Z
Updated: 2 hours 5 min ago

Packing Django, Python and Chromium together

Thu, 09/21/2017 - 21:07

I would really like to distribute something like Electron for Python web applications build using Django framework. I didn't find a solution yet, so I would aks if there is one available. If not, how could I create one easily on my own?

I use the latest versions of Django and Python. I would also use Chromium, because I have to care about accessibility for screen reader users and I know that Chromium is fully accessible to that users group.

Why does this code change b: a=[4,3] b=a print(b) a[1]=6 print(b)

Thu, 09/21/2017 - 21:07

Why does this code change b:

a=[4,3] b=a print(b) a[1]=6 print(b) [4, 3] [4, 6]

and this does not

a=[4,3] b=a print(b) a=[6,7] print(b) [4, 3] [4, 3]

or

a=[4,3] b=a+a print(b) a[1]=1 print(b) [4, 3, 4, 3] [4, 3, 4, 3]

When does Python make a separate copy of a variable and when does it create a sort of a "pointer" to the same variable (if i got it right)?

Thanks

Php Mysql inserting values from a variable to database

Thu, 09/21/2017 - 21:06

equivalent to mongo db - entity frame work

<?php session_start(); $servername = getenv('IP'); $username = getenv('C9_USER'); $name2=$_POST['name']; $password2=$_POST['password1']; try { $db = new PDO("mysql:dbname=c9;host=$servername", $username, "" ); $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );//Error Handling $db->exec('CREATE TABLE IF NOT EXISTS users (' . 'ID INT AUTO_INCREMENT PRIMARY KEY, ' . 'name TEXT, ' . 'password TEXT ' . ')'); $db->exec( 'INSERT INTO users (' . 'name, password ) VALUES (' . "$name2 , $password2 " . ')' ); } catch(PDOException $e) { echo $e->getMessage(); } header("Content-type:application/json"); ?>

I am using cloud 9 and I am getting sql syntax error near the insert query. Can anyone suggest a possible suggestion. Thanks in advance.

Fail early if JIRA credentials are incorrect

Thu, 09/21/2017 - 21:04

I am connecting to JIRA using the jira python package:

def connect_to_JIRA(): ''' Generic function to get JIRA connection ''' if settings.JIRA_AVAILABLE: try: jira_conn = JIRA( basic_auth=(settings.JIRA_USER, settings.JIRA_PASSWORD), server=settings.JIRA_SERVER ) return jira_conn except Exception as e: log.error("Unexpected problem connecting to JIRA") raise else: log.error("JIRA credentials not configured or incomplete") raise

Which works fine, but if the credentials are incorrect (not missing) then it goes through a 1-2 minute long song and dance:

WARNING:root:Got recoverable error from GET [my jira server address], will retry [1/3] in 1.7998166159998785s. Err: 401 Unauthorized WARNING:root:Got recoverable error from GET [my jira server address], will retry [2/3] in 39.04052373359595s. Err: 401 Unauthorized WARNING:root:Got recoverable error from GET [my jira server address], will retry [3/3] in 46.35106211454652s. Err: 401 Unauthorized

before finally triggering my except clause. Is there any way to make it "fail fast"?

Python - Most efficient way to define a piecewise function

Thu, 09/21/2017 - 21:02

I have a piecewise mathematical function that needs to be evaluated a lot of times, as a subfunction in quad and curve_fit routines. In trying to improve the performance of my program, I found that a lot of time was spent in evaluating conditions in the if statements.

My function looks like :

def myfunc(x): if x < x0: return 0. elif x < x1: return func1(x) elif x < x2: return func2(x) else: return 0.

Is there a way to define the same function to reduce the function evaluation time?

note:

x0 < x1 < x2

Php if statement in footer.php Wordpress Footer.php notworking

Thu, 09/21/2017 - 20:59

i'm making this system to hide the social icon when nothing is filled in, and show it with the data if filled in.

But for some reason when using this code the whole footer.php crashes, and the footer is gone?

Anyone know's why?

<?php if ( !get_theme_mod(('pocketcars_url2') == '') ) : ?> <a href="<?php echo esc_url( get_theme_mod( 'pocketcars_url1' ) ); ?>" class="social1"><i class="fa fa-twitter" aria-hidden="true"></i></a> <?php endif; ?>

Excel VBA - Do Until Blank Cell

Thu, 09/21/2017 - 20:52

I'm recording a macro and need some help. I'd like copy and paste the values from the column G of the "SalesData" worksheet into cells A2, A12, A22 etc of the "Results" worksheet until there's no more values in the column G.

VBA is pretty new to me, I've tried using Do/Until, but everything crashed. Could you please help me? Please see the code I've recorded below. Thank you!

Sub(x) Sheets("SalesData").Select Range("G2").Select Selection.Copy Sheets("Results").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("A12").Select Sheets("SalesData").Select Range("G3").Select Application.CutCopyMode = False Selection.Copy Sheets("Results").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("A22").Select Sheets("SalesData").Select Range("G4").Select Application.CutCopyMode = False Selection.Copy Sheets("Results").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("A32").Select Sheets("SalesData").Select Range("G5").Select Application.CutCopyMode = False Selection.Copy Sheets("Results").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False End Sub

How do I find the sum of values for a multidimensional array and replace values of unused indexes?

Thu, 09/21/2017 - 20:50

I have 4x4 2D array that already has values in each index. I want to have a function that calculates the sum of a row/column of the array and store it at the first/final column and have the other indexes revert to 0.

This is what I have to render my array:

public static void print2Darray(int[][] numbers) { for (int i = 0; i < numbers.length; i++) { for (int j = 0; j < numbers.length; j++) { System.out.print(numbers[i][j]); System.out.print("\t"); } System.out.println(); } }

Which displays something like this:

10 15 30 40 15 5 8 2 20 2 4 2 1 4 5 0

Currently this is the function that I have:

public static void sumLeft(int[][] numbers) { for (int i = 0; i < numbers.length; i++) { numbers[i][0] = (numbers[i][0] + numbers[i][1] + numbers[i][2] + numbers[i][3]); if (i == 3) { numbers[0][1] = 0; numbers[0][2] = 0; numbers[0][3] = 0; numbers[1][1] = 0; numbers[1][2] = 0; numbers[1][3] = 0; numbers[2][1] = 0; numbers[2][2] = 0; numbers[2][3] = 0; numbers[3][1] = 0; numbers[3][2] = 0; numbers[3][3] = 0; } } }

Which does this:

95 0 0 0 30 0 0 0 28 0 0 0 10 0 0 0

I just want to find an algorithm that would do this without "cheating" or just hacking my way through it.

AppDomainSetup could not be found

Thu, 09/21/2017 - 20:47

Fiddling around Microsoft Orleans. This is the silo I've written from the tutorial, I get wierd error the "AppDomainSetup couldn't be found" although I can see it in the docs under System.

Searching google leads to nowhere...

class Program { static SiloHost siloHost; static void Main(string[] args) { AppDomain hostDomain = AppDomain.CreateDomain("OrleansHost", null, new AppDomainSetup() { AppDomainInitializer = InitSilo }); DoSomeClientWork(); Console.WriteLine("Orleans Silo is running.\nPress Enter to terminate..."); Console.ReadLine(); hostDomain.DoCallBack(ShutdownSilo); } }

Error: Could not find or load main class. Running maven jar-with-dependencies

Thu, 09/21/2017 - 20:41

I am using Maven to manage a personal project and am getting this maven error whenever I try to run my jar with dependencies.

$ java -jar .\SpotifyAutomation-1.0-SNAPSHOT-jar-with-dependencies.jar Error: Could not find or load main class SpotifyRunner

(I do a clean and install before running).

My pom file looks like this:

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpotifyAutomation</groupId> <artifactId>SpotifyAutomation</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib</classpathPrefix> <mainClass>SpotifyRunner</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-server</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>se.michaelthelin.spotify</groupId> <artifactId>spotify-web-api-java</artifactId> <version>1.5.0</version> </dependency> </dependencies>

Any insight on how I might go about fixing this? I have tried switching around my classpathPrefix but to no avail. My project has one module and one package.

My project structure is shown in the below image: Project Structure

ParseInt Prompt not displaying in Table

Thu, 09/21/2017 - 20:39

Any help would be greatly appreciated, I'm currently having issues with user input by prompt, to be saved as a variable so it can go through a for loop and then inserted into a table. I'm sure my mistake is in the way I'm formatting the insert into the table.

var investment = parseInt(prompt("What will be your initial investment?", "0"), 10); var interest_rate = parseInt(prompt("What will be your interest rate?", "0"), 10); var deposit_amount = parseInt(prompt("What will be your monthly deposit?", "0"), 10); var start_age = parseInt(prompt("What is your age?", "0"), 10); var beg_balance = 0; var end_balance = 0; var daily_interest_rate = interest_rate / 365; var calculated_interest = 0; var accrued_interest = 0; var cumulative_deposits = 0; var day = 0; document.write("<table>") document.write("<tr><th>Age</th><th>Beg Balance</th><th>Interest</th><th>Deposits</th><th>Ending Balance</th></tr>") beg_balance = investment; for (var yearly = start_age + 1; yearly <= end_age; yearly++) { for (var daily = 1; daily <= 365; daily++) { day++; calculated_interest = (daily_interest_rate) * (beg_balance + cumulative_deposits + accrued_interest); accrued_interest += calculated_interest; if (day == 30) { day = 0; cumulative_deposits += deposit_amount; } } end_balance = beg_balance + cumulative_deposits + accrued_interest; document.write("<tr>"); document.write("<td>" + yearly.toFixed(2) + "</td><td>" + beg_balance.toFixed(2) + "</td><td>" + accrued_interest.toFixed(2) + "</td><td>" + cumulative_deposits.toFixed(2) + "</td><td>" + end_balance.toFixed(2) + "</td>"); document.write("</tr>"); beg_balance = end_balance; cumulative_deposits = 0; accrued_interest = 0; } document.write("</table>")

Is there a performance cost for not declaring the "type" attribute in the <style> tag?

Thu, 09/21/2017 - 20:38

The type attribute in the <style> tag identifies the type of media being used.

If the type attribute is not declared, it defaults to text/css.

Is there a performance cost (however small) for not declaring type="text/css" in the <style> tag?

How to indicates to ui component when async jobs finishes?

Thu, 09/21/2017 - 20:37

I have a manager class that communicates with a view component, and this manager class has a method that performing bunch of api calls before it returns a value, so I want the component to have some kind of indicator for when the api calls ended cause I need to disable some button while the data still keep on coming, so did this:

export class MyManager { public stillBringingData = new BehaviorSubject<boolean>(false); public myAsyncFunc(animals: Animal[]): void { let counter: number = 0; animals.forEach((animal: Animal) => { counter++; this._myApService.getAnimalInfo(animal.id).subscribe((animalInfo: AnimalInfo) => { //currentAnimalInfo is some behaviour subject hat the client listen too this.currentAnimalInfo.next(animalInfo) }); this.stillBringingData.next(counter === animals.length) }); } }

and the ui component listening to this behaviour subject with a subscription.

it feels a bit clumsy, does there a more classic way?

working with angular 4 / Observables / typescript

thanks

How can I get the result type of a member function applied to a class member in an unevaluated context

Thu, 09/21/2017 - 20:37

I'm not even sure this question's title is correct. What I'm trying to do is fairly gnarly to me so I don't even know how to describe it in a concise manner. Sorry about that.

I have a container of values which are wrapped in some kind of "safe" value class. I need a function that takes a pointer to that container, a reference to one of its member and the following happens:

If the pointer passed is valid, the function returns the value inside the wrapped value.

If the pointer passed is nullptr, the function returns a default-constructed value.

Anyhoo, here some code.

template<typename T> class Wrapped { T t; public: T& operator*() { return t; } }; class Container { public: Wrapped<int> i; Wrapped<string> s; }; // Compiler error with R. // I'd like R to be the return type of invoking operator* on the member that's represented by M. // I've tried about 50 different versions of declarations to declare the type of R. This one feels like it most closely represents what I'm trying to achieve. // R should be the T in Wrapped<T>. template <typename T, typename M, typename R = decltype(declval<M>().operator*())> R value_or_default(T* object, M member, R default_value = R{}) { object ? *((*object).*member) : default_value; } Container c; auto actual_int = value_or_default(&c, &Container::i); // Returns *(c.i). auto default_string = value_or_default(nullptr, &Container::s); // Returns string{}.

Adjusting bounds in Leaflet (R) with sf column

Thu, 09/21/2017 - 20:21

I'm making a little app in Shiny that holds data for countries and regions, and where users will be able to choose a region. Then the idea is that the leaflet map that I have in the app will zoom in and focus on the chosen region (i.e. user clicks "Europe" and the map zooms in on Europe).

I can't figure out how I should go about using the simple featuresgeometry column as the filter for the leaflet map. Here's a simply example (not in Shiny, but the problem is not Shiny-related, I imagine).

library(rnaturalearth) library(dplyr) library(leaflet) # sf data: earth <- ne_countries(returnclass = "sf") %>% select(Region = region_un, geometry) # little dataset: df <- data_frame( Region = c("Europe", "Africa", "Asia", "Oceania", "Americas"), Score = c(0.85, 0.77, 0.81, 0.93, 0.79) ) # join: df <- full_join(df, earth) # simulate what I'm doing in Shiny: input <- list() input$region <- "Europe" df2 <- filter(df, Region == input$region) leaflet(df2) %>% addTiles()

This produces:

Which is the same as if I had used df (the unfiltered dataframe). Any ideas on how I could go about this? I couldn't find it in the Shiny/leaflet docs.

Detecting which screen user exited app

Thu, 09/21/2017 - 19:13

I haven't been able to find anything on this so far, so if you could either guide or point me in the direction of where I can figure this out I would greatly appreciate it.

I was wondering if we can detect from what view controller a user either quit, or exited the app (through the home button or maybe even a phone call came in etc...). I am working on a game where users ask one another multiple questions at a time and I want to make sure that if a user views the first question, answers incorrectly and quits the app before answering the second question, he/ she cannot access the first question again on app reboot. I would like it to be so that the user gets 0 points in the case the app is quit while on this view controller.

Using arrays in for loops python

Thu, 09/21/2017 - 18:43

I am trying to run all the elements in just_test_data to all the elements in just_train_data, and return the lowest number, then run the new just_test_data through all the just_train_data, and so on until all the just_test_data has been run.

The error I keep getting is in the line

step_1 = (abs(just_test_data[i] - just_train_data[n]) ** 2) IndexError: arrays used as indices must be of integer (or boolean) type

When I first try to run the loop.

import numpy as np testing_data = np.genfromtxt("C:\Users\zkrumlinde\Desktop\Statistical Programming\Week 3\iris-testing-data.csv", delimiter= ',') training_data = np.genfromtxt("C:\Users\zkrumlinde\Desktop\Statistical Programming\Week 3\iris-training-data.csv", delimiter= ',') #create 4 arrays, the first two with the measurements of training and testing data #the last two have the labels of each line just_test_data = np.array(testing_data[:, 0:4]) just_train_data = np.array(training_data[:, 0:4]) testing_labels = np.array(testing_data[:, 4]) training_labels = np.array(training_data[:, 4]) n = 0 while n < len(just_train_data): for i in just_test_data: old_distance = 'inf' step_1 = (abs(just_test_data[i] - just_train_data[n]) ** 2) step_2 = sum(step_1) new_distance = np.sqrt(step_2) if new_distance < old_distance: old_distance = new_distance index = n n = n + 1 print(training_labels[index])

How to debug undefined method form_with error

Thu, 09/21/2017 - 17:33

I'm getting the error:

undefined form_with for #<#<Class:0x7ac62e0>:0x551e5a8> in articles#new

The error occurs in the following file: new.html.erb Which has:

<%= form_with(model: [@article] , local: true) do |f| %> <p> <%= f.label :title %><enter code here`br> <%= f.text_field :title %> </p>

And the controller articles_controller.rb has:

class ArticlesController < ApplicationController def new end end

JSch: Is there a way to expose user environment variables to "exec" channel?

Thu, 09/21/2017 - 16:42

I am trying to run commands which uses local Linux logical paths like cat $test_dir/test.dat, but the logical path $test_dir (which is a user environment variable) is not available via ChannelExec. But when I use interactive ChannelShell, I am able to see the user variables and the commands run fine on the interactive session. I can view system level environment variable only from "exec" session. Is that even possible using JSch library, if yes then how shall I achieve it and if not what library shall I use to achieve this?

Adding my class code below: `public class SecureShell {

private static final Logger logger = LogManager.getLogger(SecureShell.class); private String uName; private String pWord; private String hName; private int port; private Session session = null; private Channel channel = null; /**Create an instance to start and stop the remote shell and execute commands remotely via java. * * @param uName * host username * @param pWord * host password * @param hName * host name * @param port * host port number */ public SecureShell(String uName, String pWord, String hName, int port) { this.uName = uName; this.pWord = pWord; this.hName = hName; this.port = port; } /**Create an instance to start and stop the remote shell and execute commands remotely via java. * *@param uName * host username * @param pWord * host password * @param hName * host name */ public SecureShell(String uName, String pWord, String hName) { this.uName = uName; this.pWord = pWord; this.hName = hName; this.port = 22; } /**Start the session with the host. * @return * true if the session started successfully, false otherwise */ public boolean startSession() { JSch jsch = new JSch(); try { session = jsch.getSession(uName, hName, port); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setPassword(pWord); session.connect(); } catch (JSchException jsche) { logger.error(jsche.getMessage()); return false; } return true; } /** Execute commands on the host; * @param command * command to be executed on the host. * @return * status of the execution */ public int execute(String command) { int status = -1; if(session != null && session.isConnected()) { try { channel = session.openChannel("exec"); //((ChannelExec)channel).setEnv("LC_XXX", "xxxxxxx"); ((ChannelExec)channel).setPty(true); ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); byte[] buffer = new byte[1024]; while(true){ while(in.available()>0){ int i=in.read(buffer, 0, 1024); System.out.print(new String(buffer, 0, i)); if(i<0) break; } if(channel.isClosed()){ if(in.available()>0) continue; status = channel.getExitStatus(); break; } } } catch (JSchException jsche) { logger.error(jsche.getMessage()); } catch (IOException ioe) { logger.error(ioe.getMessage()); } finally { if(channel!=null && channel.isConnected()) channel.disconnect(); } } return status; } /**Stop the session with the remote. * */ public void stopSession() { if(session!=null && session.isConnected()) session.disconnect(); } public static void main(String[] args) { SecureShell ssh = new SecureShell("user", "password", "hostname"); ssh.startSession(); System.out.println(ssh.execute("env")); ssh.stopSession(); }

}`

Java list check if an element is duplcate and mark it

Thu, 09/21/2017 - 11:59

I have a list of objects, in that list could be duplicate elements and I need to check each element in that list with all elements the list, if I found a duplicate element I have to mark it as duplicate.

I did this with normal for loop as show :

for (int i = 0; i < records.size() - 1; i++) { Record record = records.get(i); for (int k = i + 1; k < records.size(); k++) { Record currentRecord = records.get(k); if (RecordsParser.isDuplicateRecord(record, currentRecord)) { currentRecord.setValid(false); currentRecord.setErrorCode(ErrorCodes.DUPLICATE_ID); } } }

So my question is : Is there any way to this logic with lambda expresion in a cleanner way ?

Pages