// app.js or break it up into seperate files
// whatever structure is your flavor
angular.module('myApp', [])
.constant('CONFIG', {
'APP_NAME' : 'My Awesome App',
'APP_VERSION' : '0.0.0',
'GOOGLE_ANALYTICS_ID' : '',
'BASE_URL' : '',
'SYSTEM_LANGUAGE' : ''
})
.controller('GlobalVarController', ['$scope', 'CONFIG', function($scope, CONFIG) {
// If you wish to show the CONFIG vars in the console:
console.log(CONFIG);
// And your CONFIG vars in .constant will be passed to the HTML doc with this:
$scope.config = CONFIG;
}]);
In your HTML:
<span ng-controller="GlobalVarController">{{config.APP_NAME}} | v{{config.APP_VERSION}}</span>
I see, that this is still needed for 5.4+ and I just had the same problem, but none of the answers were clean enough, so I tried to accomplish the availability with ServiceProviders
. Here is what i did:
SettingsServiceProvider
php artisan make:provider SettingsServiceProvider
GlobalSettings
)php artisan make:model GlobalSettings
register
method in \App\Providers\SettingsServiceProvider
. As you can see, I retrieve my settings using the eloquent model for it with Setting::all()
.
public function register()
{
$this->app->singleton('App\GlobalSettings', function ($app) {
return new GlobalSettings(Setting::all());
});
}
Collection
parameter) in GlobalSettings
class GlobalSettings extends Model
{
protected $settings;
protected $keyValuePair;
public function __construct(Collection $settings)
{
$this->settings = $settings;
foreach ($settings as $setting){
$this->keyValuePair[$setting->key] = $setting->value;
}
}
public function has(string $key){ /* check key exists */ }
public function contains(string $key){ /* check value exists */ }
public function get(string $key){ /* get by key */ }
}
config/app.php
'providers' => [
// [...]
App\Providers\SettingsServiceProvider::class
]
php artisan config:cache
you can use your singleton as follows.
$foo = app(App\GlobalSettings::class);
echo $foo->has("company") ? $foo->get("company") : "Stack Exchange Inc.";
You can read more about service containers and service providers in Laravel Docs > Service Container and Laravel Docs > Service Providers.
This is my first answer and I had not much time to write it down, so the formatting ist a bit spacey, but I hope you get everything.
I forgot to include the boot
method of SettingsServiceProvider
, to make the settings variable global available in views, so here you go:
public function boot(GlobalSettings $settinsInstance)
{
View::share('globalsettings', $settinsInstance);
}
Before the boot methods are called all providers have been registered, so we can just use our GlobalSettings
instance as parameter, so it can be injected by Laravel.
In blade template:
{{ $globalsettings->get("company") }}
A global variable would be best expressed in an external JavaScript file:
var system_status;
Make sure that this has not been used anywhere else. Then to access the variable on your page, just reference it as such. Say, for example, you wanted to fill in the results on a textbox,
document.getElementById("textbox1").value = system_status;
To ensure that the object exists, use the document ready feature of jQuery.
Example:
$(function() {
$("#textbox1")[0].value = system_status;
});
Hi to pass values from one js file to another js file we can use Local storage concept
<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
Two.js file
function myFunction() {
var test =localStorage.name;
alert(test);
}
Three.js File
localStorage.name = 1;
You can try the keyword use
in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
Global variables are not extern
nor static
by default on C and C++.
When you declare a variable as static
, you are restricting it to the current source file. If you declare it as extern
, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern
keyword) you will get a link error (symbol not found).
Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal
. If you declare it as static
, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal
.
What you can do in C++, that you can't in C, is to declare the variable as const
on the header, like this:
const int varGlobal = 7;
And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define
for constants.
If you need a global variable visible on multiple sources and not const
, declare it as extern
on the header, and then define it, this time without the extern keyword, on a source file:
Header included by multiple files:
extern int varGlobal;
In one of your source files:
int varGlobal = 7;
Create this subclass
public class MyApp extends Application {
String foo;
}
In the AndroidManifest.xml add android:name
Example
<application android:name=".MyApp"
android:icon="@drawable/icon"
android:label="@string/app_name">
Your session status are set once you start a session, and by default, take the current GLOBAL value.
If you disconnected after you did SET @@GLOBAL.wait_timeout=300
, then subsequently reconnected, you'd see
SHOW SESSION VARIABLES LIKE "%wait%";
Result: 300
Similarly, at any time, if you did
mysql> SET session wait_timeout=300;
You'd get
mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout | 300 |
+---------------+-------+
I am new to Rust, but this solution seems to work:
#[macro_use]
extern crate lazy_static;
use std::sync::{Arc, Mutex};
lazy_static! {
static ref GLOBAL: Arc<Mutex<GlobalType> =
Arc::new(Mutex::new(GlobalType::new()));
}
Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.
Both solutions should provide a safe approach to using global variables.
With a different opinion, I think the global
variables might be the best choice if you are going to publish your code to npm
, cuz you cannot be sure that all packages are using the same release of your code. So if you use a file for exporting a singleton
object, it will cause issues here.
You can choose global
, require.main
or any other objects which are shared across files.
Otherwise, install your package as an optional dependency package can avoid this problem.
Please tell me if there are some better solutions.
You cannot delete a variable if you declared it (with var x;
) at the time of first use.
However, if your variable x
first appeared in the script without a declaration, then you can use the delete
operator (delete x;
) and your variable will be deleted, very similar to deleting an element of an array or deleting a property of an object.
Well, running example:
WARNING! NEVER DO THIS AT HOME/WORK! Only in classroom ;)
Use semaphores, shared variables, etc. to avoid rush conditions.
from threading import Thread
import time
a = 0 # global variable
def thread1(threadname):
global a
for k in range(100):
print("{} {}".format(threadname, a))
time.sleep(0.1)
if k == 5:
a += 100
def thread2(threadname):
global a
for k in range(10):
a += 1
time.sleep(0.2)
thread1 = Thread(target=thread1, args=("Thread-1",))
thread2 = Thread(target=thread2, args=("Thread-2",))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
and the output:
Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 2
Thread-1 3
Thread-1 3
Thread-1 104
Thread-1 104
Thread-1 105
Thread-1 105
Thread-1 106
Thread-1 106
Thread-1 107
Thread-1 107
Thread-1 108
Thread-1 108
Thread-1 109
Thread-1 109
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
If the timing were right, the a += 100
operation would be skipped:
Processor executes at T a+100
and gets 104. But it stops, and jumps to next thread
Here, At T+1 executes a+1
with old value of a, a == 4
. So it computes 5.
Jump back (at T+2), thread 1, and write a=104
in memory.
Now back at thread 2, time is T+3 and write a=5
in memory.
Voila! The next print instruction will print 5 instead of 104.
VERY nasty bug to be reproduced and caught.
Public Class Form1
Public Shared SomeValue As Integer = 5
End Class
The answer:
MessageBox.Show("this is the number"&GlobalVariables.SomeValue)
As Christian's answer with assign()
shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<-
operator, ie
a <<- "new"
inside the function.
Sooner or later you will need to change how that variable is set or what happens when it is accessed, or you just need to hunt down where it is changed.
It is practically always better to not have global variables. Just write the dam get and set methods, and be gland you when you need them a day, week or month later.
This needs bash 4.1 if you use
{fd}
orlocal -n
.The rest should work in bash 3.x I hope. I am not completely sure due to
printf %q
- this might be a bash 4 feature.
Your example can be modified as follows to archive the desired effect:
# Add following 4 lines:
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$@" "$?"; }
_capture() { { out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$@")"; }
e=2
# Add following line, called "Annotation"
function test1_() { passback e; }
function test1() {
e=4
echo "hello"
}
# Change following line to:
capture ret test1
echo "$ret"
echo "$e"
prints as desired:
hello
4
Note that this solution:
e=1000
, too.$?
if you need $?
The only bad sideffects are:
bash
._
)_capture
just replace all occurances of 3
with another (higher) number.The following (which is quite long, sorry for that) hopefully explains, how to adpot this recipe to other scripts, too.
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
d1=$(d)
d2=$(d)
d3=$(d)
d4=$(d)
echo $x $d1 $d2 $d3 $d4
outputs
0 20171129-123521 20171129-123521 20171129-123521 20171129-123521
while the wanted output is
4 20171129-123521 20171129-123521 20171129-123521 20171129-123521
Shell variables (or generally speaking, the environment) is passed from parental processes to child processes, but not vice versa.
If you do output capturing, this usually is run in a subshell, so passing back variables is difficult.
Some even tell you, that it is impossible to fix. This is wrong, but it is a long known difficult to solve problem.
There are several ways on how to solve it best, this depends on your needs.
Here is a step by step guide on how to do it.
There is a way to pass back variables to a parental shell. However this is a dangerous path, because this uses eval
. If done improperly, you risk many evil things. But if done properly, this is perfectly safe, provided that there is no bug in bash
.
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; d=$(date +%Y%m%d-%H%M%S); _passback x d; }
x=0
eval `d`
d1=$d
eval `d`
d2=$d
eval `d`
d3=$d
eval `d`
d4=$d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-124945 20171129-124945 20171129-124945 20171129-124945
Note that this works for dangerous things, too:
danger() { danger="$*"; passback danger; }
eval `danger '; /bin/echo *'`
echo "$danger"
prints
; /bin/echo *
This is due to printf '%q'
, which quotes everything such, that you can re-use it in a shell context safely.
This does not only look ugly, it also is much to type, so it is error prone. Just one single mistake and you are doomed, right?
Well, we are at shell level, so you can improve it. Just think about an interface you want to see, and then you can implement it.
Let's go a step back and think about some API which allows us to easily express, what we want to do.
Well, what do we want do do with the d()
function?
We want to capture the output into a variable. OK, then let's implement an API for exactly this:
# This needs a modern bash 4.3 (see "help declare" if "-n" is present,
# we get rid of it below anyway).
: capture VARIABLE command args..
capture()
{
local -n output="$1"
shift
output="$("$@")"
}
Now, instead of writing
d1=$(d)
we can write
capture d1 d
Well, this looks like we haven't changed much, as, again, the variables are not passed back from d
into the parent shell, and we need to type a bit more.
However now we can throw the full power of the shell at it, as it is nicely wrapped in a function.
A second thing is, that we want to be DRY (Don't Repeat Yourself). So we definitively do not want to type something like
x=0
capture1 x d1 d
capture1 x d2 d
capture1 x d3 d
capture1 x d4 d
echo $x $d1 $d2 $d3 $d4
The x
here is not only redundant, it's error prone to always repeate in the correct context. What if you use it 1000 times in a script and then add a variable? You definitively do not want to alter all the 1000 locations where a call to d
is involved.
So leave the x
away, so we can write:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; output=$(date +%Y%m%d-%H%M%S); _passback output x; }
xcapture() { local -n output="$1"; eval "$("${@:2}")"; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
This already looks very good. (But there still is the local -n
which does not work in oder common bash
3.x)
d()
The last solution has some big flaws:
d()
needs to be alteredxcapture
to pass the output.
output
,
so we can never pass this one back._passback
Can we get rid of this, too?
Of course, we can! We are in a shell, so there is everything we need to get this done.
If you look a bit closer to the call to eval
you can see, that we have 100% control at this location. "Inside" the eval
we are in a subshell,
so we can do everything we want without fear of doing something bad to the parental shell.
Yeah, nice, so let's add another wrapper, now directly inside the eval
:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
# !DO NOT USE!
_xcapture() { "${@:2}" > >(printf "%q=%q;" "$1" "$(cat)"); _passback x; } # !DO NOT USE!
# !DO NOT USE!
xcapture() { eval "$(_xcapture "$@")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
However, this, again, has some major drawback:
!DO NOT USE!
markers are there,
because there is a very bad race condition in this,
which you cannot see easily:
>(printf ..)
is a background job. So it might still
execute while the _passback x
is running.sleep 1;
before printf
or _passback
.
_xcapture a d; echo
then outputs x
or a
first, respectively._passback x
should not be part of _xcapture
,
because this makes it difficult to reuse that recipe.$(cat)
),
but as this solution is !DO NOT USE!
I took the shortest route.However, this shows, that we can do it, without modification to d()
(and without local -n
)!
Please note that we not neccessarily need _xcapture
at all,
as we could have written everyting right in the eval
.
However doing this usually isn't very readable. And if you come back to your script in a few years, you probably want to be able to read it again without much trouble.
Now let's fix the race condition.
The trick could be to wait until printf
has closed it's STDOUT, and then output x
.
There are many ways to archive this:
Following the last path could look like (note that it does the printf
last because this works better here):
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_xcapture() { { printf "%q=%q;" "$1" "$("${@:2}" 3<&-; _passback x >&3)"; } 3>&1; }
xcapture() { eval "$(_xcapture "$@")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-144845 20171129-144845 20171129-144845 20171129-144845
Why is this correct?
_passback x
directly talks to STDOUT.>&3
.$("${@:2}" 3<&-; _passback x >&3)
finishes after the _passback
,
when the subshell closes STDOUT.printf
cannot happen before the _passback
,
regardless how long _passback
takes.printf
command is not executed before the complete
commandline is assembled, so we cannot see artefacts from printf
,
independently how printf
is implemented.Hence first _passback
executes, then the printf
.
This resolves the race, sacrificing one fixed file descriptor 3. You can, of course, choose another file descriptor in the case, that FD3 is not free in your shellscript.
Please also note the 3<&-
which protects FD3 to be passed to the function.
_capture
contains parts, which belong to d()
, which is bad,
from a reusability perspective. How to solve this?
Well, do it the desparate way by introducing one more thing,
an additional function, which must return the right things,
which is named after the original function with _
attached.
This function is called after the real function, and can augment things. This way, this can be read as some annotation, so it is very readable:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_capture() { { printf "%q=%q;" "$1" "$("${@:2}" 3<&-; "$2_" >&3)"; } 3>&1; }
capture() { eval "$(_capture "$@")"; }
d_() { _passback x; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
capture d1 d
capture d2 d
capture d3 d
capture d4 d
echo $x $d1 $d2 $d3 $d4
still prints
4 20171129-151954 20171129-151954 20171129-151954 20171129-151954
There is only on bit missing:
v=$(fn)
sets $?
to what fn
returned. So you probably want this, too.
It needs some bigger tweaking, though:
# This is all the interface you need.
# Remember, that this burns FD=3!
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$@" "$?"; }
_capture() { { out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$@")"; }
# Here is your function, annotated with which sideffects it has.
fails_() { passback x y; }
fails() { x=$1; y=69; echo FAIL; return 23; }
# And now the code which uses it all
x=0
y=0
capture wtf fails 42
echo $? $x $y $wtf
prints
23 42 69 FAIL
_passback()
can be elmininated with passback() { set -- "$@" "$?"; while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
_capture()
can be eliminated with capture() { eval "$({ out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)")"; }
The solution pollutes a file descriptor (here 3) by using it internally.
You need to keep that in mind if you happen to pass FDs.
Note thatbash
4.1 and above has {fd}
to use some unused FD.
(Perhaps I will add a solution here when I come around.)
Note that this is why I use to put it in separate functions like _capture
, because stuffing this all into one line is possible, but makes it increasingly harder to read and understand
Perhaps you want to capture STDERR of the called function, too.
Or you want to even pass in and out more than one filedescriptor
from and to variables.
I have no solution yet, however here is a way to catch more than one FD, so we can probably pass back the variables this way, too.
Also do not forget:
This must call a shell function, not an external command.
There is no easy way to pass environment variables out of external commands. (With
LD_PRELOAD=
it should be possible, though!) But this then is something completely different.
This is not the only possible solution. It is one example to a solution.
As always you have many ways to express things in the shell. So feel free to improve and find something better.
The solution presented here is quite far from being perfect:
bash
, so probably is hard to port to other shells.However I think it is quite easy to use:
Copy the global variable to a variable in the scope in your controller.
function MyCtrl($scope) {
$scope.variable1 = variable1;
}
Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).
But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.
The exception you get is telling you filedialog
is not in your namespace.
filedialog
(and btw messagebox
) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
if you want to use it in all of your classes you can use:
public var yourVariable = "something"
if you want to use just in one class you can use :
var yourVariable = "something"
You can do the following to learn/test the concept:
Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module
In newly added Module1 add the declaration; Public Global1 As String
in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:
Sub setMe() Global1 = "Hello" End Sub
Sub showMe() Debug.Print (Global1) End Sub
setMe()
and then Sub showMe()
to test the global visibility/accessibility of the var Global1
Hope this will help.
Do this:
$checksum = "my value";
header("Location: recordupdated.php?checksum=$checksum");
First off, the extern
keyword is not used for defining a variable; rather it is used for declaring a variable. I can say extern
is a storage class, not a data type.
extern
is used to let other C files or external components know this variable is already defined somewhere. Example: if you are building a library, no need to define global variable mandatorily somewhere in library itself. The library will be compiled directly, but while linking the file, it checks for the definition.
When you assign a variable (x = ...
), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:
x = 0
def f():
x = 1
f()
print x #=>0
and expect 1
. Instead, you need do declare that you intend to use the global x
:
x = 0
def f():
global x
x = 1
f()
print x #=>1
But note that assignment of a variable is very different from method calls. You can always call methods on anything in scope - e.g. on variables that come from an outer (e.g. the global) scope because nothing local shadows them.
Also very important: Member assignment (x.name = ...
), item assignment (collection[key] = ...
), slice assignment (sliceable[start:end] = ...
) and propably more are all method calls as well! And therefore you don't need global
to change a global's members or call it methods (even when they mutate the object).
You could use module scope. Say you have a module called utils
:
f_value = 'foo'
def f():
return f_value
f_value
is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils
from one module will be accessible to all other modules that have it imported:
>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'
Note that you can import the function by name:
>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'
But not the attribute:
>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'
This is because you're labeling the object referenced by the module attribute as f_value
in the local scope, but then rebinding it to the string bar
, while the function f
is still referring to the module attribute.
Yes, an instance variable will be initialized to a default value. For a local variable, you need to initialize before use:
public class Main {
int instaceVariable; // An instance variable will be initialized to the default value
public static void main(String[] args) {
int localVariable = 0; // A local variable needs to be initialized before use
}
}
In case you want to see the local variables of a calling function use select-frame
before info locals
E.g.:
(gdb) bt
#0 0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1 0xfec36f39 in thr_kill () from /lib/libc.so.1
#2 0xfebe3603 in raise () from /lib/libc.so.1
#3 0xfebc2961 in abort () from /lib/libc.so.1
#4 0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5 0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb)
You may want to explore the notion of namespaces. In Python, the module is the natural place for global data:
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions,
modname.itemname
.
A specific use of global-in-a-module is described here - How do I share global variables across modules?, and for completeness the contents are shared here:
The canonical way to share information across modules within a single program is to create a special configuration module (often called config or cfg). Just import the configuration module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:
File: config.py
x = 0 # Default value of the 'x' configuration setting
File: mod.py
import config
config.x = 1
File: main.py
import config
import mod
print config.x
Here is one case that caught me out, using a global as a default value of a parameter.
globVar = None # initialize value of global variable
def func(param = globVar): # use globVar as default value for param
print 'param =', param, 'globVar =', globVar # display values
def test():
global globVar
globVar = 42 # change value of global
func()
test()
=========
output: param = None, globVar = 42
I had expected param to have a value of 42. Surprise. Python 2.7 evaluated the value of globVar when it first parsed the function func. Changing the value of globVar did not affect the default value assigned to param. Delaying the evaluation, as in the following, worked as I needed it to.
def func(param = eval('globVar')): # this seems to work
print 'param =', param, 'globVar =', globVar # display values
Or, if you want to be safe,
def func(param = None)):
if param == None:
param = globVar
print 'param =', param, 'globVar =', globVar # display values
a vue3 replacement of this answer:
// Vue3
const app = Vue.createApp({})
app.config.globalProperties.$hostname = 'http://localhost:3000'
app.component('a-child-component', {
mounted() {
console.log(this.$hostname) // 'http://localhost:3000'
}
})
I checked for similar answer, but those given here don't fit my needs. I find something that, from my point of view, is what you're looking for. The only possible black point is a security matter (or maybe not) since I don't know about security.
I suggest using Interface (no need to use Class with constructor and so...), since you only have to create something like :
public interface ActivityClass {
public static final String MYSTRING_1 = "STRING";
public static final int MYINT_1 = 1;
}
Then you can access everywhere within your classes by using the following:
int myInt = ActivityClass.MYINT_1;
String myString = ActivityClass.MYSTRING_1;
Building on the answer from Sharfi, edit the /etc/my.cnf file and add just this one line:
validate_password_policy=LOW
That should sufficiently neuter the validation as requested by the OP. You will probably want to restart mysqld after this change. Depending on your OS, it would look something like:
sudo service mysqld restart
validate_password_policy takes either values 0, 1, or 2 or words LOW, MEDIUM, and STRONG which correspond to those numbers. The default is MEDIUM (1) which requires passwords contain at least one upper case letter, one lower case letter, one digit, and one special character, and that the total password length is at least 8 characters. Changing to LOW as I suggest here then only will check for length, which if it hasn't been changed through other parameters will check for a length of 8. If you wanted to shorten that length limit too, you could also add validate_password_length in to the my.cnf file.
For more info about the levels and details, see the mysql doc.
For MySQL 8, the property has changed from "validate_password_policy" to "validate_password.policy". See the updated mysql doc for the latest info.
var userProperties = PropertiesService.getUserProperties();
function globalSetting(){
//creating an array
userProperties.setProperty('gemployeeName',"Rajendra Barge");
userProperties.setProperty('gemployeeMobile',"9822082320");
userProperties.setProperty('gemployeeEmail'," [email protected]");
userProperties.setProperty('gemployeeLastlogin',"03/10/2020");
}
var userProperties = PropertiesService.getUserProperties();
function showUserForm(){
var templete = HtmlService.createTemplateFromFile("userForm");
var html = templete.evaluate();
html.setTitle("Customer Data");
SpreadsheetApp.getUi().showSidebar(html);
}
function appendData(data){
globalSetting();
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
ws.appendRow([data.date,
data.name,
data.Kindlyattention,
data.senderName,
data.customereMail,
userProperties.getProperty('gemployeeName'),
,
,
data.paymentTerms,
,
userProperties.getProperty('gemployeeMobile'),
userProperties.getProperty('gemployeeEmail'),
Utilities.formatDate(new Date(), "GMT+05:30", "dd-MM-yyyy HH:mm:ss")
]);
}
function errorMessage(){
Browser.msgBox("! All fields are mandetory");
}
I like this solution for small applications:
class App:
__conf = {
"username": "",
"password": "",
"MYSQL_PORT": 3306,
"MYSQL_DATABASE": 'mydb',
"MYSQL_DATABASE_TABLES": ['tb_users', 'tb_groups']
}
__setters = ["username", "password"]
@staticmethod
def config(name):
return App.__conf[name]
@staticmethod
def set(name, value):
if name in App.__setters:
App.__conf[name] = value
else:
raise NameError("Name not accepted in set() method")
And then usage is:
if __name__ == "__main__":
# from config import App
App.config("MYSQL_PORT") # return 3306
App.set("username", "hi") # set new username value
App.config("username") # return "hi"
App.set("MYSQL_PORT", "abc") # this raises NameError
.. you should like it because:
App
, @property
, but that requires more variable handling code per item and is object-based.--Edit--: For large applications, storing values in a YAML (i.e. properties) file and reading that in as immutable data is a better approach (i.e. blubb/ohaal's answer). For small applications, this solution above is simpler.
Unlike another programming languages, any variable declared outside any function automatically becomes global,
<script>
//declare global variable
var __foo = '123';
function __test(){
//__foo is global and visible here
alert(__foo);
}
//so, it will alert '123'
__test();
</script>
You problem is that you declare variable inside ready()
function, which means that it becomes visible (in scope) ONLY inside ready()
function, but not outside,
Solution:
So just make it global, i.e declare this one outside $(document).ready(function(){});
Declare the variable outside of functions
function dosomething(){
var i = 0; // Can only be used inside function
}
var i = '';
function dosomething(){
i = 0; // Can be used inside and outside the function
}
If there's a chance that you will reuse this code, then I would probably make the effort to go with an object-oriented perspective. Using the global namespace can be dangerous -- you run the risk of hard to find bugs due to variable names that get reused. Typically I start by using an object-oriented approach for anything more than a simple callback so that I don't have to do the re-write thing. Any time that you have a group of related functions in javascript, I think, it's a candidate for an object-oriented approach.
Because you are asking the compiler to initialize a static variable with code that is inherently dynamic.
This is explained well in the Python FAQ
What are the rules for local and global variables in Python?
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring
global
for assigned variables provides a bar against unintended side-effects. On the other hand, ifglobal
was required for all global references, you’d be usingglobal
all the time. You’d have to declare asglobal
every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of theglobal
declaration for identifying side-effects.
They have already answered how to use a global variable.
I will tell you why the use of global variables is a bad idea as a result of this question carried out in stackoverflow in Spanish.
Explicit translation of the text in Spanish:
The problem with global variables is that they create hidden dependencies. When it comes to large applications, you yourself do not know / remember / you are clear about the objects you have and their relationships.
So, you can not have a clear notion of how many objects your global variable is using. And if you want to change something of the global variable, for example, the meaning of each of its possible values, or its type? How many classes or compilation units will that change affect? If the amount is small, it may be worth making the change. If the impact will be great, it may be worth looking for another solution.
But what is the impact? Because a global variable can be used anywhere in the code, it can be very difficult to measure it.
In addition, always try to have a variable with the shortest possible life time, so that the amount of code that makes use of that variable is the minimum possible, and thus better understand its purpose, and who modifies it.
A global variable lasts for the duration of the program, and therefore, anyone can use the variable, either to read it, or even worse, to change its value, making it more difficult to know what value the variable will have at any given program point. .
Another problem is the order of destruction. Variables are always destroyed in reverse order of their creation, whether they are local or global / static variables (an exception is the primitive types, int
,enum
s, etc., which are never destroyed if they are global / static until they end the program).
The problem is that it is difficult to know the order of construction of the global (or static) variables. In principle, it is indeterminate.
If all your global / static variables are in a single compilation unit (that is, you only have a .cpp
), then the order of construction is the same as the writing one (that is, variables defined before, are built before).
But if you have more than one .cpp
each with its own global / static variables, the global construction order is indeterminate. Of course, the order in each compilation unit (each .cpp
) in particular, is respected: if the global variableA
is defined before B
,A
will be built before B
, but It is possible that between A
andB
variables of other .cpp
are initialized. For example, if you have three units with the following global / static variables:
In the executable it could be created in this order (or in any other order as long as the relative order is respected within each .cpp
):
Why is this important? Because if there are relations between different static global objects, for example, that some use others in their destructors, perhaps, in the destructor of a global variable, you use another global object from another compilation unit that turns out to be already destroyed ( have been built later).
I tried to find the source that I will use in this example, but I can not find it (anyway, it was to exemplify the use of singletons, although the example is applicable to global and static variables). Hidden dependencies also create new problems related to controlling the behavior of an object, if it depends on the state of a global variable.
Imagine you have a payment system, and you want to test it to see how it works, since you need to make changes, and the code is from another person (or yours, but from a few years ago). You open a new main
, and you call the corresponding function of your global object that provides a bank payment service with a card, and it turns out that you enter your data and they charge you. How, in a simple test, have I used a production version? How can I do a simple payment test?
After asking other co-workers, it turns out that you have to "mark true", a global bool that indicates whether we are in test mode or not, before beginning the collection process. Your object that provides the payment service depends on another object that provides the mode of payment, and that dependency occurs in an invisible way for the programmer.
In other words, the global variables (or singletones), make it impossible to pass to "test mode", since global variables can not be replaced by "testing" instances (unless you modify the code where said code is created or defined). global variable, but we assume that the tests are done without modifying the mother code).
This is solved by means of what is called * dependency injection *, which consists in passing as a parameter all the dependencies that an object needs in its constructor or in the corresponding method. In this way, the programmer ** sees ** what has to happen to him, since he has to write it in code, making the developers gain a lot of time.
If there are too many global objects, and there are too many parameters in the functions that need them, you can always group your "global objects" into a class, style * factory *, that builds and returns the instance of the "global object" (simulated) that you want , passing the factory as a parameter to the objects that need the global object as dependence.
If you pass to test mode, you can always create a testing factory (which returns different versions of the same objects), and pass it as a parameter without having to modify the target class.
Not necessarily, there may be good uses for global variables. For example, constant values ??(the PI value). Being a constant value, there is no risk of not knowing its value at a given point in the program by any type of modification from another module. In addition, constant values ??tend to be primitive and are unlikely to change their definition.
It is more convenient, in this case, to use global variables to avoid having to pass the variables as parameters, simplifying the signatures of the functions.
Another can be non-intrusive "global" services, such as a logging class (saving what happens in a file, which is usually optional and configurable in a program, and therefore does not affect the application's nuclear behavior), or std :: cout
,std :: cin
or std :: cerr
, which are also global objects.
Any other thing, even if its life time coincides almost with that of the program, always pass it as a parameter. Even the variable could be global in a module, only in it without any other having access, but that, in any case, the dependencies are always present as parameters.
Answer by: Peregring-lk
The question is really about scope, as the other guy put it.
In short, consider this "module":
Public Var1 As variant 'Var1 can be used in all
'modules, class modules and userforms of
'thisworkbook and will preserve any values
'assigned to it until either the workbook
'is closed or the project is reset.
Dim Var2 As Variant 'Var2 and Var3 can be used anywhere on the
Private Var3 As Variant ''current module and will preserve any values
''they're assigned until either the workbook
''is closed or the project is reset.
Sub MySub() 'Var4 can only be used within the procedure MySub
Dim Var4 as Variant ''and will only store values until the procedure
End Sub ''ends.
Sub MyOtherSub() 'You can even declare another Var4 within a
Dim Var4 as Variant ''different procedure without generating an
End Sub ''error (only possible confusion).
You can check out this MSDN reference for more on variable declaration and this other Stack Overflow Question for more on how variables go out of scope.
Two other quick things:
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
For non-static variables, I sorted it out via Application class dictionary as below:
At Global.asax.ac:
namespace MvcWebApplication
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
private string _licensefile; // the global private variable
internal string LicenseFile // the global controlled variable
{
get
{
if (String.IsNullOrEmpty(_licensefile))
{
string tempMylFile = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(LDLL.License)).Location), "License.l");
if (!File.Exists(tempMylFile))
File.Copy(Server.MapPath("~/Content/license/License.l"),
tempMylFile,
true);
_licensefile = tempMylFile;
}
return _licensefile;
}
}
protected void Application_Start()
{
Application["LicenseFile"] = LicenseFile;// the global variable's bed
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
And in Controller:
namespace MvcWebApplication.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View(HttpContext.Application["LicenseFile"] as string);
}
}
}
In this way we can have global variables in ASP.NET MVC :)
NOTE: If your object is not string simply write:
return View(HttpContext.Application["X"] as yourType);
I think it's local to the file you declared offset. Consider every file to be a method itself.
Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);
?
In the header file write it with extern
.
And at the global scope of one of the c files declare it without extern
.
You can create a variable with an application scope
The reason of why your code throws an UnboundLocalError
is already well explained in other answers.
But it seems to me that you're trying to build something that works like itertools.count()
.
So why don't you try it out, and see if it suits your case:
>>> from itertools import count
>>> counter = count(0)
>>> counter
count(0)
>>> next(counter)
0
>>> counter
count(1)
>>> next(counter)
1
>>> counter
count(2)
The recommended approach is:
window.greeting = "Hello World!"
You can then access it within any function:
function foo() {
alert(greeting); // Hello World!
alert(window["greeting"]); // Hello World!
alert(window.greeting); // Hello World! (recommended)
}
This approach is preferred for two reasons.
The intent is explicit. The use of the var
keyword can easily lead to declaring global vars
that were intended to be local or vice versa. This sort of variable scoping is a point of confusion for a lot of Javascript developers. So as a general rule, I make sure all variable declarations are preceded with the keyword var
or the prefix window
.
You standardize this syntax for reading the variables this way as well which means that a locally scoped var
doesn't clobber the global var
or vice versa. For example what happens here is ambiguous:
greeting = "Aloha";
function foo() {
greeting = "Hello"; // overrides global!
}
function bar(greeting) {
alert(greeting);
}
foo();
bar("Howdy"); // does it alert "Hello" or "Howdy" ?
However, this is much cleaner and less error prone (you don't really need to remember all the variable scoping rules):
function foo() {
window.greeting = "Hello";
}
function bar(greeting) {
alert(greeting);
}
foo();
bar("Howdy"); // alerts "Howdy"
On Windows 10, I was facing the same issue with JRE 1.8 (8u121).
Typing
java -version
the cmd prompt returns
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object
All the other commands, echo %JAVA_HOME%
, echo %JRE_HOME%
, echo %PATH%
, java -fullversion
worked fine.
Going to environment variables on system administration panel, remove from PATH the link C:\ProgramData\Oracle\Java\javapath
, and be sure to have set in PATH the link to C:\Program Files\Java Folder\bin
.
After that, check if in C:\Windows\System32
exists a java.exe
file; if true, delete that file.
Typing now java -version
it works fine.
In addition to all definitions, the thing that stuck in my mind was, when you make a commit, GIT creates a commit object within the repository. Commit objects should have a parent ( or multiple parents if it is a merge commit). Now, how does git know the parent of the current commit? So HEAD is a pointer to the (reference of the) last commit which will become the parent of the current commit.
It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.
But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.
To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.
The --bare flag creates a repository that doesn’t have a working directory. The bare repository is the central repository and you can't edit(store) codes here for avoiding the merging error.
For example, when you add a file in your local repository (machine 1) and push it to the bare repository, you can't see the file in the bare repository for it is always 'empty'. However, you really push something to the repository and you can see it inexplicitly by cloning another repository in your server(machine 2).
Both the local repository in machine 1 and the 'copy' repository in machine 2 are non-bare. relationship between bare and non-bare repositories
The blog will help you understand it. https://www.atlassian.com/git/tutorials/setting-up-a-repository
Change this (CURRENT_TIMESTAMP-30)
To This: DateADD(mi, -30, Current_TimeStamp)
To get the current date use GetDate().
MSDN Link to DateAdd Function
MSDN Link to Get Date Function
You may do it by using following code:
var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);
//Pour inserer :
$pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
$filetype = addslashes($_FILES['inputname']['type']);//pour le test
$namepdf = addslashes($_FILES['inputname']['name']);
if (substr($filetype, 0, 11) == 'application'){
$mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
}
//Pour afficher :
$row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
foreach($row as $result){
$file=$result['pdf'];
}
header('Content-type: application/pdf');
echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));
Here's a simple example in C++11.
#include <mutex> // mutex
#include <iostream> // cout
#include <cstdio> // getchar
#include <thread> // this_thread, yield
#include <future> // async
#include <chrono> // seconds
using namespace std;
mutex _m1;
mutex _m2;
// Deadlock will occur because func12 and func21 acquires the two locks in reverse order
void func12()
{
unique_lock<mutex> l1(_m1);
this_thread::yield(); // hint to reschedule
this_thread::sleep_for( chrono::seconds(1) );
unique_lock<mutex> l2(_m2 );
}
void func21()
{
unique_lock<mutex> l2(_m2);
this_thread::yield(); // hint to reschedule
this_thread::sleep_for( chrono::seconds(1) );
unique_lock<mutex> l1(_m1);
}
int main( int argc, char* argv[] )
{
async(func12);
func21();
cout << "All done!"; // this won't be executed because of deadlock
getchar();
}
If you need a standalone connection pool, my preference goes to C3P0 over DBCP (that I've mentioned in this previous answer), I just had too much problems with DBCP under heavy load. Using C3P0 is dead simple. From the documentation:
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("swaldman");
cpds.setPassword("test-password");
// the settings below are optional -- c3p0 can work with defaults
cpds.setMinPoolSize(5);
cpds.setAcquireIncrement(5);
cpds.setMaxPoolSize(20);
// The DataSource cpds is now a fully configured and usable pooled DataSource
But if you are running inside an application server, I would recommend to use the built-in connection pool it provides. In that case, you'll need to configure it (refer to the documentation of your application server) and to retrieve a DataSource via JNDI:
DataSource ds = (DataSource) new InitialContext().lookup("jdbc/myDS");
div.style.removeProperty('zoom');
Synchronize the data/object that you have saved into NSUserDefaults
-(void)saveCustomObject:(Player *)object
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[prefs setObject:myEncodedObject forKey:@"testing"];
[prefs synchronize];
}
Hope this will help you. Thanks
if ($("element class or id name").css("property") == "value") {
your code....
}
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
Using Javascript MutationObserver
//More Details https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
// select the target node
var target = document.querySelector('mydiv')
// create an observer instance
var observer = new MutationObserver(function(mutations) {
console.log(target.innerText);
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
-split outputs an array, and you can save it to a variable like this:
$a = -split 'Once upon a time'
$a[0]
Once
Another cute thing, you can have arrays on both sides of an assignment statement:
$a,$b,$c = -split 'Once upon a'
$c
a
What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties
inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx
Add the event listeners etc..
Hope this helps
a short summary:
track by
is used in order to link your data with the DOM generation (and mainly re-generation) made by ng-repeat.
when you add track by
you basically tell angular to generate a single DOM element per data object in the given collection
this could be useful when paging and filtering, or any case where objects are added or removed from ng-repeat
list.
usually, without track by
angular will link the DOM objects with the collection by injecting an expando property - $$hashKey
- into your JavaScript objects, and will regenerate it (and re-associate a DOM object) with every change.
full explanation:
http://www.bennadel.com/blog/2556-using-track-by-with-ngrepeat-in-angularjs-1-2.htm
a more practical guide:
http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/
(track by is available in angular > 1.2 )
You can use Guava's Streams
.
concat(Stream<? extends T>... streams)
method, which will be very short with static imports:
Stream stream = concat(stream1, stream2, of(element));
Some context up front as to where I am coming from. Code snippets are at the end.
When I can, I prefer to use an open source tool like H2O to do super high performance parallel CSV file reads, but this tool is limited in feature set. I end up writing a lot of code to create data science pipelines before feeding to H2O cluster for the supervised learning proper.
I have been reading files like 8GB HIGGS dataset from UCI repo and even 40GB CSV files for data science purposes significantly faster by adding lots of parallelism with the multiprocessing library's pool object and map function. For example clustering with nearest neighbor searches and also DBSCAN and Markov clustering algorithms requires some parallel programming finesse to bypass some seriously challenging memory and wall clock time problems.
I usually like to break the file row-wise into parts using gnu tools first and then glob-filemask them all to find and read them in parallel in the python program. I use something like 1000+ partial files commonly. Doing these tricks helps immensely with processing speed and memory limits.
The pandas dataframe.read_csv is single threaded so you can do these tricks to make pandas quite faster by running a map() for parallel execution. You can use htop to see that with plain old sequential pandas dataframe.read_csv, 100% cpu on just one core is the actual bottleneck in pd.read_csv, not the disk at all.
I should add I'm using an SSD on fast video card bus, not a spinning HD on SATA6 bus, plus 16 CPU cores.
Also, another technique that I discovered works great in some applications is parallel CSV file reads all within one giant file, starting each worker at different offset into the file, rather than pre-splitting one big file into many part files. Use python's file seek() and tell() in each parallel worker to read the big text file in strips, at different byte offset start-byte and end-byte locations in the big file, all at the same time concurrently. You can do a regex findall on the bytes, and return the count of linefeeds. This is a partial sum. Finally sum up the partial sums to get the global sum when the map function returns after the workers finished.
Following is some example benchmarks using the parallel byte offset trick:
I use 2 files: HIGGS.csv is 8 GB. It is from the UCI machine learning repository. all_bin .csv is 40.4 GB and is from my current project. I use 2 programs: GNU wc program which comes with Linux, and the pure python fastread.py program which I developed.
HP-Z820:/mnt/fastssd/fast_file_reader$ ls -l /mnt/fastssd/nzv/HIGGS.csv
-rw-rw-r-- 1 8035497980 Jan 24 16:00 /mnt/fastssd/nzv/HIGGS.csv
HP-Z820:/mnt/fastssd$ ls -l all_bin.csv
-rw-rw-r-- 1 40412077758 Feb 2 09:00 all_bin.csv
ga@ga-HP-Z820:/mnt/fastssd$ time python fastread.py --fileName="all_bin.csv" --numProcesses=32 --balanceFactor=2
2367496
real 0m8.920s
user 1m30.056s
sys 2m38.744s
In [1]: 40412077758. / 8.92
Out[1]: 4530501990.807175
That’s some 4.5 GB/s, or 45 Gb/s, file slurping speed. That ain’t no spinning hard disk, my friend. That’s actually a Samsung Pro 950 SSD.
Below is the speed benchmark for the same file being line-counted by gnu wc, a pure C compiled program.
What is cool is you can see my pure python program essentially matched the speed of the gnu wc compiled C program in this case. Python is interpreted but C is compiled, so this is a pretty interesting feat of speed, I think you would agree. Of course, wc really needs to be changed to a parallel program, and then it would really beat the socks off my python program. But as it stands today, gnu wc is just a sequential program. You do what you can, and python can do parallel today. Cython compiling might be able to help me (for some other time). Also memory mapped files was not explored yet.
HP-Z820:/mnt/fastssd$ time wc -l all_bin.csv
2367496 all_bin.csv
real 0m8.807s
user 0m1.168s
sys 0m7.636s
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000
real 0m2.257s
user 0m12.088s
sys 0m20.512s
HP-Z820:/mnt/fastssd/fast_file_reader$ time wc -l HIGGS.csv
11000000 HIGGS.csv
real 0m1.820s
user 0m0.364s
sys 0m1.456s
Conclusion: The speed is good for a pure python program compared to a C program. However, it’s not good enough to use the pure python program over the C program, at least for linecounting purpose. Generally the technique can be used for other file processing, so this python code is still good.
Question: Does compiling the regex just one time and passing it to all workers will improve speed? Answer: Regex pre-compiling does NOT help in this application. I suppose the reason is that the overhead of process serialization and creation for all the workers is dominating.
One more thing. Does parallel CSV file reading even help? Is the disk the bottleneck, or is it the CPU? Many so-called top-rated answers on stackoverflow contain the common dev wisdom that you only need one thread to read a file, best you can do, they say. Are they sure, though?
Let’s find out:
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000
real 0m2.256s
user 0m10.696s
sys 0m19.952s
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=1 --balanceFactor=1
11000000
real 0m17.380s
user 0m11.124s
sys 0m6.272s
Oh yes, yes it does. Parallel file reading works quite well. Well there you go!
Ps. In case some of you wanted to know, what if the balanceFactor was 2 when using a single worker process? Well, it’s horrible:
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=1 --balanceFactor=2
11000000
real 1m37.077s
user 0m12.432s
sys 1m24.700s
Key parts of the fastread.py python program:
fileBytes = stat(fileName).st_size # Read quickly from OS how many bytes are in a text file
startByte, endByte = PartitionDataToWorkers(workers=numProcesses, items=fileBytes, balanceFactor=balanceFactor)
p = Pool(numProcesses)
partialSum = p.starmap(ReadFileSegment, zip(startByte, endByte, repeat(fileName))) # startByte is already a list. fileName is made into a same-length list of duplicates values.
globalSum = sum(partialSum)
print(globalSum)
def ReadFileSegment(startByte, endByte, fileName, searchChar='\n'): # counts number of searchChar appearing in the byte range
with open(fileName, 'r') as f:
f.seek(startByte-1) # seek is initially at byte 0 and then moves forward the specified amount, so seek(5) points at the 6th byte.
bytes = f.read(endByte - startByte + 1)
cnt = len(re.findall(searchChar, bytes)) # findall with implicit compiling runs just as fast here as re.compile once + re.finditer many times.
return cnt
The def for PartitionDataToWorkers is just ordinary sequential code. I left it out in case someone else wants to get some practice on what parallel programming is like. I gave away for free the harder parts: the tested and working parallel code, for your learning benefit.
Thanks to: The open-source H2O project, by Arno and Cliff and the H2O staff for their great software and instructional videos, which have provided me the inspiration for this pure python high performance parallel byte offset reader as shown above. H2O does parallel file reading using java, is callable by python and R programs, and is crazy fast, faster than anything on the planet at reading big CSV files.
You have to disable the sandbox for Groovy in your job configuration.
Currently this is not possible for multibranch projects where the groovy script comes from the scm. For more information see https://issues.jenkins-ci.org/browse/JENKINS-28178
I had to add this line to settings.py in order to make it work (otherwise it showed an error when accessed from another computer)
ALLOWED_HOSTS = ['*']
then ran the server with:
python manage.py runserver 0.0.0.0:9595
Also ensure that the firewall allows connections to that port
The best way to do this is actually just use <%= form_authenticity_token.to_s %>
to print out the token directly in your rails code. You dont need to use javascript to search the dom for the csrf token as other posts mention. just add the headers option as below;
$.ajax({
type: 'post',
data: $(this).sortable('serialize'),
headers: {
'X-CSRF-Token': '<%= form_authenticity_token.to_s %>'
},
complete: function(request){},
url: "<%= sort_widget_images_path(@widget) %>"
})
If you want search for sensitive data in order to remove it from your git history (which is the reason why I landed here), there are tools for that. Github as a dedicated help page for that issue.
Here is the gist of the article:
The BFG Repo-Cleaner is a faster, simpler alternative to git filter-branch for removing unwanted data. For example, to remove your file with sensitive data and leave your latest commit untouched), run:
bfg --delete-files YOUR-FILE-WITH-SENSITIVE-DATA
To replace all text listed in passwords.txt wherever it can be found in your repository's history, run:
bfg --replace-text passwords.txt
See the BFG Repo-Cleaner's documentation for full usage and download instructions.
I know that my answer came late but it happens to me today and I solved it with the following approach:
^(([A-Z]+),)+([A-Z]+)$
So the first group (([A-Z]+),)+
will match all the repeated patterns except the final one ([A-Z]+)
that will match the final one. and this will be dynamic no matter how many repeated groups in the string.
./gradlew
Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. .
means "current directory".
You have to add the targeted map :
var markers = [
{
"title": 'This is title',
"lat": '-37.801578',
"lng": '145.060508',
"map": map,
"icon": 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png',
"description": 'Vikash Rathee. <strong> This is test Description</strong> <br/><a href="http://www.pricingindia.in/pincode.aspx">Pin Code by
City</a>'
}
];
The answer was to install the plugin individually. I installed all the three plugins shown in the screenshot together. And it created the issue. I had to install each plugin individually and then it worked fine. I am able to format the JSON string.
--another way to do this
df.columns = df.iloc[0]
df = df.reindex(df.index.drop(0)).reset_index(drop=True)
df.columns.name = None
Sample Number Group Number Sample Name Group Name
0 1.0 1.0 s_1 g_1
1 2.0 1.0 s_2 g_1
2 3.0 1.0 s_3 g_1
3 4.0 2.0 s_4 g_2
If you like it hit up arrow. Thanks
I used this and it worked : it is very simple and works fine.
JTable myTable = new JTable();
myTable.setEnabled(false);
You should declare your method first in void initState()
, so when the first time pages has been loaded, it will init your method first, hope it can help
Jon's disassemblies show, that the difference between the two versions is that the fast version uses a pair of registers (esi,edi
) to store one of the local variables where the slow version doesn't.
The JIT compiler makes different assumptions regarding register use for code that contains a try-catch block vs. code which doesn't. This causes it to make different register allocation choices. In this case, this favors the code with the try-catch block. Different code may lead to the opposite effect, so I would not count this as a general-purpose speed-up technique.
In the end, it's very hard to tell which code will end up running the fastest. Something like register allocation and the factors that influence it are such low-level implementation details that I don't see how any specific technique could reliably produce faster code.
For example, consider the following two methods. They were adapted from a real-life example:
interface IIndexed { int this[int index] { get; set; } }
struct StructArray : IIndexed {
public int[] Array;
public int this[int index] {
get { return Array[index]; }
set { Array[index] = value; }
}
}
static int Generic<T>(int length, T a, T b) where T : IIndexed {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
static int Specialized(int length, StructArray a, StructArray b) {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
One is a generic version of the other. Replacing the generic type with StructArray
would make the methods identical. Because StructArray
is a value type, it gets its own compiled version of the generic method. Yet the actual running time is significantly longer than the specialized method's, but only for x86. For x64, the timings are pretty much identical. In other cases, I've observed differences for x64 as well.
you use the scrollTop attribute
var position = document.getElementById('id').scrollTop;
Using scanf
is very easy, this is an example :
if (scanf("%d", &val_a_tester) == 1) {
... // it's an integer
}
If your compiler is GCC you can also use following syntax:
int array[256] = {[0 ... 255] = 0};
Please look at http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html#Designated-Inits, and note that this is a compiler-specific feature.
For anyone landing here who is trying to upgrade from MVC 4 to MVC5, I was able to resolve this issue by following the instructions at http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2.
I also had to install the "Microsoft.AspNet.WebApi.WebHost" package from nuget. But that's it.
Oh, and I had to create this appSetting: <add key="owin:AutomaticAppStartup" value="false" />
:)
You can do it like:
change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'
or try this:
change_column :table_name, :column_name, :integer, using: 'column_name::integer'
If you are interested to find more about this topic read this article: https://kolosek.com/rails-change-database-column
Two ways I know of:
export class SomeComponent implements OnInit
{
public localVar:any;
ngOnInit(){
this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
}
}
This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}
Another Way is to get a observable as a localVariable.
export class SomeComponent
{
public localVar:any;
constructor()
{
this.localVar = this.http.get(path).map(res => res.json());
}
}
This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}
Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.
Hope it helps
Yes, open a postscript()
device with a filename ending in .eps
, do your plot(s) and call dev.off()
.
I've created a jQuery plugin that provides 4 additonal placements: topLeft, topRight, bottomLeft, bottomRight
You just include either the minified js or unminified js and have the matching css (minified vs unminified) in the same folder.
https://github.com/dkleehammer/bootstrap-popover-extra-placements
Question is a little vague.
list_of_lines = multiple_lines.split("\n")
for line in list_of_lines:
list_of_items_in_line = line.split(",")
first_int = int(list_of_items_in_line[0])
etc.
The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this:
f = open('test.txt','r')
g = open('test1.txt','w')
while True:
x = f.readline()
x = x.rstrip()
if not x: break
print >> g, int(x, 16)
On the other hand it would be better to use for x in f
instead of readline
. Do not forget to close your files or better to use with
that close them for you:
with open('test.txt','r') as f:
with open('test1.txt','w') as g:
for x in f:
x = x.rstrip()
if not x: continue
print >> g, int(x, 16)
If you are not using any JS build tools/NPM, then you can directly include Jquery as:
import 'https://code.jquery.com/jquery-1.12.4.min.js';
const $ = window.$;
You may skip import(Line 1) if you already included jquery using script tag under head.
You may wrap it in a bash script or git alias:
cd /X/Y && git pull && cd -
This will work in all browsers
#circle {
background: #f00;
width: 200px;
height: 200px;
border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
}
If you are using post as a model (without dependency injection), you can also do:
$posts = Post::orderBy('id', 'DESC')->get();
You use the error_page property in the nginx config.
For example, if you intend to set the 404 error page to /404.html
, use
error_page 404 /404.html;
Setting the 500 error page to /500.html
is just as easy as:
error_page 500 /500.html;
You can use
Dispatcher.Invoke(Delegate, object[])
on the Application
's (or any UIElement
's) dispatcher.
You can use it for example like this:
Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
or
someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
I can't understand why this JAXB IllegalAnnotationException is thrown
I also was getting the ### counts of IllegalAnnotationExceptions
exception and it seemed to be due to an improper dependency hierarchy in my Spring wiring.
I figured it out by putting a breakpoint in the JAXB code when it does the throw. For me this was at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check()
. Then I dumped the list
variable which gives something like:
[org.mortbay.jetty.Handler is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at org.mortbay.jetty.Handler
at public org.mortbay.jetty.Handler[] org.mortbay.jetty.handler.HandlerCollection.getHandlers()
at org.mortbay.jetty.handler.HandlerCollection
at org.mortbay.jetty.handler.ContextHandlerCollection
at com.mprew.ec2.commons.server.LocalContextHandlerCollection
at private com.mprew.ec2.commons.server.LocalContextHandlerCollection com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection.arg0
at com.mprew.ec2.commons.services.jaxws_asm.SetLocalContextHandlerCollection,
org.mortbay.jetty.Handler does not have a no-arg default constructor.]
....
The does not have a no-arg default constructor
seemed to me to be misleading. Maybe I wasn't understanding what the exception was saying. But it did indicate that there was a problem with my LocalContextHandlerCollection
. I removed a dependency loop and the error cleared.
Hopefully this will be helpful to others.
This way works for me, (using Spring Boot version 2.0.1. RELEASE):
@Query("SELECT u.username FROM User u WHERE u.username LIKE %?1%")
List<String> findUsersWithPartOfName(@Param("username") String username);
Explaining: The ?1, ?2, ?3 etc. are place holders the first, second, third parameters, etc. In this case is enough to have the parameter is surrounded by % as if it was a standard SQL query but without the single quotes.
I will quote the article The Difference Between Anchors, Inputs and Buttons:
Anchors (the <a>
element) represent hyperlinks, resources a person can navigate to or download in a browser. If you want to allow your user to move to a new page or download a file, then use an anchor.
An input (<input>
) represents a data field: so some user data you mean to send to server. There are several input types related to buttons:
<input type="submit">
<input type="image">
<input type="file">
<input type="reset">
<input type="button">
Each of them has a meaning, for example "file" is used to upload a file, "reset" clears a form, and "submit" sends the data to the server. Check W3 reference on MDN or on W3Schools.
The button (<button>)
element is quite versatile:
::before
and ::after
pseudo-elements;disabled
attribute. This makes it easy to turn
them on and off.Again, check W3 reference for <button>
tag on MDN or on W3Schools.
This worked for me:
// Check if URL contains the word "car" or "CAR"
if (stripos($_SERVER['REQUEST_URI'], 'car' )!==false){
echo "Car here";
} else {
echo "No car here";
}
If you want to use HTML in the echo, be sure to use ' ' instead of " ". I use this code to show an alert on my webpage https://geaskb.nl/ where the URL contains the word "Omnik" but hide the alert on pages that do not contain the word "Omnik" in the URL.
Explanation stripos : https://www.php.net/manual/en/function.stripos
Because unsigned
type is pure evil.
The fact that in C unsigned - int
produces unsigned
is even more evil.
Here is a snapshot of the problem that burned me more than once:
// We have odd positive number of rays,
// consecutive ones at angle delta from each other.
assert( rays.size() > 0 && rays.size() % 2 == 1 );
// Get a set of ray at delta angle between them.
for( size_t n = 0; n < rays.size(); ++n )
{
// Compute the angle between nth ray and the middle one.
// The index of the middle one is (rays.size() - 1) / 2,
// the rays are evenly spaced at angle delta, therefore
// the magnitude of the angle between nth ray and the
// middle one is:
double angle = delta * fabs( n - (rays.size() - 1) / 2 );
// Do something else ...
}
Have you noticed the bug yet? I confess I only saw it after stepping in with the debugger.
Because n
is of unsigned type size_t
the entire expression n - (rays.size() - 1) / 2
evaluates as unsigned
. That expression is intended to be a signed position of the n
th ray from the middle one: the 1st ray from the middle one on the left side would have position -1, the 1st one on the right would have position +1, etc. After taking abs value and multiplying by the delta
angle I would get the angle between n
th ray and the middle one.
Unfortunately for me the above expression contained the evil unsigned and instead of evaluating to, say, -1, it evaluated to 2^32-1. The subsequent conversion to double
sealed the bug.
After a bug or two caused by misuse of unsigned
arithmetic one has to start wondering whether the extra bit one gets is worth the extra trouble. I am trying, as much as feasible, to avoid any use of unsigned
types in arithmetic, although still use it for non-arithmetic operations such as binary masks.
Downloading java dependencies is possible, if you actually really need to download them into a folder.
Example:
apply plugin: 'java'
dependencies {
runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2'
runtime group: 'org.apache.zookeeper', name: 'zookeeper', version: '3.4.6'
}
repositories { mavenCentral() }
task getDeps(type: Copy) {
from sourceSets.main.runtimeClasspath
into 'runtime/'
}
Download the dependencies (and their dependencies) into the folder runtime
when you execute gradle getDeps
.
In my case the problem was the line with default instructions in switch block:
handlePageChange = ({ btnType}) => {
let { page } = this.state;
switch (btnType) {
case 'next':
this.updatePage(page + 1);
break;
case 'prev':
this.updatePage(page - 1);
break;
default: null;
}
}
Instead of
default: null;
The line
default: ;
worked for me.
If this is something you are only going to need to do once, have you considered downloading a demo version of Crystal? There's a 30-day trial version available here: http://www.developers.net/businessobjectsshowcase/view/3154
Of course, if you need to edit these files after the 30 day period is over, you would be better off buying Crystal.
Alternatively, if all you need to do is replace a few static literal words, have you tried doing a search and replace in a text editor? (Don't forget to save the original files somewhere safe first!)
Following Code authenticates from LDAP using pure Java JNDI. The Principle is:-
Code Snippet
public static boolean authenticateJndi(String username, String password) throws Exception{
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
props.put(Context.SECURITY_PRINCIPAL, "uid=adminuser,ou=special users,o=xx.com");//adminuser - User with special priviledge, dn user
props.put(Context.SECURITY_CREDENTIALS, "adminpassword");//dn user password
InitialDirContext context = new InitialDirContext(props);
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] { "givenName", "sn","memberOf" });
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<javax.naming.directory.SearchResult> answers = context.search("o=xx.com", "(uid=" + username + ")", ctrls);
javax.naming.directory.SearchResult result = answers.nextElement();
String user = result.getNameInNamespace();
try {
props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
props.put(Context.SECURITY_PRINCIPAL, user);
props.put(Context.SECURITY_CREDENTIALS, password);
context = new InitialDirContext(props);
} catch (Exception e) {
return false;
}
return true;
}
This error happens when you have a ViewBag Non-Existent in your razor code calling a method.
Controller
public ActionResult Accept(int id)
{
return View();
}
razor:
<div class="form-group">
@Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Flag(Model.from)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@
</div>
</div>
For some reason, the .net aren't able to show the error in the correct line.
Normally this causes a lot of wasted time.
Making a class abstract
sends a message to the readers of your code that you want users of your abstract
class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.
Therefore, adding a private constructor is a better choice here. You should also make the class final
to disallow subclassing of your utility class.
Redis has configuration parameter pidfile
(e.g. /etc/redis.conf - check redis source code), for example:
# If a pid file is specified, Redis writes it where specified at startup
# and removes it at exit.
#
# When the server runs non daemonized, no pid file is created if none is
# specified in the configuration. When the server is daemonized, the pid file
# is used even if not specified, defaulting to "/var/run/redis.pid".
#
pidfile /var/run/redis.pid
If it is set or could be set, instead of searching for process id (pid) by using ps + grep
something like this could be used:
kill $(cat /var/run/redis.pid)
If required one can make redis stop script like this (adapted default redis 5.0 init.d script in redis source code):
PIDFILE=/var/run/redis.pid
if [ ! -f $PIDFILE ]
then
echo "$PIDFILE does not exist, process is not running"
else
PID=$(cat $PIDFILE)
echo "Stopping ..."
kill $PID
while [ -x /proc/${PID} ]
do
echo "Waiting for Redis to shutdown ..."
sleep 1
done
echo "Redis stopped"
fi
Since Sheet.getPhysicalNumberOfRows()
does not count empty rows and Sheet.getLastRowNum()
returns 0 both if there is one row or no rows, I use a combination of the two methods to accurately calculate the total number of rows.
int rowTotal = sheet.getLastRowNum();
if ((rowTotal > 0) || (sheet.getPhysicalNumberOfRows() > 0)) {
rowTotal++;
}
Note: This will treat a spreadsheet with one empty row as having none but for most purposes this is probably okay.
The Device File Explorer that is part of Android Studio 3.x is really good for exploring your preference file(s), cache items or database.
It looks something like this
To open The Device File Explorer:
Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool window bar.
If you using on input tag than this code will help you. I write this code by myself and I think this is very good way to use in input. but you can change it using your format. It will help user to correct their format on input tag.
$("#phone").on('input', function() { //this is use for every time input change.
var inputValue = getInputValue(); //get value from input and make it usefull number
var length = inputValue.length; //get lenth of input
if (inputValue < 1000)
{
inputValue = '1('+inputValue;
}else if (inputValue < 1000000)
{
inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, length);
}else if (inputValue < 10000000000)
{
inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, length);
}else
{
inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, 10);
}
$("#phone").val(inputValue); //correct value entered to your input.
inputValue = getInputValue();//get value again, becuase it changed, this one using for changing color of input border
if ((inputValue > 2000000000) && (inputValue < 9999999999))
{
$("#phone").css("border","black solid 1px");//if it is valid phone number than border will be black.
}else
{
$("#phone").css("border","red solid 1px");//if it is invalid phone number than border will be red.
}
});
function getInputValue() {
var inputValue = $("#phone").val().replace(/\D/g,''); //remove all non numeric character
if (inputValue.charAt(0) == 1) // if first character is 1 than remove it.
{
var inputValue = inputValue.substring(1, inputValue.length);
}
return inputValue;
}
With EF Core in .NET Core you can use the keyword ThenInclude
:
return DatabaseContext.Applications
.Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);
Include childs from childrens collection :
return DatabaseContext.Applications
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);
Get process monitor from SysInternals set it up to watch for the Lunaverse.DbVerse (on the Path field) look at the operation result. It should be obvious from there what went wrong
From developer documentation
This can be used for instance to give a single child 50%
of the total available space by giving it a layout_weight of 0.5
and setting the weightSum to 1.0
.
Addition to @Shubhayu answer
rest 3/5
can be used for other child layouts which really doesn't need any specific portion of containing layout.
this is potential use of android:weightSum
property.
you can simply do this..
<img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>
simpler with linq:
public void KillProcessesAssociatedToFile(string file)
{
GetProcessesAssociatedToFile(file).ForEach(x =>
{
x.Kill();
x.WaitForExit(10000);
});
}
public List<Process> GetProcessesAssociatedToFile(string file)
{
return Process.GetProcesses()
.Where(x => !x.HasExited
&& x.Modules.Cast<ProcessModule>().ToList()
.Exists(y => y.FileName.ToLowerInvariant() == file.ToLowerInvariant())
).ToList();
}
You can change the style applied to each activity, or if you only want to change the behavior for a specific activity, you can try this:
setDisplayOptions(int options, int mask) --- Set selected display
or
setDisplayOptions(int options) --- Set display options.
To display title on actionbar, set display options in onCreate()
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
To hide title on actionbar.
getSupportActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
Details here.
Try this
This is the simplest way to ask for permission in Marshmallow version.
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED&&ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
//TO do here if permission is granted by user
}
else
{
//ask for permission if user didnot given
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION}, 0);
}
}
Note:- Don't forget to add this same permission in manifest file also
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Second Method Code for checking the permission is granted or not?
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA}, 1);
And override the method
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// grantResult[0] means it will check for the first postion permission which is READ_EXTERNAL_STORAGE
// grantResult[1] means it will check for the Second postion permission which is CAMERA
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, "Permission not Granted", Toast.LENGTH_SHORT).show();
return;
}
}
}
I am pretty sure that you can do it using Java Reflection mechanism. It is not as straightforward as using super but it gives you more power.
class A
{
public void myMethod()
{ /* ... */ }
}
class B extends A
{
public void myMethod()
{
super.myMethod(); // calling parent method
}
}
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
jQuery provides an each()
method, not forEach()
. You can break out of each
by returning false
. forEach()
is part of the ECMA-262 standard, and the only way to break out of that that I'm aware of is by throwing an exception.
function recurs(comment) {
try {
comment.comments.forEach(function(elem) {
recurs(elem);
if (...) throw "done";
});
} catch (e) { if (e != "done") throw e; }
}
Ugly, but does the job.
From what I understand you can't pass an arguments to a filter function (when using the 'filter' filter). What you would have to do is to write a custom filter, sth like this:
.filter('weDontLike', function(){
return function(items, name){
var arrayToReturn = [];
for (var i=0; i<items.length; i++){
if (items[i].name != name) {
arrayToReturn.push(items[i]);
}
}
return arrayToReturn;
};
Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/myr4a/1/
The other simple alternative, without writing custom filters is to store a name to filter out in a scope and then write:
$scope.weDontLike = function(item) {
return item.name != $scope.name;
};
Here's a good one:
Set line-height
equal to whatever the height
is; works like a charm!
E.g:
li {
height: 30px;
line-height: 30px;
}
Try This: Application.ExitThread();
On Windows Server 2008(r2) you can't assign an application pool identity to a folder through Properties->Security. You can do it through an admin command prompt using the following though:
icacls "c:\yourdirectory" /t /grant "IIS AppPool\DefaultAppPool":(R)
Run this command on your terminal.
git reset HEAD~n
You can remove the last n commits from local repo e.g. HEAD~2. Proceed with force git push on your repository.
git push -f origin <branch>
Hope this helps!
var groupedCustomerList = userList
.GroupBy(u => u.GroupID)
.Select(grp => grp.ToList())
.ToList();
Edit:
Since node v10.0.0
we could use fs.promises.access(...)
Example async code that checks if file exists:
async function checkFileExists(file) {
return fs.promises.access(file, fs.constants.F_OK)
.then(() => true)
.catch(() => false)
}
An alternative for stat might be using the new fs.access(...)
:
minified short promise function for checking:
s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
Sample usage:
let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
checkFileExists("Some File Location")
.then(bool => console.log(´file exists: ${bool}´))
expanded Promise way:
// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
return new Promise((resolve, reject) => {
fs.access(filepath, fs.constants.F_OK, error => {
resolve(!error);
});
});
}
or if you wanna do it synchronously:
function checkFileExistsSync(filepath){
let flag = true;
try{
fs.accessSync(filepath, fs.constants.F_OK);
}catch(e){
flag = false;
}
return flag;
}
In Notepad++, you can use the Mark tab in the Find dialogue to Bookmark all lines matching your query which can be regex or normal (wildcard).
Then use Search > Bookmark > Remove Bookmarked Lines.
public static String fmt(double d) {
String val = Double.toString(d);
String[] valArray = val.split("\\.");
long valLong = 0;
if(valArray.length == 2) {
valLong = Long.parseLong(valArray[1]);
}
if (valLong == 0)
return String.format("%d", (long) d);
else
return String.format("%s", d);
}
I had to use this because d == (long)d
was giving me violation in a SonarQube report.
Another version which is simple
BiFunction<TreeSet<Employee>,List<Employee> ,TreeSet<Employee>> appendTree = (y,x) -> (y.addAll(x))? y:y;
TreeSet<Employee> outputList = appendTree.apply(new TreeSet<Employee>(Comparator.comparing(p->p.getId())),personList);
Alternative way of converting to csv. Use libreoffice
:
libreoffice --headless --convert-to csv *
Please be aware that this will only convert the first worksheet of your Excel file.
Anaconda with Windows
After conda commands it's required to accept process - Proceed ([y]/n)?
Use this one-liner for any primitive number class including double
and float
:
a += (b - (b = a));
For example:
double a = 1.41;
double b = 0;
a += (b - (b = a));
System.out.println("a = " + a + ", b = " + b);
Output is a = 0.0, b = 1.41
Thank you guys for all your help! Finally I was able to make it work perfectly thanks to a friend and also you! Here is the final code so you can also see how we solve it.
Thanks again!
Option Explicit
Sub k()
Dim x As Integer, i As Integer, a As Integer
Dim name As String
'name = InputBox("Please insert the name of the sheet")
i = 1
name = "Reserva"
Sheets(name).Cells(4, 57) = Sheets(name).Cells(4, 56)
On Error GoTo fim
x = Sheets(name).Cells(4, 56).Value
Application.Calculation = xlCalculationManual
Do While Not IsEmpty(Sheets(name).Cells(i + 4, 56))
a = 0
If Sheets(name).Cells(4 + i, 56) <> x Then
If Sheets(name).Cells(4 + i, 56) <> 0 Then
If Sheets(name).Cells(4 + i, 56) = 3 Then
a = x
Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - x
x = Cells(4 + i, 56) - x
End If
Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - a
x = Sheets(name).Cells(4 + i, 56) - a
Else
Cells(4 + i, 57) = ""
End If
Else
Cells(4 + i, 57) = ""
End If
i = i + 1
Loop
Application.Calculation = xlCalculationAutomatic
Exit Sub
fim:
MsgBox Err.Description
Application.Calculation = xlCalculationAutomatic
End Sub
Jenkins runs as another user, not as your ordinary login. So, do as this to solve the ssh problem:
su jenkins
(you may first have to do sudo passwd jenkins
to be able to set the password for jenkins. I couldn't find the default...)ssh-keygen
id_rsa.pub
) to your github account (or wherever)known_hosts
which is neccessary to do. Now you can remove the cloned repo again if you wish.I can't seem to wrap my head around why this does not work.
Because main
returns a promise; all async
functions do.
At the top level, you must either:
Use a top-level async
function that never rejects (unless you want "unhandled rejection" errors), or
Use then
and catch
, or
(Coming soon!) Use top-level await
, a proposal that has reached Stage 3 in the process that allows top-level use of await
in a module.
async
function that never rejects(async () => {
try {
var text = await main();
console.log(text);
} catch (e) {
// Deal with the fact the chain failed
}
})();
Notice the catch
; you must handle promise rejections / async exceptions, since nothing else is going to; you have no caller to pass them on to. If you prefer, you could do that on the result of calling it via the catch
function (rather than try
/catch
syntax):
(async () => {
var text = await main();
console.log(text);
})().catch(e => {
// Deal with the fact the chain failed
});
...which is a bit more concise (I like it for that reason).
Or, of course, don't handle errors and just allow the "unhandled rejection" error.
then
and catch
main()
.then(text => {
console.log(text);
})
.catch(err => {
// Deal with the fact the chain failed
});
The catch
handler will be called if errors occur in the chain or in your then
handler. (Be sure your catch
handler doesn't throw errors, as nothing is registered to handle them.)
Or both arguments to then
:
main().then(
text => {
console.log(text);
},
err => {
// Deal with the fact the chain failed
}
);
Again notice we're registering a rejection handler. But in this form, be sure that neither of your then
callbacks doesn't throw any errors, nothing is registered to handle them.
await
in a moduleYou can't use await
at the top level of a non-module script, but the top-level await
proposal (Stage 3) allows you to use it at the top level of a module. It's similar to using a top-level async
function wrapper (#1 above) in that you don't want your top-level code to reject (throw an error) because that will result in an unhandled rejection error. So unless you want to have that unhandled rejection when things go wrong, as with #1, you'd want to wrap your code in an error handler:
// In a module, once the top-level `await` proposal lands
try {
var text = await main();
console.log(text);
} catch (e) {
// Deal with the fact the chain failed
}
Note that if you do this, any module that imports from your module will wait until the promise you're await
ing settles; when a module using top-level await
is evaluated, it basically returns a promise to the module loader (like an async
function does), which waits until that promise is settled before evaluating the bodies of any modules that depend on it.
If you want to generate random numbers in range including '0' , use the following while 'max' is the maximum number in the range.
Random rand = new Random()
random_num = rand.nextInt(max+1)
The negation pseudo-class seems to be what you are looking for.
table:not(.dojoxGrid) {color:red;}
I think it will be easier using syntax-based query:
var entryPoint = (from ep in dbContext.tbl_EntryPoint
join e in dbContext.tbl_Entry on ep.EID equals e.EID
join t in dbContext.tbl_Title on e.TID equals t.TID
where e.OwnerID == user.UID
select new {
UID = e.OwnerID,
TID = e.TID,
Title = t.Title,
EID = e.EID
}).Take(10);
And you should probably add orderby
clause, to make sure Top(10)
returns correct top ten items.
I am working in Windows 7 with Python IDLE. I have two programs,
# progA
while True:
m = input('progA is running ')
print (m)
and
# progB
while True:
m = input('progB is running ')
print (m)
I open up IDLE and then open file progA.py. I run the program, and when prompted for input I enter "b" + <Enter>
and then "c" + <Enter>
I am looking at this window:
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progA.py =
progA is running b
b
progA is running c
c
progA is running
Next, I go back to Windows Start and open up IDLE again, this time opening file progB.py. I run the program, and when prompted for input I enter "x" + <Enter>
and then "y" + <Enter>
I am looking at this window:
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progB.py =
progB is running x
x
progB is running y
y
progB is running
Now two IDLE Python 3.6.3 Shell programs are running at the same time, one shell running progA while the other one is running progB.
The best way might be if else with requesting. Also, this can be easier and clear to use.
Example:
<?php
$go = $_REQUEST['go'];
?>
<?php if ($go == 'general_information'){?>
<div>
echo "hello";
}?>
Instead of using the functions that won't work well with PHP, especially when you have PHP in HTML.
I know it's way too late to answer this question, but I'll just post the solution that worked for me, in case someone runs into trouble again in the future.
I tried using genymotion's own adb tools and the original Android SDK ones, and even purging and reinstalling adb from my system, but nothing worked. I kept getting the error:
adb server is out of date. killing...
cannot bind 'tcp:5037'
ADB server didn't ACK
*failed to start daemon*
error:
So I tried adb connect [ip]
as suggested here, but I didn't work either, the same error came up.
What finally worked for me was downloading ADT, and running adb directly from the downloaded folder, instead of the system-wide command. So adb devices
will give me the error above, but /yourdownloadpath/adb devices
works just fine for me.
Hope it helped.
New answer to new question:
You cannot return pointer to automatic variable (int c[5]
) from the function. Automatic variable ends its lifetime with return enclosing block (function in this case) - so you are returning pointer to not existing array.
Either make your variable dynamic:
int* test (int a[5], int b[5]) {
int* c = new int[5];
for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
return c;
}
Or change your implementation to use std::array
:
std::array<int,5> test (const std::array<int,5>& a, const std::array<int,5>& b)
{
std::array<int,5> c;
for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
return c;
}
In case your compiler does not provide std::array
you can replace it with simple struct containing an array:
struct array_int_5 {
int data[5];
int& operator [](int i) { return data[i]; }
int operator const [](int i) { return data[i]; }
};
Old answer to old question:
Your code is correct, and ... hmm, well, ... useless. Since arrays can be assigned to pointers without extra function (note that you are already using this in your function):
int arr[5] = {1, 2, 3, 4, 5};
//int* pArr = test(arr);
int* pArr = arr;
Morever signature of your function:
int* test (int in[5])
Is equivalent to:
int* test (int* in)
So you see it makes no sense.
However this signature takes an array, not pointer:
int* test (int (&in)[5])
Using session
, I successfully passed a parameter (name
) from servlet #1 to servlet #2, using response.sendRedirect
in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name
back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name");
---but you don't need this.
If Servlet #2 calls a JSP, you can show name
this way on the JSP webpage:
<h1>Welcome ${name}</h1>
Super simple and readable, here's how you create a local proxy server to a local HTTP server with just Node.js (tested on v8.1.0). I've found it particular useful for integration testing so here's my share:
/**
* Once this is running open your browser and hit http://localhost
* You'll see that the request hits the proxy and you get the HTML back
*/
'use strict';
const net = require('net');
const http = require('http');
const PROXY_PORT = 80;
const HTTP_SERVER_PORT = 8080;
let proxy = net.createServer(socket => {
socket.on('data', message => {
console.log('---PROXY- got message', message.toString());
let serviceSocket = new net.Socket();
serviceSocket.connect(HTTP_SERVER_PORT, 'localhost', () => {
console.log('---PROXY- Sending message to server');
serviceSocket.write(message);
});
serviceSocket.on('data', data => {
console.log('---PROXY- Receiving message from server', data.toString();
socket.write(data);
});
});
});
let httpServer = http.createServer((req, res) => {
switch (req.url) {
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<html><body><p>Ciao!</p></body></html>');
break;
default:
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404 Not Found');
}
});
proxy.listen(PROXY_PORT);
httpServer.listen(HTTP_SERVER_PORT);
https://gist.github.com/fracasula/d15ae925835c636a5672311ef584b999
An easy way to do this is using the pandas
library like this.
import pandas as pd
fields = ['star_name', 'ra']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name
The problem here was the skipinitialspace
which remove the spaces in the header. So ' star_name' becomes 'star_name'
I had compatibility issues with several plugins I tried, this seems to me to be the simplest way of supporting placeholders on text inputs:
function placeholders(){
//On Focus
$(":text").focus(function(){
//Check to see if the user has modified the input, if not then remove the placeholder text
if($(this).val() == $(this).attr("placeholder")){
$(this).val("");
}
});
//On Blur
$(":text").blur(function(){
//Check to see if the use has modified the input, if not then populate the placeholder back into the input
if( $(this).val() == ""){
$(this).val($(this).attr("placeholder"));
}
});
}
Start off by opening a cmd.exe session, changing directory to the "program files" directory that has the javac.exe executable and running .\javac.exe.
If that doesn't work, reinstall java. If that works, odds are you will find (in doing that task) that you've installed a 64 bit javac.exe
, or a slightly different release number of javac.exe
, or in a different drive, etc. and selecting the right entry in your path will become child's play.
Only use the semicolon between directories in the PATH environment variable, and remember that in some systems, you need to log out and log back in before the new environment variable is accessible to all environments.
Options to avoid using SecurityContextHolder in tests:
SecurityContextHolder
using some mock library - EasyMock for exampleSecurityContextHolder.get...
in your code in some service - for example in SecurityServiceImpl
with method getCurrentPrincipal
that implements SecurityService
interface and then in your tests you can simply create mock implementation of this interface that returns the desired principal without access to SecurityContextHolder
. SUMIF didn't worked for me, had to use SUMIFS.
=SUMIFS(TableAmount,TableMonth,"January")
TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.
Hope this can help someone!
Hopefully I am not misunderstanding this document, but if your using Java 1.8, in theory, you could accomplish something like this by defining a working implementation of a default method ("defender methods") within an interface that you implement.
interface DoInterface {
void doNothing();
public default void remove() {
throw new UnsupportedOperationException("remove");
}
public default int doSomething( int arg1, int arg2) {
val = arg1 + arg2 * arg1;
log( "Value is: " + val );
return val;
}
}
class DoIt extends DoInterface {
DoIt() {
log("Called DoIt constructor.");
}
public int doSomething() {
int val = doSomething( 0, 100 );
return val;
}
}
Then, call it either way:
DoIt d = new DoIt();
d.doSomething();
d.soSomething( 5, 45 );
You can also use function:
//Works with negative numbers now
static int MyRound(double d) {
if (d < 0) {
return (int)(d - 0.5);
}
return (int)(d + 0.5);
}
Depending on the architecture it is several times faster.
Complete tutorial here
Demo link
JavaScript
$('.owl-carousel').owlCarousel({
margin: 10,
nav: true,
navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
responsive: {
0: {
items: 1
},
600: {
items: 3
},
1000: {
items: 5
}
}
});
CSS Style for navigation
.owl-carousel .nav-btn{
height: 47px;
position: absolute;
width: 26px;
cursor: pointer;
top: 100px !important;
}
.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}
.owl-carousel .prev-slide{
background: url(nav-icon.png) no-repeat scroll 0 0;
left: -33px;
}
.owl-carousel .next-slide{
background: url(nav-icon.png) no-repeat scroll -24px 0px;
right: -33px;
}
.owl-carousel .prev-slide:hover{
background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}
Extending answer of @MichaelLaCroix when a scenario is that the components can't communicate between any sort of parent-child relationship, the documentation recommends setting up a global event system.
In the case of <Filters />
and <TopBar />
don't have any of the above relationship, a simple global emitter could be used like this:
componentDidMount
- Subscribe to event
componentWillUnmount
- Unsubscribe from event
EventSystem.js
class EventSystem{
constructor() {
this.queue = {};
this.maxNamespaceSize = 50;
}
publish(/** namespace **/ /** arguments **/) {
if(arguments.length < 1) {
throw "Invalid namespace to publish";
}
var namespace = arguments[0];
var queue = this.queue[namespace];
if (typeof queue === 'undefined' || queue.length < 1) {
console.log('did not find queue for %s', namespace);
return false;
}
var valueArgs = Array.prototype.slice.call(arguments);
valueArgs.shift(); // remove namespace value from value args
queue.forEach(function(callback) {
callback.apply(null, valueArgs);
});
return true;
}
subscribe(/** namespace **/ /** callback **/) {
const namespace = arguments[0];
if(!namespace) throw "Invalid namespace";
const callback = arguments[arguments.length - 1];
if(typeof callback !== 'function') throw "Invalid callback method";
if (typeof this.queue[namespace] === 'undefined') {
this.queue[namespace] = [];
}
const queue = this.queue[namespace];
if(queue.length === this.maxNamespaceSize) {
console.warn('Shifting first element in queue: `%s` since it reached max namespace queue count : %d', namespace, this.maxNamespaceSize);
queue.shift();
}
// Check if this callback already exists for this namespace
for(var i = 0; i < queue.length; i++) {
if(queue[i] === callback) {
throw ("The exact same callback exists on this namespace: " + namespace);
}
}
this.queue[namespace].push(callback);
return [namespace, callback];
}
unsubscribe(/** array or topic, method **/) {
let namespace;
let callback;
if(arguments.length === 1) {
let arg = arguments[0];
if(!arg || !Array.isArray(arg)) throw "Unsubscribe argument must be an array";
namespace = arg[0];
callback = arg[1];
}
else if(arguments.length === 2) {
namespace = arguments[0];
callback = arguments[1];
}
if(!namespace || typeof callback !== 'function') throw "Namespace must exist or callback must be a function";
const queue = this.queue[namespace];
if(queue) {
for(var i = 0; i < queue.length; i++) {
if(queue[i] === callback) {
queue.splice(i, 1); // only unique callbacks can be pushed to same namespace queue
return;
}
}
}
}
setNamespaceSize(size) {
if(!this.isNumber(size)) throw "Queue size must be a number";
this.maxNamespaceSize = size;
return true;
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
}
NotificationComponent.js
class NotificationComponent extends React.Component {
getInitialState() {
return {
// optional. see alternative below
subscriber: null
};
}
errorHandler() {
const topic = arguments[0];
const label = arguments[1];
console.log('Topic %s label %s', topic, label);
}
componentDidMount() {
var subscriber = EventSystem.subscribe('error.http', this.errorHandler);
this.state.subscriber = subscriber;
}
componentWillUnmount() {
EventSystem.unsubscribe('error.http', this.errorHandler);
// alternatively
// EventSystem.unsubscribe(this.state.subscriber);
}
render() {
}
}
Non of the above mentioned solutions worked for me. Below is what finally worked:
#yum update
#yum install phpmyadmin
Be advised, phpmyadmin was working a few hours earlier. I don't know what happened.
After this, going to the browser, I got an error that said ./config.inic.php can't be accessed
#cd /usr/share/phpmyadmin/
#stat -c %a config.inic.php
#640
#chmod 644 config.inic.php
This shows that the file permissions were 640, then I changed them to 644. Finially, it worked.
Remember to restart httpd.
#service httpd restart
Shortest solution:
$domain = parse_url('http://google.com', PHP_URL_HOST);
Whenever you see this:
try:
y = 1 / x
except ZeroDivisionError:
pass
else:
return y
Or even this:
try:
return 1 / x
except ZeroDivisionError:
return None
Consider this instead:
import contextlib
with contextlib.suppress(ZeroDivisionError):
return 1 / x
This Solution is less vendor-dependent and works with an SQL, OleDB, and MySQL Reader:
public static string GetStringSafe(this IDataReader reader, int colIndex)
{
return GetStringSafe(reader, colIndex, string.Empty);
}
public static string GetStringSafe(this IDataReader reader, int colIndex, string defaultValue)
{
if (!reader.IsDBNull(colIndex))
return reader.GetString(colIndex);
else
return defaultValue;
}
public static string GetStringSafe(this IDataReader reader, string indexName)
{
return GetStringSafe(reader, reader.GetOrdinal(indexName));
}
public static string GetStringSafe(this IDataReader reader, string indexName, string defaultValue)
{
return GetStringSafe(reader, reader.GetOrdinal(indexName), defaultValue);
}
check the build tools version in build.gradle(for module app). Then go to android sdk manager see if the version is installed if not install it or change the build tools version to the one which is installed like below.
android {
buildToolsVersion "22.0.1"
..
..
..
}
You need to change the sshd_config
file in the remote server (probably in /etc/ssh/sshd_config
).
Change
PasswordAuthentication no
to
PasswordAuthentication yes
And then restart the sshd
daemon.
private void SaveFileStream(String path, Stream stream)
{
var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
stream.CopyTo(fileStream);
fileStream.Dispose();
}
Try to see, if the service "SQL Server (MSSQLSERVER)" it's started, this solved my problem.
Try regex.
You need something that would match 20 words (or 20 word boundaries).
So (my regex is terrible so correct me if this isn't accurate):
/(\w+\b){20}/
And here are some examples of regex in php.
Use sys.getsizeof
to get the size of an object, in bytes.
>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>
Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.
"pull-left" is what you need, it looks like you are using Bootstrap 2, I am not sure if that is available, consider bootstrap 3, unless ofcourse it is a huge rework! ... for Bootstrap 3 but you need to make sure you have 12 columns in each row as well, otherwise you will have issues.
I had downloaded it from http://gradle.org/gradle-download/. I use Homebrew
, but I missed installing gradle
using it.
To save some MBs by downloading it over again using Homebrew, I symlinked the gradle
binary from the downloaded (and extracted) zip archive in the /usr/local/bin/
. This is the same place where Homebrew symlinks all other binaries.
cd /usr/local/bin/
ln -s ~/Downloads/gradle-2.12/bin/gradle
Now check whether it works or not:
gradle -v
Check permissions on templates and appname directories, either with ls -l or try doing an absolute path open() from django.
@DawidDrozd's answer above is excellent.
I would add one point. Recent versions of the Clang compiler complain about requiring a "bridging cast" if attempting to use his code.
This seems reasonable: using a trampoline creates a potential bug: since Objective-C classes are reference counted, if we pass their address around as a void *, we risk having a hanging pointer if the class is garbage collected up while the callback is still active.
Solution 1) Cocoa provides CFBridgingRetain and CFBridgingRelease macro functions which presumably add and subtract one from the reference count of the Objective-C object. We should therefore be careful with multiple callbacks, to release the same number of times as we retain.
// C++ Module
#include <functional>
void cppFnRequiringCallback(std::function<void(void)> callback) {
callback();
}
//Objective-C Module
#import "CppFnRequiringCallback.h"
@interface MyObj : NSObject
- (void) callCppFunction;
- (void) myCallbackFn;
@end
void cppTrampoline(const void *caller) {
id callerObjC = CFBridgingRelease(caller);
[callerObjC myCallbackFn];
}
@implementation MyObj
- (void) callCppFunction {
auto callback = [self]() {
const void *caller = CFBridgingRetain(self);
cppTrampoline(caller);
};
cppFnRequiringCallback(callback);
}
- (void) myCallbackFn {
NSLog(@"Received callback.");
}
@end
Solution 2) The alternative is to use the equivalent of a weak reference (ie. no change to the retain count), without any additional safety.
The Objective-C language provides the __bridge cast qualifier to do this (CFBridgingRetain and CFBridgingRelease seem to be thin Cocoa wrappers over the Objective-C language constructs __bridge_retained and release respectively, but Cocoa does not appear to have an equivalent for __bridge).
The required changes are:
void cppTrampoline(void *caller) {
id callerObjC = (__bridge id)caller;
[callerObjC myCallbackFn];
}
- (void) callCppFunction {
auto callback = [self]() {
void *caller = (__bridge void *)self;
cppTrampoline(caller);
};
cppFunctionRequiringCallback(callback);
}
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
You can query results for a particular hashtag (snowy in this case) using the following url
It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour
https://api.instagram.com/v1/tags/snowy/media/recent
Sample response
{
"pagination": {
"next_max_tag_id": "1370433362010",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "1370433362010",
"next_min_id": "1370443976800",
"min_tag_id": "1370443976800",
"next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"snowy"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": null,
"created_time": "1370418343",
"link": "http://instagram.com/p/aK1yrGRi3l/",
"likes": {
"count": 1,
"data": [
{
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
}
]
},
"images": {
"low_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
"width": 612,
"height": 612
}
},
"users_in_photo": [],
"caption": {
"created_time": "1370418353",
"text": "#snowy",
"from": {
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
},
"id": "471425773832908504"
},
"user_has_liked": false,
"id": "471425689728724453_404174490",
"user": {
"username": "iri92lol",
"website": "",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"full_name": "Iri",
"bio": "",
"id": "404174490"
}
}
}
You can play around here :
You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.
All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.
Truncate String to Specific Length
If you have entered block of sentence/text and you want to save only specified length out of it text. Add the following extension to Class
extension String {
func trunc(_ length: Int) -> String {
if self.characters.count > length {
return self.substring(to: self.characters.index(self.startIndex, offsetBy: length))
} else {
return self
}
}
func trim() -> String{
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
Use
var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
//str is length 74
print(str)
//O/P: Lorem Ipsum is simply dummy text of the printing and typesetting industry.
str = str.trunc(40)
print(str)
//O/P: Lorem Ipsum is simply dummy text of the
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, csv, sqlite3
def main():
con = sqlite3.connect(sys.argv[1]) # database file input
cur = con.cursor()
cur.executescript("""
DROP TABLE IF EXISTS t;
CREATE TABLE t (COL1 TEXT, COL2 TEXT);
""") # checks to see if table exists and makes a fresh table.
with open(sys.argv[2], "rb") as f: # CSV file input
reader = csv.reader(f, delimiter=',') # no header information with delimiter
for row in reader:
to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8")] # Appends data from CSV file representing and handling of text
cur.execute("INSERT INTO neto (COL1, COL2) VALUES(?, ?);", to_db)
con.commit()
con.close() # closes connection to database
if __name__=='__main__':
main()
This should do the trick...
'recalculate all open workbooks
Application.Calculate
'recalculate a specific worksheet
Worksheets(1).Calculate
' recalculate a specific range
Worksheets(1).Columns(1).Calculate
Some more ways to iterate:
scala> xs.foreach (println)
first
second
third
foreach, and similar, map, which would return something (the results of the function, which is, for println, Unit, so a List of Units)
scala> val lens = for (x <- xs) yield (x.length)
lens: Array[Int] = Array(5, 6, 5)
work with the elements, not the index
scala> ("" /: xs) (_ + _)
res21: java.lang.String = firstsecondthird
folding
for(int i=0, j=0; i+j<100; i+=j*2, j+=i+2) {...}
can be done with recursion:
def ijIter (i: Int = 0, j: Int = 0, carry: Int = 0) : Int =
if (i + j >= 100) carry else
ijIter (i+2*j, j+i+2, carry / 3 + 2 * i - 4 * j + 10)
The carry-part is just some example, to do something with i and j. It needn't be an Int.
for simpler stuff, closer to usual for-loops:
scala> (1 until 4)
res43: scala.collection.immutable.Range with scala.collection.immutable.Range.ByOne = Range(1, 2, 3)
scala> (0 to 8 by 2)
res44: scala.collection.immutable.Range = Range(0, 2, 4, 6, 8)
scala> (26 to 13 by -3)
res45: scala.collection.immutable.Range = Range(26, 23, 20, 17, 14)
or without order:
List (1, 3, 2, 5, 9, 7).foreach (print)
I had the same question, so I created Git Merger.
hope this helps :)
This is my experience
.navbar { min-height:38px; }
.navbar .navbar-brand{ padding: 0 12px;font-size: 16px;line-height: 38px;height: 38px; }
.navbar .navbar-nav > li > a { padding-top: 0px; padding-bottom: 0px; line-height: 38px; }
.navbar .navbar-toggle { margin-top: 3px; margin-bottom: 0px; padding: 8px 9px; }
.navbar .navbar-form { margin-top: 2px; margin-bottom: 0px }
.navbar .navbar-collapse {border-color: #A40303;}
Check out How to Install Pip article article for more information.
As of 2019,
Download get-pip.py provided by https://pip.pypa.io using the following command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Run get-pip.py using the following command:
sudo python get-pip.py
After you done installing, run this command to check if pip is installed.
pip --version
Remove get-pip.py file after installing pip.
rm get-pip.py
I have the same issue with Entity Framework 6.1.3
But with different scenario. My model property is of type nullable DateTime
DateTime? CreatedDate { get; set; }
So I need to query on today's date to check all the record, so this what works for me. Which means I need to truncate both records to get the proper query on DbContext
:
Where(w => DbFunctions.TruncateTime(w.CreatedDate) == DbFunctions.TruncateTime(DateTime.Now);
Got an easy progress bar function that i wrote the other day:
#!/bin/bash
# 1. Create ProgressBar function
# 1.1 Input is currentState($1) and totalState($2)
function ProgressBar {
# Process data
let _progress=(${1}*100/${2}*100)/100
let _done=(${_progress}*4)/10
let _left=40-$_done
# Build progressbar string lengths
_fill=$(printf "%${_done}s")
_empty=$(printf "%${_left}s")
# 1.2 Build progressbar strings and print the ProgressBar line
# 1.2.1 Output example:
# 1.2.1.1 Progress : [########################################] 100%
printf "\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%"
}
# Variables
_start=1
# This accounts as the "totalState" variable for the ProgressBar function
_end=100
# Proof of concept
for number in $(seq ${_start} ${_end})
do
sleep 0.1
ProgressBar ${number} ${_end}
done
printf '\nFinished!\n'
Or snag it from,
https://github.com/fearside/ProgressBar/
Just use this for the closing tag:
@:</tr>
And leave your if/else as is.
Seems like the if statement doesn't wanna' work.
It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.
I would partially disagree with Milan's suggestion of embedding the requested representation in the URI.
If anyhow possible, URIs should only be used for addressing resources and not for tunneling HTTP methods/verbs. Eventually, specific business action (edit, lock, etc.) could be embedded in the URI if create (POST) or update (PUT) alone do not serve the purpose:
POST http://shonzilla.com/orders/08/165;edit
In the case of requesting a particular representation in URI you would need to disrupt your URI design eventually making it uglier, mixing two distinct REST concepts in the same place (i.e. URI) and making it harder to generically process requests on the server-side. What Milan is suggesting and many are doing the same, incl. Flickr, is exactly this.
Instead, a more RESTful approach would be using a separate place to encode preferred representation by using Accept
HTTP header which is used for content negotiation where client tells to the server which content types it can handle/process and server tries to fulfill client's request. This approach is a part of HTTP 1.1 standard, software compliant and supported by web browsers as well.
Compare this:
GET /orders/08/165.xml HTTP/1.1 or GET /orders/08/165&format=xml HTTP/1.1
to this:
GET /orders/08/165 HTTP/1.1 Accept: application/xml
From a web browser you can request any content type by using setRequestHeader
method of XMLHttpRequest
object. For example:
function getOrder(year, yearlyOrderId, contentType) { var client = new XMLHttpRequest(); client.open("GET", "/order/" + year + "/" + yearlyOrderId); client.setRequestHeader("Accept", contentType); client.send(orderDetails); }
To sum it up: the address, i.e. the URI of a resource should be independent of its representation and XMLHttpRequest.setRequestHeader
method allows you to request any representation using the Accept
HTTP header.
Cheers!
Shonzilla
// This is for first date
first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((first.getTime())/1000); // get the actual epoch values
second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((second.getTime())/1000); // get the actual epoch values
diff= second - first ;
one_day_epoch = 24*60*60 ; // calculating one epoch
if ( diff/ one_day_epoch > 365 ) // check , is it exceei
{
alert( 'date is exceeding one year');
}
Another explanation I've figured out for myself
When you create the Flask application, the folder where templates
is looked for is the folder of the application according to name you've provided to Flask constructor:
app = Flask(__name__)
The __name__
here is the name of the module where application is running. So the appropriate folder will become the root one for folders search.
projects/
yourproject/
app/
templates/
So if you provide instead some random name the root folder for the search will be current folder.
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
Yeah, no checkbox for you in iOS (-:
Here, this is what I did to create a checkbox:
UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:
[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];
Now in the target method do the following:
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected; /* Toggle */
[checkbox setSelected:checkBoxSelected];
}
That's it!
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
They are opposing each other.
JSON.Stringify()
converts JSON to string and JSON.Parse()
parses a string into JSON.
Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.
In my case this amounted to defining my column as:
`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''
This is in my opinion preferential to adjusting your queries.
Try this:
Select Project_Name, ReleaseDate, TaskName
From DB_Table
Where Project_Name like '{?Pm-?Proj_Name}'
And ReleaseDate >= currentdate
currentdate should be a valid database function or field to work. If you are using MS SQL Server, use GETDATE() instead.
If all you want is to filter records in a subreport based on a parameter from the main report, it might be easier to simply add the table to the subreport, and then create a Project_Name link between the main report and subreport. You can then use the Select Expert to filter the ReleaseDate as well.
Don't like any of those solutions.
this is how i do it:
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='"
. sqlEsc($somename) . "' ;";
then i use my own sqlEsc function:
function sqlEsc($val)
{
global $mysqli;
return mysqli_real_escape_string($mysqli, $val);
}
version for data.table based on code from dmanuge :
convNumValues<-function(ds){
ds<-data.table(ds)
dsnum<-data.table(data.matrix(ds))
num_cols <- sapply(dsnum,function(x){mean(as.numeric(is.na(x)))<0.5})
nds <- data.table( dsnum[, .SD, .SDcols=attributes(num_cols)$names[which(num_cols)]]
,ds[, .SD, .SDcols=attributes(num_cols)$names[which(!num_cols)]] )
return(nds)
}
based on this
I modified the original to this:
^(?:(?:(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec))(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:(?:0?2|(?:Feb))(\/|-|\.)(?:29)\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
The way to do this without use of plugins is to make a subclass of google's OverlayView() method.
https://developers.google.com/maps/documentation/javascript/reference?hl=en#OverlayView
You make a custom function and apply it to the map.
function Label() {
this.setMap(g.map);
};
Now you prototype your subclass and add HTML nodes:
Label.prototype = new google.maps.OverlayView; //subclassing google's overlayView
Label.prototype.onAdd = function() {
this.MySpecialDiv = document.createElement('div');
this.MySpecialDiv.className = 'MyLabel';
this.getPanes().overlayImage.appendChild(this.MySpecialDiv); //attach it to overlay panes so it behaves like markers
}
you also have to implement remove and draw functions as stated in the API docs, or this won't work.
Label.prototype.onRemove = function() {
... // remove your stuff and its events if any
}
Label.prototype.draw = function() {
var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); // translate map latLng coords into DOM px coords for css positioning
var pos = this.get('position');
$('.myLabel')
.css({
'top' : position.y + 'px',
'left' : position.x + 'px'
})
;
}
That's the gist of it, you'll have to do some more work in your specific implementation.
Try following source code it worked for me
//Fetching id from shared preferences
SharedPreferences sharedPreferences;
sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");
Here is an answer for Python 3.8 and OpenPyXL 3.0.0.
I tried to avoid using the get_column_letter
function but failed.
This solution uses the newly introduced assignment expressions aka "walrus operator":
import openpyxl
from openpyxl.utils import get_column_letter
workbook = openpyxl.load_workbook("myxlfile.xlsx")
worksheet = workbook["Sheet1"]
MIN_WIDTH = 10
for i, column_cells in enumerate(worksheet.columns, start=1):
width = (
length
if (length := max(len(str(cell_value) if (cell_value := cell.value) is not None else "")
for cell in column_cells)) >= MIN_WIDTH
else MIN_WIDTH
)
worksheet.column_dimensions[get_column_letter(i)].width = width
Probably not helpful, but if the array is the only thing that you'll be displaying, you could always set
header('Content-type: text/plain');
If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis=0)
print(x_normed)
# [[ 1. 1. 1. ]
# [ 0.765 0.5 0.7 ]
# [ 0.8 0.7 0.18 ]]
x.max(0)
takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,)
containing the maximum value in each column. You can then divide x
by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.
If x
contains negative values you would need to subtract the minimum first:
x_normed = (x - x.min(0)) / x.ptp(0)
Here, x.ptp(0)
returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.
Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)
To quote the most relevant bits:
[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.
The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”
Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.
The full post explains this in more detail. At RTM, the MSDN docs on this should be better.
I ran into this problem yesterday, so I created a React-friendly solution.
Check out react-native-listener. It's working very well so far. Feedback appreciated.
You have to copy the bits over a new image with the target resolution, like this:
using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
{
using (Bitmap newBitmap = new Bitmap(bitmap))
{
newBitmap.SetResolution(300, 300);
newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
}
}
The accepted answer no longer works. When running the command xcode-select --install
it tells you to use "Software Update" to install updates.
In this link is the updated method:
Open a Terminal and then:
cd /Library/Developer/CommandLineTools/Packages/
open macOS_SDK_headers_for_macOS_10.14.pkg
This will open an installation Wizard.
After updating to Mojave 10.15.1 it seems that using xcode-select --install
works as intended.
I'm on Windows and have used 4 methods: SFTP, WinSCP, Unison and Sublime Text on Linux with X11 forwarding over SSH to Windows (yes you can do this without messy configs and using a free tool).
The fourth way is the best if you can install software on your Linux machine.
The fourth way:
MobaXterm
subl
Note: When invoking subl if it complains for a certain library - ensure you install them to successfully invoke sublimetext from mobaxterm.
If you can't install software on your Linux box, the best is Unison. Why?
SFTP
Setup: Install the SFTP Sublime Text package. This package requires a license.
In the sftp-config, I usually set:
"upload_on_save": true,
"sync_down_on_open": true,
This, in addition to an SSH terminal to the machine gives me a fairly seamless remote editing experience.
WinSCP
From then on, WinSCP will keep your changes synchronized.
Work in the local folder using SublimeText. Just make sure that Sublime Text is set to guess the line endings from the file that is being edited.
Unison
I have found that if source tree is massive (around a few hundred MB with a deep hierarchy), then the WinSCP method described above might be a bit slow. You can get much better performance using Unison. The down side is that Unison is not automatic (you need to trigger it with a keypress) and requires a server component to be running on your linux machine. The up side is that the transfers are incredibly fast, it is very reliable and ignoring files, folders and extensions are incredibly easy to setup.
Here is an example I came up with that wraps another class with a debouncer. This lends itself nicely to being made into a decorator/higher order function:
export class DebouncedThingy extends React.Component {
static ToDebounce = ['someProp', 'someProp2'];
constructor(props) {
super(props);
this.state = {};
}
// On prop maybe changed
componentWillReceiveProps = (nextProps) => {
this.debouncedSetState();
};
// Before initial render
componentWillMount = () => {
// Set state then debounce it from here on out (consider using _.throttle)
this.debouncedSetState();
this.debouncedSetState = _.debounce(this.debouncedSetState, 300);
};
debouncedSetState = () => {
this.setState(_.pick(this.props, DebouncedThingy.ToDebounce));
};
render() {
const restOfProps = _.omit(this.props, DebouncedThingy.ToDebounce);
return <Thingy {...restOfProps} {...this.state} />
}
}
You can write
i = 5 + tup()[0]
Tuples can be indexed just like lists.
The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.
You are trying to use the wrong interface type. The type Function is not appropriate in this case because it receives a parameter and has a return value. Instead you should use Consumer (formerly known as Block)
The Function type is declared as
interface Function<T,R> {
R apply(T t);
}
However, the Consumer type is compatible with that you are looking for:
interface Consumer<T> {
void accept(T t);
}
As such, Consumer is compatible with methods that receive a T and return nothing (void). And this is what you want.
For instance, if I wanted to display all element in a list I could simply create a consumer for that with a lambda expression:
List<String> allJedi = asList("Luke","Obiwan","Quigon");
allJedi.forEach( jedi -> System.out.println(jedi) );
You can see above that in this case, the lambda expression receives a parameter and has no return value.
Now, if I wanted to use a method reference instead of a lambda expression to create a consume of this type, then I need a method that receives a String and returns void, right?.
I could use different types of method references, but in this case let's take advantage of an object method reference by using the println
method in the System.out
object, like this:
Consumer<String> block = System.out::println
Or I could simply do
allJedi.forEach(System.out::println);
The println
method is appropriate because it receives a value and has a return type void, just like the accept
method in Consumer.
So, in your code, you need to change your method signature to somewhat like:
public static void myForEach(List<Integer> list, Consumer<Integer> myBlock) {
list.forEach(myBlock);
}
And then you should be able to create a consumer, using a static method reference, in your case by doing:
myForEach(theList, Test::displayInt);
Ultimately, you could even get rid of your myForEach
method altogether and simply do:
theList.forEach(Test::displayInt);
About Functions as First Class Citizens
All been said, the truth is that Java 8 will not have functions as first-class citizens since a structural function type will not be added to the language. Java will simply offer an alternative way to create implementations of functional interfaces out of lambda expressions and method references. Ultimately lambda expressions and method references will be bound to object references, therefore all we have is objects as first-class citizens. The important thing is the functionality is there since we can pass objects as parameters, bound them to variable references and return them as values from other methods, then they pretty much serve a similar purpose.
Update to this for using Hibernate 4.3.x / 5.0.x - you could just set this property to true:
<prop key="hibernate.jdbc.lob.non_contextual_creation">true</prop>
to get rid of that error message. Same effect but without the "threw exception" detail. See LobCreatorBuilder source for details.
Be careful, Martijn Pieters's answer isn't suitable for version 1.2.1+. You can't set it globally without patching the library.
You can do this instead:
import requests
from requests.adapters import HTTPAdapter
s = requests.Session()
s.mount('http://www.github.com', HTTPAdapter(max_retries=5))
s.mount('https://www.github.com', HTTPAdapter(max_retries=5))
For those of you who don't care about following arbitrary restriction imposed by Microsoft you can simply add a host file entry to the IP of the server your attempting to connect to rather then use that instead of the IP to bypass this restriction:
Enter-PSSession -Computername NameOfComputerIveAddedToMyHostFile -credentials $cred
if for whatever reason you are interested in navigating up a specific number of directories you could also do: nth_path=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && cd ../../../ && pwd)
. This would give 3 parents directories up
I tried many GUI's, and the best for me continue being "SQLyog-comunity" by using wine. Is complete, is nice, and is intuitive. (and in wine work perfect)
select t2.*
from t1 join t2 on t2.url='site.com/path/%' + cast(t1.id as varchar) + '%/more'
where t1.id > 9000
Using concat like suggested is even better though
I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.
I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.
The project goals were very simple;
Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;
ConfigurationManager.AppSettings.Add(key_name, data_value)
That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.
After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.
With a little trial and error, I found the following code would do exactly what I wanted;
ConfigurationManager.AppSettings.Set(key_name, data_value)
Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.
In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;
appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True
With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.
This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.
I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.
I think the NSURLSession
api fits better in this situation. Because if you write swift code your project target is at least iOS 7 and iOS 7 supports NSURLSession
api. Anyway here is the code
let url = "YOUR_URL"
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)) { data, response, error in
// Handle result
}.resume()
One way is this:
select id, name, priority from table a
order by case when name='core' then -1 else priority end asc, priority asc
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
I have tried to make note about these and have collected and written examples from a java perspective.
Putting it here for any java developer who is looking into the same subject.
To get the value of a pointer, just de-reference the pointer.
int *ptr;
int value;
*ptr = 9;
value = *ptr;
value is now 9.
I suggest you read more about pointers, this is their base functionality.
if you want to find Monday then 'dayOfWeek' is 1 if it is Tuesday it will be 2 and so on.
var date=new Date();
getNextDayOfWeek(date, 2);
// this is for finding next tuesday
function getNextDayOfWeek(date, dayOfWeek) {
// Code to check that date and dayOfWeek are valid left as an exercise ;)
var resultDate = new Date(date.getTime());
resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);
return resultDate;
}
Hope this will be helpfull to you, thank you
Like with SQL Server Management Studio (already explained), it is also possible with Datagrip as explained here.
- Right-click an SQL statement, and select Explain plan.
- In the Output pane, click Plan.
- By default, you see the tree representation of the query. To see the query plan, click the Show Visualization icon, or press Ctrl+Shift+Alt+U
This is my preferred method. Pretty straight forward:
http://www.codeproject.com/KB/webforms/GridViewConfirmDelete.aspx
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
To compare entire revisions, it's simply:
svn diff -r 8979:11390
If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:
svn diff -r PREV:HEAD
(Note, without anything specified afterwards, all files in the specified revisions are compared.)
You can compare a specific file if you add the file path afterwards:
svn diff -r 8979:HEAD /path/to/my/file.php
Try this
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
//var values = rows.getValues();
var Names = sheet.getRange("A2:A7");
var Name = [
Names.getCell(1, 1).getValue(),
Names.getCell(2, 1).getValue(),
.....
Names.getCell(5, 1).getValue()]
You can define arrays simply as follows, instead of allocating and then assigning.
var arr = [1,2,3,5]
Your initial error was because of the following line, and ones like it
var Name[0] = Name_cell.getValue();
Since Name
is already defined and you are assigning the values to its elements, you should skip the var
, so just
Name[0] = Name_cell.getValue();
Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.
The high spike that you have is due to the DC (non-varying, i.e. freq = 0) portion of your signal. It's an issue of scale. If you want to see non-DC frequency content, for visualization, you may need to plot from the offset 1 not from offset 0 of the FFT of the signal.
Modifying the example given above by @PaulH
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = 10 + np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
plt.subplot(2, 1, 1)
plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]))
plt.subplot(2, 1, 2)
plt.plot(xf[1:], 2.0/N * np.abs(yf[0:N/2])[1:])
The output plots:
Another way, is to visualize the data in log scale:
Using:
plt.semilogy(xf, 2.0/N * np.abs(yf[0:N/2]))
Will show:
I present you with the cleanest way ever, in the form of the world's smallest jquery plugin:
jQuery.fn.reverse = [].reverse;
Usage:
$('jquery-selectors-go-here').reverse().each(function () {
//business as usual goes here
});
-All credit to Michael Geary in his post here: http://www.mail-archive.com/[email protected]/msg04261.html
Try this:
(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
$_.LastWriteTime -gt (Get-Date).AddDays(-3)
}).Count
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
Checkout there might be two instances of Eclipse are pointing to same Android SDK...just keep one instance of Eclipse and try again...that's why you are getting Exception as "established connection was aborted by the software in your host machine"...go in details of android adb(Android Debug Bridge) you will get it...
What you are describing is a change of state in the parent. You pass that to the child via a prop. As you suggested, you would watch
that prop. When the child takes action, it notifies the parent via an emit
, and the parent might then change the state again.
var Child = {_x000D_
template: '<div>{{counter}}</div>',_x000D_
props: ['canI'],_x000D_
data: function () {_x000D_
return {_x000D_
counter: 0_x000D_
};_x000D_
},_x000D_
watch: {_x000D_
canI: function () {_x000D_
if (this.canI) {_x000D_
++this.counter;_x000D_
this.$emit('increment');_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
new Vue({_x000D_
el: '#app',_x000D_
components: {_x000D_
'my-component': Child_x000D_
},_x000D_
data: {_x000D_
childState: false_x000D_
},_x000D_
methods: {_x000D_
permitChild: function () {_x000D_
this.childState = true;_x000D_
},_x000D_
lockChild: function () {_x000D_
this.childState = false;_x000D_
}_x000D_
}_x000D_
})
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>_x000D_
<div id="app">_x000D_
<my-component :can-I="childState" v-on:increment="lockChild"></my-component>_x000D_
<button @click="permitChild">Go</button>_x000D_
</div>
_x000D_
If you truly want to pass events to a child, you can do that by creating a bus (which is just a Vue instance) and passing it to the child as a prop.
You can use JavaScript like... Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id="data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
From your comment:
Example: WHERE (Note is null) ^ (ID is null)
you could probably try:
where
(case when Note is null then 1 else 0 end)
<>(case when ID is null then 1 else 0 end)
I know this has been closed for a while, but I thought it might be useful to promote another async solution built on the requests library.
list_of_requests = ['http://moop.com', 'http://doop.com', ...]
from simple_requests import Requests
for response in Requests().swarm(list_of_requests):
print response.content
The docs are here: http://pythonhosted.org/simple-requests/
The double slash, //
, is floor division:
>>> 7//3
2
Every service that is bound in activity must be unbind on app close.
So try using
onPause(){
unbindService(YOUR_SERVICE);
super.onPause();
}
PRAGMA table_info([tablename]);
Modals always load the content into an element on the page, which more often than not is a div
. Think of this div
as the iframe
equivalent when it comes to jQuery UI Dialogs. Now it depends on your requirements whether you want static content that resides within the page or you want to fetch the content from some other location. You may use this code and see if it works for you:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui-1.8.23.custom.css"/>
</head>
<body>
<p>First open a modal <a href="http://ibm.com" class="example"> dialog</a></p>
<div id="dialog"></div>
</body>
<!--jQuery-->
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script src="js/jquery-ui-1.8.23.custom.min.js"></script>
<script type="text/javascript">
$(function(){
//modal window start
$(".example").unbind('click');
$(".example").bind('click',function(){
showDialog();
var titletext=$(this).attr("title");
var openpage=$(this).attr("href");
$("#dialog").dialog( "option", "title", titletext );
$("#dialog").dialog( "option", "resizable", false );
$("#dialog").dialog( "option", "buttons", {
"Close": function() {
$(this).dialog("close");
$(this).dialog("destroy");
}
});
$("#dialog").load(openpage);
return false;
});
//modal window end
//Modal Window Initiation start
function showDialog(){
$("#dialog").dialog({
height: 400,
width: 500,
modal: true
}
</script>
</html>
There are, however, a few things which you should keep in mind. You will not be able to load remote URL's on your local system, you need to upload to a server if you want to load remote URL. Even then, you may only load URL's which belong to the same domain; e.g. if you upload this file to 'www.example.com' you may only access files hosted on 'www.example.com'. For loading external links this might help. All this information you will find in the link as suggested by @Robin.
If you already have the figure object use:
f.set_figheight(15)
f.set_figwidth(15)
But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:
f, axs = plt.subplots(2,2,figsize=(15,15))
This helps really handy:
The advantages of an abstract class are:
Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.
This Works Better and Faster For Me
<html>
<head>
<script>
function showRSS(str) {
if (str.length==0) {
document.getElementById("rssOutput").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("rssOutput").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getrss.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="ZDN">ZDNet News</option>
<option value="job">Job</option>
</select>
</form>
<br>
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html>
**The Backend File **
<?php
//get the q parameter from URL
$q=$_GET["q"];
//find out which feed was selected
if($q=="Google") {
$xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
} elseif($q=="ZDN") {
$xml=("https://www.zdnet.com/news/rss.xml");
}elseif($q == "job"){
$xml=("https://ngcareers.com/feed");
}
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
//output elements from "<channel>"
echo("<p><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");
//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
$count = $x->length;
// print_r( $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue);
// return;
for ($i=0; $i <= $count; $i++) {
//Title
$item_title = $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue;
//Link
$item_link = $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue;
//Description
$item_desc = $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue;
//Category
$item_cat = $x->item(0)->getElementsByTagName('category')->item(0)->nodeValue;
echo ("<p>Title: <a href='" . $item_link
. "'>" . $item_title . "</a>");
echo ("<br>");
echo ("Desc: ".$item_desc);
echo ("<br>");
echo ("Category: ".$item_cat . "</p>");
}
?>
The technical definition of an operating system is "a platform that consists of specific set of libraries and infrastructure for applications to be built upon and interact with each other". A kernel is an operating system in that sense.
The end-user definition is usually something around "a software package that provides a desktop, shortcuts to applications, a web browser and a media player". A kernel doesn't match that definition.
So for an end-user a Linux distribution (say Ubuntu) is an Operating System while for a programmer the Linux kernel itself is a perfectly valid OS depending on what you're trying to achieve. For instance embedded systems are mostly just kernel with very small number of specialized processes running on top of them. In that case the kernel itself becomes the OS itself.
I think you can draw the line at what the majority of the applications running on top of that OS do require. If most of them require only kernel, the kernel is the OS, if most of them require X Window System running, then your OS becomes X + kernel.
the algorithm : ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) < 25
In many situations, a custom attribute attached to a pd.DataFrame
object is not necessary. In addition, note that pandas
-object attributes may not serialize. So pickling will lose this data.
Instead, consider creating a dictionary with appropriately named keys and access the dataframe via dfs['some_label']
.
df = pd.DataFrame()
dfs = {'some_label': df}
I use a generic query I call "dump" (why? I don't know) that looks like this:
SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |
spool &1..txt
@@&1
spool off
exit
I then call SQL*Plus passing the actual SQL script I want to run as an argument:
sqlplus -S user/password@database @dump.sql my_real_query.sql
The result is written to a file
my_real_query.sql.txt
.