FAQ Database Discussion Community


Overriding a constant value at runtime

ios,constants,objective-c-runtime
I'm using some external library via cocoapods and was requested to customize its standard behavior. I found out, that this behavior depends on a constant, declared in a library. Like so static const NSInteger CONSTANT_NAME = @".."; This constant is used throughout the code, so swizzling every affected method and...

How to override a class constant in PHP?

php,oop,constants
When working with constants, I've always tried to define constants like the following which allows end-users to override their values. if ( ! defined( 'MY_CONST' ) ) define ( 'MY_CONST', 10 ); I've now started to work with classes (OOP) and would like to know if there's a way to...

A linear time, constant space algorithm for finding an element with 1 occurrence in a list [duplicate]

algorithm,list,constants,time-complexity,space-complexity
This question already has an answer here: Finding a single number in a list [duplicate] 11 answers Given a list of n integers, where every integer in the list exists twice, except for one element, which exist once in the list. For example, [1 3 3 6 2 7...

Powering a Math constant in Julia is slow

constructor,constants,julia-lang
I'm pretty sure this has to be a bug... Ok, so basically, when I pass a Math Constant type to the power (^) function and iterate it several times... The loop is really slow and uses a lot of memory allocation. The example is trivial as it doesnt produce any...

Why final Byte as a case in switch statement doesn't compile?

java,switch-statement,constants
byte a = 125; final byte b = 2; final Byte c = 3; switch (a) { case b: // works fine break; case c: // Constant Expression required break; } Since cis a final variable, isn't it a compile time constant and hence a valid case label?...

What's the best way to get a Class object for an array type?

java,arrays,reflection,constants,literals
It's easy to get a class literal for a class: String.class But how can I get a class object for an array type? This works, but it's ugly, and probably not a compile time constant: new byte[0].getClass() I looked in the JLS but the only thing I found out is...

Is there any way of protecting a variable for being modified at runtime in C?

c,variables,constants
I was wondering if there is any way of protecting a variable for being modified once initialized (something like "constantize" a variable at runtime ). For example: #include <stdio.h> #include <stdlib.h> int main(void) { int v, op; scanf( "%d", &op ); if( op == 0 ) v = 1; else...

Php: json to constants

php,eval,constants
I have a Json that contains a few contants I'd like to auto-define. It works fine with simple "key": "val" statements, but I can't make it work for eval staments: $cat test.php <?php function objDefinition($obj) { foreach ($obj as $key => $val) { $val = $val; \define($key, $val); } }...

Interface constant declaration example in Java's SDK

java,interface,constants
Is there an example of an Interface in Java's built-in library (JDK) that contains a constant field? From the documentation, constant declaration can be defined in interfaces, but I can't remember seeing such. public interface OperateCar { // constant declarations, if any ... } ...

Is extracting a large number of String literals a good idea? [closed]

java,string,memory-management,constants,static-analysis
In a legacy code base I am dealing with, there are vast number of String literals. A large number of them are duplicates. For example, the string "userID" is used say in 500 places. There are maybe a thousand such literals which are used in a repeated manner. IntelliJ Idea...

Non-existant constant return true

php,constants
Each time user logs in, I extract a serialized array containing rights. When I unserialize the array and try to assign each right to a constant, non-existant constants return TRUE. For instance, here is my call to database : $req_level = $pdo->prepare('SELECT * FROM users_levels WHERE level_id = ?'); $req_level->execute(array($row['level_id']));...

Check if string can be mutated in C

c,arrays,string,const,constants
Say I have this function: void f(char *s) { s[0] = 'x'; } This function will sometimes cause errors and sometimes not. For example, char *s = "test"; f(s); // Error char t[] = "test"; f(t); // Success Inside function f, is it possible to determine whether or not s[0]...

Why PHP constants declared as case insensitive can be reassigned

php,constants
Lately I found a bug in a huge system I'm working on caused by this behaviour: Consider this: define('TEST',10); echo TEST; // prints 10 define('TEST',20); // Error -> already assigned. But if we declare it as insensitive: define('TEST',10,true); echo TEST; // prints 10 define('TEST',20); // no error ???? echo TEST;...

How to use constant memory for beginners (Cuda C)

c,memory,cuda,constants
I have 3 constant variables (A,B,C) which I would like to save in the constant memory; I figured out one way to do it by typing this lines of code: // CUDA global constants __constant__ int A; __constant__ int B; __constant__ int C; int main(void) { float pA=1; float pB=2;...

Swift: Declaring a constant in a subclass but still have a reference to it in the superclass?

ios,swift,constants,subclass,superclass
Let's say you had the class Apple with several subclasses. class Apple { let color = "" } class redDelicious :Apple { let color = "Red" } class grannySmith :Apple { let color = "Green" } func eatApple (appleToEat: Apple) { if appleToEat.color == "Red" { //do something } else...

Android Constants

java,android,constants
I am working on some old code that we pulled from a decompiled APK (no one has the code base anymore, just the APK from our developer account). There is a line of code in it: localAlarmManager.setRepeating(3, 10000L + SystemClock.elapsedRealtime(), 25200000L, localPendingIntent); What are the Android constants that would be...

Define global constant in Matlab

matlab,namespaces,global-variables,constants,superglobals
I want to define SI global prefixes in Matlab to make my code self explaining. I defined it in startup.m: % define SI prefix global SI SI.milli = 1e-3; SI.micro = 1e-6; % and so on.. It works fine, if I run test.m directly % test.m file Area = 10...

DB Table of constants vs constants in code

php,mysql,constants
Eternal question. I have a table moments_of_day: id name 1 Morning 2 Afternoon 3 Evening 4 Night And then an other table, meals, references it with moments_of_day_id. And then, in my PHP code I want to get all meals of morning. What's the best option? Should I repeat constants in...

what is the difference between constant variables and final variables in java? [duplicate]

java,variables,constants,final
This question already has an answer here: Difference between Static and final? 8 answers Please help me understand the difference between the constant variables and final variables in Java .I am a bit confused with it....

Can i use Dynamic variable(like time) to construct static final variable(constant)

java,android,exception,constants,static-variables
For building File name i'm constructing name like below mentioned way public static final String JSON_LOG_FILE_NAME = "JSON" +getUserName() + System.currentTimeMillis() + ".txt"; this is working till yesterday and now it is giving exceptioninintializationerror. And my doubt is can use dynamic values like android device time and database values as...

Constants in C: declaration separate from definition

c,gcc,constants
All C code: Why is this allowed: int main() { const int *i; int j=2; i=&j; } But not this: int main() { const int i; int j=2; i=j; } Is there a way to declare a local constant variable and then define it elsewhere within the scope? The first...

Are mutable constants safe?

python,constants,mutability
Are there any sort of 'gotchas' associated with having a constant that is a list, or any other mutable object? Currently my context has to do with constants that will be passed to a call, but I ask the question generically as I don't feel that topic impacts the question...

Why does this code works well? It changes the Constant storage area string;

linux,module,kernel,constants
this is a simple linux kernel module code to reverse a string which should Oops after insmod,but it works well,why? #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> static char *words = "words"; static int __init words_init(void) { printk(KERN_INFO "debug info\n"); int len = strlen(words); int k; for ( k = 0;...

Best practice to store arrays

data,constants,superglobals
I'm using this code to prepare values for meta data selection in posting and search forms. <select> <?php $my_custom_meta_regions = array ( 'region1' => 'Region1', 'region2' => 'Region1', 'region3' => 'Region1' ); forearch ($my_custom_meta_regions as $key->$value) : ?> <option value="<?php echo $key; ?>"><?php echo $value; ?></option> ?> The problem is...

AngularJS constants in main module

angularjs,constants,angular-resource
It looks like there's several ways to define constants in Angular. In this example we are defining two constants in our main module config.js: 'use strict'; angular.module('app') .constant('URL', 'http://localhost:8080/users') .constant('RESOURCES', (function () { var resource = 'http://localhost:8080'; return { USERS: resource + '/users' } })); }()); We have a factory...

Inject constant to other modules config using Angular JS

javascript,angularjs,dependency-injection,constants,provider
I would like to share some variables like base paths throughout my application. These variables needs to be accessible during module configuration. My opinion was, that I can use a constant or provider for that. I've got several modules and each one has it's own routing configuration. In these routing...

ruby on rails, colon at back or front of variables

ruby-on-rails,ruby,variables,constants,colon
I am new to ruby , and rails both. I think Rails is one of the best API, and ruby is quite unique, it seems that ruby can cleverly do "assumptions" to help developer. But I am not too sure to what extend. my questions is about colon in variable....

How can a constant be defined without using a literal?

java,constants,final,literals
I'm struggling to understand how a constant can be defined without using a literal. Does final int A = 1 + 1 count?

How to handle lots of constants in Haskell?

haskell,constants
I’m working on a library allowing a developper to control a Minitel (the french videotex terminal). I have a lot of constant values and I would like to know the best way to manage them with Haskell. It's a common question among beginners but I haven't found a satisfying answer....

Swift optional values during initialization preventing default initializer inheritance

swift,initialization,constants,optional,swift-playground
In Swift: 1) If you provide a default value for all of the stored properties in a class, then you inherit the default initializer, ie - init(). -- AND -- 2) A property of any optional type defaults to the value of nil, ie - var shouldBeNill: String? //should initially...

Gemfile constants redefinition, “warning: already initialized constant”

ruby,gem,constants,gemfile
In my Gemfile I have two gems that both define the same set of constants. The two gems are sentiment_lib and engtagger. This means whenever I run a task I get more than 10 warnings like this: ...engtagger/porter.rb:6: warning: already initialized constant Stemmable::STEP_2_LIST ...stemmer/porter.rb:10: warning: previous definition of STEP_2_LIST was...

angularjs constant code lint

angularjs,ionic-framework,constants,lint
I'm using 02_jshint.js to code lint my Ionic project, everything goes well until I receive this error: 35:4 -> Missing semicolon. -> }) and it's pointing to the last constant's bracket of my code: angular.module('myApp.constants',['ionic']) .constant('A','2.1.4') .constant('B','1.1.3') .constant("c", { "d": "cost1", "e": "cost2", "f": "cost3" }) I would like to...

possible inconsistency in constant values? [closed]

c++,pointers,constants
In the code below p is constant both the pointer and value but b can change the value of *p. It is not intuitive. Shouldn't the compiler produce a warning at least? int b{3} const int* const p{&b} //*p = 5; // correctly produces error b = 5; // constant...

How to define a constant record containing other constant records in Delphi? Specific case: matrix using vectors

delphi,constants,delphi-xe2,record
Say I have a simple record in a unit, such as: TVector2D = record public class function New(const x, y: Accuracy): TVector2D; static; public x, y: Accuracy; end; I then have a second record in the same unit that is built using a set of the above records, such as:...

Using NSMutableAttributedString as a Constant in iOS

ios,swift,nsstring,constants
I just started to learn Swift and came across something I don't understand. In a tutorial the author creates a NSMutableAttributedString within a constant. Later on that constant is altered. What I don't understand is how this is possible without getting any errors. Does NSMutableAttributedString somehow, for lack of a...

Counter as variable in for-in-loops

variables,swift,constants,declaration,for-in-loop
When normally using a for-in-loop, the counter (in this case number) is a constant in each iteration: for number in 1...10 { // do something } This means I cannot change number in the loop: for number in 1...10 { if number == 5 { ++number } } // doesn't...

What is the value of ABAP constants with prefix “%_”?

constants,sap,abap
We are writing a tool in Java to analyze ABAP programs. The code is extracted and given to us as text, so we do not have direct access to the ABAP system. One task is to resolve the value of constants. We now discovered constants whose name starts with %_....

What is the perl syntax to remove extraneous spaces from a perl heredoc in 'use constant'

perl,replace,constants,heredoc
I have the following structure through various pieces of code in my code base. The use of the heredoc is good for myself and others to be able to understand the code but provides unnecessary bulk for transferring the data over a network to the database. use constant FIND_OBJECTS_SQL =>...

When to use constants instead of instance variables in Ruby?

ruby,variables,instance,constants
I understand that instance variables are mean to be states, and constants are meant to be constant. Is there any reason (besides convention) to use a constant instead of an instance variable? Is there a memory/speed advantage to using constants?

Can I declare only specific elements of an array as constant? (C/C++/Fortran)

c++,c,arrays,fortran,constants
Scenario: I pass e.g. a 2D matrix as argument in a function and I would like to be able to read and change all the elements, BUT I would like to prevent any accidental writting in let's say the last column. So I would like somehow to tell the compiler...

Read constants from command line as global variables

c++,class,constants
In my program I have defined a header constants.h where I define constants that will be used in my program, which contains multiple classes. No I would like to read the constants from the command line and initialize these constants such that they can be used in the same way...

Constants and properties in java

java,configuration,constants,config,properties-file
Java best practices recommends read properties as constants. So, what do you think is the best approach to reach it? My approach is: A Configuration class to read the properties file only one time (singleton pattern) and use this class to read properties when needed as constants. And a Constants...

Array of constant pointers to functions

c,function,pointers,constants,ansi
I want to make an array of constant pointers to functions. Something like this: #include <stdio.h> #include <stdlib.h> int f( int x); int g( int x ); const int ( *pf[ ] )( int x ) = { f, g }; int main(void) { int i, x = 4, nf...

Notice: Undefined index: $error in C:\wamp\www\btb_sandbox\upload_2.php on line 35 [duplicate]

php,syntax-error,constants
This question already has an answer here: Reference - What does this error mean in PHP? 28 answers I'm having this kind of Error stated below, I don't understand completely about it. If I press upload button without selecting files! Notice: Undefined index: $error in C:\wamp\www\btb_sandbox\upload_2.php on line 35...

Why isn't a final variable always a constant expression?

java,expression,constants,compile-time-constant,narrowing
In the below code: final int a; a=2; byte b=a; // error: possible loss of precision Why do I get this error? Isn't a final variable compile time constant expression and hence implicitly narrowed to byte during the assignment? In other words isn't the above code equivalent to: final int...

Ada: How to define a random constant?

random,constants,ada
I am currently working through John English' "Ada 95: The Craft of Object-Oriented Programming". I am at task 5.1: Write a program to play a simple guessing game. Define an integer type with a range of values from 1 to 1000 and declare a secret value as a constant of...

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="--------"...

Can the constants be defined inside a model file of a framework in PHP?

php,model-view-controller,model,constants,phpfox
I'm using PHPFox framework. I've to define two constants which would be used only by two functions present within that model class file. So can I define the constants at the beginning of this model class file or would it cause any issue or is it against the coding standards?...

Am I using constant memory correctly?

c,memory,cuda,constants
I wrote a simple Cuda C program which takes N numbers and multiplies them by a factor c; since this factor is a constant I decided to put it in the constant memory. Here is the main.cu code: #include <stdlib.h> #include <stdio.h> __constant__ float c; // IS THIS OK? typedef...

How to use constant in class namespace as the array and template parameters?

c++,compiler-errors,constants,static-members,c++98
I want to use the constant in class namespace as the size of a static array and the template parameter in another class. I have follow errors // MS VS 2010 C++98 // A.h class A { public: const static int someNumber; }; // A.cpp #include <A.h> const int A::someNumber...

Is there anything wrong with using static const structs to limit name collisions of constants in C?

c,struct,const,constants,name-collision
For example, if I were to create a hierarchical static const struct like this in a header (.h) file: static const struct { struct { char STATIC /* = 0 */; char DYNAMIC /* = 1 */; } ALLOCATION; struct { char TABLE /* = 0 */; char LIST /*...

How to use constant powers of 2 readable in c++?

c++,binary,coding-style,constants,code-readability
I need several integer constants with 2^n and 2^n - 1 in my GNU c++ code. What is a good practise to keep the code readable? The code uses decimal values at the moment 4294967296 and 65536 which is hard to debug in future. 2^12 is not implemented in standard...

making a default value in a first row

java,table,constants
I have this code that add row depends on the user input. But now i want the first row of the second column to have a default value of 0 and the rest of it is null. code of the table DefaultTableModel dm = new DefaultTableModel(); table.setModel(dm); dm.addColumn("PROCESS"); dm.addColumn("CPU Time");...

Declare a php constant within a php variable

php,string,variables,echo,constants
I have the following code: <?php $background_holder = echo get_bloginfo('template_directory');'/images/banner.jpg';?> background-image: url("<?php echo get_theme_mod('header_background_image', $background_holder;); ?>"); I'm trying to set a constant for the $background_holder and then add it to the background image variable. I'm sure I've just written something slightly wrong, but currently this does nothing....

Constant in PHP class and “static” keyword

php,oop,constants,php-5.4
Please consider this code: class App { const ALERT_ERROR=1; const ALERT_WARN=2; const ALERT_INFO=3; public static function alert($title,$type=ALERT_ERROR) { switch ($type){ default: case static::ALERT_ERROR: $class="alert-danger"; break; case static::ALERT_WARN: $class="alert-warning"; break; case static::ALERT_INFO: $class="alert-info"; break; } ... } } I have some trouble with the static::constant syntax inside the switch. I some...

How to write the constant in my function?

php,function,constants
function insert_data($array){ $dbh=new PDO('sqlite:C:\test.sqlite'); $sql = "INSERT INTO quote (symbol,price) VALUES (?,?)"; $q = $dbh->prepare($sql); $q->execute($array); $dbh=null; } I want to define C:\test.sqlite as a constant. define('db_name','C:\test.sqlite'); But i can't use the constant in my function insert_data. function insert_data($array){ $dbh=new PDO("sqlite:db_name"); $sql = "INSERT INTO quote (symbol,price) VALUES (?,?)"; $q...

Difference between a normal variable and a constant variable?

java,oop,variables,constants
What's the difference between the two? Is the only way to make a variable constant to add final to it? Integer HoursInDay = 24; final Integer HoursInDay = 24; Edit: I know this is a bland question, But I want to know the specifics...

Best way to handle multiple constants in a container with numba?

python,enums,constants,numba
I'm doing some bitshifting in python and want to speed it up with numba. For that, I have lots of constant integer values, that I have to handle in a possibly well readable manner. I would like to group them together to enum-like objects, having all the constants within one...

How to check to see if a function in R is a constant function?

r,function,constants
An R function is passed to me, which is defined on some interval of the Real Line and returns a numeric value. Is there a way to check to see if the function is constant? Example functions: f1<-function(x) {11} f2<-function(x) {x+2} f3<-function(x) {1+1} f4<-function(x) {return(3)} I am looking for a...

How would i sort a queue using only one additional queue

algorithm,queue,constants,analysis
So basically, Im asked to sort a queue, and i can only use one helper queue , and am only allowed constant amount of additional memory. How would i sort a queue using only one additional queue ?...

Swift constant that depends on another constant

ios,swift,constants
I'm attempting to create a constant that depends on another in the following way: class Thingy { let paddingConstant = 13.0 let paddingDict = ["padding": paddingConstant] } The bottom line gives me an error "Thingy.Type does not have a member named 'paddingConstant'". Is it possible to declare a constant that...

How to access a variable from a H file

ios,objective-c,constants
I'm defining some variables in a Constants.h file. #ifndef Constants_h #define Constants_h static NSString *SERVER_IMG_URL = @"http://localhost/img"; ... If I import Constants.h in a M file. How I can access to SERVER_IMG_URL?? I want to use it, to not repeat the url in all files, only call this variable. Because,...

Where are TYPO3 constants from constant editor stored?

typo3,constants
In Typo3 Backend -> Template -> Constants there is a constant editor. Where does TYPO3 saving the constants? Tried an fgrep -ri for an existing pattern, in case of saving to filesystem - no matches. Tried an MySQL search for an existing pattern, in case of saving to DB -...

Using eval() to check if global variable isset

php,eval,constants
I am trying to check defined variables based on passing a single portion of the variable. (The rest of the variable is static and all other portions of it are the same), so I made a test to find out if this is possible. It does not work, but perhaps...

Why can't I define STATUS as a constant?

php,constants
When I define STATUS, it defaults to 0. Yet all the other constants work. define('LOCATION',07); define('STATUS',08); echo 'x'.STATUS."x\n";exit; define('TERM_DATE',09); $ php synchronize.php x0x ...

Can't declare class constant nor property variable

php,class,properties,constants,declaration
class Model { public $DATABASE_NAME = 'dealer-kunde-skuska'; // OR const DATABASE_NAME = 'dealer-kunde-skuska'; } None of above declarations works. It returns error: Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in ... on line 5 What could be wrong?...

Wordpress ajax request and defined constants

ajax,wordpress,request,constants
I cannot access my custom defined constants (in functions.php) when I'm doing ajax request with: add_action( 'wp_ajax_form_request', 'form_request' ); add_action( 'wp_ajax_nopriv_form_request', 'form_request' ); Accessible only standart WP constants, like TEMPLATEPATH. Is possible access my own, defined in functions.php?...