lib
.lib\__init__.py
.In lib\BoxTime.py
, write a function foo()
like this:
def foo():
print "foo!"
In your client code in the directory above lib
, write:
from lib import BoxTime
BoxTime.foo()
Run your client code. You will get:
foo!
Much later -- in linux, it would look like this:
% cd ~/tmp
% mkdir lib
% touch lib/__init__.py
% cat > lib/BoxTime.py << EOF
heredoc> def foo():
heredoc> print "foo!"
heredoc> EOF
% tree lib
lib
+-- BoxTime.py
+-- __init__.py
0 directories, 2 files
% python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib import BoxTime
>>> BoxTime.foo()
foo!
Try just importing the functions needed from main.py? So,
from main import SomeFunction
It could be that you've named a function in batch.py the same as one in main.py, and when you import main.py the program runs the main.py function instead of the batch.py function; doing the above should fix that. I hope.
I'm running Eclipse 4.2.0 (Juno) and PyDev 2.8.1, and ran into this problem with a lib installed to my site-packages path. According to this SO question:
...there is an issue with PyDev and pyc files. In the case of the particular lib I tried to reference, all that is delivered is pyc files.
Here's what I did to address this:
Run uncompyle2 against the *.pyc files in the site-packages lib. Example:
uncompyle2 -r -o /tmp /path/to/site-packages/lib
The unresolved import error relating to .pyc files should now disappear.
Note: imp is deprecated since Python 3.4 in favor of importlib
As mentioned the imp module provides you loading functions:
imp.load_source(name, path)
imp.load_compiled(name, path)
I've used these before to perform something similar.
In my case I defined a specific class with defined methods that were required. Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:
import imp
import os
def load_from_file(filepath):
class_inst = None
expected_class = 'MyClass'
mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])
if file_ext.lower() == '.py':
py_mod = imp.load_source(mod_name, filepath)
elif file_ext.lower() == '.pyc':
py_mod = imp.load_compiled(mod_name, filepath)
if hasattr(py_mod, expected_class):
class_inst = getattr(py_mod, expected_class)()
return class_inst
To add to what people have said about from x import *
: besides making it more difficult to tell where names came from, this throws off code checkers like Pylint. They will report those names as undefined variables.
you are confusing the concept of appending and prepending. the following code is prepending:
sys.path.insert(1,'/thePathToYourFolder/')
it places the new information at the beginning (well, second, to be precise) of the search sequence that your interpreter will go through. sys.path.append()
puts things at the very end of the search sequence.
it is advisable that you use something like virtualenv
instead of manually coding your package directories into the PYTHONPATH
everytime. for setting up various ecosystems that separate your site-packages and possible versions of python, read these two blogs:
if you do decide to move down the path to environment isolation you would certainly benefit by looking into virtualenvwrapper: http://www.doughellmann.com/docs/virtualenvwrapper/
all of you guys didn't mention a case where someone "like me" would install django befor installing virtualenv...so for all the people of my kind ther if you did that...reinstall django after activating the virtualenv..i hope this helps
Try to look Create constants using a "settings" module? and Can I prevent modifying an object in Python?
Another one useful link: http://code.activestate.com/recipes/65207-constants-in-python/ tells us about the following option:
from copy import deepcopy
class const(object):
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
print 'NO WAY this is a const' # put here anything you want(throw exc and etc)
return deepcopy(self.__dict__[name])
self.__dict__[name] = value
def __getattr__(self, name, value):
if self.__dict__.has_key(name):
return deepcopy(self.__dict__[name])
def __delattr__(self, item):
if self.__dict__.has_key(item):
print 'NOOOOO' # throw exception if needed
CONST = const()
CONST.Constant1 = 111
CONST.Constant1 = 12
print a.Constant1 # 111
CONST.Constant2 = 'tst'
CONST.Constant2 = 'tst1'
print a.Constant2 # 'tst'
So you could create a class like this and then import it from you contants.py module. This will allow you to be sure that value would not be changed, deleted.
Download sqlite3:
wget http://www.sqlite.org/2016/sqlite-autoconf-3150000.tar.gz
Follow these steps to install:
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make install
I had the same problem, and I solved it by adding the following code to the top of the python file:
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
Number of repetitions of os.path.dirname
depends on where is the file located your project hierarchy. For instance, in my case the project root is three levels up.
I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this:
(NOTE: From your initial post, I am assuming you are using an *NIX-based machine and are running things from the command line, so this advice is tailored to that. Since I run Ubuntu, this is what I did)
1) Change directory (cd) to the directory above the directory where your files are. In this case, you're trying to run the mountain.py
file, and trying to call the toolkit.interface.py
module, which are in separate directories. In this case, you would go to the directory that contains paths to both those files (or in other words, the closest directory that the paths of both those files share). Which in this case is the toolkit
directory.
2) When you are in the tookit
directory, enter this line of code on your command line:
export PYTHONPATH=.
This sets your PYTHONPATH to ".", which basically means that your PYTHONPATH will now look for any called files within the directory you are currently in, (and more to the point, in the sub-directory branches of the directory you are in. So it doesn't just look in your current directory, but in all the directories that are in your current directory).
3) After you've set your PYTHONPATH in the step above, run your module from your current directory (the toolkit
directory). Python should now find and load the modules you specified.
Hope this helps. I was quite frustrated with this myself.
There is now a headless version of opencv-python
which removes the graphical dependencies (like libSM). You can see the normal / headless version on the releases page (and the GitHub issue leading to this); just add -headless
when installing, e.g.,
pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless
FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name
A.B
designates a submodule namedB
in a package namedA
....
When importing the package, Python searches through the directories on
sys.path
looking for the package subdirectory.The
__init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such asstring
, from unintentionally hiding valid modules that occur later on the module search path.
You need to set it up to something like this:
man
|- __init__.py
|- Mans
|- __init__.py
|- man1.py
|- MansTest
|- __init.__.py
|- SoftLib
|- Soft
|- __init__.py
|- SoftWork
|- __init__.py
|- manModules.py
|- Unittests
|- __init__.py
|- man1test.py
SECOND, for the "ModuleNotFoundError: No module named 'Soft'
" error caused by from ...Mans import man1
in man1test.py, the documented solution to that is to add man1.py to sys.path
since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path
directly, you can also modify PYTHONPATH
:
sys.path
is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).- The installation-dependent default.
THIRD, for from ...MansTest.SoftLib import Soft
which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.
With that said, here's how I got it to work.
man1.py:
from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH
def foo():
print("called foo in man1.py")
print("foo call module1 from manModules: " + module1())
man1test.py
# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1
man1.foo()
manModules.py
def module1():
return "module1 in manModules"
Terminal output:
$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
...
from ...Mans import man1
File "/temp/man/Mans/man1.py", line 2, in <module>
from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'
$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules
As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).
My Python version is Python 3.5.2 and the solution proposed in the accepted answer didn't work for me. I've still were given an error
FileNotFoundError: [Errno 2] No such file or directory
when I was running my_script.py
from the terminal. Although it worked fine when I run it through Run/Debug Configurations from PyCharm IDE (PyCharm 2018.3.2 (Community Edition)).
Solution:
instead of using:
my_path = os.path.abspath(os.path.dirname(__file__)) + some_rel_dir_path
as suggested in the accepted answer, I used:
my_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) + some_rel_dir_path
Explanation:
Changing os.path.dirname(__file__)
to os.path.dirname(os.path.abspath(__file__))
solves the following problem:
When we run our script like that: python3 my_script.py
the __file__
variable has a just a string value of "my_script.py" without path leading to that particular script. That is why method dirname(__file__)
returns an empty string "". That is also the reson why my_path = os.path.abspath(os.path.dirname(__file__)) + some_rel_dir_path
is actually the same thing as my_path = some_rel_dir_path
. Consequently FileNotFoundError: [Errno 2] No such file or directory
is given when trying to use open
method because there is no directory like "some_rel_dir_path".
Running script from PyCharm IDE Running/Debug Configurations worked because it runs a command python3 /full/path/to/my_script.py
(where "/full/path/to" is specified by us in "Working directory" variable in Run/Debug Configurations) instead of justpython3 my_script.py
like it is done when we run it from the terminal.
Hope that will be useful.
In my case, simply missed filename:
from A.B.C import func_a (x)
from A.B.C.D import func_a (O)
where D is file.
You can reload a module when it has already been imported by using the reload
builtin function (Python 3.4+ only):
from importlib import reload
import foo
while True:
# Do some things.
if is_changed(foo):
foo = reload(foo)
In Python 3, reload
was moved to the imp
module. In 3.4, imp
was deprecated in favor of importlib
, and reload
was added to the latter. When targeting 3 or later, either reference the appropriate module when calling reload
or import it.
I think that this is what you want. Web servers like Django's development server use this so that you can see the effects of your code changes without restarting the server process itself.
To quote from the docs:
Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time. As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero. The names in the module namespace are updated to point to any new or changed objects. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.
As you noted in your question, you'll have to reconstruct Foo
objects if the Foo
class resides in the foo
module.
If you are using python 3+ then try adding below lines
import os, sys
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)
import sys
sys.path.append("..") # Adds higher directory to python modules path.
In python3, __init__.py
is no longer necessary. If the current directory of the console is the directory where the python script is located, everything works fine with
import user
However, this won't work if called from a different directory, which does not contain user.py
.
In that case, use
from . import user
This works even if you want to import the whole file instead of just a class from there.
This one works best for me. Use:
os.path.abspath('')
On mac it should print something like:
'/Users/<your username>/<path_to_where_you_at>'
To get the abs path to the current wd, this one is better because now you can go up if you want, like this:
os.path.abspath('../')
And now:
'/Users/<your username>/'
So if you wanna import utils
from here '/Users/<your username>/'
All you've got left to do is:
import sys
sys.path.append(os.path.abspath('../'))
The very first time you import goo
from anywhere (inside or outside a function), goo.py
(or other importable form) is loaded and sys.modules['goo']
is set to the module object thus built. Any future import within the same run of the program (again, whether inside or outside a function) just look up sys.modules['goo']
and bind it to barename goo
in the appropriate scope. The dict lookup and name binding are very fast operations.
Assuming the very first import
gets totally amortized over the program's run anyway, having the "appropriate scope" be module-level means each use of goo.this
, goo.that
, etc, is two dict lookups -- one for goo
and one for the attribute name. Having it be "function level" pays one extra local-variable setting per run of the function (even faster than the dictionary lookup part!) but saves one dict lookup (exchanging it for a local-variable lookup, blazingly fast) for each goo.this
(etc) access, basically halving the time such lookups take.
We're talking about a few nanoseconds one way or another, so it's hardly a worthwhile optimization. The one potentially substantial advantage of having the import
within a function is when that function may well not be needed at all in a given run of the program, e.g., that function deals with errors, anomalies, and rare situations in general; if that's the case, any run that does not need the functionality will not even perform the import (and that's a saving of microseconds, not just nanoseconds), only runs that do need the functionality will pay the (modest but measurable) price.
It's still an optimization that's only worthwhile in pretty extreme situations, and there are many others I would consider before trying to squeeze out microseconds in this way.
This is my 2 utility functions using only pathlib. It infers the module name from the path By default, it recursively loads all python files from folders and replaces init.py by the parent folder name. But you can also give a Path and/or a glob to select some specific files.
from pathlib import Path
from importlib.util import spec_from_file_location, module_from_spec
from typing import Optional
def get_module_from_path(path: Path, relative_to: Optional[Path] = None):
if not relative_to:
relative_to = Path.cwd()
abs_path = path.absolute()
relative_path = abs_path.relative_to(relative_to.absolute())
if relative_path.name == "__init__.py":
relative_path = relative_path.parent
module_name = ".".join(relative_path.with_suffix("").parts)
mod = module_from_spec(spec_from_file_location(module_name, path))
return mod
def get_modules_from_folder(folder: Optional[Path] = None, glob_str: str = "*/**/*.py"):
if not folder:
folder = Path(".")
mod_list = []
for file_path in sorted(folder.glob(glob_str)):
mod_list.append(get_module_from_path(file_path))
return mod_list
You can add to the system-path at runtime:
import sys
sys.path.insert(0, 'path/to/your/py_file')
import py_file
This is by far the easiest way to do it.
Any library/package you import must have its dependencies and subordinate parts in the same python directory. in linux if you
Python3.x -m pip install <your_library_name_without_braces>
what happens is, it installs on the default python. so first make sure that only 1 python 2.x and 1 python 3.x versions are on your pc.
If you want to successfully install matplotlib you need these lines,
python -m pip install matplotlib pillow numpy pandas
the last 2 were auxiliary libs, and must have.
Just use change dir function from os module:
os.chdir("Here new director")
than you can import normally More Info
First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
function from Python 3 into Python 2.6+.
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
I created this bash command.
for l in $(pip freeze); do p=$(echo "$l" | cut -d'=' -f1); f=$(find . -type f -exec grep "$p" {} \; | grep 'import'); [[ ! -z "$f" ]] && echo "$l" ; done;
in your main file add this:
import sys
import os
sys.path.append(os.path.abspath(os.path.join(__file__,mainScriptDepth)))
mainScriptDepth = the depth of the main file from the root of the project.
Here in your case mainScriptDepth = "../../"
.
Hopefully, this will be of value to someone out there - I went through half a dozen stackoverflow posts trying to figure out relative imports similar to whats posted above here. I set up everything as suggested but I was still hitting ModuleNotFoundError: No module named 'my_module_name'
Since I was just developing locally and playing around, I hadn't created/run a setup.py
file. I also hadn't apparently set my PYTHONPATH
.
I realized that when I ran my code as I had been when the tests were in the same directory as the module, I couldn't find my module:
$ python3 test/my_module/module_test.py 2.4.0
Traceback (most recent call last):
File "test/my_module/module_test.py", line 6, in <module>
from my_module.module import *
ModuleNotFoundError: No module named 'my_module'
However, when I explicitly specified the path things started to work:
$ PYTHONPATH=. python3 test/my_module/module_test.py 2.4.0
...........
----------------------------------------------------------------------
Ran 11 tests in 0.001s
OK
So, in the event that anyone has tried a few suggestions, believes their code is structured correctly and still finds themselves in a similar situation as myself try either of the following if you don't export the current directory to your PYTHONPATH:
$ PYTHONPATH=. python3 test/my_module/module_test.py
PYTHONPATH=.
, create a setup.py
file with contents like the following and run python setup.py development
to add packages to the path:# setup.py from setuptools import setup, find_packages setup( name='sample', packages=find_packages() )
I have had this issue a couple times in the past few months. I haven't seen a good solution for fedora systems posted, so here's yet another solution. I'm using RHEL7, and I discovered the following:
If you have urllib3
installed via pip
, and requests
installed via yum
you will have issues, even if you have the correct packages installed. The same will apply if you have urllib3
installed via yum
, and requests
installed via pip
. Here's what I did to fix the issue:
sudo pip uninstall requests
sudo pip uninstall urllib3
sudo yum remove python-urllib3
sudo yum remove python-requests
(confirm that all those libraries have been removed)
sudo yum install python-urllib3
sudo yum install python-requests
Just be aware that this will only work for systems that are running Fedora, Redhat, or CentOS.
Sources:
This very question (in the comments to this answer).
This github issue.
If someone is looking for a workaround, I stumbled upon one. Here's a bit of context. I wanted to test out one of the methods I've in a file. When I run it from within
if __name__ == "__main__":
it always complained of the relative imports. I tried to apply the above solutions, but failed to work, since there were many nested files, each with multiple imports.
Here's what I did. I just created a launcher, an external program that would import necessary methods and call them. Though, not a great solution, it works.
Expanding on Mihail's answer, I believe the non-hackish way (as in, not handling the file paths directly) is the following:
__init__.py
file under Foo/
import pkgutil
import sys
def load_all_modules_from_dir(dirname):
for importer, package_name, _ in pkgutil.iter_modules([dirname]):
full_package_name = '%s.%s' % (dirname, package_name)
if full_package_name not in sys.modules:
module = importer.find_module(package_name
).load_module(full_package_name)
print module
load_all_modules_from_dir('Foo')
You'll get:
<module 'Foo.bar' from '/home/.../Foo/bar.pyc'>
<module 'Foo.spam' from '/home/.../Foo/spam.pyc'>
I found the following way works for importing a package from the script's parent directory. In the example, I would like to import functions in env.py
from app.db
package.
.
+-- my_application
+-- alembic
+-- env.py
+-- app
+-- __init__.py
+-- db
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
The changelog is sloppily worded. from __future__ import absolute_import
does not care about whether something is part of the standard library, and import string
will not always give you the standard-library module with absolute imports on.
from __future__ import absolute_import
means that if you import string
, Python will always look for a top-level string
module, rather than current_package.string
. However, it does not affect the logic Python uses to decide what file is the string
module. When you do
python pkg/script.py
pkg/script.py
doesn't look like part of a package to Python. Following the normal procedures, the pkg
directory is added to the path, and all .py
files in the pkg
directory look like top-level modules. import string
finds pkg/string.py
not because it's doing a relative import, but because pkg/string.py
appears to be the top-level module string
. The fact that this isn't the standard-library string
module doesn't come up.
To run the file as part of the pkg
package, you could do
python -m pkg.script
In this case, the pkg
directory will not be added to the path. However, the current directory will be added to the path.
You can also add some boilerplate to pkg/script.py
to make Python treat it as part of the pkg
package even when run as a file:
if __name__ == '__main__' and __package__ is None:
__package__ = 'pkg'
However, this won't affect sys.path
. You'll need some additional handling to remove the pkg
directory from the path, and if pkg
's parent directory isn't on the path, you'll need to stick that on the path too.
This may sound crazy but you can just create a symbolic link to the file you want to import if you're just creating a wrapper script to it.
import importlib
module = importlib.import_module('my_package.my_module')
my_class = getattr(module, 'MyClass')
my_instance = my_class()
Couldn't find any definitive reference, but I see that the example code for os.walk uses os.path but only imports os
Try to run it as:
python3 -m p_03_using_bisection_search
The easiest way without any modification to your script is to set PYTHONPATH environment variable. Because sys.path is initialized from these locations:
Just run:
export PYTHONPATH=/absolute/path/to/your/module
You sys.path will contains above path, as show below:
print sys.path
['', '/absolute/path/to/your/module', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
You can also use importlib
directly
import importlib
try:
importlib.import_module(module_name)
except ImportError:
# Handle error
As to me, i need to caffe to my python path. I can add it's path to the file
/home/xy/.bashrc
by add
export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH
.
to my /home/xy/.bashrc
file.
But when I use pycharm, the path is still not in.
So I can add path to PYTHONPATH
variable, by run -> edit Configuration.
If you'd like your script to install missing packages and continue, you could do something like this (on example of 'krbV' module in 'python-krbV' package):
import pip
import sys
for m, pkg in [('krbV', 'python-krbV')]:
try:
setattr(sys.modules[__name__], m, __import__(m))
except ImportError:
pip.main(['install', pkg])
setattr(sys.modules[__name__], m, __import__(m))
The OOP way of doing this would be to make your module a class instead of a set of unbound methods. Then you could use __init__
or a setter method to set the variables from the caller for use in the module methods.
I have the same problem and I solved it and the explanation is as follow:
If the Seaborn package is not installed in anaconda, you will not be able to update it, namely, if in the Terminal we type: conda update seaborn
it will fail showing: "PackageNotFoundError: Package not found: 'seaborn' Package 'seaborn' is not installed in /Users/yifan/anaconda"
Thus we need to install seaborn in anaconda first by typing in Terminal: conda install -c https://conda.anaconda.org/anaconda seaborn
Then the seaborn will be fetched and installed in the environment of anaconda, namely in my case, /Users/yifan/anaconda
Once this installation is done, we will be able to import seaborn in python.
Side note, to check and list all discoverable environments where python is installed in anaconda, type in Terminal: conda info --envs
Take a look at http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports. You could do
from .mod1 import stuff
In general I would consider setting up of an environment variable (like PYTHONPATH)
to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.
Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the
test environment as well, leading to situations like the tests running fine for a
particular developer but probably failing when some one launches the tests.
e.preventDefault() works fine only if you dont have problem on your javascripts, check your javascripts if e.preventDefault() doesn't work chances are some other parts of your JS doesn't work also
Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:
input.ng-pristine.ng-invalid {
-webkit-box-shadow: none;
-ms-box-shadow: none;
box-shadow:none;
}
Google now allows to hide the Badge, from the FAQ :
I'd like to hide the reCAPTCHA v3 badge. What is allowed?
You are allowed to hide the badge as long as you include the reCAPTCHA branding visibly in the user flow. Please include the following text: This site is protected by reCAPTCHA and the Google <a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply.
For example:
So you can simply hide it using the following CSS :
.grecaptcha-badge {
visibility: hidden;
}
Do not use display: none;
as it appears to disable the spam checking (thanks @Zade)
I'd like to give more codes to make it clear.
struct A
{
operator bool() const { return true; }
};
struct B
{
explicit operator bool() const { return true; }
};
int main()
{
A a1;
if (a1) cout << "true" << endl; // OK: A::operator bool()
bool na1 = a1; // OK: copy-initialization selects A::operator bool()
bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization
B b1;
if (b1) cout << "true" << endl; // OK: B::operator bool()
// bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization
}
You should use space partitioning to solve this problem.
Read up on Binary Space Partitioning and Quadtrees
It means you're trying to call something that isn't a function
const foo = 'string'
foo() // error
Define is evaluated before compilation by the pre-processor, while variables are referenced at run-time. This means you control how your application is built (not how it runs)
Here are a couple examples that use define which cannot be replaced by a variable:
#define min(i, j) (((i) < (j)) ? (i) : (j))
note this is evaluated by the pre-processor, not during runtime
ASP.NET MVC doesn't work on events like ASP classic; there's no "button click event". Your controller methods correspond to requests sent to the server.
Instead, you need to wrap that form in code something like this:
@using (Html.BeginForm("SignUp", "Account", FormMethod.Post))
{
<!-- form goes here -->
<input type="submit" value="Sign Up" />
}
This will set up a form, and then your submit input will trigger a POST, which will hit your SignUp()
method, assuming your routes are properly set up (the defaults should work).
I think you will need to edit the doxys file and set GENERATE_UML (something like that) to true. And you need to have dot/graphviz installed.
Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw
for width: 100%
to get rid of the horizontal scrollbar.
You could use the following. It supports Bootstrap 3.x above.
<img src="..." alt="..." class="img-responsive center-block" />
I like to use:
import os
clear = lambda : os.system('cls') # or clear for Linux
clear()
update as you loading contents dynamically so you use.
$(document).on('click', 'span', function () {
alert(this.id);
});
old code
$('span').click(function(){
alert(this.id);
});
or you can use .on
$('span').on('click', function () {
alert(this.id);
});
this
refers to current span element clicked
this.id
will give the id
of the current span clicked
This worked for me:
#image-id {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
width: auto;
margin: 0 auto;
}
You can also prepend your command with env
to inject Environment variables like so:
0 * * * * env VARIABLE=VALUE /usr/bin/mycommand
You need some sort of Inter Process Communication. Use a pipe or a shared buffer.
cmd (command):
netdom renamecomputer %COMPUTERNAME% /Newname "NEW-NAME"
powershell (windows 2008/2012):
netdom renamecomputer "$env:COMPUTERNAME" /Newname "NEW-NAME"
after that, you need to reboot your computer.
You have your ssh clone
statement wrong: git clone username [email protected]:root/test.git
That statement would try to clone a repository named username
into the location relative to your current path, [email protected]:root/test.git
.
You want to leave out username
:
git clone [email protected]:root/test.git
i had to use a csv parser about 5 years ago. seems there are at least two csv standards: http://en.wikipedia.org/wiki/Comma-separated_values and what microsoft does in excel.
i found this libaray which eats both: http://ostermiller.org/utils/CSV.html, but afaik, it has no way of inferring what data type the columns were.
I use this method:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class TEST {
static Scanner scn;
public static void main(String[] args) {
String text = "";
try{
scn = new Scanner(new File("test.txt"));
}catch(FileNotFoundException ex){System.out.println(ex.getMessage());}
while(scn.hasNext()){
text += scn.next();
}
String[] arry = text.split(",");
//if need converting to float do this:
Float[] arrdy = new Float[arry.length];
for(int i = 0; i < arry.length; i++){
arrdy[i] = Float.parseFloat(arry[i]);
}
System.out.println(Arrays.toString(arrdy));
}
}
UPDATE
Now we need to use Custom Targets
SAMPLE CODE
Glide.with(mContext)
.asBitmap()
.load("url")
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
How does one use glide to download an image into a bitmap?
The above all answer are correct but outdated
because in new version of Glide implementation 'com.github.bumptech.glide:glide:4.8.0'
You will find below error in code
.asBitmap()
is not available in glide:4.8.0
SimpleTarget<Bitmap>
Here is solution
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
Glide.with(this)
.load("")
.apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
.into(new Target<Drawable>() {
@Override
public void onLoadStarted(@Nullable Drawable placeholder) {
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
}
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
Bitmap bitmap = drawableToBitmap(resource);
imageView.setImageBitmap(bitmap);
// now you can use bitmap as per your requirement
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
@Override
public void getSize(@NonNull SizeReadyCallback cb) {
}
@Override
public void removeCallback(@NonNull SizeReadyCallback cb) {
}
@Override
public void setRequest(@Nullable Request request) {
}
@Nullable
@Override
public Request getRequest() {
return null;
}
@Override
public void onStart() {
}
@Override
public void onStop() {
}
@Override
public void onDestroy() {
}
});
}
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.
One is
org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)
Another is
org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)
Pay attention to the opposite position of parameters.
See man git-add
:
-f, --force
Allow adding otherwise ignored files.
So run this
git add --force my/ignore/file.foo
I would like to add the following point.
You can also make it a const &
and const &&
So,
struct s{
void val1() const {
// *this is const here. Hence this function cannot modify any member of *this
}
void val2() const & {
// *this is const& here
}
void val3() const && {
// The object calling this function should be const rvalue only.
}
void val4() && {
// The object calling this function should be rvalue reference only.
}
};
int main(){
s a;
a.val1(); //okay
a.val2(); //okay
// a.val3() not okay, a is not rvalue will be okay if called like
std::move(a).val3(); // okay, move makes it a rvalue
}
Feel free to improve the answer. I am no expert
If above answer didn't work for you as it didn't work for me on my Xiaomi Mi5.I tried to figure out the Core reason behind it and solve it. In MIUI, in order to change "Install via USB" option, you must be connected to the internet and signed in your Mi account. Due to some reason, requests from out of the China servers are getting rejected, so I connected to one open China VPN and tried again to enable 'Install via USB' and I got success. For detailed solution and VPN details, see this useful Youtube video: https://youtu.be/MeKUJlD-Ke4
As jcmiller11 suggested, setting the width and height helps. A slightly nicer solution is to retrieve the width and height of the canvas before drawing the chart. Then using those numbers for setting the chart on each subsequent re-draw of the chart. This makes sure there are no constants in the javascript code.
ctx.canvas.originalwidth = ctx.canvas.width;
ctx.canvas.originalheight = ctx.canvas.height;
function drawchart() {
ctx.canvas.width = ctx.canvas.originalwidth;
ctx.canvas.height = ctx.canvas.originalheight;
var chartctx = new Chart(ctx);
myNewBarChart = chartctx.Bar(data, chartSettings);
}
If your actual concern is the dynamicness of the webapp context (the "AppName" part), then just retrieve it dynamically by HttpServletRequest#getContextPath()
.
<head>
<link rel="stylesheet" href="${pageContext.request.contextPath}/templates/style/main.css" />
<script src="${pageContext.request.contextPath}/templates/js/main.js"></script>
<script>var base = "${pageContext.request.contextPath}";</script>
</head>
<body>
<a href="${pageContext.request.contextPath}/pages/foo.jsp">link</a>
</body>
If you want to set a base path for all relative links so that you don't need to repeat ${pageContext.request.contextPath}
in every relative link, use the <base>
tag. Here's an example with help of JSTL functions.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<head>
<c:set var="url">${pageContext.request.requestURL}</c:set>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />
<link rel="stylesheet" href="templates/style/main.css" />
<script src="templates/js/main.js"></script>
<script>var base = document.getElementsByTagName("base")[0].href;</script>
</head>
<body>
<a href="pages/foo.jsp">link</a>
</body>
This way every relative link (i.e. not starting with /
or a scheme) will become relative to the <base>
.
This is by the way not specifically related to Tomcat in any way. It's just related to HTTP/HTML basics. You would have the same problem in every other webserver.
Use CultureInfo
class to change your culture info.
var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);
You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).
You must login to have a valid session before downloading anything below.
*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)
*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.
Xcode 12
12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)
12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)
12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)
Xcode 11
11.7 (Latest as of Sept 02 2020)
11.4.1 (Requires macOS 10.15.2 or later)
11 (Requires macOS 10.14.4 or later)
Xcode 10 (unsupported for iTunes Connect)
Xcode 9
Xcode 8
Xcode 7
Xcode 6
Even Older Versions (unsupported for iTunes Connect)
In my case, my site was hosted on shared hosting and there was a resource over usage not even relating to my database, thus my database was locked down, the hosting panel was Plesk
u should add a theme
to ur all activities (u should add theme
for all application in ur <application>
in ur manifest)
but if u have set different theme to ur activity u can use :
android:theme="@style/Theme.AppCompat"
or each kind of AppCompat
theme!
you can make a shell script with those commands, and then chmod +x <scriptname.sh>
, and then just run it by
./scriptname.sh
Its very simple to write a bash script
Mockup sh file:
#!/bin/sh
sudo command1
sudo command2
.
.
.
sudo commandn
Create table #temp1
(
id int identity(1,1),
name varchar(50),
profession varchar(50)
)
Create table #temp2
(
id int identity(1,1),
name varchar(50),
profession varchar(50)
)
-----main query ------
insert into #temp1(name,profession)
output inserted.name,inserted.profession into #temp2
select 'Shekhar','IT'
I'm doing it like this:
Models are ViewScoped
converter:
@Named
@ViewScoped
public class ViewScopedFacesConverter implements Converter, Serializable
{
private static final long serialVersionUID = 1L;
private Map<String, Object> converterMap;
@PostConstruct
void postConstruct(){
converterMap = new HashMap<>();
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object object) {
String selectItemValue = String.valueOf( object.hashCode() );
converterMap.put( selectItemValue, object );
return selectItemValue;
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String selectItemValue){
return converterMap.get(selectItemValue);
}
}
and bind to component with:
<f:converter binding="#{viewScopedFacesConverter}" />
If you will use entity id rather than hashCode you can hit a collision- if you have few lists on one page for different entities (classes) with the same id
Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.
As a very blunt hammer, useful for testing, you can use the enable_seqscan
and enable_indexscan
parameters. See:
These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_
params and walk away.
Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?
See also this old newsgroup post.
If Khanh TO's solution caused UI issues for you (like it did for me) try using $timeout
to not update the attribute until it has been unchanged for 500ms.
var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
var newWidth = window.innerWidth,
updateStuffTimer;
if (newWidth !== oldWidth) {
$timeout.cancel(updateStuffTimer);
}
updateStuffTimer = $timeout(function() {
updateStuff(newWidth); // Update the attribute based on window.innerWidth
}, 500);
});
$scope.$on('$destroy',function (){
$(window).off('resize.doResize'); // remove the handler added earlier
});
Reference: https://gist.github.com/tommaitland/7579618
opening a file using fopen
before we can read(or write) information from (to) a file on a disk we must open the file. to open the file we have called the function fopen.
1.firstly it searches on the disk the file to be opened.
2.then it loads the file from the disk into a place in memory called buffer.
3.it sets up a character pointer that points to the first character of the buffer.
this the way of behaviour of fopen function
there are some causes while buffering process,it may timedout. so while comparing fopen(high level i/o) to open (low level i/o) system call , and it is a faster more appropriate than fopen.
Actually, as I know, you can't do some actions exactly when resize is off, simply because you don't know future user's actions. But you can assume the time passed between two resize events, so if you wait a little more than this time and no resize is made, you can call your function.
Idea is that we use setTimeout
and it's id in order to save or delete it. For example we know that time between two resize events is 500ms, therefore we will wait 750ms.
var a;_x000D_
$(window).resize(function(){_x000D_
clearTimeout(a);_x000D_
a = setTimeout(function(){_x000D_
// call your function_x000D_
},750);_x000D_
});
_x000D_
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy
In this case, list1
is of type ArrayList
.
List<Integer> list2 = Arrays.asList(ia);
Here, the list is returned as a List
view, meaning it has only the methods attached to that interface. Hence why some methods are not allowed on list2
.
ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));
Here, you ARE creating a new ArrayList
. You're simply passing it a value in the constructor. This is not an example of casting. In casting, it might look more like this:
ArrayList list1 = (ArrayList)Arrays.asList(ia);
So this is long after the initial question, and technically it isn't a direct answer to how to use Ajax call to populate exterior variable as the question asks. However in research and responses it's been found to be extremely difficult to do this without disabling asynchronous functions within the call, or by descending into what seems like the potential for callback hell. My solution for this has been to use Axios. Using this has dramatically simplified my usages of asynchronous calls getting in the way of getting at data.
For example if I were trying to access session variables in PHP, like the User ID, via a call from JS this might be a problem. Doing something like this..
async function getSession() {
'use strict';
const getSession = await axios("http:" + url + "auth/" + "getSession");
log(getSession.data);//test
return getSession.data;
}
Which calls a PHP function that looks like this.
public function getSession() {
$session = new SessionController();
$session->Session();
$sessionObj = new \stdClass();
$sessionObj->user_id = $_SESSION["user_id"];
echo json_encode($sessionObj);
}
To invoke this using Axios do something like this.
getSession().then(function (res) {
log(res);//test
anyVariable = res;
anyFunction(res);//set any variable or populate another function waiting for the data
});
The result would be, in this case a Json object from PHP.
{"user_id":"1111111-1111-1111-1111-111111111111"}
Which you can either use in a function directly in the response section of the Axios call or set a variable or invoke another function.
Proper syntax for the Axios call would actually look like this.
getSession().then(function (res) {
log(res);//test
anyVariable = res;
anyFunction(res);//set any variable or populate another function waiting for the data
}).catch(function (error) {
console.log(error);
});
For proper error handling.
I hope this helps anyone having these issues. And yes I am aware this technically is not a direct answer to the question but given the answers supplied already I felt the need to provide this alternative solution which dramatically simplified my code on the client and server sides.
The storage_path
function returns the fully qualified path to the storage directory:
$path = storage_path();
You may also use the storage_path
function to generate a fully qualified path to a given file relative to the storage directory:
$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');
Source: Laravel Doc
If undocumented features aren't your game, the same can be accomplished here:
Handlebars.registerHelper('index_of', function(context,ndx) {
return context[ndx];
});
Then in a template
{{#index_of this 1}}{{/index_of}}
I wrote the above before I got a hold of
this.[0]
I can't see one getting too far with handlebars without writing your own helpers.
new String(byteArray, 0, bytesRead);
does not modify the array. You need to use System.arrayCopy
to trim the array to the actual data size. Otherwise you are processing all 102400 bytes most of which are zeros.
Sounds like a job for set
with a custom IFS
.
IFS=-
set $STR
var1=$1
var2=$2
(You will want to do this in a function with a local IFS
so you don't mess up other parts of your script where you require IFS
to be what you expect.)
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
There's these exciting new properties in CSS3:
font-smooth:always;
-webkit-font-smoothing: antialiased;
Still not done much testing with them myself though, and they almost definitely won't be any good for IE. Could be useful for Chrome on Windows or maybe Firefox though. Last time I checked, they didn't antialias small stuff automatically like they do in OSX.
UPDATE
These are not supported in IE or Firefox. The font-smooth property is only available in iOS safari as far as I remember
public static object GetProperty(object target, string name)
{
var site = System.Runtime.CompilerServices.CallSite<Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, name, target.GetType(), new[]{Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(0,null)}));
return site.Target(site, target);
}
Add reference to Microsoft.CSharp. Works also for dynamic types and private properties and fields.
Edit: While this approach works, there is almost 20× faster method from the Microsoft.VisualBasic.dll assembly:
public static object GetProperty(object target, string name)
{
return Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(target, name, CallType.Get);
}
When you have some styles on a parent element that interfere with a popover, you’ll want to specify a custom container so that the popover’s HTML appears within that element instead.
For instance say the parent for a popover is body then you can use.
<a href="#" data-toggle="tooltip" data-container="body"> Popover One </a>
Other case might be when popover is placed inside some other element and you want to show popover over that element, then you'll need to specify that element in data-container. ex: Suppose, we have popover inside a bootstrap modal with id as 'modal-two', then you'll need to set 'data-container' to 'modal-two'.
<a href="#" data-toggle="tooltip" data-container="#modal-two"> Popover Two </a>
Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).
ParentNode.insertBefore(<your element>, ParentNode.firstChild);
There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:
http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html
If you have more then 1 dimension array
with open("file.txt", 'w') as output:
for row in values:
output.write(str(row) + '\n')
Code to write without '[' and ']'
with open("file.txt", 'w') as file:
for row in values:
s = " ".join(map(str, row))
file.write(s+'\n')
Use set:
yourList = new ArrayList<Blog>(new LinkedHashSet<Blog>(yourList));
This will create list without duplicates and the element order will be as in original list.
Just do not forget to implement hashCode()
and equals(
) for your class Blog.
Because when you do
window.location.href = "#"+anchor;
You load a new page, you can do:
<a href="#" onclick="jumpTo('one');">One</a>
<a href="#" id="one"></a>
<script>
function getPosition(element){
var e = document.getElementById(element);
var left = 0;
var top = 0;
do{
left += e.offsetLeft;
top += e.offsetTop;
}while(e = e.offsetParent);
return [left, top];
}
function jumpTo(id){
window.scrollTo(getPosition(id));
}
</script>
Call your hosting company and either have them set up regular log backups or set the recovery model to simple. I'm sure you know what informs the choice, but I'll be explicit anyway. Set the recovery model to full if you need the ability to restore to an arbitrary point in time. Either way the database is misconfigured as is.
If you set the margin to be margin:0 auto
the image will be centered.
This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.
For Travers an String you can also use charAt()
with the string.
like :
String str = "xyz"; // given String
char st = str.charAt(0); // for example we take 0 index element
System.out.println(st); // print the char at 0 index
charAt()
is method of string handling in java which help to Travers the string for specific character.
For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there
Your question makes an assertion, that "Writing exception-safe code is very hard". I will answer your questions first, and then, answer the hidden question behind them.
Do you really write exception safe code?
Of course, I do.
This is the reason Java lost a lot of its appeal to me as a C++ programmer (lack of RAII semantics), but I am digressing: This is a C++ question.
It is, in fact, necessary when you need to work with STL or Boost code. For example, C++ threads (boost::thread
or std::thread
) will throw an exception to exit gracefully.
Are you sure your last "production ready" code is exception safe?
Can you even be sure, that it is?
Writing exception-safe code is like writing bug-free code.
You can't be 100% sure your code is exception safe. But then, you strive for it, using well-known patterns, and avoiding well-known anti-patterns.
Do you know and/or actually use alternatives that work?
There are no viable alternatives in C++ (i.e. you'll need to revert back to C and avoid C++ libraries, as well as external surprises like Windows SEH).
To write exception safe code, you must know first what level of exception safety each instruction you write is.
For example, a new
can throw an exception, but assigning a built-in (e.g. an int, or a pointer) won't fail. A swap will never fail (don't ever write a throwing swap), a std::list::push_back
can throw...
The first thing to understand is that you must be able to evaluate the exception guarantee offered by all of your functions:
The following code seems like correct C++, but in truth, offers the "none" guarantee, and thus, it is not correct:
void doSomething(T & t)
{
if(std::numeric_limits<int>::max() > t.integer) // 1. nothrow/nofail
t.integer += 1 ; // 1'. nothrow/nofail
X * x = new X() ; // 2. basic : can throw with new and X constructor
t.list.push_back(x) ; // 3. strong : can throw
x->doSomethingThatCanThrow() ; // 4. basic : can throw
}
I write all my code with this kind of analysis in mind.
The lowest guarantee offered is basic, but then, the ordering of each instruction makes the whole function "none", because if 3. throws, x will leak.
The first thing to do would be to make the function "basic", that is putting x in a smart pointer until it is safely owned by the list:
void doSomething(T & t)
{
if(std::numeric_limits<int>::max() > t.integer) // 1. nothrow/nofail
t.integer += 1 ; // 1'. nothrow/nofail
std::auto_ptr<X> x(new X()) ; // 2. basic : can throw with new and X constructor
X * px = x.get() ; // 2'. nothrow/nofail
t.list.push_back(px) ; // 3. strong : can throw
x.release() ; // 3'. nothrow/nofail
px->doSomethingThatCanThrow() ; // 4. basic : can throw
}
Now, our code offers a "basic" guarantee. Nothing will leak, and all objects will be in a correct state. But we could offer more, that is, the strong guarantee. This is where it can become costly, and this is why not all C++ code is strong. Let's try it:
void doSomething(T & t)
{
// we create "x"
std::auto_ptr<X> x(new X()) ; // 1. basic : can throw with new and X constructor
X * px = x.get() ; // 2. nothrow/nofail
px->doSomethingThatCanThrow() ; // 3. basic : can throw
// we copy the original container to avoid changing it
T t2(t) ; // 4. strong : can throw with T copy-constructor
// we put "x" in the copied container
t2.list.push_back(px) ; // 5. strong : can throw
x.release() ; // 6. nothrow/nofail
if(std::numeric_limits<int>::max() > t2.integer) // 7. nothrow/nofail
t2.integer += 1 ; // 7'. nothrow/nofail
// we swap both containers
t.swap(t2) ; // 8. nothrow/nofail
}
We re-ordered the operations, first creating and setting X
to its right value. If any operation fails, then t
is not modified, so, operation 1 to 3 can be considered "strong": If something throws, t
is not modified, and X
will not leak because it's owned by the smart pointer.
Then, we create a copy t2
of t
, and work on this copy from operation 4 to 7. If something throws, t2
is modified, but then, t
is still the original. We still offer the strong guarantee.
Then, we swap t
and t2
. Swap operations should be nothrow in C++, so let's hope the swap you wrote for T
is nothrow (if it isn't, rewrite it so it is nothrow).
So, if we reach the end of the function, everything succeeded (No need of a return type) and t
has its excepted value. If it fails, then t
has still its original value.
Now, offering the strong guarantee could be quite costly, so don't strive to offer the strong guarantee to all your code, but if you can do it without a cost (and C++ inlining and other optimization could make all the code above costless), then do it. The function user will thank you for it.
It takes some habit to write exception-safe code. You'll need to evaluate the guarantee offered by each instruction you'll use, and then, you'll need to evaluate the guarantee offered by a list of instructions.
Of course, the C++ compiler won't back up the guarantee (in my code, I offer the guarantee as a @warning doxygen tag), which is kinda sad, but it should not stop you from trying to write exception-safe code.
How can a programmer guarantee that a no-fail function will always succeed? After all, the function could have a bug.
This is true. The exception guarantees are supposed to be offered by bug-free code. But then, in any language, calling a function supposes the function is bug-free. No sane code protects itself against the possibility of it having a bug. Write code the best you can, and then, offer the guarantee with the supposition it is bug-free. And if there is a bug, correct it.
Exceptions are for exceptional processing failure, not for code bugs.
Now, the question is "Is this worth it ?".
Of course, it is. Having a "nothrow/no-fail" function knowing that the function won't fail is a great boon. The same can be said for a "strong" function, which enables you to write code with transactional semantics, like databases, with commit/rollback features, the commit being the normal execution of the code, throwing exceptions being the rollback.
Then, the "basic" is the very least guarantee you should offer. C++ is a very strong language there, with its scopes, enabling you to avoid any resource leaks (something a garbage collector would find it difficult to offer for the database, connection or file handles).
So, as far as I see it, it is worth it.
nobar made a comment that I believe, is quite relevant, because it is part of "how do you write exception safe code":
swap()
functions. It should be noted, however, that std::swap()
can fail based on the operations that it uses internallythe default std::swap
will make copies and assignments, which, for some objects, can throw. Thus, the default swap could throw, either used for your classes or even for STL classes. As far as the C++ standard is concerned, the swap operation for vector
, deque
, and list
won't throw, whereas it could for map
if the comparison functor can throw on copy construction (See The C++ Programming Language, Special Edition, appendix E, E.4.3.Swap).
Looking at Visual C++ 2008 implementation of the vector's swap, the vector's swap won't throw if the two vectors have the same allocator (i.e., the normal case), but will make copies if they have different allocators. And thus, I assume it could throw in this last case.
So, the original text still holds: Don't ever write a throwing swap, but nobar's comment must be remembered: Be sure the objects you're swapping have a non-throwing swap.
Dave Abrahams, who gave us the basic/strong/nothrow guarantees, described in an article his experience about making the STL exception safe:
http://www.boost.org/community/exception_safety.html
Look at the 7th point (Automated testing for exception-safety), where he relies on automated unit testing to make sure every case is tested. I guess this part is an excellent answer to the question author's "Can you even be sure, that it is?".
t.integer += 1;
is without the guarantee that overflow will not happen NOT exception safe, and in fact may technically invoke UB! (Signed overflow is UB: C++11 5/4 "If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.") Note that unsigned integer do not overflow, but do their computations in an equivalence class modulo 2^#bits.
Dionadar is referring to the following line, which indeed has undefined behaviour.
t.integer += 1 ; // 1. nothrow/nofail
The solution here is to verify if the integer is already at its max value (using std::numeric_limits<T>::max()
) before doing the addition.
My error would go in the "Normal failure vs. bug" section, that is, a bug. It doesn't invalidate the reasoning, and it does not mean the exception-safe code is useless because impossible to attain. You can't protect yourself against the computer switching off, or compiler bugs, or even your bugs, or other errors. You can't attain perfection, but you can try to get as near as possible.
I corrected the code with Dionadar's comment in mind.
Use simple CSS height: 100%; matches the height of the parent and using height: 100vh matches the height of the viewport.
Use vh instead of %;
Do Mouse move while page is loading should work.
page.sendEvent('click',200, 660);
do { phantom.page.sendEvent('mousemove'); } while (page.loading);
UPDATE
When submitting the form, nothing was returned, so the program stopped. The program did not wait for the page to load as it took a few seconds for the redirect to begin.
telling it to move the mouse until the URL changes to the home page gave the browser as much time as it needed to change. then telling it to wait for the page to finish loading allowed the page to full load before the content was grabbed.
page.evaluate(function () {
document.getElementsByClassName('btn btn-primary btn-block')[0].click();
});
do { phantom.page.sendEvent('mousemove'); } while (page.evaluate(function()
{
return document.location != "https://www.bestwaywholesale.co.uk/";
}));
do { phantom.page.sendEvent('mousemove'); } while (page.loading);
You can use the lock
statement instead. I think this can only replace the second version. Also, remember that both synchronized
and lock
need to operate on an object.
You can use...
document.getElementById('theForm').submit();
...but don't replace the innerHTML
. You could hide the form and then insert a processing... span
which will appear in its place.
var form = document.getElementById('theForm');
form.style.display = 'none';
var processing = document.createElement('span');
processing.appendChild(document.createTextNode('processing ...'));
form.parentNode.insertBefore(processing, form);
Your table width is 90% which is relative to it's container.
If you squeeze the page, you are probably squeezing the table width as well. The width of the cells reduce too and the browser compensate by increasing the height.
To have the height untouched, you have to make sure the widths of the cells can hold the intented content. Fixing the table width is probably something you want to try. Or perhaps play around with the min-width of the table.
$("#pageCSS").attr('href', './css/new_css.css');
You can now finally do:
let a = 5;
let b = 10;
[a, b] = [b, a]; // ES6
console.log(a, b);
_x000D_
A lot of this has to do with polymorphism. When you assign
X = new Y();
X can be much less 'specific' than Y, but not the other way around. X is just the handle you are accessing Y with, Y is the real instantiated thing,
You get an error here because Integer is a Number, but Number is not an Integer.
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error
As such, any method of X that you call must be valid for Y. Since X is more generally it probably shares some, but not all of Y's methods. Still, any arguments given must be valid for Y.
In your examples with add, an int (small i) is not a valid Object or Integer.
ArrayList<?> a = new ArrayList<?>();
This is no good because you can't actually instantiate an array list containing ?'s. You can declare one as such, and then damn near anything can follow in new ArrayList<Whatever>();
I had to install IIS Media Services 4.1 from the Windows Web App Gallery.
I am using those commands on MacOs after getting the same error
sudo /usr/local/mysql/support-files/mysql.server start
sudo /usr/local/mysql/support-files/mysql.server stop
sudo /usr/local/mysql/support-files/mysql.server restart
You just subindex it with [:5]
indicating that you want (up to) the first 5 elements.
>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]
Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!
>>> x[5:]
[11, 12]
This should also work and is a closer answer to what is asked in the question:
for i in range(len(x)):
if valeur.item(i) <= 0.6:
print ("this works")
else:
print ("valeur is too high")
You can do something like this instead.
return new DateTime(2010, Month, 1).ToString("MMM");
As paxdiablo said make -f pax.mk
would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.
Also you can just type make
if your file name is makefile/Makefile
.
Suppose you have two files named makefile
and Makefile
in the same directory then makefile
is executed if make
alone is given. You can even pass arguments to makefile.
Check out more about makefile at this Tutorial : Basic understanding of Makefile
If you can NOT find the .m3u8
file you will need to do a couple of steps different.
1) Go to the network tab and sort by Media
2) You will see something here and select the first item. In my example, it's an mpd
file. then copy the Request URL.
3) Next, download the file using your favorite command line tool using the URL from step 2.
youtube-dl -f bestvideo+bestaudio https://url.com/destination/stream.mpd
4) Depending on the encoding you might have to join the audio and video files together but this will depend on a video by video case.
Change IDs and data attributes as you wish!
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
I've found the sticky footer solution a bit painful on responsive sites, given that the height of your nav and footer can differ depending on the device. If you only care about working on modern browsers, you can accomplish your goal using a bit of Javascript.
If this is your HTML:
<div class="nav">
</div>
<div class="wrapper">
</div>
<div class="footer">
</div>
Then use this JQuery on every page:
$(function(){
/* Sets the minimum height of the wrapper div to ensure the footer reaches the bottom */
function setWrapperMinHeight() {
$('.wrapper').css('minHeight', window.innerHeight - $('.nav').height() - $('.footer').height());
}
/* Make sure the main div gets resized on ready */
setWrapperMinHeight();
/* Make sure the wrapper div gets resized whenever the screen gets resized */
window.onresize = function() {
setWrapperMinHeight();
}
});
I assume you found this code on Exercise 14: Prompting And Passing.
Do the following:
script = '*some arguments*'
user_name = '*some arguments*'
and that works perfectly
You can try this:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
Just to clarify how to unpack the arguments, and take care of missing arguments etc.
def func(**keyword_args):
#-->keyword_args is a dictionary
print 'func:'
print keyword_args
if keyword_args.has_key('b'): print keyword_args['b']
if keyword_args.has_key('c'): print keyword_args['c']
def func2(*positional_args):
#-->positional_args is a tuple
print 'func2:'
print positional_args
if len(positional_args) > 1:
print positional_args[1]
def func3(*positional_args, **keyword_args):
#It is an error to switch the order ie. def func3(**keyword_args, *positional_args):
print 'func3:'
print positional_args
print keyword_args
func(a='apple',b='banana')
func(c='candle')
func2('apple','banana')#It is an error to do func2(a='apple',b='banana')
func3('apple','banana',a='apple',b='banana')
func3('apple',b='banana')#It is an error to do func3(b='banana','apple')
I see that Character.isDigit perfectly suits the need, since the input will be just one symbol. Of course we don't have any info about this kb object but just in case it's a java.util.Scanner instance, I'd also suggest using java.io.InputStreamReader for command line input. Here's an example:
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
try {
reader.read();
}
catch(Exception e) {
e.printStackTrace();
}
reader.close();
git stash
to save your uncommited changesgit stash list
to list your saved uncommited stashesgit stash apply stash@{x}
where x can be 0,1,2..no of stashes that you have madeDoes the race conditions really matter if you first try an update followed by an insert? Lets say you have two threads that want to set a value for key key:
Thread 1: value = 1
Thread 2: value = 2
Example race condition scenario
The other thread fails with insert (with error duplicate key) - thread 2.
But; in a multithreaded environment, the OS scheduler decides on the order of the thread execution - in the above scenario, where we have this race condition, it was the OS that decided on the sequence of execution. Ie: It is wrong to say that "thread 1" or "thread 2" was "first" from a system viewpoint.
When the time of execution is so close for thread 1 and thread 2, the outcome of the race condition doesn't matter. The only requirement should be that one of the threads should define the resulting value.
For the implementation: If update followed by insert results in error "duplicate key", this should be treated as success.
Also, one should of course never assume that value in the database is the same as the value you wrote last.
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
Assuming a
is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1]
, it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
I wrote this so I could edit all tables and columns to null at once:
select
case
when sc.max_length = '-1' and st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(MAX) NULL'
when st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(' + cast(sc.max_length as varchar(4)) + ') NULL'
else
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + ' NULL'
end as query
from sys.columns sc
inner join sys.types st on st.system_type_id = sc.system_type_id
inner join sys.objects so on so.object_id = sc.object_id
where so.type = 'U'
and st.name <> 'timestamp'
order by st.name
How about alias gcc99= gcc -std=c99
?
You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster
Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?
I think to add timestamp to every record and get the latest. In this situation you can get any ids, pack rows and other ops.
When I used Electron + Angular such order helped me to solve problem
<script src="./assets/js/jquery-3.3.1.min.js"></script>
<script src="./assets/js/jquery-3.3.1.slim.min.js"></script>
<script src="./assets/js/popper.min.js"></script>
<script src="./assets/js/bootstrap.min.js"></script>
If you don't want to load the calendar twice and you don't have a version where defaultDate is implemented, do the following:
Change the following method:
function Calendar(element, options, eventSources) {
...
var date = new Date();
...
}
to:
function Calendar(element, options, eventSources) {
...
var date = options.defaultDate ? options.defaultDate : new Date();
...
}
This worked for me:
static void ClearLine(){
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
This works fine on iOS 9 - 11.
Haven't tested on earlier versions.
[NSURL URLWithString:@"https://itunes.apple.com/app/idXXXXXXXXXX?action=write-review"];
As rcs stated, cex
will do the job in base graphics package. I reckon that you're not willing to do your graph in ggplot2
but if you do, there's a size
aesthetic attribute, that you can easily control (ggplot2
has user-friendly function arguments: instead of typing cex
(character expansion), in ggplot2
you can type e.g. size = 2
and you'll get 2mm point).
Here's the example:
### base graphics ###
plot(mpg ~ hp, data = mtcars, pch = 16, cex = .9)
### ggplot2 ###
# with qplot()
qplot(mpg, hp, data = mtcars, size = I(2))
# or with ggplot() + geom_point()
ggplot(mtcars, aes(mpg, hp), size = 2) + geom_point()
# or another solution:
ggplot(mtcars, aes(mpg, hp)) + geom_point(size = 2)
code for radio button -
<div>
<span class="radio inline" style="margin-right: 10px;">@Html.RadioButton("Gender", "Female",false) Female</span>
<span class="radio inline" style="margin-right: 10px;">@Html.RadioButton("Gender", "Male",false) Male</span>
<div class='GenderValidation' style="color:#ee8929;"></div>
</div>
<input class="btn btn-primary" type="submit" value="Create" id="create"/>
and jQuery code-
<script>
$(document).ready(function () {
$('#create').click(function(){
var gender=$('#Gender').val();
if ($("#Gender:checked").length == 0){
$('.GenderValidation').text("Gender is required.");
return false;
}
});
});
</script>
package com.json;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJSONFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/My Workspace/JSON Test/file.json"));
JSONArray array = (JSONArray) obj;
JSONObject jsonObject = (JSONObject) array.get(0);
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Navbars are built with flexbox! Instead of floats, you’ll need flexbox and margin utilities.
For Align Right use justify-content-end
on the collapse
div:
<div class="collapse navbar-collapse justify-content-end">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
</ul>
</div>
Full example here: https://jsbin.com/kemawa/edit?output
I think the closest to the OP's intuition is an inline if statement:
df['que'] = (df['one'] if ((df['one'] >= df['two']) and (df['one'] <= df['three']))
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
To just get the list of the changed files with the paths, use
svn diff --summarize -r<rev-of-commit>:<rev-of-commit - 1>
For example:
svn diff --summarize -r42:41
should result in something like
M path/to/modifiedfile
A path/to/newfile
My solution is:
-vm
D:/work/Java/jdk1.6.0_13/bin/javaw.exe
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-framework
plugins\org.eclipse.osgi_3.4.3.R34x_v20081215-1030.jar
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, STUFF((
SELECT ',' + T.maskdetail
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH('')), 1, 1, '') as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by A.maskid
, A.maskname
, A.schoolid
, B.schoolname
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Util {
public static Timestamp convertStringToTimestamp(String strDate) {
try {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
// you can change format of date
Date date = formatter.parse(strDate);
Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
}
}
It's easier if you get these values into a list of tuples. To do this, you can use list slicing and the zip function.
data_in = [2010,2,2009,4,1989,8,2009,7]
data_pairs = zip(data_in[::2],data_in[1::2])
Zip takes an arbitrary number of lists, in this case the even and odd entries of data_in
, and puts them together into a tuple.
Now we can use the setdefault
method.
data_dict = {}
for x in data_pairs:
data_dict.setdefault(x[0],[]).append(x[1])
setdefault
takes a key and a default value, and returns either associated value, or if there is no current value, the default value. In this case, we will either get an empty or populated list, which we then append the current value to.
In Rails 4(Using HAML):
=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'
include
folder where you have installed
Codeblocks. int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
in that line.Just use a MaterialButton and the app:backgroundTint and android:textColor attributes:
<MaterialButton
app:backgroundTint="@color/my_color"
android:textColor="@android:color/white"/>
Here is a way to add Parameters to the script if you used
pipeline.Commands.AddScript(Script);
This is with using an HashMap as paramaters the key being the name of the variable in the script and the value is the value of the variable.
pipeline.Commands.AddScript(script));
FillVariables(pipeline, scriptParameter);
Collection<PSObject> results = pipeline.Invoke();
And the fill variable method is:
private static void FillVariables(Pipeline pipeline, Hashtable scriptParameters)
{
// Add additional variables to PowerShell
if (scriptParameters != null)
{
foreach (DictionaryEntry entry in scriptParameters)
{
CommandParameter Param = new CommandParameter(entry.Key as String, entry.Value);
pipeline.Commands[0].Parameters.Add(Param);
}
}
}
this way you can easily add multiple parameters to a script. I've also noticed that if you want to get a value from a variable in you script like so:
Object resultcollection = runspace.SessionStateProxy.GetVariable("results");
//results being the name of the v
you'll have to do it the way I showed because for some reason if you do it the way Kosi2801 suggests the script variables list doesn't get filled with your own variables.
I found this:
// Remove tag bottom and top margins
$tagvs = array( 'p' => array(
0 => array('h' => 0, 'n' => 0),
1 => array('h' => 0, 'n' => 0)
)
);
$pdf->setHtmlVSpace($tagvs);
in here: https://tcpdf.org/examples/example_061/
Use it to remove 'p' tags properties (bottom and top), then position the 'p' text inside a cell.
I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?
If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.
Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.
i think the problem is that there is no data in the success-function because the request breaks up with an 401 error in your case and thus has no success.
if you use
$.ajax({
url: "https://app.asana.com/-/api/0.1/workspaces/",
type: 'GET',
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
there will be your 401 code i think (this link says so)
Depending on the sort order, you can do this :
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i2.CompareTo(i1)
));
... or this :
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i1.CompareTo(i2)
));
i1 and i2 are just reversed.
You can pass data as the third argument to call()
. Or, depending on your API, it's possible you may want to use the sixth parameter.
From the docs:
$this->call($method, $uri, $parameters, $files, $server, $content);
you can access the children of a vuejs component with this.$children
. if you want to use the query selector on the current component instance then this.$el.querySelector(...)
just doing a simple console.log(this)
will show you all the properties of a vue component instance.
additionally if you know the element you want to access in your component, you can add the v-el:uniquename
directive to it and access it via this.$els.uniquename
The reason that you get the 404 File Not Found
error, is that your path to CSS given as a value to the href
attribute is missing context path.
An HTTP request URL contains the following parts:
http://[host]:[port][request-path]?[query-string]
The request path is further composed of the following elements:
Context path: A concatenation of a forward slash (/) with the context
root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]
Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
Path info: The part of the request path that is not part of the context path or the servlet path.
Read more here.
There are several solutions to your problem, here are some of them:
<c:url>
tag from JSTLIn my Java web applications I usually used <c:url>
tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).
If you say, that your CSS is located inside WebContent folder, then this should work:
<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />
The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):
7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.
NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.
An alternative solution is using Expression Language (EL) to add application context:
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />
Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.
<c:set>
tag from JSTLDISCLAIMER
The idea of this solution was taken from here.
To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set>
tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />
IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />
), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.
The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.
We need a class that implements ServletContextListener interface. Here is an example of such class:
package com.example.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
sc.setAttribute("ctx", sc.getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {}
}
Now in a JSP we can access this global variable using EL:
<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />
NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
...
<listener>
<listener-class>com.example.listener.AppContextListener</listener-class>
</listener>
...
</webapp>
As suggested by user @gavenkoa you can also use scriptlets like this:
<%= request.getContextPath() %>
For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.
I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.
You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.
I also ran into this problem. My situation was a little different. I was using 'working sets' to group my projects inside of eclipse. What I had done was attempt to delete a project and received errors while deleting. Ignoring the errors I removed the project from my working set and thus didn't see that I even had the project anymore. When I received my error I didn't think to look through my package explorer with 'projects', opposed to working sets, as my top view. After switching to a top level view of projects I found the project that was half deleted and was able to delete its contents from both my workspace and the hard drive.
I haven't had the error since.
Inline code takes higher precedence than the other ones. To call your other function func () call it from the f1 ().
Inside your function, add a line,
function fun () {
// Your code here
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
fun ();
}
Rewriting your whole code,
<!DOCTYPE html>
<html>
<head>
<script>
function fun()
{
alert("hello");
//validation code to see State field is mandatory.
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
fun ();
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
State: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
</form>
<table><tr><td id="Save" onclick="f1()">click</td></tr></table>
</body>
</html>
I, too, have this problem on an older Mac that I upgraded to Lion.
Before reading the terminfo tip, I was able to get vi and less working by doing "export TERM=xterm".
After reading the tip, I grabbed /usr/share/terminfo
from a newer Mac that has fresh install of Lion and does not exhibit this problem.
Now, even though echo $TERM
still yields xterm-256color
, vi and less now work fine.
This should do it:
sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *
it will replace all occurrences of "deletethis" with "" (nothing) in all files (*
), editing them in place.
In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".
The third form is the way some versions of sed
like it. (e.g. Mac OS X)
man sed
for more information.
I had a similar problem. My data is provided by a remote server. I want some value to be entered in the selectize box, but it is not sure in advance whether this value is a valid one on the server.
So I want the value to be entered in the box, and I want selectize to show the possible options just if like the user had entered the value.
I ended up using this hack (which it is probably unsupported):
var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();
Use the title
attribute while alt
is important for SEO stuff.
sys.path returns the list of paths
sys.path
A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
import sys
dirs=sys.path
for path in dirs:
print(path)
or you can print only first path by
print(dir[0])
Just remove the obsolete gems from your Gemfile. If you're talking about Heroku (you didn't mention that) then the slug is compiled each new release, just using the current contents of that file.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#suburb").blur(function() {
if ($(this).val() != '')
$("#post_code").attr("disabled", "disabled");
else
$("#post_code").removeAttr("disabled");
});
$("#post_code").blur(function() {
if ($(this).val() != '')
$("#suburb").attr("disabled", "disabled");
else
$("#suburb").removeAttr("disabled");
});
});
</script>
You'll also need to add a value attribute to the first option under your select element:
<option value=""></option>
You get a fully functional binary without sources.
Native modules also supported. (must be placed in the same folder)
JavaScript code is transformed into native code at compile-time using V8 internal compiler. Hence, your sources are not required to execute the binary, and they are not packaged.
Perfectly optimized native code can be generated only at run-time based on the client's machine. Without that info EncloseJS can generate only "unoptimized" code. It runs about 2x slower than NodeJS.
Also, node.js runtime code is put inside the executable (along with your code) to support node API for your application at run-time.
Use cases:
I think the following code is more pythonic:
from hashlib import md5
def get_md5(fname):
m = md5()
with open(fname, 'rb') as fp:
for chunk in fp:
m.update(chunk)
return m.hexdigest()
<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />
Excellent tool for cross-browser favicon - http://www.convertico.com/
From the spring docs
Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.
The <context-param>
:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
You can then use the WebApplicationContext to get a handle on your beans.
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");
See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info
Theory
String[]
can be cast to Object[]
but
List<String>
cannot be cast to List<Object>
.
Practice
For lists it is more subtle than that, because at compile time the type of a List parameter passed to a method is not checked. The method definition might as well say List<?>
- from the compiler's point of view it is equivalent. This is why the OP's example #2 gives runtime errors not compile errors.
If you handle a List<Object>
parameter passed to a method carefully so you don't force a type check on any element of the list, then you can have your method defined using List<Object>
but in fact accept a List<String>
parameter from the calling code.
A. So this code will not give compile or runtime errors and will actually (and maybe surprisingly?) work:
public static void main(String[] args) {
List argsList = new ArrayList<String>();
argsList.addAll(Arrays.asList(args));
test(argsList); // The object passed here is a List<String>
}
public static void test(List<Object> set) {
List<Object> params = new ArrayList<>(); // This is a List<Object>
params.addAll(set); // Each String in set can be added to List<Object>
params.add(new Long(2)); // A Long can be added to List<Object>
System.out.println(params);
}
B. This code will give a runtime error:
public static void main(String[] args) {
List argsList = new ArrayList<String>();
argsList.addAll(Arrays.asList(args));
test1(argsList);
test2(argsList);
}
public static void test1(List<Object> set) {
List<Object> params = set; // Surprise! Runtime error
}
public static void test2(List<Object> set) {
set.add(new Long(2)); // Also a runtime error
}
C. This code will give a runtime error (java.lang.ArrayStoreException: java.util.Collections$UnmodifiableRandomAccessList Object[]
):
public static void main(String[] args) {
test(args);
}
public static void test(Object[] set) {
Object[] params = set; // This is OK even at runtime
params[0] = new Long(2); // Surprise! Runtime error
}
In B, the parameter set
is not a typed List
at compile time: the compiler sees it as List<?>
. There is a runtime error because at runtime, set
becomes the actual object passed from main()
, and that is a List<String>
. A List<String>
cannot be cast to List<Object>
.
In C, the parameter set
requires an Object[]
. There is no compile error and no runtime error when it is called with a String[]
object as the parameter. That's because String[]
casts to Object[]
. But the actual object received by test()
remains a String[]
, it didn't change. So the params
object also becomes a String[]
. And element 0 of a String[]
cannot be assigned to a Long
!
(Hopefully I have everything right here, if my reasoning is wrong I'm sure the community will tell me. UPDATED: I have updated the code in example A so that it actually compiles, while still showing the point made.)
Here you go with:
from b in _dbContext.Burden
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }
Just to add on to the other answers, before i knew my way around git, i was looking for some way to upload existing code to a new github (or other git) repo. Here's the brief that would save time for newbs:-
Assuming you have your NEW empty github or other git repo ready:-
cd "/your/repo/dir"
git clone https://github.com/user_AKA_you/repoName # (creates /your/repo/dir/repoName)
cp "/all/your/existing/code/*" "/your/repo/dir/repoName/"
git add -A
git commit -m "initial commit"
git push origin master
Alternatively if you have an existing local git repo
cd "/your/repo/dir/repoName"
#add your remote github or other git repo
git remote set-url origin https://github.com/user_AKA_you/your_repoName
git commit -m "new origin commit"
git push origin master
In this code you access to root
directory project:
string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
then:
StreamReader r = new StreamReader(_filePath + "/cities2.json"))
In Kotlin will be :
activity?.applicationContext?.let {
it//<- you context
}
public static byte[] hexToBin(String str)
{
int len = str.length();
byte[] out = new byte[len / 2];
int endIndx;
for (int i = 0; i < len; i = i + 2)
{
endIndx = i + 2;
if (endIndx > len)
endIndx = len - 1;
out[i / 2] = (byte) Integer.parseInt(str.substring(i, endIndx), 16);
}
return out;
}
shift
spaces.Restrictions:
Pseudocode:
Function:
String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
How to invoke it:
System.out.println(cipher("abc", 3)); //prints def
System.out.println(cipher("xyz", 3)); //prints abc
For anyone interested: if you are using Intellj, just simply put hibernate.cfg.xml
under src/main/resources
.
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash
value in it's name. So problem is this HASH
is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4
here 6AB17FE4
is the hash value(8 bit). So I am referring a single script which will be fruitful to all
DECLARE @Command NVARCHAR(MAX)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'ProcedureAlerts'
set @col_name = N'EmailSent'
select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name) + ']'
--print @Command
exec sp_executesql @Command
It will drop your default constraint. However if you want to create it again you can simply try this
ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
Finally, just simply run a DROP
command to drop the column.
Try this one:
First set up tab order.
Then in form load event we can send a tab key press programmatically to application. So that application will give focus to 1st contol in the tab order.
in form load even write this line.
SendKeys.Send("{TAB}");
This did work for me.
I think for readability and speed @oxrock's solution is the best, so here is the code rewritten for python 3+:
def num_factors(n):
results = set()
for i in range(1, int(n**0.5) + 1):
if n % i == 0: results.update([i,int(n/i)])
return results
You could try https://hacss.io:
<a href="http://www.google.com" class=":hover{text-decoration:none;}">Google</a>
UPDATE
syntax is wrongWHERE
clause to target your specific rowChange
UPDATE `access_users`
(`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)
VALUES (:firstname, :surname, :telephone, :email)
to
UPDATE `access_users`
SET `contact_first_name` = :firstname,
`contact_surname` = :surname,
`contact_email` = :email,
`telephone` = :telephone
WHERE `user_id` = :user_id -- you probably have some sort of id
You need to change from queue import Queue
to from multiprocessing import Queue
.
The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.
For details, you can read some source code or contact me!
Use bind_rows()
from the dplyr package:
bind_rows(list_of_dataframes, .id = "column_label")
Considering the case that windows users prefer working on CRLF
and linux/mac users prefer working on LF
on text files. Providing the answer from the perspective of a repository maintainer:
For me the best strategy(less problems to solve) is: keep all text files with LF
inside git repo even if you are working on a windows-only project. Then give the freedom to clients to work on the line-ending style of their preference, provided that they pick a core.autocrlf
property value that will respect your strategy (LF on repo) while staging files for commit.
Staging is what many people confuse when trying to understand how newline strategies work. It is essential to undestand the following points before picking the correct value for core.autocrlf
property:
.git/
sub-directory with converted line-endings (depending on core.autocrlf
value on your client config). All this is done locally. core.autocrlf
is like providing an answer to the question (exact same question on all OS):
false:
"do none of the above", input:
"do only b"true
: "do a and and b"Fortunately
core.autocrlf: true
, linux/mac:
core.autocrlf: false
) will be compatible with LF-only-repo strategy.Unfortunately:
core.autocrlf
valuecore.autocrlf=false
and add a file with CRLF for commit.To detect ASAP non-lf text files committed by the above clients you can follow what is described on --- update 2 ---: (git grep -I --files-with-matches --perl-regexp '\r' HEAD
, on a client compiled using: --with-libpcre
flag)
And here is the catch:. I as a repo maintainer keep a git.autocrlf=input
so that I can fix any wrongly committed files just by adding them again for commit. And I provide a commit text: "Fixing wrongly committed files".
As far as .gitattributes
is concearned. I do not count on it, because there are more ui clients that do not understand it. I only use it to provide hints for text and binary files, and maybe flag some exceptional files that should everywhere keep the same line-endings:
*.java text !eol # Don't do auto-detection. Treat as text (don't set any eol rule. use client's)
*.jpg -text # Don't do auto-detection. Treat as binary
*.sh text eol=lf # Don't do auto-detection. Treat as text. Checkout and add with eol=lf
*.bat text eol=crlf # Treat as text. Checkout and add with eol=crlf
Answer: To avoid a single letter change commit, appear as a 5000-line change, just because the client that performed the change auto-converted the full file from crlf to lf (or the opposite) before adding it for commit. This can be rather painful when there is a conflict resolution involved. Or it could in some cases be the cause of unreasonable conflicts.
The dafaults of git client will work in most cases. Even if you only have windows only clients, linux only clients or both. These are:
core.autocrlf=true
means convert lines to CRLF on checkout and convert lines to LF when adding files.core.autocrlf=input
means don't convert lines on checkout (no need to since files are expected to be committed with LF) and convert lines to LF (if needed) when adding files.
(-- update3 -- : Seems that this is false
by default, but again it is fine)The property can be set in different scopes. I would suggest explicitly setting in the --global
scope, to avoid some IDE issues described at the end.
git config core.autocrlf
git config --global core.autocrlf
git config --system core.autocrlf
git config --local core.autocrlf
git config --show-origin core.autocrlf
Also I would strongly discourage using on windows git config --global core.autocrlf false
(in case you have windows only clients) in contrast to what is proposed to git documentation. Setting to false will commit files with CRLF in the repo. But there is really no reason. You never know whether you will need to share the project with linux users. Plus it's one extra step for each client that joins the project instead of using defaults.
Now for some special cases of files (e.g. *.bat
*.sh
) which you want them to be checked-out with LF or with CRLF you can use .gitattributes
To sum-up for me the best practice is:
git grep -I --files-with-matches --perl-regexp '\r' HEAD
(Note: on windows clients works only through git-bash
and on linux clients only if compiled using --with-libpcre
in ./configure
). core.autocrlf=input
(--- update 3 --).gitattributes
core.autocrlf
described above to its default values..gitattributes
. git-clients of IDEs may ignore them or treat them differrently.As said some things can be added in git attributes:
# Always checkout with LF
*.sh text eol=lf
# Always checkout with CRLF
*.bat text eol=crlf
I think some other safe options for .gitattributes
instead of using auto-detection for binary files:
-text
(e.g for *.zip
or *.jpg
files: Will not be treated as text. Thus no line-ending conversions will be attempted. Diff might be possible through conversion programs)text !eol
(e.g. for *.java
,*.html
: Treated as text, but eol style preference is not set. So client setting is used.)-text -diff -merge
(e.g for *.hugefile
: Not treated as text. No diff/merge possible)One painful example of a client that will commit files wrongly:
netbeans 8.2 (on windows), will wrongly commit all text files with CRLFs, unless you have explicitly set core.autocrlf
as global. This contradicts to the standard git client behaviour, and causes lots of problems later, while updating/merging. This is what makes some files appear different (although they are not) even when you revert.
The same behaviour in netbeans happens even if you have added correct .gitattributes
to your project.
Using the following command after a commit, will at least help you detect early whether your git repo has line ending issues: git grep -I --files-with-matches --perl-regexp '\r' HEAD
I have spent hours to come up with the best possible use of .gitattributes
, to finally realize, that I cannot count on it.
Unfortunately, as long as JGit-based editors exist (which cannot handle .gitattributes
correctly), the safe solution is to force LF everywhere even on editor-level.
Use the following anti-CRLF
disinfectants.
windows/linux clients: core.autocrlf=input
committed .gitattributes
: * text=auto eol=lf
committed .editorconfig
(http://editorconfig.org/) which is kind of standardized format, combined with editor plugins:
This issue was due to lack of database. If it is a fresh installation, you need to manually create one and assign user with privileges.
Please check in wp-config.php for any bad configurations and make sure that database and tables are not missing or corrupted.
An Outlet is a link from code to UI. If you want to show or hide an UI element, if you want to get the text of a textfield or enable or disable an element (or a hundred other things) you have to define an outlet of that object in the sources and link that outlet through the “interface object” to the UI element. After that you can use the outlet just like any other variable in your coding.
IBAction – a special method triggered by user-interface objects. Interface Builder recognizes them.
@interface Controller
{
IBOutlet id textField; // links to TextField UI object
}
- (IBAction)doAction:(id)sender; // e.g. called when button pushed
For further information please refer Apple Docs
As the accepted answer requires you to add a Frame Layout, here how you can do it with material design.
Add this if you haven't already
implementation 'com.google.android.material:material:1.0.0'
Now change to Cardview to MaterialCardView
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp"
app:strokeWidth="1dp"
app:strokeColor="@color/black">
Now you need to change the activity theme to Theme.Material. If you are using Theme.Appcompact I will suggest you to move to Theme.Material for future projects for having better material design in you app.
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
Check out this link : http://webdesignerwall.com/tutorials/css-specific-for-internet-explorer
Another option is to declare CSS rules that can only be read by Explorer. For example, add an asterisk (*) before the CSS property will target IE7 or add an underscore before the property will target IE6. However, this method is not recommended because they are not valid CSS syntax.
IE8 or below: to write CSS rules specificially to IE8 or below, add a backslash and 9 (\9) at the end before the semicolon. IE7 or below: add an asterisk (*) before the CSS property. IE6: add an underscore (_) before the property. .box {
background: gray; /* standard */
background: pink\9; /* IE 8 and below */
*background: green; /* IE 7 and below */
_background: blue; /* IE 6 */
}
You can accomplish this using the mysqldump command-line function.
For example:
If it's an entire DB, then:
$ mysqldump -u [uname] -p db_name > db_backup.sql
If it's all DBs, then:
$ mysqldump -u [uname] -p --all-databases > all_db_backup.sql
If it's specific tables within a DB, then:
$ mysqldump -u [uname] -p db_name table1 table2 > table_backup.sql
You can even go as far as auto-compressing the output using gzip (if your DB is very big):
$ mysqldump -u [uname] -p db_name | gzip > db_backup.sql.gz
If you want to do this remotely and you have the access to the server in question, then the following would work (presuming the MySQL server is on port 3306):
$ mysqldump -P 3306 -h [ip_address] -u [uname] -p db_name > db_backup.sql
It should drop the .sql
file in the folder you run the command-line from.
EDIT: Updated to avoid inclusion of passwords in CLI commands, use the -p
option without the password. It will prompt you for it and not record it.
Omar's third solution as an HTML Helper would be:
public static IHtmlString FormatNewLines(this HtmlHelper helper, string input)
{
return helper.Raw(helper.Encode(input).Replace("\n", "<br />"));
}
This is not another code as you have already helped yourself; but for you to take a look at the performance when using Excel functions in VBA.
PS:
**On a latter note, if you wish to do pattern matching
then you may consider ScriptingObject **Regex
.
You need to login to your mysql terminal first using
mysql -u username -p password
Then use this:
SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;
output will be like this:
STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB
You can also set sql mode by this:
SET GLOBAL sql_mode=TRADITIONAL;
In Eclipse goto Run->Run Configuration find the Name of the class you have been running, select it, click the Target tab then in "Additional Emulator Command Line Options" add:
-Xms512M -Xmx1524M
then click apply.
There's a couple of ways to accomplish this decently efficiently.
First -
If possible, you can do some sort of bulk insert to a temporary table. This depends somewhat on your RDBMS/host language, but at worst this can be accomplished with a simple dynamic SQL (using a VALUES()
clause), and then a standard update-from-another-table. Most systems provide utilities for bulk load, though
Second -
And this is somewhat RDBMS dependent as well, you could construct a dynamic update statement. In this case, where the VALUES(...)
clause inside the CTE has been created on-the-fly:
WITH Tmp(id, px, py) AS (VALUES(id1, newsPosX1, newPosY1),
(id2, newsPosX2, newPosY2),
......................... ,
(idN, newsPosXN, newPosYN))
UPDATE TableToUpdate SET posX = (SELECT px
FROM Tmp
WHERE TableToUpdate.id = Tmp.id),
posY = (SELECT py
FROM Tmp
WHERE TableToUpdate.id = Tmp.id)
WHERE id IN (SELECT id
FROM Tmp)
(According to the documentation, this should be valid SQLite syntax, but I can't get it to work in a fiddle)
DateTime dt = new DateTime(laterDate);
DateTime newDate = dt.minus( new DateTime ( previousDate ).getMillis());
System.out.println("No of days : " + newDate.getDayOfYear() - 1 );
As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
now exists.
dateID is int column contains date in Int format
spark.sql("SELECT from_unixtime(unix_timestamp(cast(dateid as varchar(10)), 'yyyymmdd'), 'yyyy-mm-dd') from XYZ").show(50, false)
Use the SQLCMD utility.
http://technet.microsoft.com/en-us/library/ms162773.aspx
There is a connect statement that allows you to swing from database server A to server B in the same batch.
:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]] Connects to an instance of SQL Server. Also closes the current connection.
On the other hand, if you are familiar with PowerShell, you can programmatic do the same.
http://technet.microsoft.com/en-us/library/cc281954(v=sql.105).aspx
In my case the none of the answers above worked! since I had different productFlavors just adding repositories{
flatDir{
dirs 'libs'
}
}
did not work! I ended up with specifying exact location of libs directory:
repositories{
flatDir{
dirs 'src/main/libs'
}
}
Guess one should introduce flatDirs like this when there's different productFlavors in build.gradle
onStart()
means Activity
entered into visible state and layout is created but can't interact with this activity layout.
Resume()
means now you can do interaction with activity layout.
this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)
DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
*/
DECLARE NAME_FOUND VARCHAR DEFAULT "";
SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
RETURN NAME_FOUND;
END;//
Since C-style strings are always terminated with the null character (\0
), you can check whether the string is empty by writing
do {
...
} while (url[0] != '\0');
Alternatively, you could use the strcmp
function, which is overkill but might be easier to read:
do {
...
} while (strcmp(url, ""));
Note that strcmp
returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is nonempty.
Hope this helps!
A new byte array will automatically be initialized with all zeroes. You don't have to do anything.
The more general approach to initializing with other values, is to use the Arrays
class.
import java.util.Arrays;
byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );
Now emojis are supported! :white_check_mark:
/ :heavy_check_mark:
gives a good impression and is widely supported:
Function | MySQL / MariaDB | PostgreSQL | SQLite
:------------ | :-------------| :-------------| :-------------
substr | :heavy_check_mark: | :white_check_mark: | :heavy_check_mark:
renders to (here on older chromium 65.0.3x) :
From the documentation
Note that
filter(function, iterable)
is equivalent to[item for item in iterable if function(item)]
In python3, rather than returning a list; filter, map return an iterable. Your attempt should work on python2 but not in python3
Clearly, you are getting a filter object, make it a list.
shesaid = list(filter(greetings(), ["hello", "goodbye"]))
silly way:
onclick="javascript:CapacityChart();"
You should read about discrete javascript, and use a frameworks bind method to bind callbacks to dom events.
Simply delete that column using: del df['column_name']
Lookup move /?
on Windows and man mv
on Unix systems
This cannot be done with CMake. You have to generate two separate build folders. One for the x86 NMake build and one for the x64 NMake build. You cannot generate a single Visual Studio project covering both architectures with CMake, either.
To build Visual Studio projects from the command line for both 32-bit and 64-bit without starting a Visual Studio command prompt, use the regular Visual Studio generators.
For CMake 3.13 or newer, run the following commands:
cmake -G "Visual Studio 16 2019" -A Win32 -S \path_to_source\ -B "build32"
cmake -G "Visual Studio 16 2019" -A x64 -S \path_to_source\ -B "build64"
cmake --build build32 --config Release
cmake --build build64 --config Release
For earlier versions of CMake, run the following commands:
mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" \path_to_source\
popd
mkdir build64 & pushd build64
cmake -G "Visual Studio 15 2017 Win64" \path_to_source\
popd
cmake --build build32 --config Release
cmake --build build64 --config Release
CMake generated projects that use one of the Visual Studio generators can be built from the command line with using the option --build
followed by the build directory. The --config
option specifies the build configuration.
I guess this thread is getting old but I can't believe nobody has mentioned Math.Floor
//will always be .02 cents
(10.02m - System.Math.Floor(10.02m))
Here is my function to draw multiple lines of text center in canvas (only break the line, don't break-word)
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
let text = "Hello World \n Hello World 2222 \n AAAAA \n thisisaveryveryveryveryveryverylongword. "
ctx.font = "20px Arial";
fillTextCenter(ctx, text, 0, 0, c.width, c.height)
function fillTextCenter(ctx, text, x, y, width, height) {
ctx.textBaseline = 'middle';
ctx.textAlign = "center";
const lines = text.match(/[^\r\n]+/g);
for(let i = 0; i < lines.length; i++) {
let xL = (width - x) / 2
let yL = y + (height / (lines.length + 1)) * (i+1)
ctx.fillText(lines[i], xL, yL)
}
}
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>
_x000D_
If you want to fit text size to canvas, you can also check here
Unless you have a special situation that requires a non thread-pool thread, just use a thread pool thread like this:
Action secondFooAsync = new Action(SecondFoo);
secondFooAsync.BeginInvoke(new AsyncCallback(result =>
{
(result.AsyncState as Action).EndInvoke(result);
}), secondFooAsync);
Gaurantees that EndInvoke is called to take care of the clean up for you.
C has 'for' and 'while' keywords. If a foreach statement in a language like C# looks like this ...
foreach (Element element in collection)
{
}
... then the equivalent of this foreach statement in C might be be like:
for (
Element* element = GetFirstElement(&collection);
element != 0;
element = GetNextElement(&collection, element)
)
{
//TODO: do something with this element instance ...
}
Use TO_CHAR
function.
select TO_CHAR(BLOB_FIELD) from TABLE_WITH_BLOB where ID = '<row id>'
Converts NCHAR
, NVARCHAR2
, CLOB
, or NCLOB
data to the database character set. The value returned is always VARCHAR2
.
In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.
Working with cursors consists of several steps:
Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]
You can get the maximum like this:
>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]]
A B
0 1 -2
1 2 8
2 3 1
>>> df[["A", "B"]].max(axis=1)
0 1
1 8
2 3
and so:
>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If you know that "A" and "B" are the only columns, you could even get away with
>>> df["C"] = df.max(axis=1)
And you could use .apply(max, axis=1)
too, I guess.
I know this is old, but this hung me up for awhile. The properties of the object in your list must be actual "properties", not just public members.
public class FileName
{
public string ThisFieldWorks {get;set;}
public string ThisFieldDoesNot;
}
CREATE LOGIN AdminLOGIN WITH PASSWORD = 'pass'
GO
Use MyDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AdminLOGIN')
BEGIN
CREATE USER [AdminLOGIN] FOR LOGIN [AdminLOGIN]
EXEC sp_addrolemember N'db_owner', N'AdminLOGIN'
EXEC master..sp_addsrvrolemember @loginame = N'adminlogin', @rolename = N'sysadmin'
END;
GO
this full help you for network using:
1- Right-click on SQL Server instance at root of Object Explorer, click on Properties
Select Security from the left pane.
2- Select the SQL Server and Windows Authentication mode radio button, and click OK.
3- Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).
4- Close sql server application and reopen it
5- open 'SQL Server Configuration Manager' and tcp enabled for network
6-Double-click the TCP/IP protocol, go to the IP Addresses tab and scroll down to the IPAll section.
7-Specify the 1433 in the TCP Port field (or another port if 1433 is used by another MSSQL Server) and press the OK
8-Open in Sql Server: Security And Login And Right Click on Login Name And Select Peroperties And Select Server Roles And
Checked The Sysadmin And Bulkadmin then Ok.
9-firewall: Open cmd as administrator and type:
netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
You can change the name of the column, therefore instead of "COUNT(*)" you would have something meaningful. You will have to update your "RowCount.sql" script for that.
For example:
SQL> select count(*) as RecordCountFromTableOne from TableOne;
Will be displayed as:
RecordCountFromTableOne
-----------------------
0
If you want to have space in the title, you need to enclose it in double quotes
SQL> select count(*) as "Record Count From Table One" from TableOne;
Will be displayed as:
Record Count From Table One
---------------------------
0
I am using window 10 and i performed below steps to resolve this issue.
Above steps helped me to resolve the issue.
It's really surprising to me that the redirection methods in ProcessBuilder
don't accept an OutputStream
, only File
. Yet another proof of forced boilerplate code that Java forces you to write.
That said, let's look at a list of comprehensive options:
inheritIO
will do the job.redirect*(file)
.InputStream
in a separate thread. See the answers that use a Runnable
or CompletableFuture
. You can also adapt the code below to do this.PrintWriter
, that may or may not be the stdout (very useful for testing), you can do the following:static int execute(List<String> args, PrintWriter out) {
ProcessBuilder builder = new ProcessBuilder()
.command(args)
.redirectErrorStream(true);
Process process = null;
boolean complete = false;
try {
process = builder.start();
redirectOut(process.getInputStream(), out)
.orTimeout(TIMEOUT, TimeUnit.SECONDS);
complete = process.waitFor(TIMEOUT, TimeUnit.SECONDS);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException e) {
LOG.warn("Thread was interrupted", e);
} finally {
if (process != null && !complete) {
LOG.warn("Process {} didn't finish within {} seconds", args.get(0), TIMEOUT);
process = process.destroyForcibly();
}
}
return process != null ? process.exitValue() : 1;
}
private static CompletableFuture<Void> redirectOut(InputStream in, PrintWriter out) {
return CompletableFuture.runAsync(() -> {
try (
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
) {
bufferedReader.lines()
.forEach(out::println);
} catch (IOException e) {
LOG.error("Failed to redirect process output", e);
}
});
}
Advantages of the code above over the other answers thus far:
redirectErrorStream(true)
redirects the error stream to the output stream, so that we only have to bother with one.CompletableFuture.runAsync
runs from the ForkJoinPool
. Note that this code doesn't block by calling get
or join
on the CompletableFuture
but sets a timeout instead on its completion (Java 9+). There's no need for CompletableFuture.supplyAsync
because there's nothing really to return from the method redirectOut
.BufferedReader.lines
is simpler than using a while
loop.Your approach is OK
Maybe slightly clearer (to me anyway!)
UPDATE
T1
SET
[Description] = t2.[Description]
FROM
Table1 T1
JOIN
[Table2] t2 ON t2.[ID] = t1.DescriptionID
Both this and your query should run the same performance wise because it is the same query, just laid out differently.
You can use:
Sub returnname(ByVal TableName As String)
MsgBox (Range("Table15").Rows.count)
End Sub
and call the function as below
Sub called()
returnname "Table15"
End Sub
this is a good sample for understand directive phases http://codepen.io/anon/pen/oXMdBQ?editors=101
var app = angular.module('myapp', [])
app.directive('slngStylePrelink', function() {
return {
scope: {
drctvName: '@'
},
controller: function($scope) {
console.log('controller for ', $scope.drctvName);
},
compile: function(element, attr) {
console.log("compile for ", attr.name)
return {
post: function($scope, element, attr) {
console.log('post link for ', attr.name)
},
pre: function($scope, element, attr) {
$scope.element = element;
console.log('pre link for ', attr.name)
// from angular.js 1.4.1
function ngStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) {
element.css(style, '');
});
}
if (newStyles) element.css(newStyles);
}
$scope.$watch(attr.slngStylePrelink, ngStyleWatchAction, true);
// Run immediately, because the watcher's first run is async
ngStyleWatchAction($scope.$eval(attr.slngStylePrelink));
}
};
}
};
});
html
<body ng-app="myapp">
<div slng-style-prelink="{height:'500px'}" drctv-name='parent' style="border:1px solid" name="parent">
<div slng-style-prelink="{height:'50%'}" drctv-name='child' style="border:1px solid red" name='child'>
</div>
</div>
</body>
Readonly is an attribute as defined in html, so treat it like one.
You need to have something like readonly="readonly" in the object you are working with if you want it not to be editable. And if you want it to be editable again you won't have something like readonly='' (this is not standard if I understood correctly). You really need to remove the attribute as a whole.
As such, while using jquery adding it and removing it is what makes sense.
Set something readonly:
$("#someId").attr('readonly', 'readonly');
Remove readonly:
$("#someId").removeAttr('readonly');
This was the only alternative that really worked for me. Hope it helps!
The error seems not to be one of a character field, but more of a numeric one. (If it were a string problem like WW mentioned, you'd get a 'value too big' or something similar.) Probably you are using more digits than are allowed, e.g. 1,000000001 in a column defined as number (10,2).
Look at the source code as WW mentioned to figure out what column may be causing the problem. Then check the data if possible that is being used there.
Try
git add -u
The "u
" option stands for update. This will update the repo and actually delete files from the repo that you have deleted in your local copy.
git add -u [filename]
to stage a delete to just one file. Once pushed, the file will no longer be in the repo.
Alternatively,
git add -A .
is equivalent to
git add .
git add -u .
Note the extra '.' on git add -A
and git add -u
Warning: Starting with git 2.0 (mid 2013), this will always stage files on the whole working tree.
If you want to stage files under the current path of your working tree, you need to use:
git add -A .
Also see: Difference of git add -A
and git add .
You need to start creating the JAR at the root of the files.
So, for instance:
jar cvf program.jar -C path/to/classes .
That assumes that path/to/classes
contains the com
directory.
FYI, these days it is relatively uncommon for most people to use the jar
command directly, as they will use a build tool such as Ant or Maven to take care of that (and other aspects of the build). It is well worth the effort of allowing one of those tools to take care of all aspects of your build, and it's even easier with a good IDE to help write the build.xml
(Ant) or pom.xml
(Maven).
Here is how a kotlin extension for showing and hiding the soft keyboard can be made:
fun View.showKeyboard() {
this.requestFocus()
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
Then you can just do this:
editText.showKeyboard()
// OR
editText.hideKeyboard()
in normal time, checkboxes return an on/off value.
you can verify it with this code:
<form action method="POST">
<input type="checkbox" name="hello"/>
</form>
<?php
if(isset($_POST['hello'])) echo('<p>'.$_POST['hello'].'</p>');
?>
this will return
<p>off</p>
or
<p>on</p>
It works with option value:
from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@class='class_name']/option[@value='option_value']").click()
I had similar problem and i solved it following way.
Solve as follows:
Function prototype declarations and global variable should be in test.h file and you can not initialize global variable in header file.
Function definition and use of global variable in test.c file
if you initialize global variables in header it will have following error
multiple definition of `_ test'| obj\Debug\main.o:path\test.c|1|first defined here|
Just declarations of global variables in Header file no initialization should work.
Hope it helps
Cheers
Text inside an ifdef/endif
or ifndef/endif
pair will be left in or removed by the pre-processor depending on the condition. ifdef
means "if the following is defined" while ifndef
means "if the following is not defined".
So:
#define one 0
#ifdef one
printf("one is defined ");
#endif
#ifndef one
printf("one is not defined ");
#endif
is equivalent to:
printf("one is defined ");
since one
is defined so the ifdef
is true and the ifndef
is false. It doesn't matter what it's defined as. A similar (better in my opinion) piece of code to that would be:
#define one 0
#ifdef one
printf("one is defined ");
#else
printf("one is not defined ");
#endif
since that specifies the intent more clearly in this particular situation.
In your particular case, the text after the ifdef
is not removed since one
is defined. The text after the ifndef
is removed for the same reason. There will need to be two closing endif
lines at some point and the first will cause lines to start being included again, as follows:
#define one 0
+--- #ifdef one
| printf("one is defined "); // Everything in here is included.
| +- #ifndef one
| | printf("one is not defined "); // Everything in here is excluded.
| | :
| +- #endif
| : // Everything in here is included again.
+--- #endif
The answer I was searching for was answered here: How to use python argparse with args other than sys.argv?
If main.py
and parse_args()
is written in this way, then the parsing can be done nicely
# main.py
import argparse
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument('--input', default='my_input.txt')
return parser
def main(args):
print(args.input)
if __name__ == "__main__":
parser = parse_args()
args = parser.parse_args()
main(args)
Then you can call main()
and parse arguments with parser.parse_args(['--input', 'foobar.txt'])
to it in another python script:
# temp.py
from main import main, parse_args
parser = parse_args()
args = parser.parse_args([]) # note the square bracket
# to overwrite default, use parser.parse_args(['--input', 'foobar.txt'])
print(args) # Namespace(input='my_input.txt')
main(args)
Photoshop - right click layer -> blending options -> color overlay change color and save
Where is your problem??
For the stored procedure, just create:
CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
SELECT * -- I would *strongly* recommend specifying the columns EXPLICITLY
FROM dbo.Emp
WHERE ID = @EmpID
That's all there is.
From your ASP.NET application, just create a SqlConnection
and a SqlCommand
(don't forget to set the CommandType = CommandType.StoredProcedure
)
DataTable tblEmployees = new DataTable();
using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
_cmd.Parameters["@EmpID"].Value = 42;
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_dap.Fill(tblEmployees);
}
YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();
and then fill e.g. a DataTable
with that data and bind it to e.g. a GridView.
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
The error is that you cannot initialize a static const char*
within the class. You can only initialize integer variables there.
You need to declare the member variable in the class, and then initialize it outside the class:
// header file
class Foo {
static const char *SOMETHING;
// rest of class
};
// cpp file
const char *Foo::SOMETHING = "sommething";
If this seems annoying, think of it as being because the initialization can only appear in one translation unit. If it was in the class definition, that would usually be included by multiple files. Constant integers are a special case (which means the error message perhaps isn't as clear as it might be), and compilers can effectively replace uses of the variable with the integer value.
In contrast, a char*
variable points to an actual object in memory, which is required to really exist, and it's the definition (including initialization) which makes the object exist. The "one definition rule" means you therefore don't want to put it in a header, because then all translation units including that header would contain the definition. They could not be linked together, even though the string contains the same characters in both, because under current C++ rules you've defined two different objects with the same name, and that's not legal. The fact that they happen to have the same characters in them doesn't make it legal.
A similar code I once wrote to remove strings not starting with SB.1 from an array of strings
my @adoSymbols=('SB.1000','RT.10000','PC.10000');
##Remove items from an array from backward
for(my $i=$#adoSymbols;$i>=0;$i--) {
unless ($adoSymbols[$i] =~ m/^SB\.1/) {splice(@adoSymbols,$i,1);}
}
Follow these steps:
Hope it helps