for me it was just a little compile error and sadly Android Studio doesn't show it . please search manually . trying to enable work offline and clean&rebuild may help you more
You can check it from your command prompt by running gem help commands
and then selecting the proper command:
kirti@kirti-Aspire-5733Z:~$ gem help commands
GEM commands are:
build Build a gem from a gemspec
cert Manage RubyGems certificates and signing settings
check Check a gem repository for added or missing files
cleanup Clean up old versions of installed gems in the local
repository
contents Display the contents of the installed gems
dependency Show the dependencies of an installed gem
environment Display information about the RubyGems environment
fetch Download a gem and place it in the current directory
generate_index Generates the index files for a gem server directory
help Provide help on the 'gem' command
install Install a gem into the local repository
list Display gems whose name starts with STRING
lock Generate a lockdown list of gems
mirror Mirror all gem files (requires rubygems-mirror)
outdated Display all gems that need updates
owner Manage gem owners on RubyGems.org.
pristine Restores installed gems to pristine condition from
files located in the gem cache
push Push a gem up to RubyGems.org
query Query gem information in local or remote repositories
rdoc Generates RDoc for pre-installed gems
regenerate_binstubs Re run generation of executable wrappers for gems.
search Display all gems whose name contains STRING
server Documentation and gem repository HTTP server
sources Manage the sources and cache file RubyGems uses to
search for gems
specification Display gem specification (in yaml)
stale List gems along with access times
uninstall Uninstall gems from the local repository
unpack Unpack an installed gem to the current directory
update Update installed gems to the latest version
which Find the location of a library file you can require
yank Remove a specific gem version release from
RubyGems.org
For help on a particular command, use 'gem help COMMAND'.
Commands may be abbreviated, so long as they are unambiguous.
e.g. 'gem i rake' is short for 'gem install rake'.
kirti@kirti-Aspire-5733Z:~$
Now from the above I can see the command environment
is helpful. So I would do:
kirti@kirti-Aspire-5733Z:~$ gem help environment
Usage: gem environment [arg] [options]
Common Options:
-h, --help Get help on this command
-V, --[no-]verbose Set the verbose level of output
-q, --quiet Silence commands
--config-file FILE Use this config file instead of default
--backtrace Show stack backtrace on errors
--debug Turn on Ruby debugging
Arguments:
packageversion display the package version
gemdir display the path where gems are installed
gempath display path used to search for gems
version display the gem format version
remotesources display the remote gem servers
platform display the supported gem platforms
<omitted> display everything
Summary:
Display information about the RubyGems environment
Description:
The RubyGems environment can be controlled through command line arguments,
gemrc files, environment variables and built-in defaults.
Command line argument defaults and some RubyGems defaults can be set in a
~/.gemrc file for individual users and a /etc/gemrc for all users. These
files are YAML files with the following YAML keys:
:sources: A YAML array of remote gem repositories to install gems from
:verbose: Verbosity of the gem command. false, true, and :really are the
levels
:update_sources: Enable/disable automatic updating of repository metadata
:backtrace: Print backtrace when RubyGems encounters an error
:gempath: The paths in which to look for gems
:disable_default_gem_server: Force specification of gem server host on
push
<gem_command>: A string containing arguments for the specified gem command
Example:
:verbose: false
install: --no-wrappers
update: --no-wrappers
:disable_default_gem_server: true
RubyGems' default local repository can be overridden with the GEM_PATH and
GEM_HOME environment variables. GEM_HOME sets the default repository to
install into. GEM_PATH allows multiple local repositories to be searched for
gems.
If you are behind a proxy server, RubyGems uses the HTTP_PROXY,
HTTP_PROXY_USER and HTTP_PROXY_PASS environment variables to discover the
proxy server.
If you would like to push gems to a private gem server the RUBYGEMS_HOST
environment variable can be set to the URI for that server.
If you are packaging RubyGems all of RubyGems' defaults are in
lib/rubygems/defaults.rb. You may override these in
lib/rubygems/defaults/operating_system.rb
kirti@kirti-Aspire-5733Z:~$
Finally to show you what you asked, I would do:
kirti@kirti-Aspire-5733Z:~$ gem environment gemdir
/home/kirti/.rvm/gems/ruby-2.0.0-p0
kirti@kirti-Aspire-5733Z:~$ gem environment gempath
/home/kirti/.rvm/gems/ruby-2.0.0-p0:/home/kirti/.rvm/gems/ruby-2.0.0-p0@global
kirti@kirti-Aspire-5733Z:~$
Update (June 2016): I now try to support touch and mouse input on every resolution, since the device landscape is slowly blurring the lines between what things are and aren't touch devices. iPad Pros are touch-only with the resolution of a 13" laptop. Windows laptops now frequently come with touch screens.
Other similar SO answers (see other answer on this question) might have different ways to try to figure out what sort of device the user is using, but none of them are fool-proof. I encourage you to check those answers out if you absolutely need to try to determine the device.
iPhones, for one, ignore the handheld
query (Source). And I wouldn't be surprised if other smartphones do, too, for similar reasons.
The current best way that I use to detect a mobile device is to know its width and use the corresponding media query to catch it. That link there lists some popular ones. A quick Google search would yield you any others you might need, I'm sure.
For more iPhone-specific ones (such as Retina display), check out that first link I posted.
Nice solution by leocaseiro
<input class="ng-hide" id="input-file-id" multiple type="file" />
<label for="input-file-id" class="md-button md-raised md-primary">Choose Files</label>
View in codepen
Watch out! checking the radiobutton with setChecked()
is not changing the state inside the RadioGroup. For example this method from the radioGroup will return a wrong result: getCheckedRadioButtonId()
.
Check the radioGroup always with
mOption.check(R.id.option1);
you've been warned ;)
From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
You can use fall-through:
switch (pageid)
{
case "listing-page":
case "home-page":
alert("hello");
break;
case "details-page":
alert("goodbye");
break;
}
You can also use string.match().
var string1 = "aBc";
var match = string1.match(/AbC/i);
if(match) {
}
If you are using apache 2.2 inside your virtual host you should add following directive (mod_authz_host):
Order deny,allow
Deny from all
Allow from 10.0.0.1
You can even specify a subnet
Allow from 10.0.0
Apache 2.4 looks like a little different as configuration. Maybe better you specify which version of apache are you using.
The account which is running the service might not have mapped the D:-drive (they are user-specific). Try sharing the directory, and use full UNC-path in your backupConfig
.
Your watcher
of type FileSystemWatcher
is a local variable, and is out of scope when the OnStart
method is done. You probably need it as an instance or class variable.
I need context for using arrayAdapter IN fragment, when I was using getActivity error occurs but when i replace it with getContext it works for me
listView LV=getView().findViewById(R.id.listOFsensors);
LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));
A solution very simple, but you have to know the index of the original position and the index of the new position:
list1[index1],list1[index2]=list1[index2],list1[index1]
You may be able to simply access a pre-arranged file path on the system. This is preferable since files added to the webapp directory might be lost or the webapp may not be unpacked depending on system configuration.
In our server, we define a system property set in the App Server's JVM which points to the "home directory" for our app's external data. Of course this requires modification of the App Server's configuration (-DAPP_HOME=... added to JVM_OPTS at startup), we do it mainly to ease testing of code run outside the context of an App Server.
You could just as easily retrieve a path from the servlet config:
<web-app>
<context-param>
<param-name>MyAppHome</param-name>
<param-value>/usr/share/myapp</param-value>
</context-param>
...
</web-app>
Then retrieve this path and use it as the base path to read the file supplied by the client.
public class MyAppConfig implements ServletContextListener {
// NOTE: static references are not a great idea, shown here for simplicity
static File appHome;
static File customerDataFile;
public void contextInitialized(ServletContextEvent e) {
appHome = new File(e.getServletContext().getInitParameter("MyAppHome"));
File customerDataFile = new File(appHome, "SuppliedFile.csv");
}
}
class DataProcessor {
public void processData() {
File dataFile = MyAppConfig.customerDataFile;
// ...
}
}
As I mentioned the most likely problem you'll encounter is security restrictions. Nothing guarantees webapps can ready any files above their webapp root. But there are generally simple methods for granting exceptions for specific paths to specific webapps.
Regardless of the code in which you then need to access this file, since you are running within a web application you are guaranteed this is initialized first, and can stash it's value somewhere convenient for the rest of your code to refer to, as in my example or better yet, just simply pass the path as a paramete to the code which needs it.
If you need fixed size types, use types like uint32_t (unsigned integer 32 bits) defined in stdint.h. They are specified in C99.
For pages on the same domain and different subdomain, you can set the document.domain
property via javascript.
Both the parent frame and the iframe need to set their document.domain to something that is common betweeen them.
i.e.
www.foo.mydomain.com
and api.foo.mydomain.com
could each use either foo.mydomain.com
or just mydomain.com
and be compatible (no, you can't set them both to com
, for security reasons...)
also, note that document.domain is a one way street. Consider running the following three statements in order:
// assume we're starting at www.foo.mydomain.com
document.domain = "foo.mydomain.com" // works
document.domain = "mydomain.com" // works
document.domain = "foo.mydomain.com" // throws a security exception
Modern browsers can also use window.postMessage to talk across origins, but it won't work in IE6. https://developer.mozilla.org/en/DOM/window.postMessage
You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()
If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:
@Path("/resource")
class MyResource {
// one way to get HttpServletResponse
@Context
private HttpServletResponse anotherServletResponse;
// another way
Response myMethod(@Context HttpServletResponse servletResponse) {
// ... code
}
}
The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).
All this peace of code put into *.bat file and run all at once:
My code for creating user in oracle. crate_drop_user.sql file
drop user "USER" cascade;
DROP TABLESPACE "USER";
CREATE TABLESPACE USER DATAFILE 'D:\ORA_DATA\ORA10\USER.ORA' SIZE 10M REUSE
AUTOEXTEND
ON NEXT 5M EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO
/
CREATE TEMPORARY TABLESPACE "USER_TEMP" TEMPFILE
'D:\ORA_DATA\ORA10\USER_TEMP.ORA' SIZE 10M REUSE AUTOEXTEND
ON NEXT 5M EXTENT MANAGEMENT LOCAL
UNIFORM SIZE 1M
/
CREATE USER "USER" PROFILE "DEFAULT"
IDENTIFIED BY "user_password" DEFAULT TABLESPACE "USER"
TEMPORARY TABLESPACE "USER_TEMP"
/
alter user USER quota unlimited on "USER";
GRANT CREATE PROCEDURE TO "USER";
GRANT CREATE PUBLIC SYNONYM TO "USER";
GRANT CREATE SEQUENCE TO "USER";
GRANT CREATE SNAPSHOT TO "USER";
GRANT CREATE SYNONYM TO "USER";
GRANT CREATE TABLE TO "USER";
GRANT CREATE TRIGGER TO "USER";
GRANT CREATE VIEW TO "USER";
GRANT "CONNECT" TO "USER";
GRANT SELECT ANY DICTIONARY to "USER";
GRANT CREATE TYPE TO "USER";
create file import.bat and put this lines in it:
SQLPLUS SYSTEM/systempassword@ORA_alias @"crate_drop_user.SQL"
IMP SYSTEM/systempassword@ORA_alias FILE=user.DMP FROMUSER=user TOUSER=user GRANTS=Y log =user.log
Be carefull if you will import from one user to another. For example if you have user named user1 and you will import to user2 you may lost all grants , so you have to recreate it.
Good luck, Ivan
For a pure python module you can find the source by looking at themodule.__file__
.
The datetime module, however, is written in C, and therefore datetime.__file__
points to a .so file (there is no datetime.__file__
on Windows), and therefore, you can't see the source.
If you download a python source tarball and extract it, the modules' code can be found in the Modules subdirectory.
For example, if you want to find the datetime code for python 2.6, you can look at
Python-2.6/Modules/datetimemodule.c
You can also find the latest Mercurial version on the web at https://hg.python.org/cpython/file/tip/Modules/_datetimemodule.c
Define a helper function like this
function checkWhitespace(inputString){
let stringArray = inputString.split(' ');
let output = true;
for (let el of stringArray){
if (el!=''){
output=false;
}
}
return output;
}
Then check your input field value by passing through as an argument. If function returns true, that means value is only white space.
As an example
let inputValue = $('#firstName').val();
if(checkWhitespace(inputValue)) {
// Show Warnings or return warnings
}else {
// // Block of code-probably store input value into database
}
listofIDs.Select(int.Parse).ToList()
I don't care if the page reloads or displays the results immediately;
Good!
Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.
I just want to have a button on my website make a PHP file run.
That can be done with a form with a single button:
<form action="">
<input type="submit" value="my button"/>
</form>
That's it.
Pretty much. Also note that there are cases where ajax is really the way to go.
That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.
If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?
Because the PHP code is not in the HTML just fine
. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.
You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.
If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.
Use a form to do the call. You can have it to direct the user to a particlar file:
<form action="myphpfile.php">
<input type="submit" value="click on me!">
</form>
The user will end up in the page myphpfile.php
. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).
I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.
You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden"
and use POST
):
<form action="" method="POST">
<input type="text" value="default value, you can edit it" name="myfield">
<input type="submit" value = "post">
</form>
What do I need to know about it to call a PHP file that will create a text file on a button press?
see: How to write into a file in PHP.
I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
//Ok we got a POST, probably from a FORM, read from $_POST.
var_dump($_PSOT); //Use this to see what info we got!
}
else
{
//You could assume you got a GET
var_dump($_GET); //Use this to see what info we got!
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta char-set="utf-8">
<title>Page title</title>
</head>
<body>
<form action="" method="POST">
<input type="text" value="default value, you can edit it" name="myfield">
<input type="submit" value = "post">
</form>
</body>
</html>
Note: you can remove var_dump
, it is just for debugging purposes.
I know the next stage, you will be asking how to:
There is a single answer for that: Sessions.
I'll give a more extensive template for Post-Redirect-Get
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
var_dump($_PSOT);
//Do stuff...
//Write results to session
session_start();
$_SESSION['stuff'] = $something;
//You can store stuff such as the user ID, so you can remeember him.
//redirect:
header('Location: ', true, 303);
//The redirection will cause the browser to request with GET
//The results of the operation are in the session variable
//It has empty location because we are redirecting to the same page
//Otherwise use `header('Location: anotherpage.php', true, 303);`
exit();
}
else
{
//You could assume you got a GET
var_dump($_GET); //Use this to see what info we got!
//Get stuff from session
session_start();
if (array_key_exists('stuff', $_SESSION))
{
$something = $_SESSION['stuff'];
//we got stuff
//later use present the results of the operation to the user.
}
//clear stuff from session:
unset($_SESSION['stuff']);
//set headers
header('Content-Type: text/html; charset=utf-8');
//This header is telling the browser what are we sending.
//And it says we are sending HTML in UTF-8 encoding
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta char-set="utf-8">
<title>Page title</title>
</head>
<body>
<?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
<form action="" method="POST">
<input type="text" value="default value, you can edit it" name="myfield">
<input type="submit" value = "post">
</form>
</body>
</html>
Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.
Also, use UTF-8 because UTF-8!
Notes:
I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.
If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.
Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.
Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.
So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
var_dump($_PSOT);
header('Location: ', true, 303);
exit();
}
else
{
var_dump($_GET);
header('Content-Type: text/html; charset=utf-8');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta char-set="utf-8">
<title>Page title</title>
<script>
function ajaxmagic()
{
$.post( //call the server
"test.php", //At this url
{
field: "value",
name: "John"
} //And send this data to it
).done( //And when it's done
function(data)
{
$('#fromAjax').html(data); //Update here with the response
}
);
}
</script>
</head>
<body>
<input type="button" value = "use ajax", onclick="ajaxmagic()">
<span id="fromAjax"></span>
</body>
</html>
The above code will send a POST request to the page test.php
.
Note: You can mix sessions
with ajax
and stuff if you want.
... for these or any other, please make another questions. That's too much for this one.
Here's a method that handles .tar.gz
properly, even in a path with dots in directory names:
private static final String getExtension(final String filename) {
if (filename == null) return null;
final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1);
final int afterLastBackslash = afterLastSlash.lastIndexOf('\\') + 1;
final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash);
return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1);
}
afterLastSlash
is created to make finding afterLastBackslash
quicker since it won't have to search the whole string if there are some slashes in it.
The char[]
inside the original String
is reused, adding no garbage there, and the JVM will probably notice that afterLastSlash
is immediately garbage in order to put it on the stack instead of the heap.
ng g c --dry-run so you can see what you are about to do before you actually do it will save some frustration. Just shows you what it is going to do without actually doing it.
API keys are just one way of authenticating users of web services.
To create a valid DSA format private key supported by Paramiko in Puttygen.
Click on Conversions then Export OpenSSH Key
Another way to do this would be to add before adding lines in your output, the following line :
output.writerow(dict(zip(dr.fieldnames, dr.fieldnames)))
The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.
Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH
environment variable (or other language equivalent, like PYTHONPATH
, LD_LIBRARY_PATH
) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like
var logger = new Logger() //sane, simple code
And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.
No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.
P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.
The package broom
comes in handy here (it uses the "tidy" format).
tidy(mg)
will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).
Example from broom
's github repo:
lmfit <- lm(mpg ~ wt, mtcars)
require(broom)
tidy(lmfit)
term estimate std.error statistic p.value
1 (Intercept) 37.285 1.8776 19.858 8.242e-19
2 wt -5.344 0.5591 -9.559 1.294e-10
is.data.frame(tidy(lmfit))
[1] TRUE
If there is a one to one mapping between entity and entity_property you can use entity_id as the identifier.
Here is how I would do it (please ignore worry Logger class calls):
public boolean isElementExist(By by) {
int count = driver.findElements(by).size();
if (count>=1) {
Logger.LogMessage("isElementExist: " + by + " | Count: " + count, Priority.Medium);
return true;
}
else {
Logger.LogMessage("isElementExist: " + by + " | Could not find element", Priority.High);
return false;
}
}
public boolean isElementNotExist(By by) {
int count = driver.findElements(by).size();
if (count==0) {
Logger.LogMessage("ElementDoesNotExist: " + by, Priority.Medium);
return true;
}
else {
Logger.LogMessage("ElementDoesExist: " + by, Priority.High);
return false;
}
}
public boolean isElementVisible(By by) {
try {
if (driver.findElement(by).isDisplayed()) {
Logger.LogMessage("Element is Displayed: " + by, Priority.Medium);
return true;
}
}
catch(Exception e) {
Logger.LogMessage("Element is Not Displayed: " + by, Priority.High);
return false;
}
return false;
}
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/META-INF/PersistenceContext.xml
</param-value>
</context-param>
I have initialized my PersistenceContext.xml
within <context-param>
because all my servlets will be interacting with database in MVC framework.
Howerver,
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:ApplicationContext.xml
</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.organisation.project.rest</param-value>
</init-param>
</servlet>
in the aforementioned code, I am configuring jersey and the ApplicationContext.xml
only to rest layer. For the same I am using </init-param>
Don't check. Go ahead and assume that it is the right input, and catch an exception if it isn't.
intresult = None
while intresult is None:
input = raw_input()
try: intresult = int(input)
except ValueError: pass
I've had to do this a few times to-date. Note that this only works on 1 file at a time.
Get a list of all commits that modified a file. The one at the bottom will the the first commit:
git log --pretty=oneline --branches -- pathToFile
To remove the file from history use the first commit sha1 and the path to file from the previous command, and fill them into this command:
git filter-branch --index-filter 'git rm --cached --ignore-unmatch <path-to-file>' -- <sha1-where-the-file-was-first-added>..
(left, upper, right, lower) means two points,
with an 800x600 pixel image, the image's left upper point is (0, 0), the right lower point is (800, 600).
So, for cutting the image half:
from PIL import Image
img = Image.open("ImageName.jpg")
img_left_area = (0, 0, 400, 600)
img_right_area = (400, 0, 800, 600)
img_left = img.crop(img_left_area)
img_right = img.crop(img_right_area)
img_left.show()
img_right.show()
The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Note that the coordinates refer to the implied pixel corners; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5).
Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples, with the upper left corner given first. For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600).
Swift 4 solution:
UIApplication.shared.open(NSURL(string:"http://yo.lo")! as URL, options: [String : Any](), completionHandler: nil)
Regarding the Carmac method, it seems like it would be quite easy just to iterate once more, which should double the number of digits of accuracy. It is, after all, an extremely truncated iterative method -- Newton's, with a very good first guess.
Regarding your current best, I see two micro-optimizations:
I.e:
// Divide out powers of 4 using binary search
if((n & 0x3L) == 0) {
n >>=2;
if((n & 0xffffffffL) == 0)
n >>= 32;
if((n & 0xffffL) == 0)
n >>= 16;
if((n & 0xffL) == 0)
n >>= 8;
if((n & 0xfL) == 0)
n >>= 4;
if((n & 0x3L) == 0)
n >>= 2;
}
Even better might be a simple
while ((n & 0x03L) == 0) n >>= 2;
Obviously, it would be interesting to know how many numbers get culled at each checkpoint -- I rather doubt the checks are truly independent, which makes things tricky.
Attempting to "convert them all" is the wrong approach to the problem.
Firstly, you need to understand the limitations of what you are trying to do. As others have pointed out, diacritics are there for a reason: they are essentially unique letters in the alphabet of that language with their own meaning / sound etc.: removing those marks is just the same as replacing random letters in an English word. This is before you even go onto consider the Cyrillic languages and other script based texts such as Arabic, which simply cannot be "converted" to English.
If you must, for whatever reason, convert characters, then the only sensible way to approach this it to firstly reduce the scope of the task at hand. Consider the source of the input - if you are coding an application for "the Western world" (to use as good a phrase as any), it would be unlikely that you would ever need to parse Arabic characters. Similarly, the Unicode character set contains hundreds of mathematical and pictorial symbols: there is no (easy) way for users to directly enter these, so you can assume they can be ignored.
By taking these logical steps you can reduce the number of possible characters to parse to the point where a dictionary based lookup / replace operation is feasible. It then becomes a small amount of slightly boring work creating the dictionaries, and a trivial task to perform the replacement. If your language supports native Unicode characters (as Java does) and optimises static structures correctly, such find and replaces tend to be blindingly quick.
This comes from experience of having worked on an application that was required to allow end users to search bibliographic data that included diacritic characters. The lookup arrays (as it was in our case) took perhaps 1 man day to produce, to cover all diacritic marks for all Western European languages.
You should try slicing the image if possible into a smaller piece which could be repeated. I have sliced that image to a 101x101px image.
CSS:
body{
background-image: url(SO_texture_bg.jpg);
background-repeat:repeat;
}
But in some cases, we wouldn't be able to slice the image to a smaller one. In that case, I would use the whole image. But you could also use the CSS3 methods like what Mustafa Kamal had mentioned.
Wish you good luck.
Here lies your problem:
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text); // tv is null
}
--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.
The error message is very clear and even tells you at what method. From the documentation:
public final View findViewById (int id)
Look for a child view with the given id. If this view has the given id, return this view.
Parameters
id The id to search for.
Returns
The view that has the given id in the hierarchy or null
http://developer.android.com/reference/android/view/View.html#findViewById%28int%29
In other words: You have no view with the id you give as a parameter.
You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.
You can get the Java EE Edition of eclipse with has it pre-installed.
To create and run your first servlet:
doGet()
method.That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.
Try the following to convert it to hex
public static string ToHex(this int value) {
return String.Format("0x{0:X}", value);
}
And back again
public static int FromHex(string value) {
// strip the leading 0x
if ( value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
value = value.Substring(2);
}
return Int32.Parse(value, NumberStyles.HexNumber);
}
As simple as this !
var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);
Probably good for small results, works in all versions of TSQL:
SELECT
*
FROM
(SELECT TOP (N) *
FROM
(SELECT TOP (M + N - 1)
FROM
Table
ORDER BY
MyColumn) qasc
ORDER BY
MyColumn DESC) qdesc
ORDER BY
MyColumn
I am not sure how to see the actual rows/records that come back.
Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.
In SQL Developer, you can execute a procedure that returns a ref cursor as follows
var rc refcursor
exec proc_name(:rc)
After that, if you execute the following, it will show the results from the cursor:
print rc
If you don't have access to sysjobs table (someone elses server etc) you might be have or be allowed access to sysjobs_view
SELECT *
from msdb..sysjobs_view s
left join master.sys.syslogins l on s.owner_sid = l.sid
or
SELECT *, SUSER_SNAME(s.owner_sid) AS owner
from msdb..sysjobs_view s
I would use a StringBuilder class for doing string manipulation as it will more efficient (being mutable)
string flights = "Flight A, B,C,D";
StringBuilder message = new StringBuilder();
message.Append("Hi We have these flights for you: ");
message.Append(flights);
message.Append(" . Which one do you want?");
This one works for me, I used 'request' library with json()
check out the doc in requests for humans
import requests
url = 'here goes your url'
obj = requests.get(url).json()
The way I handled this was switching the className of a label based on a condition. This way you only need one label and you can have different classes for different states... Hope that helps!
I like the idea of Chasmo, but I preffer to use the advantages of things like
convert $(ls *.pdf) ../merged.pdf
Giving multiple source files to convert
leads to merging them into a common pdf. This command merges all files with .pdf
extension in the actual directory into merged.pdf
in the parent dir.
Maybe It is OpenJPA's bug, When rollback it reset the @Version field, but the pcVersionInit keep true. I have a AbstraceEntity which declared the @Version field. I can workaround it by reset the pcVersionInit field. But It is not a good idea. I think it not work when have cascade persist entity.
private static Field PC_VERSION_INIT = null;
static {
try {
PC_VERSION_INIT = AbstractEntity.class.getDeclaredField("pcVersionInit");
PC_VERSION_INIT.setAccessible(true);
} catch (NoSuchFieldException | SecurityException e) {
}
}
public T call(final EntityManager em) {
if (PC_VERSION_INIT != null && isDetached(entity)) {
try {
PC_VERSION_INIT.set(entity, false);
} catch (IllegalArgumentException | IllegalAccessException e) {
}
}
em.persist(entity);
return entity;
}
/**
* @param entity
* @param detached
* @return
*/
private boolean isDetached(final Object entity) {
if (entity instanceof PersistenceCapable) {
PersistenceCapable pc = (PersistenceCapable) entity;
if (pc.pcIsDetached() == Boolean.TRUE) {
return true;
}
}
return false;
}
find . -type l -ls
Explanation: find
from the current directory .
onwards all references of -type l
ink and list -ls
those in detail.
Plain and simple...
Expanding upon this answer, here are a couple more symbolic link related find
commands:
find . -lname link_target
Note that link_target
is a pattern that may contain wildcard characters.
find -L . -type l -ls
The -L
option instructs find
to follow symbolic links, unless when broken.
find -L . -type l -delete -exec ln -s new_target {} \;
More find
examples can be found here: https://hamwaves.com/find/
select FOUND_ROWS();
will return no. of records selected by select query.
It looks like a bug http://code.google.com/p/android/issues/detail?id=939.
Finally I have to write something like this:
<stroke android:width="3dp"
android:color="#555555"
/>
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
/>
<corners android:radius="1dp"
android:bottomRightRadius="2dp" android:bottomLeftRadius="0dp"
android:topLeftRadius="2dp" android:topRightRadius="0dp"/>
I have to specify android:bottomRightRadius="2dp" for left-bottom rounded corner (another bug here).
Here's an example of using text-overflow:
.text {_x000D_
display: block;_x000D_
width: 100px;_x000D_
overflow: hidden;_x000D_
white-space: nowrap;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<span class="text">Hello world this is a long sentence</span>
_x000D_
This can be a somewhat confusing way of defining the size but you are basically specifying the area of the marker. This means, to double the width (or height) of the marker you need to increase s
by a factor of 4. [because A = WH => (2W)(2H)=4A]
There is a reason, however, that the size of markers is defined in this way. Because of the scaling of area as the square of width, doubling the width actually appears to increase the size by more than a factor 2 (in fact it increases it by a factor of 4). To see this consider the following two examples and the output they produce.
# doubling the width of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*4**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()
gives
Notice how the size increases very quickly. If instead we have
# doubling the area of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*2**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()
gives
Now the apparent size of the markers increases roughly linearly in an intuitive fashion.
As for the exact meaning of what a 'point' is, it is fairly arbitrary for plotting purposes, you can just scale all of your sizes by a constant until they look reasonable.
Hope this helps!
Edit: (In response to comment from @Emma)
It's probably confusing wording on my part. The question asked about doubling the width of a circle so in the first picture for each circle (as we move from left to right) it's width is double the previous one so for the area this is an exponential with base 4. Similarly the second example each circle has area double the last one which gives an exponential with base 2.
However it is the second example (where we are scaling area) that doubling area appears to make the circle twice as big to the eye. Thus if we want a circle to appear a factor of n
bigger we would increase the area by a factor n
not the radius so the apparent size scales linearly with the area.
Edit to visualize the comment by @TomaszGandor:
This is what it looks like for different functions of the marker size:
x = [0,2,4,6,8,10,12,14,16,18]
s_exp = [20*2**n for n in range(len(x))]
s_square = [20*n**2 for n in range(len(x))]
s_linear = [20*n for n in range(len(x))]
plt.scatter(x,[1]*len(x),s=s_exp, label='$s=2^n$', lw=1)
plt.scatter(x,[0]*len(x),s=s_square, label='$s=n^2$')
plt.scatter(x,[-1]*len(x),s=s_linear, label='$s=n$')
plt.ylim(-1.5,1.5)
plt.legend(loc='center left', bbox_to_anchor=(1.1, 0.5), labelspacing=3)
plt.show()
I came here because I had funny-char-syndrome on my requests
output. I thought response.text
would give me a properly decoded string, but in the output I found funny double-chars where German umlauts should have been.
Turns out response.encoding
was empty somehow and so response
did not know how to properly decode the content and just treated it as ASCII (I guess).
My solution was to get the raw bytes with 'response.content' and manually apply decode('utf_8')
to it. The result was schöne Umlaute.
The correctly decoded
fĂ¼r
vs. the improperly decoded
fAzr
Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.
Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.
So, answering your questions:
There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.
GUI:
Output:
Conventions:
Tools:
Update: Since Python 3.5 you can use type hints which is a compact, machine-readable syntax:
from typing import Dict, Union
def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
"""
Explanation: this function takes two arguments: `i` and `d`.
`i` is annotated simply as `int`. `d` is a dictionary with `str` keys
and values that can be either `str` or `int`.
The return type is `int`.
"""
The main advantage of this syntax is that it is defined by the language and that it's unambiguous, so tools like PyCharm can easily take advantage from it.
As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)
Duration column = End - Start
Another way of adding schema dynamically or if you want to change it to something else
DECLARE @schema AS VARCHAR(256) = 'dbo.'
--User can also use SELECT SCHEMA_NAME() to get the default schema name
DECLARE @ID INT
declare @SQL nvarchar(max) = 'EXEC ' + @schema +'spSelectCaseBookingDetails @BookingID = ' + CAST(@ID AS NVARCHAR(10))
No need to cast @ID if it is nvarchar or varchar
execute (@SQL)
There are two ways to delete a stash:
$ git stash drop <stash_id>
. $ git stash clear
.Use both of them with caution, it maybe is difficult to revert the once deleted stashes.
Here is the reference article.
Make sure you are not facing a "cross module" problem
If the component which is using the pipe, doesn't belong to the module which has declared the pipe component "globally" then the pipe is not found and you get this error message.
In my case I've declared the pipe in a separate module and imported this pipe module in any other module having components using the pipe.
I have declared a that the component in which you are using the pipe is
the Pipe Module
import { NgModule } from '@angular/core';
import { myDateFormat } from '../directives/myDateFormat';
@NgModule({
imports: [],
declarations: [myDateFormat],
exports: [myDateFormat],
})
export class PipeModule {
static forRoot() {
return {
ngModule: PipeModule,
providers: [],
};
}
}
Usage in another module (e.g. app.module)
// Import APPLICATION MODULES
...
import { PipeModule } from './tools/PipeModule';
@NgModule({
imports: [
...
, PipeModule.forRoot()
....
],
Element.style
MDNvar toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
_x000D_
#content{
display:none;
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
About the ^
bitwise XOR as I/O toggler
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
.classList.toggle()
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.classList.toggle("show");
});
_x000D_
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
.toggle()
Docs; .fadeToggle()
Docs; .slideToggle()
Docs$("#toggle").on("click", function(){
$("#content").toggle(); // .fadeToggle() // .slideToggle()
});
_x000D_
#content{
display:none;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
.toggleClass()
Docs.toggle()
toggles an element's display
"block"/"none"
values
$("#toggle").on("click", function(){
$("#content").toggleClass("show");
});
_x000D_
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
<summary>
and <details>
(unsupported on IE and Opera Mini)
<details>
<summary>TOGGLE</summary>
<p>Some content...</p>
</details>
_x000D_
checkbox
[id^=toggle],
[id^=toggle] + *{
display:none;
}
[id^=toggle]:checked + *{
display:block;
}
_x000D_
<label for="toggle-1">TOGGLE</label>
<input id="toggle-1" type="checkbox">
<div>Some content...</div>
_x000D_
radio
[id^=switch],
[id^=switch] + *{
display:none;
}
[id^=switch]:checked + *{
display:block;
}
_x000D_
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>
<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>
<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
_x000D_
:target
(just to make sure you have it in your arsenal)
[id^=switch] + *{
display:none;
}
[id^=switch]:target + *{
display:block;
}
_x000D_
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>
<i id="switch1"></i>
<div>1 Merol Muspi ...</div>
<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
_x000D_
If you pick one of JS / jQuery way to actually toggle a className
, you can always add animated transitions to your element, here's a basic example:
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function(){
content.classList.toggle("appear");
}, false);
_x000D_
#content{
/* DON'T USE DISPLAY NONE/BLOCK! Instead: */
background: #cf5;
padding: 10px;
position: absolute;
visibility: hidden;
opacity: 0;
transition: 0.6s;
-webkit-transition: 0.6s;
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
#content.appear{
visibility: visible;
opacity: 1;
transform: translateX(0);
-webkit-transform: translateX(0);
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some Togglable content...</div>
_x000D_
The accepted answer won't work from 1.2.0-rc1+ (Github issue).
Here's a quick fix created by endorama:
/*global angular */
(function (ng) {
'use strict';
var app = ng.module('ngLoadScript', []);
app.directive('script', function() {
return {
restrict: 'E',
scope: false,
link: function(scope, elem, attr) {
if (attr.type === 'text/javascript-lazy') {
var code = elem.text();
var f = new Function(code);
f();
}
}
};
});
}(angular));
Simply add this file, load ngLoadScript
module as application dependency and use type="text/javascript-lazy"
as type for script you which to load lazily in partials:
<script type="text/javascript-lazy">
console.log("It works!");
</script>
I wrote this answer back in '09 when Android was relatively new, and there were many not well established areas in Android development. I have added a long addendum at the bottom of this post, addressing some criticism, and detailing a philosophical disagreement I have with the use of Singletons rather than subclassing Application. Read it at your own risk.
ORIGINAL ANSWER:
The more general problem you are encountering is how to save state across several Activities and all parts of your application. A static variable (for instance, a singleton) is a common Java way of achieving this. I have found however, that a more elegant way in Android is to associate your state with the Application context.
As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.
The way to do this is to create your own subclass of android.app.Application, and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context
using the Context.getApplicationContext()
method (Activity
also provides a method getApplication()
which has the exact same effect). Following is an extremely simplified example, with caveats to follow:
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
This has essentially the same effect as using a static variable or singleton, but integrates quite well into the existing Android framework. Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).
Something to note from the example above; suppose we had instead done something like:
class MyApp extends Application {
private String myState = /* complicated and slow initialization */;
public String getState(){
return myState;
}
}
Now this slow initialization (such as hitting disk, hitting network, anything blocking, etc) will be performed every time Application is instantiated! You may think, well, this is only once for the process and I'll have to pay the cost anyways, right? For instance, as Dianne Hackborn mentions below, it is entirely possible for your process to be instantiated -just- to handle a background broadcast event. If your broadcast processing has no need for this state you have potentially just done a whole series of complicated and slow operations for nothing. Lazy instantiation is the name of the game here. The following is a slightly more complicated way of using Application which makes more sense for anything but the simplest of uses:
class MyApp extends Application {
private MyStateManager myStateManager = new MyStateManager();
public MyStateManager getStateManager(){
return myStateManager ;
}
}
class MyStateManager {
MyStateManager() {
/* this should be fast */
}
String getState() {
/* if necessary, perform blocking calls here */
/* make sure to deal with any multithreading/synchronicity issues */
...
return state;
}
}
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyStateManager stateManager = ((MyApp)getApplicationContext()).getStateManager();
String state = stateManager.getState();
...
}
}
While I prefer Application subclassing to using singletons here as the more elegant solution, I would rather developers use singletons if really necessary over not thinking at all through the performance and multithreading implications of associating state with the Application subclass.
NOTE 1: Also as anticafe commented, in order to correctly tie your Application override to your application a tag is necessary in the manifest file. Again, see the Android docs for more info. An example:
<application
android:name="my.application.MyApp"
android:icon="..."
android:label="...">
</application>
NOTE 2: user608578 asks below how this works with managing native object lifecycles. I am not up to speed on using native code with Android in the slightest, and I am not qualified to answer how that would interact with my solution. If someone does have an answer to this, I am willing to credit them and put the information in this post for maximum visibility.
ADDENDUM:
As some people have noted, this is not a solution for persistent state, something I perhaps should have emphasized more in the original answer. I.e. this is not meant to be a solution for saving user or other information that is meant to be persisted across application lifetimes. Thus, I consider most criticism below related to Applications being killed at any time, etc..., moot, as anything that ever needed to be persisted to disk should not be stored through an Application subclass. It is meant to be a solution for storing temporary, easily re-creatable application state (whether a user is logged in for example) and components which are single instance (application network manager for example) (NOT singleton!) in nature.
Dayerman has been kind enough to point out an interesting conversation with Reto Meier and Dianne Hackborn in which use of Application subclasses is discouraged in favor of Singleton patterns. Somatik also pointed out something of this nature earlier, although I didn't see it at the time. Because of Reto and Dianne's roles in maintaining the Android platform, I cannot in good faith recommend ignoring their advice. What they say, goes. I do wish to disagree with the opinions, expressed with regards to preferring Singleton over Application subclasses. In my disagreement I will be making use of concepts best explained in this StackExchange explanation of the Singleton design pattern, so that I do not have to define terms in this answer. I highly encourage skimming the link before continuing. Point by point:
Dianne states, "There is no reason to subclass from Application. It is no different than making a singleton..." This first claim is incorrect. There are two main reasons for this. 1) The Application class provides a better lifetime guarantee for an application developer; it is guaranteed to have the lifetime of the application. A singleton is not EXPLICITLY tied to the lifetime of the application (although it is effectively). This may be a non-issue for your average application developer, but I would argue this is exactly the type of contract the Android API should be offering, and it provides much more flexibility to the Android system as well, by minimizing the lifetime of associated data. 2) The Application class provides the application developer with a single instance holder for state, which is very different from a Singleton holder of state. For a list of the differences, see the Singleton explanation link above.
Dianne continues, "...just likely to be something you regret in the future as you find your Application object becoming this big tangled mess of what should be independent application logic." This is certainly not incorrect, but this is not a reason for choosing Singleton over Application subclass. None of Diane's arguments provide a reason that using a Singleton is better than an Application subclass, all she attempts to establish is that using a Singleton is no worse than an Application subclass, which I believe is false.
She continues, "And this leads more naturally to how you should be managing these things -- initializing them on demand." This ignores the fact that there is no reason you cannot initialize on demand using an Application subclass as well. Again there is no difference.
Dianne ends with "The framework itself has tons and tons of singletons for all the little shared data it maintains for the app, such as caches of loaded resources, pools of objects, etc. It works great." I am not arguing that using Singletons cannot work fine or are not a legitimate alternative. I am arguing that Singletons do not provide as strong a contract with the Android system as using an Application subclass, and further that using Singletons generally points to inflexible design, which is not easily modified, and leads to many problems down the road. IMHO, the strong contract the Android API offers to developer applications is one of the most appealing and pleasing aspects of programming with Android, and helped lead to early developer adoption which drove the Android platform to the success it has today. Suggesting using Singletons is implicitly moving away from a strong API contract, and in my opinion, weakens the Android framework.
Dianne has commented below as well, mentioning an additional downside to using Application subclasses, they may encourage or make it easier to write less performance code. This is very true, and I have edited this answer to emphasize the importance of considering perf here, and taking the correct approach if you're using Application subclassing. As Dianne states, it is important to remember that your Application class will be instantiated every time your process is loaded (could be multiple times at once if your application runs in multiple processes!) even if the process is only being loaded for a background broadcast event. It is therefore important to use the Application class more as a repository for pointers to shared components of your application rather than as a place to do any processing!
I leave you with the following list of downsides to Singletons, as stolen from the earlier StackExchange link:
and add my own:
another way is, you assign a column value for a given row based on the index position of a row, the index position always starts with zero, and the last index position is the length of the dataframe:
df["COL_NAME"].iloc[0]=x
This looks like valid Python code, so if the file is on your project's classpath (and not in some other directory or in arbitrary places) one way would be just to rename the file to "abc.py" and import it as a module, using import abc
. You can even update the values using the reload
function later. Then access the values as abc.path1
etc.
Of course, this can be dangerous in case the file contains other code that will be executed. I would not use it in any real, professional project, but for a small script or in interactive mode this seems to be the simplest solution.
Just put the abc.py
into the same directory as your script, or the directory where you open the interactive shell, and do import abc
or from abc import *
.
You would have to use the JavascriptExecutor class:
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");
What do you mean by an "anonymous object?" myObj
is not anonymous since you've assigned an object literal to a variable. You can just test this:
if (typeof myObj.prop2 === 'function')
{
// do whatever
}
It can be very useful a few times, but in general, no fall-through is the desired behavior. Fall-through should be allowed, but not implicit.
An example, to update old versions of some data:
switch (version) {
case 1:
// Update some stuff
case 2:
// Update more stuff
case 3:
// Update even more stuff
case 4:
// And so on
}
This answer is for OSX
I needed to resolve two things to successfully install android studio:
You can use:
print df.columns[5:]
Index([u'2004', u'2005', u'2006', u'2007', u'2008', u'2009', u'2010', u'2011',
u'2012', u'2013', u'2014'],
dtype='object')
for col in df.columns[5:]:
df[col] = pd.to_numeric(df[col], errors='coerce')
print df
GeoName ComponentName IndustryId IndustryClassification \
37926 Alabama Real GDP by state 9 213
37951 Alabama Real GDP by state 34 42
37932 Alabama Real GDP by state 15 327
Description 2004 2005 2006 2007 \
37926 Support activities for mining 99 98 117 117
37951 Wholesale trade 9898 10613 10952 11034
37932 Nonmetallic mineral products manufacturing 980 968 940 1084
2008 2009 2010 2011 2012 2013 2014
37926 115 87 96 95 103 102 NaN
37951 11075 9722 9765 9703 9600 9884 10199.0
37932 861 724 714 701 589 641 NaN
Another solution with filter
:
print df.filter(like='20')
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
37926 99 98 117 117 115 87 96 95 103 102 (NA)
37951 9898 10613 10952 11034 11075 9722 9765 9703 9600 9884 10199
37932 980 968 940 1084 861 724 714 701 589 641 (NA)
for col in df.filter(like='20').columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
print df
GeoName ComponentName IndustryId IndustryClassification \
37926 Alabama Real GDP by state 9 213
37951 Alabama Real GDP by state 34 42
37932 Alabama Real GDP by state 15 327
Description 2004 2005 2006 2007 \
37926 Support activities for mining 99 98 117 117
37951 Wholesale trade 9898 10613 10952 11034
37932 Nonmetallic mineral products manufacturing 980 968 940 1084
2008 2009 2010 2011 2012 2013 2014
37926 115 87 96 95 103 102 NaN
37951 11075 9722 9765 9703 9600 9884 10199.0
37932 861 724 714 701 589 641 NaN
You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :
$content = $_POST['content'];
$lines = explode(PHP_EOL, $content);
$results = '';
foreach($lines as $line)
{
$items = explode(' ', $line);
$q = str_replace("^", "^/", $items[1]);
if (substr($q, strlen($q) - 1) !== '$') $q .= '$';
$buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';
$results .= $buffer.PHP_EOL;
}
die($results);
Easy Peasy:
StringBuilder sb= new StringBuilder();
for(Entry<String,String> entry : map.entrySet()) {
sb.append(entry.getKey() + "_" + entry.getValue() + "|");
}
String requiredString = sb.substring(0, sb.length() - 1);
<script>
function SetBack(dir) {
document.getElementById('body').style.backgroundImage=dir;
}
SetBack('url(myniftybg.gif)');
</script>
On mac, open the terminal and type:
cd /usr/local/mysql/bin
then type:
./mysql -u root -p
It will ask you for the mysql root password. Enter your password and use mysql database in the terminal.
if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.
After thorough research I found the solution
Encoding
let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String =plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String) // bXkgcGxhbmkgdGV4dA==
Decoding
let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
println(decodedString) // my plain data
More on this http://creativecoefficient.net/swift/encoding-and-decoding-base64/
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
Use specific value:
[Display(Name = "Date")]
public DateTime EntryDate {get; set;} = DateTime.Now;//by C# v6
<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>
The above link will open the PDF in full screen mode, that's the best you can achieve.
Try os.path.splitext it should do what you want.
import os
print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg'
systeminfo
is a command that will output system information, including available memory
Using collections.defaultdict
is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.
Here it's used twice: for the resulting dict, and for each of the values in the dict.
import collections
def aggregate_names(errors):
result = collections.defaultdict(lambda: collections.defaultdict(list))
for real_name, false_name, location in errors:
result[real_name][false_name].append(location)
return result
Combining this with your code:
dictionary = aggregate_names(previousFunction(string))
Or to test:
EXAMPLES = [
('Fred', 'Frad', 123),
('Jim', 'Jam', 100),
('Fred', 'Frod', 200),
('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)
Try using this :
function checkValue(){_x000D_
var value = $('#doc_title').val();_x000D_
if (value.length > 0) {_x000D_
$('#doc_title').val("");_x000D_
$('#doc_title').focus(); // To focus the input _x000D_
}_x000D_
else{_x000D_
//do something_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<body>_x000D_
<input type="text" id="doc_title" value="Sample text"/>_x000D_
<button onclick="checkValue()">Check Value</button>_x000D_
</body>
_x000D_
you could connect all the data you need from the file to a single string, and in the excel sheet seperate it with text to column. here is an example i did for same issue, enjoy:
Sub CP()
Dim ToolFile As String
Cells(3, 2).Select
For i = 0 To 5
r = ActiveCell.Row
ToolFile = Cells(r, 7).Value
On Error Resume Next
ActiveCell.Value = CP_getdatta(ToolFile)
'seperate data by "-"
Selection.TextToColumns Destination:=Range("C3"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Cells(r + 1, 2).Select
Next
End Sub
Function CP_getdatta(ToolFile As String) As String
Workbooks.Open Filename:=ToolFile, UpdateLinks:=False, ReadOnly:=True
Range("A56000").Select
Selection.End(xlUp).Select
x = CStr(ActiveCell.Value)
ActiveCell.Offset(0, 20).Select
Selection.End(xlToLeft).Select
While IsNumeric(ActiveCell.Value) = False
ActiveCell.Offset(0, -1).Select
Wend
' combine data to 1 string
CP_getdatta = CStr(x & "-" & ActiveCell.Value)
ActiveWindow.Close False
End Function
I often use this workaround in CLI where instead of configuring my .gitignore
, I create a separate .include
file where I define the (sub)directories I want included in spite of directories directly or recursively ignored by .gitignore
.
Thus, I additionally use
git add `cat .include`
during staging, before committing.
To the OP, I suggest using a .include
which has these lines:
<parent_folder_path>/application/language/gr/*
NOTE: Using cat
does not allow usage of aliases (within .include
) for specifying $HOME (or any other specific directory). This is because the line homedir/app1/*
when passed to git add
using the above command appears as git add 'homedir/app1/*'
, and enclosing characters in single quotes ('') preserves the literal value of each character within the quotes, thus preventing aliases (such as homedir) from functioning (see Bash Single Quotes).
Here is an example of a .include
file I use in my repo here.
/home/abhirup/token.txt
/home/abhirup/.include
/home/abhirup/.vim/*
/home/abhirup/.viminfo
/home/abhirup/.bashrc
/home/abhirup/.vimrc
/home/abhirup/.condarc
The problem with homebrew/versions
is that someone has to have that specific version of software listed in the repository for you to be able to use it. Also, since brew versions
is no longer supported, another solution is required. For solutions that indicate using brew switch
, this will only work if you haven't done a brew cleanup
since the version needs to exist on your computer.
I had a problem with wanting to install a specific older version of docker-machine
which wasn't listed in homebrew/versions
. I solved this using the below, which should also work for any brew installed software. The example below will use docker-machine
as the package I want to downgrade from version 0.5.0 to 0.4.1.
Go to your homebrew Formula
directory.
You can determine this by running brew info [any package name]
.
For example, brew info docker-machine
gives me a line that shows me
a path - /usr/local/Cellar/docker-machine/0.5.0
. This tells me that on my machine, homebrew is installed at /usr/local
and my Formula
directory is located by default at /usr/local/Library/Formula
Locate the specific formula file (.rb) for your package.
Since I want to downgrade docker-machine
, I can see a docker-machine.rb
file.
Get the version history for this formula file .
Enter git log docker-machine.rb
. This will list out the complete commit history for this file. You will see output like this:
...more commit 20c7abc13d2edd67c8c1d30c407bd5e31229cacc Author: BrewTestBot Date: Thu Nov 5 16:14:18 2015 +0000 docker-machine: update 0.5.0 bottle. commit 8f615708184884e501bf5c16482c95eff6aea637 Author: Vincent Lesierse Date: Tue Oct 27 22:25:30 2015 +0100 docker-machine 0.5.0 Updated docker-machine to 0.5.0 Closes #45403. Signed-off-by: Dominyk Tiller commit 5970e1af9b13dcbeffd281ae57c9ab90316ba423 Author: BrewTestBot Date: Mon Sep 21 14:04:04 2015 +0100 docker-machine: update 0.4.1 bottle. commit 18fcbd36d22fa0c19406d699308fafb44e4c8dcd Author: BrewTestBot Date: Sun Aug 16 09:05:56 2015 +0100 docker-machine: update 0.4.1 bottle. ...more
The tricky part is to find the latest commit for the specific version you want. In the above, I can tell the latest 0.4.1 version was committed with this commit tag : commit 5970e1af9b13dcbeffd281ae57c9ab90316ba423
. The commits above this point start using version 0.5.0 (git log entries are listed from latest to earliest date).
Get a previous version of the formula file. Using the commit tag from step #3 (you can use the first 6 chars), you can get an older version of the formula file using the following:
git checkout 5970e1 docker-machine.rb
Uninstall your current package version.
Just run the normal brew commands to uninstall the current version of your package.
Ex. brew uninstall docker-machine
Install the older package version
Now, you can just run the normal brew install command and it will install the formula that you have checkout out.
Ex. brew install docker-machine
You may need to re-link by using the brew link docker-machine
if necessary.
If at any time you want to revert back to the latest version of a specific package, go into the Formula directory and issue the following commands on your formula file (.rb)
git reset HEAD docker-machine.rb
git checkout -- docker-machine.rb
Then you can brew uninstall docker-machine
and brew install docker-machine
to get the latest version and keep it that way going forward.
This tidbit is useful for displaying elapsed time to varying degrees of granularity.
I personally think that questions of efficiency are practically meaningless here, so long as something grossly inefficient isn't being done. Premature optimization is the root of quite a bit of evil. This is fast enough that it'll never be your choke point.
intervals = (
('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),
)
def display_time(seconds, granularity=2):
result = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append("{} {}".format(value, name))
return ', '.join(result[:granularity])
..and this provides decent output:
In [52]: display_time(1934815)
Out[52]: '3 weeks, 1 day'
In [53]: display_time(1934815, 4)
Out[53]: '3 weeks, 1 day, 9 hours, 26 minutes'
You can emojis!
$('#test').on('click', () => {
alert(' Build is too fast');
})
Another way of solving this is to use the DictReader class, which "skips" the header row and uses it to allowed named indexing.
Given "foo.csv" as follows:
FirstColumn,SecondColumn
asdf,1234
qwer,5678
Use DictReader like this:
import csv
with open('foo.csv') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
print(row['FirstColumn']) # Access by column header instead of column number
print(row['SecondColumn'])
Step 1: Simply put all the required code in a "MAIN.BAT" file.
Step 2: Create another bat file, say MainCaller.bat, and just copy/paste these 3 lines of code:
REM THE MAIN FILE WILL BE CALLED FROM HERE..........
CD "File_Path_Where_Main.bat_is_located"
MAIN.BAT > log.txt
Step 3: Just double click "MainCaller.bat".
All the output will be logged into the text file named "log".
Use the load
event:
img = new Image();
img.onload = function(){
// image has been loaded
};
img.src = image_url;
Also have a look at:
GetUserId()
is an extension method on IIdentity
and it is in Microsoft.AspNet.Identity.IdentityExtensions
. Make sure you have added the namespace with using Microsoft.AspNet.Identity;
.
Check your .bashrc
file for aliases.
do like this:
departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
return;
}
Review your first line. Your stack trace is clearly not from the code you've pasted here, so I don't know precisely what you've done.
>>> my_set=([1,2,3,4])
>>> my_set
[1, 2, 3, 4]
>>> type(my_set)
<type 'list'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>
What you wanted was set([1, 2, 3, 4])
.
>>> my_set = set([1, 2, 3, 4])
>>> my_set
set([1, 2, 3, 4])
>>> type(my_set)
<type 'set'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>
The "not callable" exception means you were doing something like set()()
- attempting to call a set
instance.
dynamically typed language helps to quickly prototype algorithm concepts without the overhead of about thinking what variable types need to be used (which is a necessity in statically typed language).
Granted, the answer I linked in the comments is not very helpful. You can specify your own string converter like so.
In [25]: pd.set_option('display.float_format', lambda x: '%.3f' % x)
In [28]: Series(np.random.randn(3))*1000000000
Out[28]:
0 -757322420.605
1 -1436160588.997
2 -1235116117.064
dtype: float64
I'm not sure if that's the preferred way to do this, but it works.
Converting numbers to strings purely for aesthetic purposes seems like a bad idea, but if you have a good reason, this is one way:
In [6]: Series(np.random.randn(3)).apply(lambda x: '%.3f' % x)
Out[6]:
0 0.026
1 -0.482
2 -0.694
dtype: object
The trick here is to not become a zealot.
One thing to note here is that no one in the pro file system camp has listed a particular file system. Does this mean that everything from FAT16 to ZFS handily beats every database?
No.
The truth is that many databases beat many files systems, even when we're only talking about raw speed.
The correct course of action is to make the right decision for your precise scenario, and to do that, you'll need some numbers and some use case estimates.
The size of storage required and how big the numbers can be.
On SQL Server:
tinyint
1 byte, 0 to 255smallint
2 bytes, -215 (-32,768) to 215-1 (32,767)int
4 bytes, -231 (-2,147,483,648) to 231-1 (2,147,483,647)bigint
8 bytes, -263 (-9,223,372,036,854,775,808) to 263-1 (9,223,372,036,854,775,807)You can store the number 1 in all 4, but a bigint
will use 8 bytes, while a tinyint
will use 1 byte.
I use vim in macos, and the original ctags doesn't work well, so I download newest and configure make make install it. I install ctgas in /usr/local/bin/ctags(to keep original one)
"taglist
let Tlist_Ctags_Cmd = "/usr/local/bin/ctags"
let Tlist_WinWidth = 50
map <leader>ta :TlistToggle<cr>
map <leader>bta :!/usr/local/bin/ctags -R .<CR>
set tags=tags;/
map <M-j> <C-]>
map <M-k> <C-T>
What about using PRIOR,
so
SELECT id, parent_id, PRIOR name
FROM tbl
START WITH id = 1
CONNECT BY PRIOR id = parent_id`
or if you want to get the root name
SELECT id, parent_id, CONNECT_BY_ROOT name
FROM tbl
START WITH id = 1
CONNECT BY PRIOR id = parent_id
Constructor
The constructor function comes with every class, constructors are not specific to Angular but are concepts derived from Object oriented designs. The constructor creates an instance of the component class.
OnInit
The ngOnInit
function is one of an Angular component’s life-cycle methods. Life cycle methods (or hooks) in Angular components allow you to run a piece of code at different stages of the life of a component.
Unlike the constructor method, ngOnInit
method comes from an Angular interface (OnInit
) that the component needs to implement in order to use this method. The ngOnInit
method is called shortly after the component is created.
Another easy way to get this:
Person myPet = GetPersonFromDatabase();
// check for myPet == null... AND for myPet.PetType == null
if ( myPet.PetType == "cat" ) <--- fall down go boom!
You cannot add methods to an existing type unless the existing type is marked as partial, you can only add methods that appear to be a member of the existing type through extension methods. Since this is the case you cannot add static methods to the type itself since extension methods use instances of that type.
There is nothing stopping you from creating your own static helper method like this:
static class DateTimeHelper
{
public static DateTime Tomorrow
{
get { return DateTime.Now.AddDays(1); }
}
}
Which you would use like this:
DateTime tomorrow = DateTimeHelper.Tomorrow;
I'm aware that this question is a bit old, but I consider that my small update could help other programmers.
I didn't want to modify WhoIsRich's answer because it's really great, but I adapted it to fulfill my needs:
If the Automatically Detect Settings is unchecked then check it.
On Error Resume Next
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
sKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"
sValueName = "DefaultConnectionSettings"
' Get registry value where each byte is a different setting.
oReg.GetBinaryValue &H80000001, sKeyPath, sValueName, bValue
' Check byte to see if detect is currently on.
If (bValue(8) And 8) = 8 Then
' To change the value to Off.
bValue(8) = bValue(8) And Not 8
' Check byte to see if detect is currently off.
ElseIf (bValue(8) And 8) = 0 Then
' To change the value to On.
bValue(8) = bValue(8) Or 8
End If
'Write back settings value
oReg.SetBinaryValue &H80000001, sKeyPath, sValueName, bValue
Set oReg = Nothing
Finally, you only need to save it in a .VBS file (VBScript) and run it.
You need to open the file in binary b
mode to take care of blank lines in Python 2. This isn't required in Python 3.
So, change open('test.csv', 'w')
to open('test.csv', 'wb')
.
var item = list[oldIndex];
list.RemoveAt(oldIndex);
if (newIndex > oldIndex) newIndex--;
// the actual index could have shifted due to the removal
list.Insert(newIndex, item);
Put into Extension methods they look like:
public static void Move<T>(this List<T> list, int oldIndex, int newIndex)
{
var item = list[oldIndex];
list.RemoveAt(oldIndex);
if (newIndex > oldIndex) newIndex--;
// the actual index could have shifted due to the removal
list.Insert(newIndex, item);
}
public static void Move<T>(this List<T> list, T item, int newIndex)
{
if (item != null)
{
var oldIndex = list.IndexOf(item);
if (oldIndex > -1)
{
list.RemoveAt(oldIndex);
if (newIndex > oldIndex) newIndex--;
// the actual index could have shifted due to the removal
list.Insert(newIndex, item);
}
}
}
On most POSIX systems, it is ignored. But, check your system to be sure.
XNU
The mode string can also include the letter 'b' either as last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with ISO/IEC 9899:1990 ('ISO C90') and has no effect; the 'b' is ignored.
Linux
The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two- character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)
In my case, there was a mistake in the list of the parameters was not well formed. So make sure the parameters are well formed. For e.g. correct format of parameters
data: {'reporter': reporter,'partner': partner,'product': product}
For UTF 8 Conversion and Currency Symbol Export Use this:
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
window.location.href = uri + base64(format(template, ctx))
}
})()
In my case, this error comes from my trial to remove dependencies to MSVC-version dependent runtime library DLL (msvcr10.dll or so) and/or remove static runtime library too, to remove excess fat from my executables.
So I use /NODEFAULTLIB linker switch, my self-made "msvcrt-light.lib" (google for it when you need), and mainCRTStartup()
/ WinMainCRTStartup()
entries.
It is IMHO since Visual Studio 2015, so I stuck to older compilers.
However, defining symbol _NO_CRT_STDIO_INLINE removes all hassle, and a simple "Hello World" application is again 3 KB small and doesn't depend to unusual DLLs. Tested in Visual Studio 2017.
I did it in my project:
Global Events in application.js:
$(document).bind("ajaxSend", function(){
$("#loading").show();
}).bind("ajaxComplete", function(){
$("#loading").hide();
});
"loading" is the element to show and hide!
References: http://api.jquery.com/Ajax_Events/
I solved it this way:
First, I stopped all running containers:
docker-compose down
Then I executed a lsof
command to find the process using the port (for me it was port 9000)
sudo lsof -i -P -n | grep 9000
Finally, I "killed" the process (in my case, it was a VSCode extension):
kill -9 <process id>
If you want every cell in the grid to have the same background color, you can just do this:
dataGridView1.DefaultCellStyle.BackColor = Color.Green;
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
<?php if(!class_exists('PDO2')) {
class PDO2 {
private static $_instance;
public static function getInstance() {
if (!isset(self::$_instance)) {
try {
self::$_instance = new PDO(
'mysql:host=***;dbname=***',
'***',
'***',
array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_general_ci",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int) $e->getCode());
}
}
return self::$_instance;
}
public static function closeInstance() {
return self::$_instance = null;
}
}
}
$req = PDO2::getInstance()->prepare('SELECT * FROM table');
$req->execute();
$count = $req->rowCount();
$results = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
// Do other requests maybe
// And close connection
PDO2::closeInstance();
// print output
Full example, with custom class PDO2.
XCode 10 with Swift 4.2
import UIKit
class ViewController: UIViewController {
var timer = Timer()
var totalSecond = 10
override func viewDidLoad() {
super.viewDidLoad()
startTimer()
}
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
@objc func updateTime() {
print(timeFormatted(totalSecond))
if totalSecond != 0 {
totalSecond -= 1
} else {
endTimer()
}
}
func endTimer() {
timer.invalidate()
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
return String(format: "0:%02d", seconds)
}
}
Problem solved! I just figured out how to solve the issue, but I would still like to know if this is normal behavior or not.
It seems that even though the Websocket connection establishes correctly (indicated by the 101 Switching Protocols request), it still defaults to long-polling. The fix was as simple as adding this option to the Socket.io connection function:
{transports: ['websocket']}
So the code finally looks like this:
const app = express();
const server = http.createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log('connected socket!');
socket.on('greet', function(data) {
console.log(data);
socket.emit('respond', { hello: 'Hey, Mr.Client!' });
});
socket.on('disconnect', function() {
console.log('Socket disconnected');
});
});
and on the client:
var socket = io('ws://localhost:3000', {transports: ['websocket']});
socket.on('connect', function () {
console.log('connected!');
socket.emit('greet', { message: 'Hello Mr.Server!' });
});
socket.on('respond', function (data) {
console.log(data);
});
And the messages now appear as frames:
This Github issue pointed me in the right direction. Thanks to everyone who helped out!
Sam's solution should be sufficient. I've used combination of both histogram difference and template matching because not one method was working for me 100% of the times. I've given less importance to histogram method though. Here's how I've implemented in simple python script.
import cv2
class CompareImage(object):
def __init__(self, image_1_path, image_2_path):
self.minimum_commutative_image_diff = 1
self.image_1_path = image_1_path
self.image_2_path = image_2_path
def compare_image(self):
image_1 = cv2.imread(self.image_1_path, 0)
image_2 = cv2.imread(self.image_2_path, 0)
commutative_image_diff = self.get_image_difference(image_1, image_2)
if commutative_image_diff < self.minimum_commutative_image_diff:
print "Matched"
return commutative_image_diff
return 10000 //random failure value
@staticmethod
def get_image_difference(image_1, image_2):
first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])
img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
img_template_diff = 1 - img_template_probability_match
# taking only 10% of histogram diff, since it's less accurate than template method
commutative_image_diff = (img_hist_diff / 10) + img_template_diff
return commutative_image_diff
if __name__ == '__main__':
compare_image = CompareImage('image1/path', 'image2/path')
image_difference = compare_image.compare_image()
print image_difference
In my case I have configured as below in my springboot application.properties file then I am able to connect to the sqlserver database using service account:
url=jdbc:sqlserver://SERVER_NAME:PORT_NUMBER;databaseName=DATABASE_NAME;sendStringParametersAsUnicode=false;multiSubnetFailover=true;integratedSecurity=true
jdbcUrl=${url}
username=YourDomain\\$SERVICE-ACCOUNT-USER-NAME
password=
hikari.connection-timeout=60000
hikari.maximum-pool-size=5
driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
Alternate solution :
reduce(lambda x,newObj : x +[newObj] if somecond else x,myarr,myarr)
Use union
as follows:
val sc = new SparkContext(...)
val r1 = sc.textFile("xxx1")
val r2 = sc.textFile("xxx2")
...
val rdds = Seq(r1, r2, ...)
val bigRdd = sc.union(rdds)
Then the bigRdd
is the RDD with all files.
//decode base64 string to image
imageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
//setImageBitmap is imp
Instead of using list.index(x)
which returns the index of x if it is found in list or returns a #ValueError
message if x is not found, you could use list.count(x)
which returns the number of occurrences of x in list (validation that x is indeed in the list) or it returns 0 otherwise (in the absence of x). The cool thing about count()
is that it doesn't break your code or require you to throw an exception for when x is not found
I see that Character.isDigit perfectly suits the need, since the input will be just one symbol. Of course we don't have any info about this kb object but just in case it's a java.util.Scanner instance, I'd also suggest using java.io.InputStreamReader for command line input. Here's an example:
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
try {
reader.read();
}
catch(Exception e) {
e.printStackTrace();
}
reader.close();
This code snippet is working properly
find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash
bash 4 (recursive)
shopt -s globstar
for xls in /path/**/*.xls
do
xls2csv "$xls" "${xls%.xls}.csv"
done
If you need to pass URL params
theres a great post explanation by Tyler McGinnis on his site, Link to the post
here are code examples:
on the history.push component:
this.props.history.push(`/home:${this.state.userID}`)
on the router component you define the route:
<Route path='/home:myKey' component={Home} />
on the Home component:
componentDidMount(){
const { myKey } = this.props.match.params
console.log(myKey )
}
If all your divs start with editDialog as you stated, then you can use the following selector:
$("div[id^='editDialog']")
Or you could use a class selector instead if it's easier for you
<div id="editDialog-0" class="editDialog">...</div>
$(".editDialog")
F.ex. http://docs.oracle.com/javase/7/docs/ has a link to download "JDK 7 Documentation" in the sidebar under "Downloads". I'd expect the same for other versions.
The Abstract Factory pattern is used in various places.
E.g., DatagramSocketImplFactory
, PreferencesFactory
. There are many more---search the Javadoc for interfaces which have the word "Factory" in their name.
Also there are quite a few instances of the Factory pattern, too.
To clear all data:
click on Misc>Remove all objects
.
Your good to go.
To clear the console:
click on edit>Clear console
.
No need for any code.
This is how you can do it (you can run this file as-is):
import requests
import unittest
from unittest import mock
# This is the class we want to test
class MyGreatClass:
def fetch_json(self, url):
response = requests.get(url)
return response.json()
# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
if args[0] == 'http://someurl.com/test.json':
return MockResponse({"key1": "value1"}, 200)
elif args[0] == 'http://someotherurl.com/anothertest.json':
return MockResponse({"key2": "value2"}, 200)
return MockResponse(None, 404)
# Our test case class
class MyGreatClassTestCase(unittest.TestCase):
# We patch 'requests.get' with our own method. The mock object is passed in to our test case method.
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_fetch(self, mock_get):
# Assert requests.get calls
mgc = MyGreatClass()
json_data = mgc.fetch_json('http://someurl.com/test.json')
self.assertEqual(json_data, {"key1": "value1"})
json_data = mgc.fetch_json('http://someotherurl.com/anothertest.json')
self.assertEqual(json_data, {"key2": "value2"})
json_data = mgc.fetch_json('http://nonexistenturl.com/cantfindme.json')
self.assertIsNone(json_data)
# We can even assert that our mocked method was called with the right parameters
self.assertIn(mock.call('http://someurl.com/test.json'), mock_get.call_args_list)
self.assertIn(mock.call('http://someotherurl.com/anothertest.json'), mock_get.call_args_list)
self.assertEqual(len(mock_get.call_args_list), 3)
if __name__ == '__main__':
unittest.main()
Important Note: If your MyGreatClass
class lives in a different package, say my.great.package
, you have to mock my.great.package.requests.get
instead of just 'request.get'. In that case your test case would look like this:
import unittest
from unittest import mock
from my.great.package import MyGreatClass
# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
# Same as above
class MyGreatClassTestCase(unittest.TestCase):
# Now we must patch 'my.great.package.requests.get'
@mock.patch('my.great.package.requests.get', side_effect=mocked_requests_get)
def test_fetch(self, mock_get):
# Same as above
if __name__ == '__main__':
unittest.main()
Enjoy!
EADDRINUSE
means that the port(which we try to listen in node application) is already being used. In order to overcome, we need to identify which process is running with that port.
For example if we are trying to listen our node application in 3000 port. We need to check whether that port is already is being used by any other process.
$sudo netstat -plunt |grep :3000
That the above command gives below result.
tcp6 0 0 :::3000 :::* LISTEN 25315/node
Now you got process ID(25315), Kill that process.
kill -9 25315
npm run start
Note: This solution for linux users.
You need to have your DBA modify the init.ora file, adding the directory you want to access to the 'utl_file_dir' parameter. Your database instance will then need to be stopped and restarted because init.ora is only read when the database is brought up.
You can view (but not change) this parameter by running the following query:
SELECT *
FROM V$PARAMETER
WHERE NAME = 'utl_file_dir'
Share and enjoy.
Now that bash is out for windows 10, if you want to access program files from bash, you can do it like so:
cd /mnt/c/Program\ Files
.
i used this code and it works fine for me, just change +92xxxxxxxxxx to your valid whatsapp number, with country code
<script type="text/javascript">
(function () {
var options = {
whatsapp: "+92xxxxxxxxxx", // WhatsApp number
call_to_action: "Message us", // Call to action
position: "right", // Position may be 'right' or 'left'
};
var proto = document.location.protocol, host = "whatshelp.io", url = proto + "//static." + host;
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
})();
</script>
Follow bellow steps:
shell> mysqldump -hlocalhost -uroot -p database1 > dump.sql
mysql> CREATE DATABASE database2;
shell> mysql -hlocalhost -uroot -p database2 < dump.sql
If you want to drop database1 otherwise leave it.
mysql> DROP DATABASE database1;
Note : shell> denote command prompt and mysql> denote mysql prompt.
If this is an attempt to use one GET action for several views that POST to several actions with different models, then try add a GET action for each POST action that redirects to the first GET to prevent 404 on refresh.
Long shot but common scenario.
Here are my personal, super-condensed notes, as far as this subject pertains to me currently, for anyone who's interested:
If you need your certificate for HTTPS connections you can add the .bks file as a raw resource to your application and extend DefaultHttpConnection so your certificates are used for HTTPS connections.
public class MyHttpClient extends DefaultHttpClient {
private Resources _resources;
public MyHttpClient(Resources resources) {
_resources = resources;
}
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
if (_resources != null) {
registry.register(new Scheme("https", newSslSocketFactory(), 443));
} else {
registry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
}
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
KeyStore trusted = KeyStore.getInstance("BKS");
InputStream in = _resources.openRawResource(R.raw.mystore);
try {
trusted.load(in, "pwd".toCharArray());
} finally {
in.close();
}
return new SSLSocketFactory(trusted);
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.
$('#myDiv').hide()
will hide the div...
This is tested in android 7.0 up to android 10.0 and it works
Use this code to check if string contains special character and numbers:
name = firstname.getText().toString(); //name is the variable that holds the string value
Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern number = Pattern.compile("[0-9]", Pattern.CASE_INSENSITIVE);
Matcher matcher = special.matcher(name);
Matcher matcherNumber = number.matcher(name);
boolean constainsSymbols = matcher.find();
boolean containsNumber = matcherNumber.find();
if(constainsSymbols == true){
//string contains special symbol/character
}
else if(containsNumber == true){
//string contains numbers
}
else{
//string doesn't contain special characters or numbers
}
The previous solutions have used the custom StructType.
With spark-sql 2.4.5 (scala version 2.12.10) it is now possible to specify the schema as a string using the schema
function
import org.apache.spark.sql.SparkSession;
val sparkSession = SparkSession.builder()
.appName("sample-app")
.master("local[2]")
.getOrCreate();
val pageCount = sparkSession.read
.format("csv")
.option("delimiter","|")
.option("quote","")
.schema("project string ,article string ,requests integer ,bytes_served long")
.load("dbfs:/databricks-datasets/wikipedia-datasets/data-001/pagecounts/sample/pagecounts-20151124-170000")
Here's the most basic way:
$url = "http://other-site/image.png";
$dir = "/my/local/dir/";
$rfile = fopen($url, "r");
$lfile = fopen($dir . basename($url), "w");
while(!feof($url)) fwrite($lfile, fread($rfile, 1), 1);
fclose($rfile);
fclose($lfile);
But if you're doing lots and lots of this (or your host blocks file access to remote systems), consider using CURL, which is more efficient, mildly faster and available on more shared hosts.
You can also spoof the user agent to look like a desktop rather than a bot!
$url = "http://other-site/image.png";
$dir = "/my/local/dir/";
$lfile = fopen($dir . basename($url), "w");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
curl_setopt($ch, CURLOPT_FILE, $lfile);
fclose($lfile);
curl_close($ch);
With both instances, you might want to pass it through GD to make sure it really is an image.
//This piece of code will handle the leap year addition as well.
function updateExpiryDate(controlID, value) {
if ( $("#ICMEffectiveDate").val() != '' &&
$("#ICMTermYears").val() != '') {
var effectiveDate = $("#ICMEffectiveDate").val();
var date = new Date(effectiveDate);
var termYears = $("#ICMTermYears").val();
date = new Date(date.setYear(date.getFullYear() + parseInt(termYears)));
var expiryDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
$('#ICMExpiryDate').val(expiryDate);
}
}
have at look at the static methods DateTime.Parse()
and DateTime.TryParse()
. They will allow you to pass in your date string and a format string, and get a DateTime object in return.
This declaration:
double F[1000][1000000];
would occupy 8 * 1000 * 1000000 bytes on a typical x86 system. This is about 7.45 GB. Chances are your system is running out of memory when trying to execute your code, which results in a segmentation fault.
Generalizing on rotmax's answer, here is a full solution to search & replace all instances in a string. If both substrings are of different size, the substring is replaced using string::erase and string::insert., otherwise the faster string::replace is used.
void FindReplace(string& line, string& oldString, string& newString) {
const size_t oldSize = oldString.length();
// do nothing if line is shorter than the string to find
if( oldSize > line.length() ) return;
const size_t newSize = newString.length();
for( size_t pos = 0; ; pos += newSize ) {
// Locate the substring to replace
pos = line.find( oldString, pos );
if( pos == string::npos ) return;
if( oldSize == newSize ) {
// if they're same size, use std::string::replace
line.replace( pos, oldSize, newString );
} else {
// if not same size, replace by erasing and inserting
line.erase( pos, oldSize );
line.insert( pos, newString );
}
}
}
I use this:
function fnIsAppleMobile()
{
if (navigator && navigator.userAgent && navigator.userAgent != null)
{
var strUserAgent = navigator.userAgent.toLowerCase();
var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
if (arrMatches != null)
return true;
} // End if (navigator && navigator.userAgent)
return false;
} // End Function fnIsAppleMobile
var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
public ActionResult PersonTest()
{
return View();
}
[HttpPost]
public ActionResult PersonSubmit(Vh.Web.Models.Person person)
{
System.Threading.Thread.Sleep(2000); /*simulating slow connection*/
/*Do something with object person*/
return Json(new {msg="Successfully added "+person.Name });
}
<script type="text/javascript">
function send() {
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}
$('#target').html('sending..');
$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
}
</script>
try out like this
body {
background: #fff url("!--MIZO-PRO--!") no-repeat center 15px top 15px/100px;
}
/* 100px is the background size */
Try this:
Basically, just account for each event:
Html:
<input id = "textbox" type = "text">
Jquery:
$("#textbox").keyup(function() {
alert($(this).val());
});
$("#textbox").change(function() {
alert($(this).val());
});
Google Drive has an extension to open MDB files.
I'm not sure how well BLOBs work because I couldn't get my images to display but all the text came up.
Try this:
To unskew the image use a nested div for the image and give it the opposite skew value. So if you had 20deg on the parent then you can give the nested (image) div a skew value of -20deg.
.container {_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#parallelogram {_x000D_
width: 150px;_x000D_
height: 100px;_x000D_
margin: 0 0 0 -20px;_x000D_
-webkit-transform: skew(20deg);_x000D_
-moz-transform: skew(20deg);_x000D_
-o-transform: skew(20deg);_x000D_
background: red;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.image {_x000D_
background: url(http://placekitten.com/301/301);_x000D_
position: absolute;_x000D_
top: -30px;_x000D_
left: -30px;_x000D_
right: -30px;_x000D_
bottom: -30px;_x000D_
-webkit-transform: skew(-20deg);_x000D_
-moz-transform: skew(-20deg);_x000D_
-o-transform: skew(-20deg);_x000D_
}
_x000D_
<div class="container">_x000D_
<div id="parallelogram">_x000D_
<div class="image"></div>_x000D_
</div>_x000D_
</div>
_x000D_
The example:
You can type them manually but the editor will assist you.
http://developer.android.com/reference/android/Manifest.permission.html
You can see the snap sot below.
As soon as you type "a" inside the quotes you get a list of permissions and also hint to move caret up and down to select the same.
A possible workaround would be to use the multi-cursor. select the >< part of your example use Ctrl+Shift+L or select all occurrences. Then use the arrow keys to move all the cursors between the tags and press enter to insert a newline everywhere.
This won't work in all situations.
You can also use Ctrl+D for select next match, which adds the next match to the selection and adds a cursor. And use Ctrl+K Ctrl+D to skip a selection.
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info:
This thread provides the code necessary: http://bytes.com/forum/thread251367.html
but here's the relevant code:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, Pack=1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
[DllImport("kernel32.dll", ExactSpelling=true) ]
internal static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]
internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr
phtok );
[DllImport("advapi32.dll", SetLastError=true) ]
internal static extern bool LookupPrivilegeValue( string host, string name,
ref long pluid );
[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]
internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen );
[DllImport("user32.dll", ExactSpelling=true, SetLastError=true) ]
internal static extern bool ExitWindowsEx( int flg, int rea );
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
internal const int EWX_LOGOFF = 0x00000000;
internal const int EWX_SHUTDOWN = 0x00000001;
internal const int EWX_REBOOT = 0x00000002;
internal const int EWX_FORCE = 0x00000004;
internal const int EWX_POWEROFF = 0x00000008;
internal const int EWX_FORCEIFHUNG = 0x00000010;
private void DoExitWin( int flg )
{
bool ok;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok );
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid );
ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero );
ok = ExitWindowsEx( flg, 0 );
}
Usage:
DoExitWin( EWX_SHUTDOWN );
or
DoExitWin( EWX_REBOOT );
My solution displays the percentage of the tarball that
is currently being uncompressed and written. I use this
when writing out 2GB root filesystem images. You really
need a progress bar for these things. What I do is use
gzip --list
to get the total uncompressed size of the
tarball. From that I calculate the blocking-factor needed
to divide the file into 100 parts. Finally, I print a
checkpoint message for each block. For a 2GB file this
gives about 10MB a block. If that is too big then you can
divide the BLOCKING_FACTOR by 10 or 100, but then it's
harder to print pretty output in terms of a percentage.
Assuming you are using Bash then you can use the following shell function
untar_progress ()
{
TARBALL=$1
BLOCKING_FACTOR=$(gzip --list ${TARBALL} |
perl -MPOSIX -ane '$.==2 && print ceil $F[1]/50688')
tar --blocking-factor=${BLOCKING_FACTOR} --checkpoint=1 \
--checkpoint-action='ttyout=Wrote %u% \r' -zxf ${TARBALL}
}
I'm getting OpenJDK 8 from the official Debian repositories, rather than some random PPA or non-free Oracle binary. Here's how I did it:
sudo apt-get install debian-keyring debian-archive-keyring
Make /etc/apt/sources.list.d/debian-jessie-backports.list
:
deb http://httpredir.debian.org/debian/ jessie-backports main
Make /etc/apt/preferences.d/debian-jessie-backports
:
Package: *
Pin: release o=Debian,a=jessie-backports
Pin-Priority: -200
Then finally do the install:
sudo apt-get update
sudo apt-get -t jessie-backports install openjdk-8-jdk
I just had the same problem with Parent/Child collections and found that post which has solved my case. I Only wanted to show the List of parent collection items and didn't need any of the child data, therefore i used the following and it worked fine:
JsonConvert.SerializeObject(ResultGroups, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
JSON.NET Error Self referencing loop detected for type
it also referes to the Json.NET codeplex page at:
http://json.codeplex.com/discussions/272371
Documentation: ReferenceLoopHandling setting
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
http://www.tutorialspoint.com/mysql/mysql-date-time-functions.htm
use Date function directly. Hope it works
Here is my solution:
git log --all --full-history --oneline -- <RELATIVE_FILE_PATH>
git checkout <COMMIT_SHA>^ -- <RELATIVE_FILE_PATH>
I don't use the same version, but uninstall actions are the same: Looking for file uninstall-postgresql inside directory
/Library/PostgreSQL/9.6
then run it.
(Screenshot in macOS 10.13)
then
sudo rm -rf /Library/PostgreSQL/
to delete all unnecessary directory.
If you're on Windows, research proc_open
or popen
...
But if we're on the same server "Linux" running cpanel then this is the right approach:
#!/usr/bin/php
<?php
$pid = shell_exec("nohup nice php -f
'path/to/your/script.php' /dev/null 2>&1 & echo $!");
While(exec("ps $pid"))
{ //you can also have a streamer here like fprintf,
// or fgets
}
?>
Don't use fork()
or curl
if you doubt you can handle them, it's just like abusing your server
Lastly, on the script.php
file which is called above, take note of this make sure you wrote:
<?php
ignore_user_abort(TRUE);
set_time_limit(0);
ob_start();
// <-- really optional but this is pure php
//Code to be tested on background
ob_flush(); flush();
//this two do the output process if you need some.
//then to make all the logic possible
str_repeat(" ",1500);
//.for progress bars or loading images
sleep(2); //standard limit
?>
My MaxHeightScrollView
custom view
public class MaxHeightScrollView extends ScrollView {
private int maxHeight;
public MaxHeightScrollView(Context context) {
this(context, null);
}
public MaxHeightScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray styledAttrs =
context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView);
try {
maxHeight = styledAttrs.getDimensionPixelSize(R.styleable.MaxHeightScrollView_mhs_maxHeight, 0);
} finally {
styledAttrs.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (maxHeight > 0) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
style.xml
<declare-styleable name="MaxHeightScrollView">
<attr name="mhs_maxHeight" format="dimension" />
</declare-styleable>
Using
<....MaxHeightScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:mhs_maxHeight="100dp"
>
...
</....MaxHeightScrollView>
I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:
var urlHelper = new UrlHelper(this.ControllerContext);
Or, you could just use the Controller.Url
property if you inherit from Controller
.
Here's another way of doing the code above using the openpyxl
module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.
from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')
Semaphore allows multiple threads (up to a set number) to access a shared object. Monitors allow mutually exclusive access to a shared object.
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
If you want to fix quickly, Forward Engineer again and check "Generate DROP SCHEMA" option and proceed.
I assume the database doesn't contain data, so dropping it won't affect.
File file = new File(dir, "App.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);
I had the same problem and after several attempts, it worked out for me this way. I don't know why, but setting data and type separately screwed up my intent.
initialize the Start property in the constructor
Start = DateTime.Now;
This worked for me when I was trying to add few new fields to the ASP .Net Identity Framework's Users table (AspNetUsers) using Code First. I updated the Class - ApplicationUser in IdentityModels.cs and I added a field lastLogin of type DateTime.
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
CreatedOn = DateTime.Now;
LastPassUpdate = DateTime.Now;
LastLogin = DateTime.Now;
}
public String FirstName { get; set; }
public String MiddleName { get; set; }
public String LastName { get; set; }
public String EmailId { get; set; }
public String ContactNo { get; set; }
public String HintQuestion { get; set; }
public String HintAnswer { get; set; }
public Boolean IsUserActive { get; set; }
//Auditing Fields
public DateTime CreatedOn { get; set; }
public DateTime LastPassUpdate { get; set; }
public DateTime LastLogin { get; set; }
}
after generating XML you can just Replace your XML <Marks>... content here </Marks>
tags with <SubjectMarks>... content here </SubjectMarks>tag
. and pass updated XML to your DB.
Edit: I here explain complete process here.
Your XML Generate Like as below.
<NewDataSet>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>80</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>79</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>88</Marks>
</StudentMarks>
</NewDataSet>
Here you can assign XML to string variable like as
string strXML = DataSet.GetXML();
strXML = strXML.Replace ("<Marks>","<SubjectMarks>");
strXML = strXML.Replace ("<Marks/>","<SubjectMarks/>");
and now pass strXML To your DB. Hope it will help for you.
use the following code,
iv.setImageResource(getResources().getIdentifier("apple", "drawable", getPackageName()));
Please check this jQuery plugin,
with this you can overlay all the page or elements, works great for me,
Examples:
Block a div:
$('div.test').block({ message: null });
Block the page:
$.blockUI({ message: '<h1><img src="busy.gif" /> Just a moment...</h1>' });
Hope that help someone
Greetings
I have same problem in WordPress site, I added in .htaccess file then working fine for me.
php_value max_execution_time 6000000
In our case it was the fact that the developer was running the application pool under his own account, and had reset his password but forgot to change it on the application pool. Duh...
You can get all your fingerprints from https://console.developers.google.com/projectselector/apis/credentials
And use this Kotlin code to convert it to keyhash:
fun main(args: Array<String>) {
listOf("<your_production_sha1_fingerprint>",
"<your_debug1_sha1_fingerprint>",
"<your_debug2_sha1_fingerprint>")
.map { it.split(":") }
.map { it.map { it.toInt(16).toByte() }.toByteArray() }
.map { String(Base64.getEncoder().encode(it)) }
.forEach { println(it) }
}
If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.
Go to Search > Find in Files
(Ctrl+Shift+F for the keyboard addicted) and enter:
(test1|test2)
*.txt
Follow current doc.
to have the path of the current file to be filled.Regular Expression
Can we guarantee it will not die?
As long there is no reference returned, it's perfectly fine to do so. words
will be moved to the variable receiving the result.
The local variable will go out of scope. after it was moved (or copied).
This is the answer, hope it helps someone :)
First there are two variations on how the xml can be written:
<row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row>
Answer:
SELECT
Tbl.Col.value('IdInvernadero[1]', 'smallint'),
Tbl.Col.value('IdProducto[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
Tbl.Col.value('Cantidad[1]', 'int'),
Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
Answer:
SELECT
Tbl.Col.value('@IdInvernadero', 'smallint'),
Tbl.Col.value('@IdProducto', 'smallint'),
Tbl.Col.value('@IdCaracteristica1', 'smallint'),
Tbl.Col.value('@IdCaracteristica2', 'smallint'),
Tbl.Col.value('@Cantidad', 'int'),
Tbl.Col.value('@Folio', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
Taken from:
The context referenced by 'this'
keyword in JavasSript is different.
look at the following code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<input id="btnSubmit" type="button" value="Submit" />
<script>
function disable() {
this.disabled = true;
}
var btnSubmit = document.getElementById('btnSubmit');
btnSubmit.onclick = disable();
//btnSubmit.addEventListener('click', disable, false);
</script>
</body>
</html>
What it does is really simple. when you click the button, the button will be disabled automatically.
First when you try to hook up the events in this way button.onclick = function(),
onclick event will be triggered by clicking the button, however, the button will not be disabled because there's no explicit binding between button.onclick and onclick event handler. If you debug see the 'this'
object, you can see it refers to 'window'
object.
Secondly, if you comment btnSubmit.onclick = disable();
and uncomment
//btnSubmit.addEventListener('click', disable, false);
you can see that the button is disabled because with this way there's explicit binding between button.onclick event and onclick event handler. If you debug into disable function, you can see 'this'
refers to the button control
rather than the window
.
This is something I don't like about JavaScript which is inconsistency.
Btw, if you are using jQuery($('#btnSubmit').on('click', disable);
), it uses explicit binding.
Looks like you are missing a leading slash. Perhaps try:
Scanner s = new Scanner(new File("/home/me/java/ex.txt"));
(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)
RollingFileAppender
does this. You just need to set maxBackupIndex
to the highest value for the backup file.
Use the System.getenv(String)
method, passing the name of the variable to read.
Expanding on René Nyffenegger's answer, for those who do not have access to PowerShell version 6.x, we use Split Path, which doesn't test for file existence:
Split-Path "C:\Folder\SubFolder\myfile.txt" -Leaf
This returns "myfile.txt". If we know that the file name doesn't have periods in it, we can split the string and take the first part:
(Split-Path "C:\Folder\SubFolder\myfile.txt" -Leaf).Split('.') | Select -First 1
or
(Split-Path "C:\Folder\SubFolder\myfile.txt" -Leaf).Split('.')[0]
This returns "myfile". If the file name might include periods, to be safe, we could use the following:
$FileName = Split-Path "C:\Folder\SubFolder\myfile.txt.config.txt" -Leaf
$Extension = $FileName.Split('.') | Select -Last 1
$FileNameWoExt = $FileName.Substring(0, $FileName.Length - $Extension.Length - 1)
This returns "myfile.txt.config". Here I prefer to use Substring() instead of Replace() because the extension preceded by a period could also be part of the name, as in my example. By using Substring we return the filename without the extension as requested.
Try
.test {
white-space:pre-wrap;
}
_x000D_
<a class="test" href="#">
Notes
<span>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
</span>
</a>
_x000D_
This answer is going to briefly explain how the native files are handled on the latest launcher.
As of 4/29/2017 the Minecraft launcher for Windows extracts all native files and places them info %APPDATA%\Local\Temp{random folder}. That folder is temporary and is deleted once the javaw.exe process finishes (when Minecraft is closed). The location of that temporary folder must be provided in the launch arguments as the value of
-Djava.library.path=
Also, the latest launcher (2.0.847) does not show you the launch arguments so if you need to check them yourself you can do so under the Task Manager (simply enable the Command Line tab and expand it) or by using the WMIC
utility as explained here.
Hope this helps some people who are still interested in doing this in 2017.
Not Sure which version of selenium you are referring to, however some commands in selenium * can now do this: http://release.seleniumhq.org/selenium-core/0.8.0/reference.html
Etc..
I only need to support HTML5 browsers that support typed arrays (DataView, ArrayBuffer, etc.) I think I took the Joseph Myers code and modified it to support passing in a Uint8Array. I did not catch all the improvements, and there are still probably some char() array artifacts that can be improved on. I needed this for adding to the PouchDB project.
var PouchUtils = {};
PouchUtils.Crypto = {};
(function () {
PouchUtils.Crypto.MD5 = function (uint8Array) {
function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i = 64; i <= s.length; i += 64) {
md5cycle(state, md5blk(s.subarray(i - 64, i)));
}
s = s.subarray(i - 64);
var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < s.length; i++)
tail[i >> 2] |= s[i] << ((i % 4) << 3);
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i++) tail[i] = 0;
}
tail[14] = n * 8;
md5cycle(state, tail);
return state;
}
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
function md5blk(s) { /* I figured global was faster. */
var md5blks = [], i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s[i]
+ (s[i + 1] << 8)
+ (s[i + 2] << 16)
+ (s[i + 3] << 24);
}
return md5blks;
}
var hex_chr = '0123456789abcdef'.split('');
function rhex(n) {
var s = '', j = 0;
for (; j < 4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
+ hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}
function hex(x) {
for (var i = 0; i < x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}
function md5(s) {
return hex(md51(s));
}
function add32(a, b) {
return (a + b) & 0xFFFFFFFF;
}
return md5(uint8Array);
};
})();
You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.
So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded
event or functions like $.ready
in jQuery.
This should work:
$('.myClass, .myOtherClass').removeClass('theclass');
You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.
It's the same as you would do in CSS.
Just change the first line as follows :
include ActionView::Helpers
that will make it works.
UPDATE: For Rails 3 use:
ActionController::Base.helpers.sanitize(str)
Credit goes to lornc's answer