I used:
pip install Pillow
and pip installed PIL in Lib\site-packages. When I moved PIL to Lib everything worked fine. I'm on Windows 10.
Two reasons, there may be more:
pip provides an uninstall
command
if an installation fails in the middle, pip will leave you in a clean state.
Here is a link to another post/thread. I was able run this script to automate registration of Python 2.7. (Make sure to run it from the Python 2.x .exe
you want to register!)
To register Python 3.x I had to modify the print
syntax and import winreg
(instead of _winreg
), then run the Python 3 .exe
.
I had the same problem and, in my case, the problem was that python was looking for packages in some ordered locations, first of all the default computer one where default old packages are.
To check what your python is looking for you can do:
>>> import sys
>>> print '\n'.join(sys.path)
This was outputting the directory '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python' before pip or brew or port folders.
The simple solution is:
export PYTHONPATH="/Library/Python/2.7/site-packages:$PYTHONPATH"
This worked well for me, I advise you to add this line to your home bash_profile file for the next time. Remember that sys.path is built using the current working directory, followed by the directories in the PYTHONPATH environment variable. Then there are the installation-dependent default dirs.
Official(?) instructions: http://peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages
If you have replaced a package with another version, then you can just delete the package(s) you don't need by deleting the PackageName-versioninfo.egg file or directory (found in the installation directory).
If you want to delete the currently installed version of a package (or all versions of a package), you should first run:
easy_install -mxN PackageName
This will ensure that Python doesn't continue to search for a package you're planning to remove. After you've done this, you can safely delete the .egg files or directories, along with any scripts you wish to remove.
That tool is part of the setuptools (now called Distribute) package. Install Distribute. Of course you'll have to fetch that one manually.
http://pypi.python.org/pypi/distribute#installation-instructions
Here is the one-liner for fedora or other rpm distros (based on @barraponto tips):
find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'
Append this to the previous command to get cleaner output:
| sed -r 's:.*/(\w+)/__.*:\1:'
If you are using windows 7 64-bit version, then the solution is found here: http://pypi.python.org/pypi/setuptools
namely, you need to download a python script, run it, and then easy_install will work normally from commandline.
P.S. I agree with the original poster saying that this should work out of the box.
I solved this issue with the following steps (on sles 11sp2)
zypper remove pip
easy_install pip=1.2.1
pip install --upgrade scons
Here are the same steps in puppet (which should work on all distros)
package { 'python-pip':
ensure => absent,
}
exec { 'python-pip':
command => '/usr/bin/easy_install pip==1.2.1',
require => Package['python-pip'],
}
package { 'scons':
ensure => latest,
provider => pip,
require => Exec['python-pip'],
}
Step 1
Install latest python updates using this command.
sudo apt-get install python-dev
Step 2
Add first dependency libxml2 version 2.7.0 or later
sudo apt-get install libxml2-dev
Step 3
Add second dependency libxslt version 1.1.23 or later
sudo apt-get install libxslt1-dev
Step 4
Install pip package management tool first. and run this command.
pip install lxml
If you have any doubt Click Here
I've had the same problem 'ImportError: No module named Crypto.Cipher'
, since using GoogleAppEngineLauncher (version > 1.8.X) with GAE Boilerplate on OSX 10.8.5 (Mountain Lion). In Google App Engine SDK with python 2.7 runtime, pyCrypto 2.6 is the suggested version.
The solution that worked for me was...
1) Download pycrypto2.6 source extract it somewhere(~/Downloads/pycrypto26
)
e.g., git clone https://github.com/dlitz/pycrypto.git
2) cd
(cd ~/Downloads/pycrypto26
) then
3) Execute the following terminal command inside the previous folder in order to install pyCrypto 2.6 manually in GAE folder.
sudo python setup.py install --install-lib /Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine
In python, Tkinter was a default package, you can repair the installation and select Tcl/Tk. When you run this, DDL should be installed like so:
I think the question makes it seem like the answer is simpler than it really is.
Running of pip will sometimes require native compilation of a module (64-bit NumPy is a common example of that). In order for pip's compilation to succeed, you need Python which was compiled with the same version of Microsoft Visual C++ as the one pip is using.
Standard Python distributions are compiled with Microsoft Visual C++ 2008. You can install an Express version of Microsoft Visual C++ 2008, but it is not maintained. Your best bet is to get an express version of a later Microsoft Visual C++ and compile Python. Then PIP and Python will be using the same Microsoft Visual C++ version.
If the package is on PYPI, download it and its dependencies to some local directory. E.g.
$ mkdir /pypi && cd /pypi $ ls -la -rw-r--r-- 1 pavel staff 237954 Apr 19 11:31 Flask-WTF-0.6.tar.gz -rw-r--r-- 1 pavel staff 389741 Feb 22 17:10 Jinja2-2.6.tar.gz -rw-r--r-- 1 pavel staff 70305 Apr 11 00:28 MySQL-python-1.2.3.tar.gz -rw-r--r-- 1 pavel staff 2597214 Apr 10 18:26 SQLAlchemy-0.7.6.tar.gz -rw-r--r-- 1 pavel staff 1108056 Feb 22 17:10 Werkzeug-0.8.2.tar.gz -rw-r--r-- 1 pavel staff 488207 Apr 10 18:26 boto-2.3.0.tar.gz -rw-r--r-- 1 pavel staff 490192 Apr 16 12:00 flask-0.9-dev-2a6c80a.tar.gz
Some packages may have to be archived into similar looking tarballs by hand. I do it a lot when I want a more recent (less stable) version of something. Some packages aren't on PYPI, so same applies to them.
Suppose you have a properly formed Python application in ~/src/myapp
. ~/src/myapp/setup.py
will have install_requires
list that mentions one or more things that you have in your /pypi
directory. Like so:
install_requires=[
'boto',
'Flask',
'Werkzeug',
# and so on
If you want to be able to run your app with all the necessary dependencies while still hacking on it, you'll do something like this:
$ cd ~/src/myapp $ python setup.py develop --always-unzip --allow-hosts=None --find-links=/pypi
This way your app will be executed straight from your source directory. You can hack on things, and then rerun the app without rebuilding anything.
If you want to install your app and its dependencies into the current python environment, you'll do something like this:
$ cd ~/src/myapp $ easy_install --always-unzip --allow-hosts=None --find-links=/pypi .
In both cases, the build will fail if one or more dependencies aren't present in /pypi
directory. It won't attempt to promiscuously install missing things from Internet.
I highly recommend to invoke setup.py develop ...
and easy_install ...
within an active virtual environment to avoid contaminating your global Python environment. It is (virtualenv that is) pretty much the way to go. Never install anything into global Python environment.
If the machine that you've built your app has same architecture as the machine on which you want to deploy it, you can simply tarball the entire virtual environment directory into which you easy_install
-ed everything. Just before tarballing though, you must make the virtual environment directory relocatable (see --relocatable option). NOTE: the destination machine needs to have the same version of Python installed, and also any C-based dependencies your app may have must be preinstalled there too (e.g. say if you depend on PIL, then libpng, libjpeg, etc must be preinstalled).
Since virtualenvs contain pip by default, I almost never install pip globally. What I do ends up looking more like:
$ sudo apt-get install python-setuptools
$ curl -O http://python-distribute.org/distribute_setup.py
$ sudo python distribute_setup.py
$ sudo easy_install virtualenv
I then proceed to install and set up virtualenvwrapper to my liking and off I go. it might also be worthwhile to take a look at Jeremy Avnet's virtualenv-burrito:
This worked for my purpose done within the Spyder Console
conda install -c anaconda pyserial
this format generally works however pymorph returned thus:
conda install -c anaconda pymorph Collecting package metadata (current_repodata.json): ...working... done Solving environment: ...working... failed with initial frozen solve. Retrying with flexible solve. Collecting package metadata (repodata.json): ...working... done Solving environment: ...working... failed with initial frozen solve. Retrying with flexible solve.
Note: you may need to restart the kernel to use updated packages.
PackagesNotFoundError: The following packages are not available from current channels:
Current channels:
To search for alternate channels that may provide the conda package you're looking for, navigate to
https://anaconda.org
and use the search bar at the top of the page.
Return the address of the thing pointed to by the iterator:
&(*iterator)
Edit: To clear up some confusion:
vector <int> vec; // a global vector of ints
void f() {
vec.push_back( 1 ); // add to the global vector
vector <int>::iterator it = vec.begin();
* it = 2; // change what was 1 to 2
int * p = &(*it); // get pointer to first element
* p = 3; // change what was 2 to 3
}
No need for vectors of pointers or dynamic allocation.
You could implement a ring buffer. Make an array of 1000 elements, and some fields to store the start and end indexes and total size. Then just store the last 1000 elements in the ring buffer, and recalculate the average as needed.
var audio = new Audio("http://rho.nu/pub/Game%20Of%20Thrones%20-%20Main%20Theme%20-%20Soundtrack.mp3");
audio.addEventListener('canplaythrough', function() {
this.currentTime = this.duration - 10;
this.loop = true;
this.play();
});
Just set loop = true in the canplaythrough eventlistener.
I use this one:
git submodule status | cut -d' ' -f3-4
Output (path + version):
tools/deploy_utils (0.2.4)
You could try using the -Clear
parameter
Example:-Clear Attribute1LDAPDisplayName, Attribute2LDAPDisplayName
There is a site called Softies on Rails that is written by a couple of ex-.NET developers that may be of some use. They have a book called Rails for .NET Developers coming out in the next few months...
I started out on a Windows box using the RadRails plugin for Eclipse and the RubyWeaver extension for Dreamweaver (back during the 1.x days of Rails). Since then I have moved to a Mac running TextMate and haven't thought of going back.
As for books, I started with The Ruby Way and Agile Web Development with Rails. It definately helps to build a background in Ruby as you start to make your way into Rails development.
Definately watch the Railscast series by Ryan Bates.
If you have more than one version of python installed, run the respective pip command.
For example for python3.6 run the following
pip3.6 install beautifulsoup4
To check the available command/version of pip and python on Mac run
ls /usr/local/bin
I took the answer above in C#/.Net, and rewrote it for Qt/C++, not to much changed, but I wanted to leave it here for anyone in the future looking for a C++'ish' answer.
bool MainWindow::isColumnExisting(QString &table, QString &columnName){
QSqlQuery q;
try {
if(q.exec("PRAGMA table_info("+ table +")"))
while (q.next()) {
QString name = q.value("name").toString();
if (columnName.toLower() == name.toLower())
return true;
}
} catch(exception){
return false;
}
return false;
}
Emacs takes many launch options. The one that you are looking for is
emacs -nw
. This will open Emacs inside the terminal disregarding the DISPLAY environment variable even if it is set.
The long form of this flag is emacs --no-window-system
.
More information about Emacs launch options can be found in the manual.
<script type="text/javascript">
var isChrome = /Chrome/.test(navigator.userAgent) && /Google
Inc/.test(navigator.vendor);
var isFirefox =
navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if (isChrome)
{
document.write('<'+'link rel="stylesheet"
href="css/chrome.css" />');
}
else if(isFirefox)
{
document.write('<'+'link rel="stylesheet"
href="css/Firefox.css" />');
}
else
{
document.write('<'+'link rel="stylesheet"
href="css/IE.css" />');
}
</script>
This works perfect for IE,Firefox and Chrome.
In order to make it work
You need to modify the value of the environment variable with the name key Path
, you can add as many paths as you want separating them with ;
. The paths you give to it can't include the name of the executable file.
If you add a path to the variable Path
all the excecutable files inside it can be called from cmd or porweshell by writing their name without .exe
and these names are not case sensitive.
Here is how to create a system environment variable from a python script:
It is important to run it with administrator privileges in order to make it work. To better understand the code, just read the comments on it.
Tested on Windows 10
import winreg
# Create environment variable for call the program from shell, only works with compiled version
def environment_var(AppPath):
# Point to the registry key of the system environment variables
key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control\Session Manager\Environment')
def add_var(path):
# Add the variable
winreg.SetValueEx(key, 'Path', 0, winreg.REG_SZ, path)
winreg.CloseKey(key)
try:
# Try to get the value of the Path variable
allPaths = winreg.QueryValueEx(key, 'Path')[0]
except Exception:
# Create the Path variable if it doesn't exist
add_var(path=AppPath)
return
# Get all the values of the existing paths
Path=allPaths.split(';')
# If the Path is empty, add the application path
if Path == ['']:
add_var(path=AppPath)
return
# Check if the application path is in the Path variable
if AppPath not in Path:
# Add the application path to the Path environment variable and add keep the others existing paths
add_var(path=AppPath+';'+allPaths)
# Only run this if the module is not imported by another
if __name__ == "__main__":
# Run the function
environment_var(AppPath=".")
You can find more information in the winreg documentation
git commit -a -m "Your commit message here"
will quickly commit all changes with the commit message. Git commit "title" and "description" (as you call them) are nothing more than just the first line, and the rest of the lines in the commit message, usually separated by a blank line, by convention. So using this command will just commit the "title" and no description.
If you want to commit a longer message, you can do that, but it depends on which shell you use.
In bash the quick way would be:
git commit -a -m $'Commit title\n\nRest of commit message...'
There are some great answers here but I wanted to point out the jvm is free to store a char value in any size space >= 2 bytes.
On many architectures there is a penalty for performing unaligned memory access so a char might easily be padded to 4 bytes. A volatile char might even be padded to the size of the CPU cache line to prevent false sharing. https://en.wikipedia.org/wiki/False_sharing
It might be non-intuitive to new Java programmers that a character array or a string is NOT simply multiple characters. You should learn and think about strings and arrays distinctly from "multiple characters".
I also want to point out that java characters are often misused. People don't realize they are writing code that won't properly handle codepoints over 16 bits in length.
In case of NULL
columns it is better to use IF
clause like this which combine the two functions of : CONCAT
and COALESCE
and uses special chars between the columns in result like space or '_'
SELECT FirstName , LastName ,
IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,'')))
AS Contact_Phone FROM TABLE1
Be careful with window.history.length
because it includes also entries for window.history.forward()
So you may have maybe window.history.length
with more than 1 entries, but no history back entries.
This means that nothing happens if you fire window.history.back()
List all python (.py
) files in the current folder and put them as __all__
variable in __init__.py
from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
var xhr;_x000D_
var beforeSend = function(){_x000D_
$('#pleasewaitDL').modal('show');_x000D_
}_x000D_
$(function () {_x000D_
$('#print_brochure_link').click(function(){_x000D_
beforeSend();_x000D_
xhr = new XMLHttpRequest();_x000D_
xhr.open("GET",$('#preparedPrintModalForm').attr('action'), true); _x000D_
xhr.responseType = "blob";_x000D_
xhr.onload = function (e) {_x000D_
if (this.status === 200) {_x000D_
var file = window.URL.createObjectURL(this.response);_x000D_
var a = document.createElement("a");_x000D_
a.href = file;_x000D_
a.download = this.response.name || "Property Brochure";_x000D_
console.log(file);_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
_x000D_
window.onfocus = function () { _x000D_
document.body.removeChild(a)_x000D_
}_x000D_
$('#pleasewaitDL').modal('hide');_x000D_
};_x000D_
};_x000D_
xhr.send($('#preparedPrintModalForm').serialize());_x000D_
});_x000D_
$('#pleasewaitDLCancel').click(function() {_x000D_
xhr.abort();_x000D_
});_x000D_
});
_x000D_
To hide the softkeyboard at the time of New Activity start or onCreate(),onStart() method etc. use the code below:
getActivity().getWindow().setSoftInputMode(WindowManager.
LayoutParams.SOFT_INPUT_STATE_HIDDEN);
To hide softkeyboard at the time of Button is click in activity:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
jasonmp85 is right about passing a different array to String.format
. The size of an array can't be changed once constructed, so you'd have to pass a new array instead of modifying the existing one.
Object newArgs = new Object[args.length+1];
System.arraycopy(args, 0, newArgs, 1, args.length);
newArgs[0] = extraVar;
String.format(format, extraVar, args);
The most likely possibility is that it was the most idiomatic choice. Not only is it easy to speak, but rather intuitive to understand. Some could argue, even more so than var
.
But I reckon there's a little more history to this.
From Wikipedia:
Dana Scott's LCF language was a stage in the evolution of lambda calculus into modern functional languages. This language introduced the let expression, which has appeared in most functional languages since that time.
State-full imperative languages such as ALGOL and Pascal essentially implement a let expression, to implement restricted scope of functions, in block structures.
I would like to believe this was an inspiration too, for the let
in Javascript.
It is not enough to manually add keys to the Windows certificate store. The certificate only contains the signed public key. You must also import the private key that is associated with the public key in the certificate. A .pfx file contains both public and private keys in a single file. That is what you need to import.
This answer actually helped when using Boost and cmake.
Adding add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)
for cmake file.
My CMakeLists.txt looks like this:
cmake_minimum_required(VERSION 3.12)
project(proj)
set(CMAKE_CXX_STANDARD 17)
set(SHARED_DIR "${CMAKE_SOURCE_DIR}/../shared")
set(BOOST_LATEST_DIR "${SHARED_DIR}/boost_1_68_0")
set(BOOST_LATEST_BIN_DIR "${BOOST_LATEST_DIR}/stage/lib")
set(BOOST_LATEST_INCLUDE_DIR "${BOOST_LATEST_DIR}/boost")
set(BOOST_SYSTEM "${BOOST_LATEST_BIN_DIR}/libboost_system.so")
set(BOOST_FS "${BOOST_LATEST_BIN_DIR}/libboost_filesystem.so")
set(BOOST_THREAD "${BOOST_LATEST_BIN_DIR}/libboost_thread.so")
set(HYRISE_SQL_PARSER_DIR "${SHARED_DIR}/hyrise_sql_parser")
set(HYRISE_SQL_PARSER_BIN_DIR "${HYRISE_SQL_PARSER_DIR}")
set(HYRISE_SQL_PARSER_INCLUDE_DIR "${HYRISE_SQL_PARSER_DIR}/src")
set(HYRISE_SQLPARSER "${HYRISE_SQL_PARSER_BIN_DIR}/libsqlparser.so")
include_directories(${CMAKE_SOURCE_DIR} ${BOOST_LATEST_INCLUDE_DIR} ${HYRISE_SQL_PARSER_INCLUDE_DIR})
set(BOOST_LIBRARYDIR "/usr/lib/x86_64-linux-gnu/")
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)
find_package(Boost 1.68.0 REQUIRED COMPONENTS system thread filesystem)
add_executable(proj main.cpp row/row.cpp row/row.h table/table.cpp table/table.h page/page.cpp page/page.h
processor/processor.cpp processor/processor.h engine_instance.cpp engine_instance.h utils.h
meta_command.h terminal/terminal.cpp terminal/terminal.h)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
target_link_libraries(proj PUBLIC Boost::system Boost::filesystem Boost::thread ${HYRISE_SQLPARSER})
endif()
In New Xampp
All you have to do is to edit the file:
C:\xampp\apache\conf\extra\httpd-xampp.conf
and go to Directory tag as below:
<Directory "C:/xampp/phpMyAdmin">
and then change
Require local
To
Require all granted
in the Directory tag.
Restart the Xampp. That's it!
A pretty nice way to do this is to use SimpleDateFormat
I'll show you how:
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);
I see that you have the date in a variable:
sdf.format(variable_name);
Cheers.
While not a complete solution I've found that…
-moz-appearance: window;
…works to some extent. You can't change the background (-color or -image) but the element can be rendered invisible with color: transparent. Not perfect but it's a start and you don't need to replace the system level element with a js one.
@dannyeuu's answer is correct. pd.concat naturally does a join on index columns, if you set the axis option to 1. The default is an outer join, but you can specify inner join too. Here is an example:
x = pd.DataFrame({'a': [2,4,3,4,5,2,3,4,2,5], 'b':[2,3,4,1,6,6,5,2,4,2], 'val': [1,4,4,3,6,4,3,6,5,7], 'val2': [2,4,1,6,4,2,8,6,3,9]})
x.set_index(['a','b'], inplace=True)
x.sort_index(inplace=True)
y = x.__deepcopy__()
y.loc[(14,14),:] = [3,1]
y['other']=range(0,11)
y.sort_values('val', inplace=True)
z = x.__deepcopy__()
z.loc[(15,15),:] = [3,4]
z['another']=range(0,22,2)
z.sort_values('val2',inplace=True)
pd.concat([x,y,z],axis=1)
Assuming such a query would return a single row, you could use either
select @EmpId = Id from dbo.Employee
Or
set @EmpId = (select Id from dbo.Employee)
You use the ajaxStop to execute code when the ajax are completed:
$(document).ajaxStop(function(){
setTimeout("window.location = 'otherpage.html'",100);
});
The main image manager in PIL
is PIL
's Image
module.
from PIL import Image
import math
foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
You can add optimize=True
to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's.
For other image extensions, you could decrease the quality of the new saved image.
You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully.
I defined this size:
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
just to show you what is (almost) normally done with horizontal images. For vertical images you might do:
x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)
. Remember, you can still delete that bit of code and define a new size.
if(checkBox.getAttribute("checked") != null) // if Checked
checkBox.click(); //to Uncheck it
You can also add an and
statement to be sure if checked is true.
I haven't found any way to do that in Android Studio, but I access the db with a remote shell instead of pulling the file each time.
Find all info here: http://developer.android.com/tools/help/sqlite3.html
1- Go to your platform-tools folder in a command prompt
2- Enter the command adb devices
to get the list of your devices
C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb devices
List of devices attached
emulator-xxxx device
3- Connect a shell to your device:
C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb -s emulator-xxxx shell
4a- You can bypass this step on rooted device
run-as <your-package-name>
4b- Navigate to the folder containing your db file:
cd data/data/<your-package-name>/databases/
5- run sqlite3 to connect to your db:
sqlite3 <your-db-name>.db
6- run sqlite3 commands that you like eg:
Select * from table1 where ...;
Note: Find more commands to run below.
There are a few steps to see the tables in an SQLite database:
List the tables in your database:
.tables
List how the table looks:
.schema tablename
Print the entire table:
SELECT * FROM tablename;
List all of the available SQLite prompt commands:
.help
And when you use a case :
CASE
WHEN TB1.COD IS NULL THEN
TB1.COD || ' - ' || TB1.NAME
ELSE
TB1.COD || ' - ' || TB1.NAME || ' - ' || TB.NM_TABELAFRETE
END AS NR_FRETE,
I've always used:
unique = (arr) => arr.filter((item, i, s) => s.lastIndexOf(item) == i);
But recently I had to get unique values for:
["1", 1, "2", 2, "3", 3]
And my old standby didn't cut it, so I came up with this:
uunique = (arr) => Object.keys(Object.assign({}, ...arr.map(a=>({[a]:true}))));
There you have it :)
public static void Main()
{
SetTimer();
Console.WriteLine("\nPress the Enter key to exit the application...\n");
Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
Console.ReadLine();
aTimer.Stop();
aTimer.Dispose();
Console.WriteLine("Terminating the application...");
}
private static void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
}
Type switches can also be used with reflection stuff:
var str = "hello!"
var obj = reflect.ValueOf(&str)
switch obj.Elem().Interface().(type) {
case string:
log.Println("obj contains a pointer to a string")
default:
log.Println("obj contains something else")
}
For Eclipse Mars use the similar approach as harshit.
1) Help -> Install New Software
2) Use url: http://download.oracle.com/otn_software/oepe/mars repository Above is the OEPE tool provided by oracle for EE development.
3) From all the suggestions, select Glassfish Tools, (Oracle Weblogic Server Tools, Oracle Weblogic Scripting Tools, Oracle patches, Oracle Maven Tools).
4) Install it.
5) Restart eclipse
In point 3) are 4 tools are in braces, I don't know minimal combination, but only install Glassfish Tools has no effect.
During restart Oepe ask for Java 8 JDK if Eclipse run on on older version.
Eclipse 4.5.0 Mars JDK : 1.8
Use acra crash reporter for android app..Acra lib
You should not execute resource intensive tasks in the main thread. It will make the UI unresponsive and you will get an ANR. It seems like you will be doing resource intensive stuff and want the user to see the ProgressDialog
. You can take a look at http://developer.android.com/reference/android/os/AsyncTask.html to do resource intensive tasks. It also shows you how to use a ProgressDialog
.
IN android studio 3.5.1 View -> Tool Windows ->Logcat
Going forward, the new HTML Intersection Observer API is the thing you're looking for. It allows you to configure a callback that is called whenever one element, called the target, intersects either the device viewport or a specified element. It's available in latest versions of Chrome, Firefox and Edge. See https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for more info.
Simple code example for observing display:none switching:
// Start observing visbility of element. On change, the
// the callback is called with Boolean visibility as
// argument:
function respondToVisibility(element, callback) {
var options = {
root: document.documentElement,
};
var observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
callback(entry.intersectionRatio > 0);
});
}, options);
observer.observe(element);
}
In action: https://jsfiddle.net/elmarj/u35tez5n/5/
You can put the file "hibernate.cfg.xml" to the src folder (src\hibernate.cfg.xml) and then init the config as the code below:
Configuration configuration = new Configuration();
sessionFactory =configuration.configure().buildSessionFactory();
Use a semicolon
OpenFileDialog of = new OpenFileDialog();
of.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
There is also an easier way to access the view instead of dealing with the nib as an array.
1) Create a custom View subclass with any outlets that you want to have access to later. --MyView
2) in the UIViewController that you want to load and handle the nib, create an IBOutlet property that will hold the loaded nib's view, for instance
in MyViewController (a UIViewController subclass)
@property (nonatomic, retain) IBOutlet UIView *myViewFromNib;
(dont forget to synthesize it and release it in your .m file)
3) open your nib (we'll call it 'myViewNib.xib') in IB, set you file's Owner to MyViewController
4) now connect your file's Owner outlet myViewFromNib to the main view in the nib.
5) Now in MyViewController, write the following line:
[[NSBundle mainBundle] loadNibNamed:@"myViewNib" owner:self options:nil];
Now as soon as you do that, calling your property "self.myViewFromNib" will give you access to the view from your nib!
A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.
Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.
You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.
ImageView
: setImageResource()
(standard method, aspect ratio is kept)
View
: setBackgroundResource()
(image is stretched)
Both
My fuller answer is here.
It's something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.company.myapp.ActivityOrFragment"
android:id="@+id/activity_or_fragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayoutFirst"
android:weightSum="100"> <!-- Overall weights sum of children elements -->
<Spinner
android:layout_width="0dp" <!-- It's 0dp because is determined by android:layout_weight -->
android:layout_weight="50"
android:layout_height="wrap_content"
android:id="@+id/spinner" />
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_below="@+id/linearLayoutFirst"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/linearLayoutSecond">
<EditText
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="75"
android:inputType="numberDecimal"
android:id="@+id/input" />
<TextView
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="25"
android:id="@+id/result"/>
</LinearLayout>
</RelativeLayout>
I changed the memory limit from .htaccess and this problem got resolved.
I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:
php_value memory_limit 512M
After scan was over, I removed this line to make the size as it was before.
The best option, in my opinion, is to use the Value
property for the ListItem
, which is available in the RadioButtonList
.
I must remark that ListItem
does NOT have an ID property.
So, in your case, to select the second element (option2) that would be:
// SelectedValue expects a string
radio1.SelectedValue = "1";
Alternatively, yet in very much the same vein you may supply an int to SelectedIndex.
// SelectedIndex expects an int, and are identified in the same order as they are added to the List starting with 0.
radio1.SelectedIndex = 1;
varName.replace(/[\r\n]/mg, '')
From what I understand they are independent of one another. By keeping the session timeout less than or equal to the authentication timeout, you can make sure any user-specific session variables are not persisted after the authentication has timed out (if that is your concern, which I think is the normal one when asking this question). Of course, you'll have to manually handle the disposal of session variables upon log-out.
Here is a decent response that may answer your question or at least point you in the right direction:
Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample
@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = {
ServiceMarker.class,
RepositoryMarker.class }
)
public class AppConfig {
}
@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};
@Autowired
private Environment env;
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
private HibernateJpaVendorAdapter vendorAdaptor() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());
return entityManagerFactoryBean;
}
private Properties jpaHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");
return properties;
}
}
public static void main(String[] args) {
try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
MyService myService = springContext.getBean(MyServiceImpl.class);
try {
myService.handleProcess(fromDate, toDate);
} catch (Exception e) {
logger.error("Exception occurs", e);
myService.handleException(fromDate, toDate, e);
}
} catch (Exception e) {
logger.error("Exception occurs in loading Spring context: ", e);
}
}
@Service
public class MyServiceImpl implements MyService {
@Inject
private MyDao myDao;
@Override
public void handleProcess(String fromDate, String toDate) {
List<Student> myList = myDao.select(fromDate, toDate);
}
}
@Repository
@Transactional
public class MyDaoImpl implements MyDao {
@PersistenceContext
private EntityManager entityManager;
public Student select(String fromDate, String toDate){
TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<Student> list = query.getResultList();
return CollectionUtils.isEmpty(list) ? null : list;
}
}
Assuming maven project:
Properties file should be in src/main/resources/database
folder
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password
hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true
ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.
Let's say you have package name a.b.c.service.impl
. MyServiceImpl is in this package and so is ServiceMarker.
public interface ServiceMarker {
}
Same for repository marker. Let's say you have a.b.c.repository.impl
or a.b.c.dao.impl
package name. Then MyDaoImpl is in this this package and also Repositorymarker
public interface RepositoryMarker {
}
//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {
private LocalDateTime fromDate;
private LocalDateTime toDate;
//getters setters
}
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return Timestamp.valueOf(dateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
}
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.2.1.RELEASE</org.springframework-version>
<hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<mysql-connector-java.version>5.1.36</mysql-connector-java.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
Hope it helps. Thanks
As said before modulo isn't sufficient because it skews the distribution. Heres my code which masks off bits and uses them to ensure the distribution isn't skewed.
static uint32_t randomInRange(uint32_t a,uint32_t b) {
uint32_t v;
uint32_t range;
uint32_t upper;
uint32_t lower;
uint32_t mask;
if(a == b) {
return a;
}
if(a > b) {
upper = a;
lower = b;
} else {
upper = b;
lower = a;
}
range = upper - lower;
mask = 0;
//XXX calculate range with log and mask? nah, too lazy :).
while(1) {
if(mask >= range) {
break;
}
mask = (mask << 1) | 1;
}
while(1) {
v = rand() & mask;
if(v <= range) {
return lower + v;
}
}
}
The following simple code lets you look at the distribution:
int main() {
unsigned long long int i;
unsigned int n = 10;
unsigned int numbers[n];
for (i = 0; i < n; i++) {
numbers[i] = 0;
}
for (i = 0 ; i < 10000000 ; i++){
uint32_t rand = random_in_range(0,n - 1);
if(rand >= n){
printf("bug: rand out of range %u\n",(unsigned int)rand);
return 1;
}
numbers[rand] += 1;
}
for(i = 0; i < n; i++) {
printf("%u: %u\n",i,numbers[i]);
}
}
I followed all steps and instructions followed by OP here, took care of blank space around username and password(even though spring takes care of whitespaces in properties file), still was either facing
could not find bean for ___Repository
(you interface which extends JPARepository)
OR after adding @EnableJPARepository
could not find bean for EntityManagerFactory
i solved it by changing spring boot starter parent version from 2.3.2 to 2.2.1 in pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
and adding following dependency
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
I did not need to add any of following, spring boot does it itself
Yes you can have multiple expression to add multiple class in ng-class.
For example:
<div ng-class="{class1:Result.length==2,class2:Result.length==3}"> Dummy Data </div>
If all fails you can try
# aptitude install nodejs
as root. You can test your install with the following command:
# node -v
If you want to install NPM, please refer following link. Hope it helps.
you can convert like below code snippet
Collection<A> obj=new Collection<return ListRetunAPI()>
A way to look at advantages of arrays is to see where is the O(1) access capability of arrays is required and hence capitalized:
In Look-up tables of your application (a static array for accessing certain categorical responses)
Memoization (already computed complex function results, so that you don't calculate the function value again, say log x)
High Speed computer vision applications requiring image processing (https://en.wikipedia.org/wiki/Lookup_table#Lookup_tables_in_image_processing)
Another option is to run the two inserts separately, leaving the FK column null, then running an update to poulate it correctly.
If there is nothing natural stored within the two tables that match from one record to another (likely) then create a temporary GUID column and populate this in your data and insert to both fields. Then you can update with the proper FK and null out the GUIDs.
E.g.:
CREATE TABLE [dbo].[table1] (
[id] [int] IDENTITY(1,1) NOT NULL,
[data] [varchar](255) NOT NULL,
CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED ([id] ASC),
JoinGuid UniqueIdentifier NULL
)
CREATE TABLE [dbo].[table2] (
[id] [int] IDENTITY(1,1) NOT NULL,
[table1_id] [int] NULL,
[data] [varchar](255) NOT NULL,
CONSTRAINT [PK_table2] PRIMARY KEY CLUSTERED ([id] ASC),
JoinGuid UniqueIdentifier NULL
)
INSERT INTO Table1....
INSERT INTO Table2....
UPDATE b
SET table1_id = a.id
FROM Table1 a
JOIN Table2 b on a.JoinGuid = b.JoinGuid
WHERE b.table1_id IS NULL
UPDATE Table1 SET JoinGuid = NULL
UPDATE Table2 SET JoinGuid = NULL
Just use parseInt()
and be sure to include the radix so you get predictable results:
parseInt(d, 10);
# How To Add Google Apps and ARM Support to Genymotion v2.0+ #
Note(Feb 2nd): Contrary to previous reports, it's been discovered that Android 4.4 does in fact work with ARM translation, although it is buggy. Follow the steps the same as before, just make sure you download the 4.4 GApps.
UPDATE-v1.1: I've gotten more up-to-date builds of libhoudini and have updated the ZIP file. This fixes a lot of app crashes and hangs. Just flash the new one, and it should work.
This guide is for getting back both ARM translation/support (this is what causes the "INSTALL_FAILED_CPU_ABI_INCOMPATIBLE" errors) and Google Play apps in your Genymotion VM.
adb reboot
) or an app like ROM Toolbox. If nescessary you can simply close the VM window, but I don't recommend it.I've tested this on Genymotion v2.0.1-v2.1 using Android 4.3 and 4.4 images. Feel free to skip the GApps steps if you only want the ARM support. It'll work perfectly fine by itself.
Old Zips: v1.0. Don't download these as they will not solve your issues. It is left for archival and experimental purposes.
Option 1
You could also solve it by adding a transparent border to the row (tr), like this
HTML
<table>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
</table>
CSS
tr {
border-top: 12px solid transparent;
border-bottom: 12px solid transparent;
}
Works like a charm, although if you need regular borders, then this method will sadly not work.
Option 2
Since rows act as a way to group cells, the correct way to do this, would be to use
table {
border-collapse: inherit;
border-spacing: 0 10px;
}
You can do something like that in pure html using an <object>
tag:
<div><object data="file.txt"></object></div>
This method has some limitations though, like, it won't fit size of the block to the content - you have to specify width
and height
manually. And styles won't be applied to the text.
I know this question is too old, but still, I think this approach would be cleaner:
cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);
In this case you wont need to go over the entire options with each()
.
Although by that time prop()
didn't exist so for older versions of jQuery use attr()
.
UPDATE
You have to be certain when using contains
because you can find multiple options, in case of the string inside cat
matches a substring of a different option than the one you intend to match.
Then you should use:
cat = $.URLDecode(cat);
$('#cbCategory option')
.filter(function(index) { return $(this).text() === cat; })
.prop('selected', true);
SELECT *
FROM my_table
WHERE substr(my_field,1,5) = "abcde";
The selected answer did not work in my Web API application. I had to use
System.Web.HttpRuntime.AppDomainAppPath
tools:ignore="ProtectedPermissions"
Try adding this attribute to that permission.
This solution worked for me:
First install django-phone-field
command: pip install django-phone-field
then on models.py
from phone_field import PhoneField
...
class Client(models.Model):
...
phone_number = PhoneField(blank=True, help_text='Contact phone number')
and on settings.py
INSTALLED_APPS = [...,
'phone_field'
]
It looks like this in the end
I didn't see anyone convert the LocalPath provided by .Net Core reflection into a usable System.IO path so here's my version.
public static string GetApplicationRoot()
{
var exePath = new Uri(System.Reflection.
Assembly.GetExecutingAssembly().CodeBase).LocalPath;
return new FileInfo(exePath).DirectoryName;
}
This will return the full C:\\xxx\\xxx
formatted path to where your code is.
So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this:
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn);
var client = new EchoServiceClient(address);
litResponse.Text = client.SendEcho("Hello World");
client.Close();
Actual working final version by valamas
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri("http://id.web/Services/EchoService.svc");
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.SendEcho("Hello World");
client.Close();
Several tips:
pragma journal_mode
). There is NORMAL
, and then there is OFF
, which can significantly increase insert speed if you're not too worried about the database possibly getting corrupted if the OS crashes. If your application crashes the data should be fine. Note that in newer versions, the OFF/MEMORY
settings are not safe for application level crashes.PRAGMA page_size
). Having larger page sizes can make reads and writes go a bit faster as larger pages are held in memory. Note that more memory will be used for your database.CREATE INDEX
after doing all your inserts. This is significantly faster than creating the index and then doing your inserts.INTEGER PRIMARY KEY
if possible, which will replace the implied unique row number column in the table.!feof(file)
!AsyncTask is very helpful!
class QueryBibleDetail extends AsyncTask<Integer, Integer, String>{
private Activity activity;
private ProgressDialog dialog;
private Context context;
public QueryBibleDetail(Activity activity){
this.activity = activity;
this.context = activity;
this.dialog = new ProgressDialog(activity);
this.dialog.setTitle("????");
this.dialog.setMessage("????:"+tome+chapterID+":"+sectionFromID+"-"+sectionToID);
if(!this.dialog.isShowing()){
this.dialog.show();
}
}
@Override
protected String doInBackground(Integer... params) {
Log.d(TAG,"??doInBackground");
publishProgress(params[0]);
if(sectionFromID > sectionToID){
return "";
}
String queryBible = "action=query_bible&article="+chapterID+"&id="+tomeID+"&verse_start="+sectionFromID+"&verse_stop="+sectionToID+"";
try{
String bible = (Json.getRequest(HOST+queryBible)).trim();
bible = android.text.Html.fromHtml(bible).toString();
return bible;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String bible){
Log.d(TAG,"??onPostExecute");
TextView bibleBox = (TextView) findViewById(R.id.bibleBox);
bibleBox.setText(bible);
this.dialog.dismiss();
}
}
Given (almost) everything on unix is a file, and lsof lists open files...
Linux : netstat -putan or lsof | grep TCP
OSX : lsof | grep TCP
Other Unixen : lsof
way...
<input type="checkbox" checked onclick="return false;" onkeydown="return false;"/>
If you are worried about tab order, only return false for the keydown event when the tab key was not pressed:
<input type="checkbox" checked onclick="return false;" onkeydown="e = e || window.event; if(e.keyCode !== 9) return false;"/>
USE this sudo dpkg --add-architecture i386 sudo apt-get update sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
Android Studio fails to build new project, timed out while wating for slave aapt process
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png
if (window.location.href.indexOf("franky") != -1)
would do it. Alternatively, you could use a regexp:
if (/franky/.test(window.location.href))
if your question is "how to bind events on ajax loaded content" you can do like this :
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
});
so you don't need to place your configuration to every you ajax code
If you need the short and technical answer go right to the last section of the answer.
If you want to know better, read it all, and i hope you'll enjoy...
I countered this problem too today, and what i discovered today is that:
the above answers are true, as:
1.1 it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again.
1.2 Anytime you're changing the headers of an HttpWebRequest
, you need to use the appropriate properties on the object itself, if they exist.
Thanks FOR and Jvenema for the leading guidelines...
But, What i found out, and that was the missing piece in the puzzle is that:
2.1 The WebHeaderCollection
class is generally accessed through WebRequest
.Headers or WebResponse
.Headers. Some common headers are considered restricted and are either exposed directly by the API (such as Content-Type) or protected by the system and cannot be changed.
The restricted headers are:
Accept
Connection
Content-Length
Content-Type
Date
Expect
Host
If-Modified-Since
Range
Referer
Transfer-Encoding
User-Agent
Proxy-Connection
So, next time you are facing this exception and don't know how to solve this, remember that there are some restricted headers, and the solution is to modify their values using the appropriate property explicitly from the WebRequest
/HttpWebRequest
class.
Edit: (useful, from comments, comment by user Kaido)
Solution is to check if the header exists already or is restricted (
WebHeaderCollection.IsRestricted(key)
) before calling add
by this code your background image go center and fix it size whatever your div size change , good for small , big , normal sizes , best for all , i use it for my projects where my background size or div size can change
background-repeat:no-repeat;
-webkit-background-size:cover;
-moz-background-size:cover;
-o-background-size:cover;
background-size:cover;
background-position:center;
in modern browsers you can do the following...
button.addEventListener( 'click', () => {
alert( 'only once!' );
}, { once: true } );
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters
You're going to have to either use JS or write a function/method in whatever non-markup language you're using to do this. For instance you could write something that will save the status to a cookie or session variable then check for it on page load. If you want to do it without reloading the page then JS is going to be your only option.
I don't think this is possible just using CSS (not cross browser at least) but the jQuery plugin ImageMapster will do what you're after. You can outline, colour in or use an alternative image for hover/active states on an image map.
Below works (in my limited testing) by doing deep compare between two object hierarchies. In handles various cases including the cases when objects themselves or their attributes are dictionaries.
def deep_comp(o1:Any, o2:Any)->bool:
# NOTE: dict don't have __dict__
o1d = getattr(o1, '__dict__', None)
o2d = getattr(o2, '__dict__', None)
# if both are objects
if o1d is not None and o2d is not None:
# we will compare their dictionaries
o1, o2 = o1.__dict__, o2.__dict__
if o1 is not None and o2 is not None:
# if both are dictionaries, we will compare each key
if isinstance(o1, dict) and isinstance(o2, dict):
for k in set().union(o1.keys() ,o2.keys()):
if k in o1 and k in o2:
if not deep_comp(o1[k], o2[k]):
return False
else:
return False # some key missing
return True
# mismatched object types or both are scalers, or one or both None
return o1 == o2
This is a very tricky code so please add any cases that might not work for you in comments.
I know this answer has already been accepted, but I thought I'd throw my 2cents in. I like to use the tomb package. It's basically a suped up quit channel, but it does nice things like pass back any errors as well. The routine under control still has the responsibility of checking for remote kill signals. Afaik it's not possible to get an "id" of a goroutine and kill it if it's misbehaving (ie: stuck in an infinite loop).
Here's a simple example which I tested:
package main
import (
"launchpad.net/tomb"
"time"
"fmt"
)
type Proc struct {
Tomb tomb.Tomb
}
func (proc *Proc) Exec() {
defer proc.Tomb.Done() // Must call only once
for {
select {
case <-proc.Tomb.Dying():
return
default:
time.Sleep(300 * time.Millisecond)
fmt.Println("Loop the loop")
}
}
}
func main() {
proc := &Proc{}
go proc.Exec()
time.Sleep(1 * time.Second)
proc.Tomb.Kill(fmt.Errorf("Death from above"))
err := proc.Tomb.Wait() // Will return the error that killed the proc
fmt.Println(err)
}
The output should look like:
# Loop the loop
# Loop the loop
# Loop the loop
# Loop the loop
# Death from above
Just as a follow up for anyone still running into this – I had added the ServicePointManager.SecurityProfile options as noted in the solution:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
And yet I continued to get the same “The request was aborted: Could not create SSL/TLS secure channel” error. I was attempting to connect to some older voice servers with HTTPS SOAP API interfaces (i.e. voice mail, IP phone systems etc… installed years ago). These only support SSL3 connections as they were last updated years ago.
One would think including SSl3 in the list of SecurityProtocols would do the trick here, but it didn’t. The only way I could force the connection was to include ONLY the Ssl3 protocol and no others:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
Then the connection goes through – seems like a bug to me but this didn’t start throwing errors until recently on tools I provide for these servers that have been out there for years – I believe Microsoft has started rolling out system changes that have updated this behavior to force TLS connections unless there is no other alternative.
Anyway – if you’re still running into this against some old sites/servers, it’s worth giving it a try.
You can compare element height and element height with line-height: 0
function lineCount(elm) {
const style = elm.getAttribute('style')
elm.style.marginTop = 0
elm.style.marginBottom = 0
elm.style.paddingTop = 0
elm.style.paddingBottom = 0
const heightAllLine = elm.offsetHeight
elm.style.lineHeight = 0
const height1line = elm.offsetHeight
const lineCount = Math.round(heightAllLine / height1line)
elm.setAttribute('style', style)
if (isNaN(lineCount)) return 0
return lineCount
}
If it is a directory you own, grant yourself access to it:
chmod u+rx,go-w openfire
That grants you permission to use the directory and the files in it (x
) and to list the files that are in it (r
); it also denies group and others write permission on the directory, which is usually correct (though sometimes you may want to allow group to create files in your directory - but consider using the sticky bit on the directory if you do).
If it is someone else's directory, you'll probably need some help from the owner to change the permissions so that you can access it (or you'll need help from root
to change the permissions for you).
if let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask,
true).first {
debugPrint("documentsPath = \(documentsPath)")
}
How about a one-liner using a list comprehension within join?
>>> foobar = "aaa bbb\t\t\tccc\nddd"
>>> print(foobar)
aaa bbb ccc
ddd
>>> print(''.join([c for c in foobar if c not in [' ', '\t', '\n']]))
aaabbbcccddd
try this
function getmoviename(id)
{
var p_url= yoururl from where you get movie name,
jQuery.ajax({
type: "GET",
url: p_url,
data: "id=" + id,
success: function(data) {
$('#summary').html(data);
}
});
}
and you html part is
<a href="javascript:void(0);" class="movie" onclick="getmoviename(youridvariable)">
Name of movie</a>
<div id="summary">Here is summary of movie</div>
This worked for me fine:
File 1:
<html>
<head></head>
<body>
<a href="#" onclick="window.open('file:///D:/Examples/file2.html'); return false">CLICK ME</a>
</body>
<footer></footer>
</html>
File 2:
<html>
...
</html>
This method works regardless of whether or not the 2 files are in the same directory, BUT both files must be local.
For obvious security reasons, if File 1 is located on a remote server you absolutely cannot open a file on some client's host computer and trying to do so will open a blank target.
ORA-12154: TNS:could not resolve the connect identifier specified?
In case the TNS is not defined you can also try this one:
If you are using C#.net 2010
or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:
static string constr = @"Data Source=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
User Id=system ;Password=yourpasswrd";
After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified
then first you have to do restart your system and run your project.
And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:
Oracle Data Provider for .NET 2.0
Oracle Providers for ASP.NET
Oracle Developer Tools for Visual Studio
Oracle Instant Client
And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......
You can directly make your Background Blur using "Visual Effect View with Blur" and "Visual Effect View with Blur and Vibrancy".
All you have to do for making Blur Background in iOS Application is...
Application Layout before clicking on any Button!
Application View After Clicking on Button which makes the whole application background Blur!
--~ print a table
function printTable(list, i)
local listString = ''
--~ begin of the list so write the {
if not i then
listString = listString .. '{'
end
i = i or 1
local element = list[i]
--~ it may be the end of the list
if not element then
return listString .. '}'
end
--~ if the element is a list too call it recursively
if(type(element) == 'table') then
listString = listString .. printTable(element)
else
listString = listString .. element
end
return listString .. ', ' .. printTable(list, i + 1)
end
local table = {1, 2, 3, 4, 5, {'a', 'b'}, {'G', 'F'}}
print(printTable(table))
Hi man, I wrote a siple code that do this in pure Lua, it has a bug (write a coma after the last element of the list) but how i wrote it quickly as a prototype I will let it to you adapt it to your needs.
Actually I think you may need to use
if (value !== null || value !== undefined)
because if you use if (value)
you may also filter 0 or false values.
Consider these two functions:
const firstTest = value => {
if (value) {
console.log('passed');
} else {
console.log('failed');
}
}
const secondTest = value => {
if (value !== null && value !== undefined) {
console.log('passed');
} else {
console.log('failed');
}
}
firstTest(0); // result: failed
secondTest(0); // result: passed
firstTest(false); // result: failed
secondTest(false); // result: passed
firstTest(''); // result: failed
secondTest(''); // result: passed
firstTest(null); // result: failed
secondTest(null); // result: failed
firstTest(undefined); // result: failed
secondTest(undefined); // result: failed
In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0
or false
or ''
values. so I used the second test, but you may need to filter them too which may cause you to use first test.
Firstly there is an extra }
after every array object
.
Secondly "geodata" is a JSONArray
. So instead of JSONObject geoObject = jObject.getJSONObject("geodata");
you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");
Once you have the JSONArray
you can fetch each entry in the JSONArray
using geoObject.get(<index>)
.
I am using org.codehaus.jettison.json
.
I had this issue when after rebooted and the last copy of VSCode reopened. The above fix did not work, but when I closed and reopened VSCode via explorer it worked. Here are the steps I did:
//received fatal error_x000D_
git remote remove origin_x000D_
git init_x000D_
git remote add origin git@github:<yoursite>/<your project>.git_x000D_
// still received an err _x000D_
//restarted VSCode and folder via IE _x000D_
//updated one char and resaved the index.html _x000D_
git add ._x000D_
git commit -m "blah"_x000D_
git push origin master
_x000D_
Note:
to remove, delete, or uninstall nvm - just remove the $NVM_DIR
folder (usually ~/.nvm
)
you can try :
rm -rf ~/.nvm
You can verify the response in 3 ways as per the Google reCAPTCHA documentation:
g-recaptcha-response
: Once user checks the checkbox (I am not a robot), a field with id g-recaptcha-response
gets populated in your HTML.
You can now use the value of this field to know if the user is a bot or not, using the below mentioed lines:-
var captchResponse = $('#g-recaptcha-response').val();
if(captchResponse.length == 0 )
//user has not yet checked the 'I am not a robot' checkbox
else
//user is a verified human and you are good to submit your form now
Before you are about to submit your form, you can make a call as follows:-
var isCaptchaValidated = false;
var response = grecaptcha.getResponse();
if(response.length == 0) {
isCaptchaValidated = false;
toast('Please verify that you are a Human.');
} else {
isCaptchaValidated = true;
}
if (isCaptchaValidated ) {
//you can now submit your form
}
You can display your reCAPTCHA as follows:-
<div class="col s12 g-recaptcha" data-sitekey="YOUR_PRIVATE_KEY" data-callback='doSomething'></div>
And then define the function in your JavaScript, which can also be used to submit your form.
function doSomething() { alert(1); }
Now, once the checkbox (I am not a robot) is checked, you will get a callback to the defined callback, which is doSomething
in your case.
Here's my pure bash solution that doesn't change IFS, and can take in a custom regex delimiter.
loop_custom_delimited() {
local list=$1
local delimiter=$2
local item
if [[ $delimiter != ' ' ]]; then
list=$(echo $list | sed 's/ /'`echo -e "\010"`'/g' | sed -E "s/$delimiter/ /g")
fi
for item in $list; do
item=$(echo $item | sed 's/'`echo -e "\010"`'/ /g')
echo "$item"
done
}
The easiest way in plain Java with no dependencies is the following one-liner:
new String(new char[generation]).replace("\0", "-")
Replace generation with number of repetitions, and the "-" with the string (or char) you want repeated.
All this does is create an empty string containing n number of 0x00 characters, and the built-in String#replace method does the rest.
Here's a sample to copy and paste:
public static String repeat(int count, String with) {
return new String(new char[count]).replace("\0", with);
}
public static String repeat(int count) {
return repeat(count, " ");
}
public static void main(String[] args) {
for (int n = 0; n < 10; n++) {
System.out.println(repeat(n) + " Hello");
}
for (int n = 0; n < 10; n++) {
System.out.println(repeat(n, ":-) ") + " Hello");
}
}
if you have number of columns in your database table more than number of columns in your csv you can proceed like this:
LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);
'compile files...' used to work for me, but not any more. after much pain, I found that using this instead works:
compile fileTree(dir: 'libs', include: '*.jar')
I have no idea why that made a difference, but, at least the damn thing is working now.
Under Windows only: You may try to use ini_set()
functionDocs for the SMTP
Docs and smtp_port
Docs settings:
ini_set('SMTP', 'mysmtphost');
ini_set('smtp_port', 25);
the problem is that there is no built in method (or at least none of us could find one) to do this in vb. However, there is one to split a string on the spaces, so I just rebuild the string and added in spaces....
Private Function characterArray(ByVal my_string As String) As String()
'create a temporary string to store a new string of the same characters with spaces
Dim tempString As String = ""
'cycle through the characters and rebuild my_string as a string with spaces
'and assign the result to tempString.
For Each c In my_string
tempString &= c & " "
Next
'return return tempString as a character array.
Return tempString.Split()
End Function
Yes, there is a module fs-extra. There is a method .emptyDir()
inside this module which does the job. Here is an example:
const fsExtra = require('fs-extra')
fsExtra.emptyDirSync(fileDir)
There is also an asynchronous version of this module too. Anyone can check out the link.
IE assumes that the clicking of a link heralds a new navigation where the current page contents will be replaced. As part of the process for perparing for that it halts the code that animates the GIFs. I doubt there is anything you can do about it (unless you aren't actually navigating in which case use return false in the onclick event).
If you want to only trigger validation when the input looses focus you can use onBlur
Trivia: React <17 listens to blur
event and >=17 listens to focusout
event.
I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time.
With Seam 2 http://seamframework.org/ you were able to resolve annotation parameters at runtime, with expression language inside double quotes.
In Seam 3 http://seamframework.org/Seam3/Solder, this feature is the module Seam Solder
Take a look at this tutorial for how to use SQL inside VBA:
http://www.ehow.com/how_7148832_access-vba-query-results.html
For a query that won't return results, use (reference here):
DoCmd.RunSQL
For one that will, use (reference here):
Dim dBase As Database
dBase.OpenRecordset
EDIT Summary and reccomendations
Using a for each cell in range
construct is not in itself slow. What is slow is repeated access to Excel in the loop (be it reading or writing cell values, format etc, inserting/deleting rows etc).
What is too slow depends entierly on your needs. A Sub that takes minutes to run might be OK if only used rarely, but another that takes 10s might be too slow if run frequently.
So, some general advice:
for index = max to min step -1
)value
, you are stuck with cell referenceseg (not tested!)
Dim rngToDelete as range
for each rw in rng.rows
if need to delete rw then
if rngToDelete is nothing then
set rngToDelete = rw
else
set rngToDelete = Union(rngToDelete, rw)
end if
endif
next
rngToDelete.EntireRow.Delete
Original post
Conventional wisdom says that looping through cells is bad and looping through a variant array is good. I too have been an advocate of this for some time. Your question got me thinking, so I did some short tests with suprising (to me anyway) results:
test data set: a simple list in cells A1
.. A1000000
(thats 1,000,000 rows)
Test case 1: loop an array
Dim v As Variant
Dim n As Long
T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
'i = i + 1
'i = r.Cells(n, 1).Value 'i + 1
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Array Count = " & Format(n, "#,###")
Result:
Array Time = 0.249 sec
Array Count = 1,000,001
Test Case 2: loop the range
T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")
Result:
Range Time = 0.296 sec
Range Count = 1,000,000
So,looping an array is faster but only by 19% - much less than I expected.
Test 3: loop an array with a cell reference
T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
i = r.Cells(n, 1).Value
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Array Count = " & Format(i, "#,###")
Result:
Array Time = 5.897 sec
Array Count = 1,000,000
Test case 4: loop range with a cell reference
T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
i = c.Value
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")
Result:
Range Time = 2.356 sec
Range Count = 1,000,000
So event with a single simple cell reference, the loop is an order of magnitude slower, and whats more, the range loop is twice as fast!
So, conclusion is what matters most is what you do inside the loop, and if speed really matters, test all the options
FWIW, tested on Excel 2010 32 bit, Win7 64 bit All tests with
ScreenUpdating
off,Calulation
manual, Events
disabled. Yes, there is a way to do this. You could use a pseudo-element after
to position a block on top of your background image. Something like this:
http://jsfiddle.net/Pevara/N2U6B/
The css for the :after
looks like this:
#the-div:hover:after {
content: ' ';
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(0,0,0,.5);
}
edit:
When you want to apply this to a non-empty element, and just get the overlay on the background, you can do so by applying a positive z-index
to the element, and a negative one to the :after
. Something like this:
#the-div {
...
z-index: 1;
}
#the-div:hover:after {
...
z-index: -1;
}
And the updated fiddle: http://jsfiddle.net/N2U6B/255/
Try this, which I think makes it clear. the underlying array is changed but our slice is not, print
just prints len()
chars, by another slice to the cap()
, you can see the changed array:
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(a)
fmt.Println(a) // prints [0..6]
fmt.Println(a[:cap(a)] // prints [0..6,100]
}
This problem is not only created by no_proxy
, because it created by git server down
issue also.
So When happening this issue first you open and check gitlab in browser.
And check if It shows any error like "503 An internal server error occured".
.
The gitlab shows "503"
page, this issue create by gitlab server down not in your system.
So you wait some time until the server going up and continue your work.
If you need this feature for one case or very few cases (your whole application is not requiring this feature). I would rather leave jQuery as is (for many reasons, including being able to update to newer versions, CDN, etc.) and have the following workaround:
// For modern browsers
$(ele).trigger("click");
// Relying on Paul Irish's conditional class names,
// <https://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/>
// (via HTML5 Boilerplate, <https://html5boilerplate.com/>) where
// each Internet Explorer version gets a class of its version
$("html.ie7").length && (function(){
var eleOnClickattr = $(ele).attr("onclick")
eval(eleOnClickattr);
})()
Maybe that is the problem with the table schema. drop the table and rerun the application.
I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.
Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist
.For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
, create a string value with name 1
and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
, and a second value with name 2
and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
. This can be sum up by this registry file:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
EDIT: actually, Chromium docs also indicate how to do it for other OS.
FOR MVC
-- WEB.CONFIG CODE IN APP SETTING --
<add key="PhaseLevel" value="1" />
-- ON VIEWS suppose you want to show or hide something based on web.config Value--
-- WRITE THIS ON TOP OF YOUR PAGE--
@{
var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString();
}
-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.
@if (phase != "1")
{
@Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml")
}
The innerHTML of your iframe is blank because your iframe tag doesn't surround any content in the parent document. In order to get the content from the page referred to by the iframe's src attribute, you need to access the iframe's contentDocument property. An exception will be thrown if the src is from a different domain though. This is a security feature that prevents you from executing arbitrary JavaScript on someone else's page, which would create a cross-site scripting vulnerability. Here is some example code the illustrates what I'm talking about:
<script src="http://prototypejs.org/assets/2009/8/31/prototype.js" type="text/javascript"></script>
<h1>Parent</h1>
<script type="text/javascript">
function on_load(iframe) {
try {
// Displays the first 50 chars in the innerHTML of the
// body of the page that the iframe is showing.
// EDIT 2012-04-17: for wider support, fallback to contentWindow.document
var doc = iframe.contentDocument || iframe.contentWindow.document;
alert(doc.body.innerHTML.substring(0, 50));
} catch (e) {
// This can happen if the src of the iframe is
// on another domain
alert('exception: ' + e);
}
}
</script>
<iframe id="child" src="iframe_content.html" onload="on_load(this)"></iframe>
To further the example, try using this as the content of the iframe:
<h1>Child</h1>
<a href="http://www.google.com/">Google</a>
<p>Use the preceeding link to change the src of the iframe
to see what happens when the src domain is different from
that of the parent page</p>
I've just gone through that process again. Always end up cloning the repo locally, upload the folder I want to have in that repo to that cloned location, commit the changes and then push it.
Note that if you're dealing with large files, you'll need to consider using something like Git LFS.
Use:
public void onClick(View v) {
switch(v.getId()){
case R.id.Button_MyCards: /** Start a new Activity MyCards.java */
Intent intent = new Intent(this, MyCards.class);
this.startActivity(intent);
break;
case R.id.Button_Exit: /** AlerDialog when click on Exit */
MyAlertDialog();
break;
}
}
Note that this will not work in Android library projects (due to http://tools.android.com/tips/non-constant-fields) where you will need to use something like:
int id = view.getId();
if (id == R.id.Button_MyCards) {
action1();
} else if (id == R.id.Button_Exit) {
action2();
}
In validation, of this question, it really depends on what !DOCTYPE
you are trying to get verification through.
My personal favorite is 4.01 Trans
where I just use the <br/>
and it clears the warnings and errors that may have popped up during validation
Strict is a much more complicated beast, It HATES "SHORTTAGS"
and quite literally only wants the <br></br>
In HTML5
or the "LAX" of the code world, there really isn't a right answer because it detects every example you put up
there as correct......
In the end, I think all that matters is what validation YOU PREFER
or the person that you are working for prefers
... with the lackadaisical
movement in code strictness in html5
we are seeing some VERY LAZY CODERS
This means the type of result the function returns, but it can be None
.
It is widespread in modern libraries oriented on Python 3.x.
For example, it there is in code of library pandas-profiling in many places for example:
def get_description(self) -> dict:
def get_rejected_variables(self, threshold: float = 0.9) -> list:
def to_file(self, output_file: Path or str, silent: bool = True) -> None:
"""Write the report to a file.
I've got solved my problem this way in EF on list of records from db
ListOfObjectToBeOrder.OrderBy(x => x.columnName).ToList();
There are little difference in command of adding AND changing DNS-IPs:
To Add:
Syntax:
netsh interface ipv4 add dnsserver "Network Interface Name" dns.server.ip index=1(for primary)2(for secondary)
Eg:
netsh interface ipv4 add dnsserver "Ethernet" 8.8.8.8 index=1
netsh interface show interface
To Set/Change: (as OP asked this)
Syntax:
netsh interface ipv4 set dnsservers "Network Interface Name" static dns.server.ip primary
Eg:
netsh interface ipv4 set dnsservers "Wi-Fi" static 8.8.4.4 primary
netsh interface ipv4 set dnsservers "Wi-Fi" dhcp
Last parameter can be none
:disable DNS, both
:set for primary and secondary DNS both, primary: for primary DNS only. You can notice here we are not using index-parameter as we did in adding DNS.
In the place of static
you can type dhcp
to make DNS setting automatic, but further parameter will not be required.
Note: Tested in windows 8,8.1 & 10.
I wanted to upvote and comment on jmbertucci's answer, but I'm not yet to be trusted with the controls. I had the same issue and resolved it as he said. If you are using Bootstrap 3.0, edit the LESS variables in variables.less The responsive break points are set around line 200:
@screen-xs: 480px;
@screen-phone: @screen-xs;
// Small screen / tablet
@screen-sm: 768px;
@screen-tablet: @screen-sm;
// Medium screen / desktop
@screen-md: 992px;
@screen-desktop: @screen-md;
// Large screen / wide desktop
@screen-lg: 1200px;
@screen-lg-desktop: @screen-lg;
// So media queries don't overlap when required, provide a maximum
@screen-xs-max: (@screen-sm - 1);
@screen-sm-max: (@screen-md - 1);
@screen-md-max: (@screen-lg - 1);
Then set the collapse value for the navbar using the @grid-float-breakpoint variable at about line 232. By default it's set to @screen-tablet . If you want you can use a pixel value, but I prefer to use the LESS variables.
$order = new WC_Order( $post_id );
If you
echo $order->id;
then you'll be returned the id of the post from which the order is made. As you've already got that, it's probably not what you want.
echo $order->get_order_number();
will return the id of the order (with a # in front of it). To get rid of the #,
echo trim( str_replace( '#', '', $order->get_order_number() ) );
as per the accepted answer.
It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:
<li><span class="foo">some text</span></li>
<li>some other text</li>
Then refer to it the usual way:
li > span.foo {...}
The MySQLdb library will actually do this for you, if you use their implementations to build an SQL query string instead of trying to build your own.
Don't do:
sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES (%s, %s)" % (val1, val2)
cursor.execute(sql)
Do:
sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES (%s, %s)"
cursor.execute(sql, (val1, val2))
In the Hibernate 5.2 and above, you able to remove the hibernate proxy as below, it will give you the actual object so you can serialize it properly:
Object unproxiedEntity = Hibernate.unproxy( proxy );
You can also try \x0d\x0a
in the "Replace with" box with "Use regular Expression" box checked to get carriage return + line feed using Visual Studio Find/Replace.
Using \n
(line feed) is the same as \x0a
Group By X
means put all those with the same value for X in the one group.
Group By X, Y
means put all those with the same values for both X and Y in the one group.
To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:
Table: Subject_Selection
+---------+----------+----------+
| Subject | Semester | Attendee |
+---------+----------+----------+
| ITB001 | 1 | John |
| ITB001 | 1 | Bob |
| ITB001 | 1 | Mickey |
| ITB001 | 2 | Jenny |
| ITB001 | 2 | James |
| MKB114 | 1 | John |
| MKB114 | 1 | Erica |
+---------+----------+----------+
When you use a group by
on the subject column only; say:
select Subject, Count(*)
from Subject_Selection
group by Subject
You will get something like:
+---------+-------+
| Subject | Count |
+---------+-------+
| ITB001 | 5 |
| MKB114 | 2 |
+---------+-------+
...because there are 5 entries for ITB001, and 2 for MKB114
If we were to group by
two columns:
select Subject, Semester, Count(*)
from Subject_Selection
group by Subject, Semester
we would get this:
+---------+----------+-------+
| Subject | Semester | Count |
+---------+----------+-------+
| ITB001 | 1 | 3 |
| ITB001 | 2 | 2 |
| MKB114 | 1 | 2 |
+---------+----------+-------+
This is because, when we group by two columns, it is saying "Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions (Count, Sum, Average, etc.) for each of those groups". In this example, this is demonstrated by the fact that, when we count them, there are three people doing ITB001 in semester 1, and two doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")
Hopefully that makes sense.
Plain and simple: A callback is a function that you give to another function, so that it can call it.
Usually it is called when some operation is completed. Since you create the callback before giving it to the other function, you can initialize it with context information from the call site. That is why it is named a call*back* - the first function calls back into the context from where it was called.
It's pretty simple
#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)
Presenting snapshot from my visual studio IDE.
To create a json class off a string, copy the string.
In Visual Sudio, click Edit > Paste special > Paste Json as classes.
This is best explained on the iOS8 Day-by-Day blog
In short, once you've set your UIViewController's modalPresentationStyle to .Popover, you can get hold of a UIPopoverPresentationClass (a new iOS8 class) via the controller's popoverPresentationController property.
Make this entry in dimens
<!--Floating action button-->
<dimen name="design_fab_image_size" tools:override="true">36dp</dimen>
Here 36dp is icon size on floating point button. This will set 36dp size for all icons for floating action button.
Updates As Per Comments
If you want to set icon size to particular Floating Action Button just go with Floating action button attributes like app:fabSize="normal" and android:scaleType="center".
<!--app:fabSize decides size of floating action button You can use normal, auto or mini as per need-->
app:fabSize="normal"
<!--android:scaleType decides how the icon drawable will be scaled on Floating action button. You can use center(to show scr image as original), fitXY, centerCrop, fitCenter, fitEnd, fitStart, centerInside.-->
android:scaleType="center"
Sorry for awakening an old question like this. But I think what the original author wanted as an answer was:
You need to force your program to make the graphic update after you make the change to the textbox1. You can do that by invoking Update();
textBox1.Text += "\r\nThread Sleeps!";
textBox1.Update();
System.Threading.Thread.Sleep(4000);
textBox1.Text += "\r\nThread awakens!";
textBox1.Update();
Normally this will be done automatically when the thread is done.
Ex, you press a button, changes are made to the text, thread dies, and then .Update()
is fired and you see the changes.
(I'm not an expert so I cant really tell you when its fired, but its something similar to this any way.)
In this case, you make a change, pause the thread, and then change the text again, and when the thread finally dies the .Update()
is fired. This resulting in you only seeing the last change made to the text.
You would experience the same issue if you had a long execution between the text changes.
You could try something like:
WebElement rxBtn = driver.findElement(By.className("icon-rx"));
WebElement otcBtn = driver.findElement(By.className("icon-otc"));
WebElement herbBtn = driver.findElement(By.className("icon-herb"));
Assert.assertEquals(true, rxBtn.isDisplayed());
Assert.assertEquals(true, otcBtn.isDisplayed());
Assert.assertEquals(true, herbBtn.isDisplayed());
This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert
whether or not they are displayed. This is using TestNG Assertions.
Try the (unofficial) binaries in this site:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
You can get the newest numpy
x64 with or without Intel MKL libs for Python 2.7 or Python 3.
If you try this:
#include<stdio.h>
void main()
{
char name[]="siva";
printf("name = %p\n", name);
printf("&name[0] = %p\n", &name[0]);
printf("name printed as %%s is %s\n",name);
printf("*name = %c\n",*name);
printf("name[0] = %c\n", name[0]);
}
Output is:
name = 0xbff5391b
&name[0] = 0xbff5391b
name printed as %s is siva
*name = s
name[0] = s
So 'name' is actually a pointer to the array of characters in memory. If you try reading the first four bytes at 0xbff5391b, you will see 's', 'i', 'v' and 'a'
Location Data
========= ======
0xbff5391b 0x73 's' ---> name[0]
0xbff5391c 0x69 'i' ---> name[1]
0xbff5391d 0x76 'v' ---> name[2]
0xbff5391e 0x61 'a' ---> name[3]
0xbff5391f 0x00 '\0' ---> This is the NULL termination of the string
To print a character you need to pass the value of the character to printf. The value can be referenced as name[0] or *name (since for an array name = &name[0]).
To print a string you need to pass a pointer to the string to printf (in this case 'name' or '&name[0]').
The select box arrow is a native ui element, it depends on the desktop theme or the web browser. Use a jQuery plugin (e.g. Select2, Chosen) or CSS.
There is no need to use Babel at this moment (JS has become very powerful) when you can simply use the default JavaScript module exports. Check full tutorial
Message.js
module.exports = 'Hello world';
app.js
var msg = require('./Messages.js');
console.log(msg); // Hello World
Add commons-collections4-x.x.jar file in your build path and try it again. It will work.
You can download it from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.0
TLDR: Use map
(returning undefined
when needed) and then filter
.
First, I believe that a map + filter function is useful since you don't want to repeat a computation in both. Swift originally called this function flatMap
but then renamed it to compactMap
.
For example, if we don't have a compactMap
function, we might end up with computation
defined twice:
let array = [1, 2, 3, 4, 5, 6, 7, 8];
let mapped = array
.filter(x => {
let computation = x / 2 + 1;
let isIncluded = computation % 2 === 0;
return isIncluded;
})
.map(x => {
let computation = x / 2 + 1;
return `${x} is included because ${computation} is even`
})
// Output: [2 is included because 2 is even, 6 is included because 4 is even]
Thus compactMap
would be useful to reduce duplicate code.
A really simple way to do something similar to compactMap
is to:
undefined
.undefined
values.This of course relies on you never needing to return undefined values as part of your original map function.
Example:
let array = [1, 2, 3, 4, 5, 6, 7, 8];
let mapped = array
.map(x => {
let computation = x / 2 + 1;
let isIncluded = computation % 2 === 0;
if (isIncluded) {
return `${x} is included because ${computation} is even`
} else {
return undefined
}
})
.filter(x => typeof x !== "undefined")
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
Here is a simple function to do this for you:
def precision(num,x):
return "{0:.xf}".format(round(num))
Here, num is the decimal number. x is the decimal up to where you want to round a floating number.
The advantage over other implementation is that it can fill zeros at the right end of the decimal to make a deciaml number up to x decimal places.
Example 1:
precision(10.2, 9)
will return
10.200000000 (up to 9 decimal points)
Example 2:
precision(10.2231, 2)
will return
10.22 (up to two decimal points)
Thanks for sharing this, I used with 2.6.7 and following query just worked,
for all docs:
db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:true})
for single doc:
db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:false})
There is not need for two separate anchor tags for Android and iOS. This should help.
// Without Contact Number
<a href="sms:?&body=message">Text Message</a>
// With Contact Number
<a href="sms:1234567890;?&body=message">Text Message</a>
// Works on both Android and iOS
Instead of the code you wrote, you may use ArrayList.addAll()
to merge the lists, Collections.sort()
to sort it and finally traverse of the resulting ArrayList to remove duplicates. The aggregate complexity is thus O(n)+O(n*log(n))+O(n)
which is equivalent to O(n*log(n))
.
Make sure that the component has the "exported" flag set to true. Also the component defining the permission should be installed before the component that uses it.
Try using this:-
mkdir -p dir;
NOTE:- This will also create any intermediate directories that don't exist; for instance,
Check out mkdir -p
or try this:-
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$Message" 1>&2
fi
I was getting the same error and i managed to solve it by configuring the MSDTC properly on the source server to allow outbound and allowed the DTC through the windows firewall.
Allow the Distributed Transaction Coordinator, tick domain , private and public options
Check that you have the correct rights set on CA certificates bundle. Usually, that means read access for everyone to CA files in the /etc/ssl/certs directory, for instance /etc/ssl/certs/ca-certificates.crt.
You can see what files have been configured for you curl version with the
curl-config --configurecommand :
$ curl-config --configure
'--prefix=/usr'
'--mandir=/usr/share/man'
'--disable-dependency-tracking'
'--disable-ldap'
'--disable-ldaps'
'--enable-ipv6'
'--enable-manual'
'--enable-versioned-symbols'
'--enable-threaded-resolver'
'--without-libidn'
'--with-random=/dev/urandom'
'--with-ca-bundle=/etc/ssl/certs/ca-certificates.crt'
'CFLAGS=-march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4' 'LDFLAGS=-Wl,-O1,--sort-common,--as-needed,-z,relro'
'CPPFLAGS=-D_FORTIFY_SOURCE=2'
Here you need read access to /etc/ssl/certs/ca-certificates.crt
$ curl-config --configure
'--build' 'i486-linux-gnu'
'--prefix=/usr'
'--mandir=/usr/share/man'
'--disable-dependency-tracking'
'--enable-ipv6'
'--with-lber-lib=lber'
'--enable-manual'
'--enable-versioned-symbols'
'--with-gssapi=/usr'
'--with-ca-path=/etc/ssl/certs'
'build_alias=i486-linux-gnu'
'CFLAGS=-g -O2'
'LDFLAGS='
'CPPFLAGS='
And the same here.
I got it working by downloading : https://cran.r-project.org/src/contrib/rJava_0.9-8.tar.gz and running command R CMD install rJava_0.9-8.tar.gz
Can you load the GUIDs into a scratch table then do a
... WHERE var IN SELECT guid FROM #scratchtable
I ran into the same problem today. And here is how I managed to run python code in Sublime Text 3:
What you need to do next is replace the content in Python.sublime-build
to
{
"cmd": ["/usr/local/bin/python", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
}
You can of course further customise it to something that works for you.
After initialize your dialog object and set the content view. Do this and enjoy.
(in the case i am setting 90% to width and 70% to height because width 90% it will be over toolbar )
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) ((int)displaymetrics.widthPixels * 0.9);
int height = (int) ((int)displaymetrics.heightPixels * 0.7);
d.getWindow().setLayout(width,height);
d.show();
label
is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center
but since the label is only as wide as the text you don't notice.
The best thing to do is to apply a specific width to the label
that is greater than the width of the content - this will give you the results you want.
I moved my htdocs folder from C:\xampp\htdocs to D:\htdocs without editing the Apache config file (httpd.conf).
Step 1) Move C:\xampp\htdocs
folder to D:\htdocs
Step 2) Create a symbolic link in C:\xampp\htdocs linked to D:\htdocs using mklink command.
D:\>mklink /J C:\xampp\htdocs D:\htdocs
Junction created for C:\xampp\htdocs <<===>> D:\htdocs
D:\>
Step 3) Done!
This page says die
is an alies of exit
, so they are identical. But also explains that:
there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script.
So, call me paranoid, but there may be no die
ing in the future.
here you go get_the_category( $post->ID );
will return the array of categories of that post you need to loop through the array
$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}
In my case, it had absolute nothing to do with network issues.
I had been using my local laravel testing environment using laradock. Because laradock runs the mysql server in a different container, you have to set your mysql host in the .env file to the name of the docker mysql container, which by default is mysql.
When I switched back to using homestead, it was trying to connect to a host named mysql, when in fact is should be looking on localhost.
What a DUH moment!
The Java Language Specification, section 15.10, states:
An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).
and
The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.
The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:
HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];
Your version is clearly better :-)
you just use variable type any and remove these types of problem.
error code :
let accessToken = res;
localStorage.setItem(LocalStorageConstants.TOKEN_KEY, accessToken);
given error Argument of type '{}' is not assignable to parameter of type 'string'.
success Code :
var accessToken:any = res;
localStorage.setItem(LocalStorageConstants.TOKEN_KEY, accessToken);
we create var type variable then use variable type any and resolve this issue.
any = handle any type of value so that remove error.
@neilfws's solution works great for data.frame
s, but not for data.table
s since they lack the row.names
property. This approach works for both:
df.expanded <- df[rep(seq(nrow(df)), df$freq), 1:2]
The code for data.table
is a tad cleaner:
# convert to data.table by reference
setDT(df)
df.expanded <- df[rep(seq(.N), freq), !"freq"]
MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.
For example, using the Content-type
header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.
Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".
A MIME type is a string identifier composed of two parts: a type
and a subtype
.
The x-
prefix of a MIME subtype simply means that it's non-standard.
The vnd
prefix means that the MIME value is vendor specific.
Key in 1 + G and it will take you to the beginning of the file. Converserly, G will take you to the end of the file.
Well, In Mapreduce there are two important phrases called Mapper and reducer both are too important, but Reducer is mandatory. In some programs reducers are optional. Now come to your question. Shuffling and sorting are two important operations in Mapreduce. First Hadoop framework takes structured/unstructured data and separate the data into Key, Value.
Now Mapper program separate and arrange the data into keys and values to be processed. Generate Key 2 and value 2 values. This values should process and re arrange in proper order to get desired solution. Now this shuffle and sorting done in your local system (Framework take care it) and process in local system after process framework cleanup the data in local system. Ok
Here we use combiner and partition also to optimize this shuffle and sort process. After proper arrangement, those key values passes to Reducer to get desired Client's output. Finally Reducer get desired output.
K1, V1 -> K2, V2 (we will write program Mapper), -> K2, V' (here shuffle and soft the data) -> K3, V3 Generate the output. K4,V4.
Please note all these steps are logical operation only, not change the original data.
Your question: What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?
Short answer: To process the data to get desired output. Shuffling is aggregate the data, reduce is get expected output.
Look in the manual http://www.php.net/manual/en/mysqli.query.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET @a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>
In your build.gradle(Module:app), add android-gif-drawable
as a dependency by adding the following code:
allprojects {
repositories {
mavenCentral()
}
}
dependencies {
compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.+'
}
implementation
, so the above line might have to be changed to:
dependencies {
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.17'
}
Then sync your project. When synchronization ends, go to your layout file and add the following code:
<pl.droidsonroids.gif.GifImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/gif_file"
/>
And that's it, you can manage it with a simple ImageView.
def median(array):
if len(array) < 1:
return(None)
if len(array) % 2 == 0:
median = (array[len(array)//2-1: len(array)//2+1])
return sum(median) / len(median)
else:
return(array[len(array)//2])
import java.util.*;
public class HelloWorld{
public static void main(String []args){
List<String> threadSafeList = new ArrayList<String>();
threadSafeList.add("A");
threadSafeList.add("D");
threadSafeList.add("F");
Set<String> threadSafeList1 = new TreeSet<String>();
threadSafeList1.add("B");
threadSafeList1.add("C");
threadSafeList1.add("E");
threadSafeList1.addAll(threadSafeList);
List mainList = new ArrayList();
mainList.addAll(Arrays.asList(threadSafeList1));
Iterator<String> mainList1 = mainList.iterator();
while(mainList1.hasNext()){
System.out.printf("total : %s %n", mainList1.next());
}
}
}
Solution for Ruby 1.8 when you have an arbitrary DateTime object:
1.8.7-p374 :001 > require 'date'
=> true
1.8.7-p374 :002 > DateTime.new(2012, 1, 15).strftime('%s')
=> "1326585600"
I am not sure in your case. But as I know to run any jar file from cmd we can use following command:
Go up to the directory where your jar file is saved:
java -jar <jarfilename>.jar
But you can check following links. I hope it'll help you:
Run Netbeans maven project from command-line?
http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html
I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.
<div id="main" class="container" role="main">
<div class="row">
<div class="span5 offset1">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
<div class="span6">
Image Here (TODO)
</div>
</div>
Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.
I think I know what you are doing wrong. If you are applying padding to the span6
like this:
<div class="span6" style="padding-left:5px;">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
It is wrong. What you have to do is add padding to the elements inside:
<div class="span6">
<h2 style="padding-left:5px;">Welcome</h2>
<p style="padding-left:5px;">Hello and welcome to my website.</p>
</div>
I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).
Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
It sounds like you basically want to take an ASCII string, or more preferably, a byte[] (as you can encode your string to a byte[] using your preferred encoding mode) into a string of ones and zeros? i.e. 101010010010100100100101001010010100101001010010101000010111101101010
This will do that for you...
//Formats a byte[] into a binary string (010010010010100101010)
public string Format(byte[] data)
{
//storage for the resulting string
string result = string.Empty;
//iterate through the byte[]
foreach(byte value in data)
{
//storage for the individual byte
string binarybyte = Convert.ToString(value, 2);
//if the binarybyte is not 8 characters long, its not a proper result
while(binarybyte.Length < 8)
{
//prepend the value with a 0
binarybyte = "0" + binarybyte;
}
//append the binarybyte to the result
result += binarybyte;
}
//return the result
return result;
}
There's no (safe) way to pause execution. You can, however, do something like this using setTimeout:
function writeNext(i)
{
document.write(i);
if(i == 5)
return;
setTimeout(function()
{
writeNext(i + 1);
}, 2000);
}
writeNext(1);
I did 2 things to solve this problem.
EDITOR=emacs crontab -e
(I have no idea why vim does not work)crontab -l
now prints the cronjobs. Now I only need to figure out why the cronjobs are still not running ;-)
Right-click on toolbar then click on "choose item" in context menu. A dialog with registered components pops up. in this dialog click "Browse" to select your assembly with the usercontrol you want to use.
PS. This assembly should be registered before.
You can import database afterwards:
docker exec -i mysql-container mysql -uuser -ppassword name_db < data.sql
For me how it worked is, I have two executable versions of python so on pip install it was installing in one version but my executable path version is different so it failed, then I changed the path in sys's environment variable and installed in the executable version of python and it was able to identify the package from site-packages
>>>Set = ["A", "B","C","D"]
>>>n = 2
>>>Subsets=[[i for i,s in zip(Set, status) if int(s) ] for status in [(format(bit,'b').zfill(len(Set))) for bit in range(2**len(Set))] if sum(map(int,status)) == n]
>>>Subsets
[['C', 'D'], ['B', 'D'], ['B', 'C'], ['A', 'D'], ['A', 'C'], ['A', 'B']]
typing "code" in dos command prompt worked for me
I like if ((item.Rate ?? 0) == 0) { }
Update 1:
You could also define an extension method like:
public static bool IsNullOrValue(this double? value, double valueToCheck)
{
return (value??valueToCheck) == valueToCheck;
}
And use it like this:
if(item.IsNullOrValue(0)){}
// but you don't get much from it
In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO TableName ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
Another way
INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
Why do you all suggest heavy scope operations? I don't see why this is not an "angular" solution:
.directive('changeClassOnScroll', function ($window) {
return {
restrict: 'A',
scope: {
offset: "@",
scrollClass: "@"
},
link: function(scope, element) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= parseInt(scope.offset)) {
element.addClass(scope.scrollClass);
} else {
element.removeClass(scope.scrollClass);
}
});
}
};
})
So you can use it like this:
<navbar change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></navbar>
or
<div change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></div>
More Suggestion
JavaScript:
$.ajax({
url: "http://FullUrl",
dataType: 'jsonp',
success: function (data) {
//Data from the server in the in the variable "data"
//In the form of an array
}
});
PHP CallBack:
<?php
$array = array(
'0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
'1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);
if(isset ($_GET['callback']))
{
header("Content-Type: application/json");
echo $_GET['callback']."(".json_encode($array).")";
}
?>
Dynamically adding directives on angularjs has two styles:
it's simple. And u can use in "link" or "compile".
var newElement = $compile( "<div my-diretive='n'></div>" )( $scope );
$element.parent().append( newElement );
It's hard, and make me headache within two days.
Using "$compile" will raise critical recursive error!! Maybe it should ignore the current directive when re-compiling element.
$element.$set("myDirective", "expression");
var newElement = $compile( $element )( $scope ); // critical recursive error.
var newElement = angular.copy(element); // the same error too.
$element.replaceWith( newElement );
So, I have to find a way to call the directive "link" function. It's very hard to get the useful methods which are hidden deeply inside closures.
compile: (tElement, tAttrs, transclude) ->
links = []
myDirectiveLink = $injector.get('myDirective'+'Directive')[0] #this is the way
links.push myDirectiveLink
myAnotherDirectiveLink = ($scope, $element, attrs) ->
#....
links.push myAnotherDirectiveLink
return (scope, elm, attrs, ctrl) ->
for link in links
link(scope, elm, attrs, ctrl)
Now, It's work well.
based on accepted answer
$output = some_function();
echo $output;
if it results array then use json_encode it will result json array which is supportable by javascript
$output = some_function();
echo json_encode($output);
If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword
$output = some_function();
echo $output;
exit;
Remember that you must first load jquery script and then the script js
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="example.js"></script>
Html is read sequentially!
To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:
$ rm -rf .git
Or to delete .gitignore and .gitmodules if any (via @aragaer):
$ rm -rf .git*
Then from the same ex-repository folder, to see if hidden folder .git is still there:
$ ls -lah
If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).
To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:
defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder
Source: http://lifehacker.com/188892/show-hidden-files-in-finder.