FAQ Database Discussion Community


Python import modules in another file

python,python-2.7,global,python-import,python-module
I'm currently re-factoring a project (formerly big one file) into several seperate python files, each of which runs a specific part of my application. Eg, GUIthread.py runs the GUI, Computethread.py does some maths, etc etc. Each thread includes the use of functions from imported modules like math, time, numpy, etc...

Flask, WSGI, and Global Variables to Hold Database Pool

python,flask,global,wsgi
I'm using WSGI/Apache2 and am trying to declare my database pool on init, to be accessible via a global var from my endpoints. I'm using Redis and Cassandra (DSE, specifically). It's my understanding that both the Redis and DSE libs offer pool management so this shouldn't be an issue. My...

Global variables have nil value, attempt to call global (a nil value) in Corona

lua,corona,global,nil,value
I attempt to get data (in a global variable) from user through a textbox from the user in functions, and use these variables to insert into a sqlite table. But, when I attempt to do so, I get an error like "attempt to call global locationGlobal (a nil value)" in...

PHP global config files

php,config,global
i have a config.php file that contains : <?php // Config File return array( //database connections 'db_type' = 'mysql'; 'db_host' = 'localhost'; 'db_user' = 'user'; 'db_pass' = 'pass'; 'db_name' = 'name'; ); then i call that in my init file (i've tried it with and without the GLOBAL) if (file_exists(ROOT...

Why is globals() a function in Python?

python,global
Python offers the function globals() to access a dictionary of all global variables. Why is that a function and not a variable? The following works: g = globals() g["foo"] = "bar" print foo # Works and outputs "bar" What is the rationale behind hiding globals in a function? And is...

I cannot get the restart button to work on my stopwatch. Using Pythonista on iPhone

python,iphone,user-interface,uibutton,global
import ui from time import * start = int(time()) def stop_time(sender): finish = int(time()) total_time = int(finish - start) button1 = str("Your time is %i seconds." % (total_time)) sender.title = None sender.title = str(button1) How do I allow the restart button to change the start variable? def restart_time(sender): start =...

Creating global array of objects (java)

java,arrays,object,global
So I'm working on a Space Invaders theme project, and I have most of my classes up and running and have started on the animation. Part of the process is the ship's weapons. I have a class for the weapons, as below (Focus on the constructor): /** * @(#)Weapon.java *...

Passing variables around a GUI (using globals)?

python,user-interface,global
I have a short program using Tkinter with two main buttons: Load Files, and Run Process. Load Files creates four lists of a few thousand objects each. Run Process runs my algorithm on these lists and generates a report for the user. My question is: In general, where should these...

How to make Window var global

c#,global,partial-classes
I am using a piece of code that allows me to edit another window, e.g. a textbox located inside: var MessageBox_Window = System.Windows.Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MessageBoxWindow) as MessageBoxWindow; I need to be able to change the contents of this window constantly however I cannot put the var in partial...

global variable returns null when sent to list

php,variables,null,return,global
I'm currently working with these two parts of code. One is for receiving the data and one for displaying it in a list, but for some reason the variable $emp_name always returns null when I'm trying to display it in the second part. The idea is to search an employee...

R scoping: disallow global variables in function

r,scope,global
Is there any way to throw a warning (and fail..) if a global variable is used within a R function? I think that is much saver and prevents unintended behaviours...e.g. sUm <- 10 sum <- function(x,y){ sum = x+y return(sUm) } due to the "typo" in return the function will...

Certain Javascript works on single pages, but not when loaded globally via a Drupal theme's javascript

javascript,jquery,drupal-7,global
On the SO-chat, I was advised to ask the following question here: I would like to load some Javascript globally on my complete website, via a Drupal theme's Javascript; insead of having to re-insert the Javascript-code each article over and over again. For example, I have managed this with the...

Declaring global inside a function

python,python-3.x,global
Lately, I've had to write functions that look like this: fruits = [] def foo(): global fruits ... What exactly does the line global fruits do? I apologize if this question has been asked before, but I could not find one like this....

Angularjs reload value in factory

global,value
I am a newbie in AngularJS and I get some difficulties. I've got an Angular value that should be available globally in some factories. It stores an adressess of other services and by default all values are null: angular.module('env_settings') .value('address', { management: null, data_store: null, repository: null, single_service: null });...

How should a global (module) object be created in a Python function?

python,url,import,global,local
I am trying to write a function to "import" a Python module from a URL (as an experiment -- there are, of course, security concerns with such an approach). In doing so, I am attempting to create the module object in the function and then to modify it with the...

Having multiple threads perform actions based on a global variable

python,multithreading,variables,global
I'm attempting to have one thread change a global variable and then have the other threads check that global variable and if it changes, perform some action. I've read through threading python docs but it's all very new to me and I'm not sure what the best options are for...

Calling jquery function with javascript

javascript,jquery,function,global
I'm trying to call fxn function outside $(document).ready(), but I can't get it working. It returns ReferenceError: fxn is not defined.. anything I missed?...

Difference between static and const variables [duplicate]

c#,variables,static,const,global
This question already has an answer here: What is the difference between Const and Static in C#? 5 answers what is the difference between "static" and "const" when it comes to declare global variables; namespace General { public static class Globals { public const double GMinimum = 1e-1; public...

declaring global perl subroutines or global aliases

perl,oop,object,global
my question is, HOPEFULLY simple. In Perl, how does one create a global scoped subroutine accessible to all objects thereafter? sub throw { die(shift); } Seems to work in global scope, but is not accessible to packages afterwards. I would like to avoid doing something of the sort of declaring...

Global variable becoming undefined from within event listener - javascript

javascript,global,addeventlistener
I have a function that creates a new image and gives it an event listener, which needs to access a global variable. The global variable (_currentSection) is defined until it gets to the declaration of the event listener, when it then becomes undefined. Here is the function: function relMouseCoords(event) {...

Do I need a global variable or better OO design in this rails application?

ruby-on-rails,ruby,variables,design,global
I'm writing a rails application that uses the discogs api ruby wrapper by buntine and most of my objects need access to the @discogs object that exists in the controller and represents the entire ruby wrapper and connection to discogs. Instead of passing @discogs to other objects, which in turn...

Global Variable - AJAX jQuery

javascript,jquery,ajax,variables,global
I'm trying to set the global variable countryCode. But the value is always null. What can I do? I tried many ways. PLS HELP! function GetGeolocation(){ $.getJSON("http://ip-api.com/json/?callback=?",function(data){ $.each(data, function(k, v) { table_body += "<tr><td>" + k + ": " + "</td><td><b>" + v + "</b></td></tr>"; if (k == "countryCode") {...

How can i define a global variable Class in Swift

class,swift,variables,global
I am new to swift, a need to define a global variable class to be used in every controller class. Thanks....

Global character array won't be reassigned or outputted correctly

c++,arrays,char,global
I'm trying to make a very basic tic tac toe program, and I'm storing the board in a character array. The array is global so I can output it from a function and also assign X's and O's to places in the main function. My code is below. The problem...

Location of Including PHP File Affects Global Variable Scope

php,xampp,global
It appears that the location of my including file affects global variables inside of the included file. It's complicated. See below: /config.php <?php $domain = 'localhost'; $database = 'db'; ?> /functions.php <?php require_once("config.php"); function getDatabase() { global $database; return $database; } ?> /endpoint.php <?php require_once($_SERVER['DOCUMENT_ROOT']."/functions.php"); print(getDatabase()); ?> /api/endpoint.php <?php require_once($_SERVER['DOCUMENT_ROOT']."/functions.php");...

Global keyboard function in Autohotkey?

windows,function,keyboard,global,autohotkey
This script "auto-presses" E while holding it down. $e:: While GetKeyState("e","P") { Random, r, 50, 250 sleep r Send e } return Is there a way to globally call this function for any key? For example: Holding A, will auto-press A and Z will auto-press Z, etc. Without manually assigning...

python : variables in a list and outside a list

python,list,global
I have a number of global variables set to False, and then I have all of these variables in a list: var1 = False var2 = False var_list = [var1, var2] $ print var_list False, False later in the script the global variables are set to True in a function:...

How to share an instance created in main with a class in another module

python,class,share,instance,global
I am having a problem with how to share a class instance between modules. Below is not the actual code, it is a simplified representation of what I'm trying to do. The variable in question is thePlot. If I make it a global, I get 'global name not defined' type...

PHP global variable is not changing [duplicate]

php,variables,global
This question already has an answer here: PHP Pass variable to next page 7 answers I have problem with PHP and globals. In this code: at the page starts, the result is: Test 123. After click in: ListBox1Click the result is: XXXXXXXX. After click in: ListBox2Click the result is:...

Convert local coordinates to scene coordinates in SceneKit

global,local,scenekit,coordinate
I have a node attached to a node and I want to convert it's coordinates to coordinates of scene. I really don't know how to do that. I've been searching on Apple's documentation and I haven't found a method that fits my need. Any suggestions?

Is it possible to use common fragment generate function globally?

java,android,android-fragments,global
I have common fragment generate function like the following: // Common Fragment generation method public void generateFragment(String speechString, String buttonString) { // Store data to be passed to the fragment in bundle format Bundle args = new Bundle(); args.putString("Speech", speechString); args.putString("ButtonTitle", buttonString); // Instantiate Speech fragment and set arguments SpeechFragment...

How can i use other function variables?

javascript,global
How can i use a in genTable? It says that a is not defined JS: function colNum(){ a=prompt(' The number of collums?'); if(!parseInt(a)) { console.log("Not number") } } function genTable(){ table = document.createElement('table'); table.setAttribute('id','tbl'); tr = document.createElement('tr'); for (var i = 0; i < a; i++) { var th1 =...

How can I change the value stored in local macro from string to numeric in Stata?

types,macros,global,local,stata
I want to generate a variable with lagged year depending on the year stored in "$S_DATE" macro I have stored the year in date macro: . local date substr("$S_DATE",8,.) . display `date' 2015 And I want to generate the new variable with gen start_year =`date'- y_passed where y_passed is a...

variable global const “macros” in C++ and optimal design patterns

c++,design-patterns,mfc,const,global
I inherited some 10 year old code I have to complete. The code is in MFC (C++). There's a .h file where the custom data structures are written and some const variables are in there as Globals. Some of these are used for MS Office file extensions, of type CString,...

Python module reusing the same object

python,global
This module returns a list. When I call the module with ipscan.scan('192.168.11', 161) the list gets appended instead of returning a new one. The only way I managed to "reset" the list was by reassign the global parameter key "node_list" like this ipscan.scan.func_globals['node_list'] = [] Being a beginner I don't...

Android simple method to create and use global variables?

java,android,variables,global
I'm coming up short when trying to locate a simple method to implement a global variable into my app (an array of Java classes that I plan to use in a couple of activities). I saw one method that looked as though it made sense and was easy to implement....

Storing this object in custom private variable

javascript,jquery,this,global
I have this js object var toggleItem = { attrData : '', toggleNew : '', toggleOld : '', //var self : this, init : function(){ self = this; self.listener(); }, listener : function(){ jQuery('.btn-save').click(function(){ var current = this.id.split('_').pop(); self.toggleNew = jQuery('.toggle-data-new_'+current).val(); self.toggleOld = jQuery('.toggle-data-old_'+current).val(); self.updateForm(); }); }, updateForm : function(){...

Setting global variables and wrap in $(window).load

javascript,variables,global
I'm trying to set some Js variables that calculate some heights and offsets, but I need to do that after the page loads b/c I've got 3rd party ads loading and shifting things around. So the issue: What I've got is: var sidebarHeight = $('.sidebar').height(), sidebarOffset = $('.sidebar').offset().top; But those...

How can I define global variables inside a twig template file?

php,variables,twig,global,templating
Is it possible to set global variables in a twig file, so that I can access that variables from other files, macros and blocks. For example, I want to have variables.twig file and in it set my variables and then I can include it in other templates. I know that...

Why is it faster to allocate memory in the heap for a local array compared to a global array?

c++,memory-management,global,local
Below is a simple experiment that I decided to run. test1() is a function that allocates memory for the global array g and then has a for loop that updates all the elements of this array. Finally it releases the allocated memory for g. Exactly the same thing is happening...

tkinter entry variable from function

python,tkinter,global,entry
This should be easy but I am suffering search fatigue for the answer I need. The code below pops up an input window. I make entries into the entry fields and the function show_entry_fields() gets the input and the window closes. I then want to use the new entry variables...

jQuery | Using globals variables in this small snippet

jquery,variables,global
i'd like to use these variables globally. the resize function does not work. only if i copy the variables. i want to use this code inside a document ready function. thanks for your help. var pageWidth = $('#page').width(), pageWidthFifth = pageWidth / 5, wrapAndSidebar = $('#sidebar-wrap, #sidebar'); wrapAndSidebar.width(pageWidthFifth); $(window).resize(function(){ wrapAndSidebar.width(pageWidthFifth);...

inconsistent need for global keyword when referencing variables in other PHP scripts

php,global,require
I've hunted for an answer to this, but still can't explain the inconsistency i'm experiencing. Heregoes... I'm writing a simple CMS in PHP and cannot understand how I can directly reference external variables from one require call but not another 1. Here's my Db_Conn.php script. <?php if(!class_exists('Db_Conn')){ class Db_Conn{ var...

Updating the global integer variable

global,drools
I am modifying the global integer variable with some value in the Rule 1. I need to get this modified value in some other rule say Rule 2. global Integer deviceCapacity; rule "Rule 1" dialect "java" no-loop true when $snrData : SensorDataVO(getWeightOffset().size()>0, $initOffset:getInitialOffset()); then for(Integer iOff:$snrData.getWeightOffset()){ $snrData.getOffsetChngesInterval().add(iOff-$initOffset); insert (new NotificationVO(iOff-$initOffset));...

C global function (not C++)

c,function,function-pointers,global
I'm trying to have a global function in C. Something that can be called from different files. I know how to make a global variable by declaring it (with extern) in all files except one, and defining it in just one file (without the extern). I need a - possibly...

Tcl $argc and $argv variables

variables,tcl,global,argv,argc
I'm kinda new to tcl but I have to write a proc that looks like this: proc TestVerb { Data Data_txt } { VERBATIM [format "// Data: $Data - $Data_txt"] if { $argc == 2} { VERBATIM {// SUCCESS //} else { exit 1 } I call the proc like...

Implementing Universal search in rails 4

ruby-on-rails,ruby,search,global
I have a rails 4 application with number of models and view pages. The application layout of my application contains a search bar. But it is inactive as of now. The purpose of search bar is to allow user to search through all the models for the keyword(s) entered, basically...

Why is 'event' available globally in Chrome but not FF?

javascript,jquery,javascript-events,event-handling,global
While working on an answer for another question, a strange bug came up related to the event object being available in an anonymous function without being passed in. In Chrome the below works fine, but FF throws an error. $(document).ready(function() { $("#uspsSideboxTrackingClose").click(function() { event.preventDefault(); console.log(event); }); }); Chrome: FireFox: ReferenceError:...

Ruby on Rails - Source a file and save ENV variable as global

ruby-on-rails,constants,global,env
I have an API key which I've saved to /home/user/api/keys that I would like to save as a global variable in my Rails app. I thought this would work, this is my config/initializers/my_constants.rb: `source "/home/user/api/keys"` API_PASS = ENV["API_PASSWORD"] And this is /home/user/api/keys (without the real value, obviously): #!/bin/bash export API_PASSWORD="--------"...

Python: access variable in a function in another file

python,variables,import,global,local
I have two files: lib.py global var def test(): var = "Hello!" return test.py from lib import * test() print(var) But despite having them in the same folder, when I run test.py, I get the following error: Traceback (most recent call last): File "C:\Test\test.py", line 5, in <module> print(var) NameError:...

C: Passing variables between files

c,scope,global
I'm trying to pass a local variable (in func1) to a function (func2) in another file, but func2 requires that as a global variable. To explain things better, here are the two files: file1.c: #include <something.h> extern void func2(); void func1(){ int a=0; func2(); } file2.c: #include <something.h> extern int...

Static member/ methods and Global scope [closed]

java,jvm,global,static-methods
In Java , there is no Global scope. then how are the Static members are stored ?

global and local variable execution context in javascript

javascript,variables,global,local
Trying to understand fundamentals of javascript I ran into a following code and expected value of variable named "foo" would be 7 and 5 however it came out as 7 and 7. Not sure why.... var foo = 5; (function Test() { foo = 7; console.log("foo=" + foo); })(); console.log("foo="...

Global variable from included file in static function

php,global
I have index.php with included file strings.php for translating phrases. In strings.php is included file based on user language: $lang.php. This $lang.php file is automatically generated from $lang.ini and contains single array: <?php $translation = array ( 'USER_PROFILE' => 'Uživatelský profil', 'MESSAGES' => 'Zprávy', 'NOTIFICATIONS' => 'Oznámení', 'SETTINGS' => 'Nastavení',...

Use Commands from argv to Initialize a Global Mutex

pthreads,global-variables,global,mutex,argv
What I wish to do is to define a global mutex using data from argv. Not a problem, except that I also want this mutex to be global. This isn't global:: int main (int argc, char **argv) { int arg_1 = atoi(argv[1]); pthread_mutex_t mutex[arg_1]; return 0; } And this isn't...

Global scope inside if/else for a running median

python,variables,if-statement,global,scoping
I'm implementing a running median algorithm in Python using two heaps. However, the heaps don't grow in size even if I push to them... I suspect it's something to do with the scoping inside if/else statements. I don't really understand how to fix this. import os import numpy import functools...