If you don't explicitly cast one of the two values to a float before doing the division then an integer division will be used (so that's why you get 0). You just need one of the two operands to be a floating point value, so that the normal division is used (and other integer value is automatically turned into a float).
Just try with
float completed = 50000.0f;
and it will be fine.
It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:
public class PrintQueue {
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
System.out.println("out");
System.err.println("err");
}
}
}
If you compile and run the program, you will see that the order of outputs in console is mixed up.
An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.
Even in this code snippet you can see that the order is mixed up sometimes:
public class PrintQueue {
public static void main(String[] args) {
System.out.println("out");
System.err.println("err");
}
}
Essentially console.log("Put a message here.")
if the browser has a supporting console.
Another typical debugging method is using alerts, alert("Put a message here.")
RE: Update II
This seems to make sense, you are trying to automate QUnit tests, from what I have read on QUnit this is an in-browser unit testing suite/library. QUnit expects to run in a browser and therefore expects the browser to recognize all of the JavaScript functions you are calling.
Based on your Maven configuration it appears you are using Rhino to execute your Javascript at the command line/terminal. This is not going to work for testing browser specifics, you would likely need to look into Selenium for this. If you do not care about testing your JavaScript in a browser but are only testing JavaScript at a command line level (for reason I would not be familiar with) it appears that Rhino recognizes a print()
method for evaluating expressions and printing them out. Checkout this documentation.
These links might be of interest to you.
You should use the built in line separator. The advantage is that you don't have to concern what system you code is running on, it will just work.
Since Java 1.7
System.lineSeparator()
Pre Java 1.7
System.getProperty("line.separator")
System.out.println("First Name: " + firstname);
System.out.println("Last Name: " + lastname);
or
System.out.println(String.format("First Name: %s", firstname));
System.out.println(String.format("Last Name: %s", lastname));
There are two ways to display tabs at the bottom of a tab activity.
Please check the link for more details.
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
if you are using django use forloop.counter
instead of loop.counter
<ul>
{% for user in userlist %}
<li>
{{ user }} {{forloop.counter}}
</li>
{% if forloop.counter == 1 %}
This is the First user
{% endif %}
{% endfor %}
</ul>
Another sort of workaround might be...
Use the HTML:
<input type="text" id="myselect"/>
<datalist id="myselect">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
<option>option 4</option>
</datalist>
In Firefox at least a focus followed by a click drops down the list of known valid values as the <datalist>
elements IFF the field happens to be empty. Otherwise, one must clear the field to see valid choices as one types in data. A new value is accepted as typed. One must handle new values in JS or other to persist them.
This is not perfect, but it suffices for my minimalist needs, so I thought I would share.
A pipe takes in data as input and transforms it to a desired output.
Add this pipe file:orderby.ts
inside your /app
folder .
//The pipe class implements the PipeTransform interface's transform method that accepts an input value and an optional array of parameters and returns the transformed value.
import { Pipe,PipeTransform } from "angular2/core";
//We tell Angular that this is a pipe by applying the @Pipe decorator which we import from the core Angular library.
@Pipe({
//The @Pipe decorator takes an object with a name property whose value is the pipe name that we'll use within a template expression. It must be a valid JavaScript identifier. Our pipe's name is orderby.
name: "orderby"
})
export class OrderByPipe implements PipeTransform {
transform(array:Array<any>, args?) {
// Check if array exists, in this case array contains articles and args is an array that has 1 element : !id
if(array) {
// get the first element
let orderByValue = args[0]
let byVal = 1
// check if exclamation point
if(orderByValue.charAt(0) == "!") {
// reverse the array
byVal = -1
orderByValue = orderByValue.substring(1)
}
console.log("byVal",byVal);
console.log("orderByValue",orderByValue);
array.sort((a: any, b: any) => {
if(a[orderByValue] < b[orderByValue]) {
return -1*byVal;
} else if (a[orderByValue] > b[orderByValue]) {
return 1*byVal;
} else {
return 0;
}
});
return array;
}
//
}
}
In your component file (app.component.ts) import the pipe that you just added using: import {OrderByPipe} from './orderby';
Then, add *ngFor="#article of articles | orderby:'id'"
inside your template if you want to sort your articles by id in ascending order or orderby:'!id'"
in descending order.
We add parameters to a pipe by following the pipe name with a colon ( : ) and then the parameter value
We must list our pipe in the pipes array of the @Component decorator. pipes: [ OrderByPipe ]
.
import {Component, OnInit} from 'angular2/core';
import {OrderByPipe} from './orderby';
@Component({
selector: 'my-app',
template: `
<h2>orderby-pipe by N2B</h2>
<p *ngFor="#article of articles | orderby:'id'">
Article title : {{article.title}}
</p>
`,
pipes: [ OrderByPipe ]
})
export class AppComponent{
articles:Array<any>
ngOnInit(){
this.articles = [
{
id: 1,
title: "title1"
},{
id: 2,
title: "title2",
}]
}
}
More info here on my github and this post on my website
Another possible option would be to use Datejs
Then you can do
Date.getDaysInMonth(2009, 9)
Although adding a library just for this function is overkill, it's always nice to know all the options you have available to you :)
@rckoenes already showed you how to correctly get your data from the JSON string.
To the question you asked: EXC_BAD_ACCESS
almost always comes when you try to access an object after it has been [auto-]released. This is not specific to JSON [de-]serialization but, rather, just has to do with you getting an object and then accessing it after it's been released. The fact that it came via JSON doesn't matter.
There are many-many pages describing how to debug this -- you want to Google (or SO) obj-c zombie objects
and, in particular, NSZombieEnabled
, which will prove invaluable to you in helping determine the source of your zombie objects. ("Zombie" is what it's called when you release an object but keep a pointer to it and try to reference it later.)
you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility. Then add the keys manually, HttpValueCollection do the encoding for you. And then just append the QueryString manually :
var qs = HttpUtility.ParseQueryString("");
qs.Add("name", "John")
qs.Add("contact", "calgary");
qs.Add("contact", "vancouver")
<a href="<%: Url.Action("GetByList", "Listing")%>?<%:qs%>">
<span>People</span>
</a>
Here's a pure-numpy implementation. It's about 5× faster than using itertools.
import numpy as np
def cartesian(arrays, out=None):
"""
Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
2-D array of shape (M, len(arrays)) containing cartesian products
formed of input arrays.
Examples
--------
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]])
"""
arrays = [np.asarray(x) for x in arrays]
dtype = arrays[0].dtype
n = np.prod([x.size for x in arrays])
if out is None:
out = np.zeros([n, len(arrays)], dtype=dtype)
m = n / arrays[0].size
out[:,0] = np.repeat(arrays[0], m)
if arrays[1:]:
cartesian(arrays[1:], out=out[0:m, 1:])
for j in xrange(1, arrays[0].size):
out[j*m:(j+1)*m, 1:] = out[0:m, 1:]
return out
Try this way, more efficient and compatible:
SimpleDateFormat time_formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
String current_time_str = time_formatter.format(System.currentTimeMillis());
//Log.i("test", "current_time_str:" + current_time_str);
I think System.Math.Truncate is what you're looking for.
Another way to do it that's designed for django, but should work in most settings, is to use django-dotenv.
color: transparent;
make the tricks for me
#videos-part:before{
font-size: 35px;
line-height: 33px;
width: 16px;
color: transparent;
content: 'AS YOU LIKE';
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUwIDUwIiBoZWlnaHQ9IjUwcHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MCA1MCIgd2lkdGg9IjUwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik04LDE0TDQsNDloNDJsLTQtMzVIOHoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbWl0ZXJsaW1pdD0iMTAiIHN0cm9rZS13aWR0aD0iMiIvPjxyZWN0IGZpbGw9Im5vbmUiIGhlaWdodD0iNTAiIHdpZHRoPSI1MCIvPjxwYXRoIGQ9Ik0zNCwxOWMwLTEuMjQxLDAtNi43NTksMC04ICBjMC00Ljk3MS00LjAyOS05LTktOXMtOSw0LjAyOS05LDljMCwxLjI0MSwwLDYuNzU5LDAsOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1taXRlcmxpbWl0PSIxMCIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIxOSIgcj0iMiIvPjxjaXJjbGUgY3g9IjE2IiBjeT0iMTkiIHI9IjIiLz48L3N2Zz4=');
background-size: 25px;
background-repeat: no-repeat;
}
Here's a simple function for formatting phone numbers with 7 to 10 digits in a more European (or Swedish?) manner:
function formatPhone($num) {
$num = preg_replace('/[^0-9]/', '', $num);
$len = strlen($num);
if($len == 7) $num = preg_replace('/([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 $2 $3', $num);
elseif($len == 8) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{3})/', '$1 - $2 $3', $num);
elseif($len == 9) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{2})/', '$1 - $2 $3 $4', $num);
elseif($len == 10) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 - $2 $3 $4', $num);
return $num;
}
After trying everything I could find and nothing worked, I just tried this:
touch ~/.bash_profile; open ~/.bash_profile
Inside the file added this line.
export PATH="$PATH:/usr/local/Cellar/openssl/1.0.2j/bin/openssl"
now it works :)
Jorns-iMac:~ jorn$ openssl version -a
OpenSSL 1.0.2j 26 Sep 2016
built on: reproducible build, date unspecified
//blah blah
OPENSSLDIR: "/usr/local/etc/openssl"
Jorns-iMac:~ jorn$ which openssl
/usr/local/opt/openssl/bin/openssl
serverIPaddress/~cpanelusername will only work for cPanel. It will not work for Parallel's Panel.
As long as you have the website created on the shared, VPS or Dedicated, you should be able to always use the following in your host file, which is what your browser will use.
67.225.235.59 somerandomservice.com www.somerandomservice.com
Following looks very simple to me:
model.layers[idx].output
Above is a tensor object, so you can modify it using operations that can be applied to a tensor object.
For example, to get the shape model.layers[idx].output.get_shape()
idx
is the index of the layer and you can find it from model.summary()
There are several methods you could use that exist in the System.IO
namespace:
Directory.GetLogicalDrives() // Returns an array of strings like "c:\"
Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name
Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path.
As suggested you could then do this:
bool IsValidFilename(string testName) {
string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]";
Regex containsABadCharacter = new Regex(regexString);
if (containsABadCharacter.IsMatch(testName)) {
return false;
}
// Check for drive
string pathRoot = Path.GetPathRoot(testName);
if (Directory.GetLogicalDrives().Contains(pathRoot)) {
// etc
}
// other checks for UNC, drive-path format, etc
return true;
}
I think you should do it the other way round.
Define your Div
s and have your a href
within each Div
, pointing to different links
To get the HTML file
input form element to only accept PDFs, you can use the accept
attribute in modern browsers such as Firefox 9+, Chrome 16+, Opera 11+ and IE10+ like such:
<input name="file1" type="file" accept="application/pdf">
You can string together multiple mime types with a comma.
The following string will accept JPG, PNG, GIF, PDF, and EPS files:
<input name="foo" type="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps">
In older browsers the native OS file dialog cannot be restricted – you'd have to use Flash or a Java applet or something like that to handle the file transfer.
And of course it goes without saying that this doesn't do anything to verify the validity of the file type. You'll do that on the server-side once the file has uploaded.
A little update – with javascript and the FileReader API you could do more validation client-side before uploading huge files to your server and checking them again.
I faced the same issue while trying to transpile some jsx with babel. Below is the solution that worked for me. You can add the following json to your .babelrc
{
"presets": [
[
"@babel/preset-react",
{ "targets": { "browsers": ["last 3 versions", "safari >= 6"] } }
]
],
"plugins": [["@babel/plugin-proposal-class-properties"]]
}
<br>
worked for me.
plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')
First use:
yarn application -list
Note down the application id Then to kill use:
yarn application -kill application_id
This may be of some help (do not literally write out the backslashes '\' in the commands, they are meant to indicate that "everything has to be on one line"):
It seems that all the commands (in grey) take any type of key file (in green) as "in" argument. Which is nice.
Here are the commands again for easier copy-pasting:
openssl rsa -in $FF -out $TF
openssl rsa -aes256 -in $FF -out $TF
openssl pkcs8 -topk8 -nocrypt -in $FF -out $TF
openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -in $FF -out $TF
and
openssl rsa -check -in $FF
openssl rsa -text -in $FF
For Angular 7+,
1) add a file "typings.d.ts" to the project's root folder (e.g., src/typings.d.ts):
declare module "*.json" {
const value: any;
export default value;
}
2) import and access JSON data either:
import * as data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
constructor() {
console.log(data.default);
}
}
or:
import data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
constructor() {
console.log(data);
}
}
Add following to your proguard-rules.txt file
-assumenosideeffects class android.util.Log {
public static *** d(...);
public static *** w(...);
public static *** v(...);
public static *** i(...);
}
I have been using the BareTail for quite some time for viewing large logs (some GBs) and it is working very well is very fast. There is a free version and a commercial Pro version.
They say that it has
Another alternative is Far Manager. Viewing a several GBs file is no problem (little memory footprint), but attempting to open the text file in the Editing mode might take several GBs of RAM, so be aware of that. I am not aware of the file size limit that can be viewed/edited in Far.
I solved this problem like this:
Add to your Base abstract class (I mean abstract class where you initialize your driver in setUpDriver() method) this part of code:
private static boolean started = false;
static{
if (!started) {
started = true;
try {
setUpDriver(); //method where you initialize your driver
} catch (MalformedURLException e) {
}
}
}
And now, if your test classes will extends from Base abstract class -> setUpDriver() method will be executed before first @Test only ONE time per run.
If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS%
shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd
:
@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f
And then execute like this:
GetNumberOfCores.cmd
echo %NumberOfCores%
The script will set a environment variable named %NumberOfCores%
and it will contain the number of processors.
I do not know much about Java but URL query arguments should be separated by "&", not "?"
http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.
I am very late to this but I want to mention that that new is actually unsafe in the Obj-C with Swift world. Swift will only create a default init method if you do not create any other initializer. Calling new on a swift class with a custom initializer will cause a crash. If you use alloc/init then the compiler will properly complain that init does not exist.
As for the code example in the question, the standard solution is to reference the class explicitly by its name, and it is even possible to do without getClassLoader()
call:
class MyClass {
public static void startMusic() {
URL songPath = MyClass.class.getResource("background.midi");
}
}
This approach still has a back side that it is not very safe against copy/paste errors in case you need to replicate this code to a number of similar classes.
And as for the exact question in the headline, there is a trick posted in the adjacent thread:
Class currentClass = new Object() { }.getClass().getEnclosingClass();
It uses a nested anonymous Object
subclass to get hold of the execution context. This trick has a benefit of being copy/paste safe...
Caution when using this in a Base Class that other classes inherit from:
It is also worth noting that if this snippet is shaped as a static method of some base class then currentClass
value will always be a reference to that base class rather than to any subclass that may be using that method.
As an alternative to Regex, running:
Sub Replacer()
Dim N As Long, i As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
If Left(Cells(i, "A").Value, 9) = "texts are" Then
Cells(i, "A").Value = "texts are replaced"
End If
Next i
End Sub
will produce:
Insert this in your Makefile
$(MAKE) -C $(KDIR) M=$(PWD) modules_install
it will install the module in the directory /lib/modules/<var>/extra/
After make , insert module with modprobe module_name (without .ko extension)
OR
After your normal make, you copy module module_name.ko into directory /lib/modules/<var>/extra/
then do modprobe module_name (without .ko extension)
The query below demonstrates use of the package and some of the information you can get.
select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual
NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.
Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.
Variant of Tim's one, good only on some implementations of Regex: ^.*?_
var subjectString = "3.04_somename.jpg";
var resultString = Regex.Replace(subjectString,
@"^ # Match start of string
.*? # Lazily match any character, trying to stop when the next condition becomes true
_ # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);
Related to this question, I just figured out why my vhost was giving me that 403.
I had tested ALL possibilities on this question and others without luck. It almost drives me mad.
I am setting up a server with releases deployment similar to Capistrano way through symlinks and when I tried to access the DocRoot folder (which is now a symlink to current release folder) it gave me the 403.
My vhost is:
DocumentRoot /var/www/site.com/html
<Directory /var/www/site.com/html>
AllowOverride All
Options +FollowSymLinks
Require all granted
</Directory>
and my main httpd.conf file was (default Apache 2.4 install):
DocumentRoot "/var/www"
<Directory "/var/www">
Options -Indexes -FollowSymLinks -Includes
(...)
It turns out that the main Options definition was taking precedence over my vhosts fiel (for me that is counter intuitive). So I've changed it to:
DocumentRoot "/var/www"
<Directory "/var/www">
Options -Indexes +FollowSymLinks -Includes
(...)
and Eureka! (note the plus sign before FollowSymLinks in MAIN httpd.conf file. Hope this help some other lost soul.
I've used js-cookie to success.
<script src="/path/to/js.cookie.js"></script>
<script>
Cookies.set('foo', 'bar');
Cookies.get('foo');
</script>
Here is another solution if you want to include different browsers in on file. If you and Mac user, from sublime menu go to, Tools > New Plugin. Delete the generated code and past the following:
import sublime, sublime_plugin
import webbrowser
class OpenBrowserCommand(sublime_plugin.TextCommand):
def run(self,edit,keyPressed):
url = self.view.file_name()
if keyPressed == "1":
navegator = webbrowser.get("open -a /Applications/Firefox.app %s")
if keyPressed == "2":
navegator = webbrowser.get("open -a /Applications/Google\ Chrome.app %s")
if keyPressed == "3":
navegator = webbrowser.get("open -a /Applications/Safari.app %s")
navegator.open_new(url)
Save. Then open up User Keybindings. (Tools > Command Palette > "User Key bindings"), and add this somewhere to the list:
{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3"}}
Now open any html file in Sublime and use one of the keybindings, which it would open that file in your favourite browser.
I was inspired by Igor and made a code block that creates a list:
def prime_number():
for num in range(2, 101):
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime and num not in num_list:
num_list.append(num)
else:
pass
return num_list
num_list = []
prime_number()
print(num_list)
You can use moment.js for that, it will convert DateTime object into valid Javascript formated date:
moment(DateOfBirth).format('DD-MMM-YYYY'); // put format as you want
Output: 28-Apr-1993
Hope it will help you :)
ALTER TABLE TABLE_NAME ADD (COLUMN_NAME_NEW varchar2(4000 char));
update TABLE_NAME set COLUMN_NAME_NEW = COLUMN_NAME;
ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;
ALTER TABLE TABLE_NAME rename column COLUMN_NAME_NEW to COLUMN_NAME;
long millis = durationInMillis % 1000;
long second = (durationInMillis / 1000) % 60;
long minute = (durationInMillis / (1000 * 60)) % 60;
long hour = (durationInMillis / (1000 * 60 * 60)) % 24;
String time = String.format("%02d:%02d:%02d.%d", hour, minute, second, millis);
Here if you mention .getPath()
then that will return the path of Jar and I guess
you will need its parent to refer to all other config files placed with the jar.
This code works on Windows. Add the code within the main class.
File jarDir = new File(MyAppName.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String jarDirpath = jarDir.getParent();
System.out.println(jarDirpath);
U can use eclipse. but u need to download pydev addon for that.
I wrap the input[type=file]
in a label tag, then style the label
to your liking, and hide the input
.
<label class="btn btn-default fileLabel" data-toggle="tooltip" data-placement="top" title="Upload">
<input type="file">
<span><i class="fa fa-upload"></i></span>
</label>
<style>
.fileLabel input[type="file"] {
position: fixed;
top: -1000px;
}
</style>
Purely CSS Solution.
(Ruby examples)
WebDriver now has support for opening tabs:
browser = Selenium::WebDriver.for :chrome
new_tab = browser.manage.new_window
Will open a new tab. Opening a window has actually become the non-standard case:
browser.manage.new_window(:window)
The tab or window will not automatically be focussed. To switch to it:
browser.switch_to.window new_tab
I had an issue with turning off a background image (a DRAFT watermark) in VBA. My change wasn't showing up (which was performed with the Sheets(1).PageSetup.CenterHeader = ""
method) - so I needed a way to refresh. The ActiveSheet.EnableCalculation
approach partly did the trick, but didn't cover unused cells.
In the end I found what I needed with a one liner that made the image vanish when it was no longer set :-
Application.ScreenUpdating = True
Normal arithmetic is base-10, so decimals represent tenths, hundredths, etc. When you try to represent a floating-point number in binary base-2 arithmetic, you are dealing with halves, fourths, eighths, etc.
In the hardware, floating points are stored as integer mantissas and exponents. Mantissa represents the significant digits. Exponent is like scientific notation but it uses a base of 2 instead of 10. For example 64.0 would be represented with a mantissa of 1 and exponent of 6. 0.125 would be represented with a mantissa of 1 and an exponent of -3.
Floating point decimals have to add up negative powers of 2
0.1b = 0.5d
0.01b = 0.25d
0.001b = 0.125d
0.0001b = 0.0625d
0.00001b = 0.03125d
and so on.
It is common to use a error delta instead of using equality operators when dealing with floating point arithmetic. Instead of
if(a==b) ...
you would use
delta = 0.0001; // or some arbitrarily small amount
if(a - b > -delta && a - b < delta) ...
Focus doesn't work on divs by default. But, according to this, you can make it work:
The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (
<input>
,<select>
, etc.) and links (<a href>
). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.
In case if you need a matrix with predefined numbers you can use the following code:
def matrix(rows, cols, start=0):
return [[c + start + r * cols for c in range(cols)] for r in range(rows)]
assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]
If you want more general information about various methods of representing numbers including Two's Complement have a look at:
Two's Complement and Signed Number Representation on Wikipedia
I encountered this error since my encoded image started with data:image/png;base64,iVBORw0...
.
This answer led me to the solution:
String partSeparator = ",";
if (data.contains(partSeparator)) {
String encodedImg = data.split(partSeparator)[1];
byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
Files.write(destinationFile, decodedImg);
}
This can be solved efficiently in O(n log (n)) as following. I am giving solution which tells if sum of any three numbers equal a given number.
import java.util.*;
public class MainClass {
public static void main(String[] args) {
int[] a = {-1, 0, 1, 2, 3, 5, -4, 6};
System.out.println(((Object) isThreeSumEqualsTarget(a, 11)).toString());
}
public static boolean isThreeSumEqualsTarget(int[] array, int targetNumber) {
//O(n log (n))
Arrays.sort(array);
System.out.println(Arrays.toString(array));
int leftIndex = 0;
int rightIndex = array.length - 1;
//O(n)
while (leftIndex + 1 < rightIndex - 1) {
//take sum of two corners
int sum = array[leftIndex] + array[rightIndex];
//find if the number matches exactly. Or get the closest match.
//here i am not storing closest matches. You can do it for yourself.
//O(log (n)) complexity
int binarySearchClosestIndex = binarySearch(leftIndex + 1, rightIndex - 1, targetNumber - sum, array);
//if exact match is found, we already got the answer
if (-1 == binarySearchClosestIndex) {
System.out.println(("combo is " + array[leftIndex] + ", " + array[rightIndex] + ", " + (targetNumber - sum)));
return true;
}
//if exact match is not found, we have to decide which pointer, left or right to move inwards
//we are here means , either we are on left end or on right end
else {
//we ended up searching towards start of array,i.e. we need a lesser sum , lets move inwards from right
//we need to have a lower sum, lets decrease right index
if (binarySearchClosestIndex == leftIndex + 1) {
rightIndex--;
} else if (binarySearchClosestIndex == rightIndex - 1) {
//we need to have a higher sum, lets decrease right index
leftIndex++;
}
}
}
return false;
}
public static int binarySearch(int start, int end, int elem, int[] array) {
int mid = 0;
while (start <= end) {
mid = (start + end) >>> 1;
if (elem < array[mid]) {
end = mid - 1;
} else if (elem > array[mid]) {
start = mid + 1;
} else {
//exact match case
//Suits more for this particular case to return -1
return -1;
}
}
return mid;
}
}
printf("\nmaximum of %d and %d is = %d",a,b,c);
This works for me (using jquery) to overload Ctrl+S, Ctrl+F and Ctrl+G:
$(window).bind('keydown', function(event) {
if (event.ctrlKey || event.metaKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 's':
event.preventDefault();
alert('ctrl-s');
break;
case 'f':
event.preventDefault();
alert('ctrl-f');
break;
case 'g':
event.preventDefault();
alert('ctrl-g');
break;
}
}
});
data = [4, 5, 6] # Your global variable
def print_data(data): # <-- Pass in a parameter called "data"
print data # <-- Note: You can access global variable inside your function, BUT for now, which is which? the parameter or the global variable? Confused, huh?
print_data(data)
I typed this in my URL bar:
javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }
Easy.
open xampp control panel -> Config -> my.ini edit with notepad. now add this below [mysqld]
skip-grant-tables
Save. Start apache and mysql.
I hope help you
I can think of a cheeky way to do it, I don't think this will be the best option but it will work.
Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow
.
table {_x000D_
width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
max-height: 60px;_x000D_
overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<th>head1</th>_x000D_
<th>head2</th>_x000D_
<th>head3</th>_x000D_
<th>head4</th>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
<table>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
You could use the "Shown" event: MSDN - Form.Shown
"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."
ICMP means Internet Control Message Protocol and is always coupled with the IP protocol (There's 2 ICMP variants one for IPv4 and one for IPv6.)
echo request and echo response are the two operation codes of ICMP used to implement ping
.
Besides the original ping program, ping might simply mean the action of checking if a remote node is responding, this might be done on several layers in a protocol stack - e.g. ARP ping for testing hosts on a local network. The term ping might be used on higher protocol layers and APIs as well, e.g. the act of checking if a database is up, done at the database layer protocol.
ICMP sits on top of IP. What you have below depends on the network you're on, and are not in themselves relevant to the operation of ping.
Ended up using http://videojs.com/ to support all browsers.
But to get the video working in IE9 and Chrome I just added html5 doc type and used mp4:
<!DOCTYPE html>
<html>
<body>
<video src="video.mp4" width="400" height="300" preload controls>
</video>
</body>
</html>
Check this find code for Database use:
function numonly(root){
>>var reet = root.value;
var arr1 = reet.length;
var ruut = reet.charAt(arr1-1);
>>>if (reet.length > 0){
var regex = /[0-9]|\./;
if (!ruut.match(regex)){
var reet = reet.slice(0, -1);
$(root).val(reet);
>>>>}
}
}
//Then use the even handler onkeyup='numonly(this)'
Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.
OpenSessionInViewFilter
calls the openSession
method of the underlying SessionFactory
and obtains a new Session
.Session
is bound to the TransactionSynchronizationManager
.OpenSessionInViewFilter
calls the doFilter
of the javax.servlet.FilterChain
object reference and the request is further processedDispatcherServlet
is called, and it routes the HTTP request to the underlying PostController
.PostController
calls the PostService
to get a list of Post
entities.PostService
opens a new transaction, and the HibernateTransactionManager
reuses the same Session
that was opened by the OpenSessionInViewFilter
.PostDAO
fetches the list of Post
entities without initializing any lazy association.PostService
commits the underlying transaction, but the Session
is not closed because it was opened externally.DispatcherServlet
starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.OpenSessionInViewFilter
can close the Session
, and the underlying database connection is released as well.At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.
The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection
as read-only which would allow the database server to avoid writing to the transaction log.
There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.
The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize
for fetching associations in batches, and FetchMode.SUBSELECT
to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.
Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.
Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.
So, make sure that in the application.properties
configuration file, you have the following entry:
spring.jpa.open-in-view=false
This will disable OSIV so that you can handle the LazyInitializationException
the right way.
Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.
I kept getting this error, when using wildcard subdomains with my app. I had the site url set to: http://myapp.com and app domain also to http://myapp.com, and also the same value for the Valid OAuth redirect URIs in the advanced tab of the settings app. I tried different combinations but only setting the http://subdomain.myapp.com as the redirect value worked, of course only for that subdomain.
The solution was to empty the redirect fields, leave it blank, that worked! ;)
In my projects I use following function to access cookies by name
function getCookie(cookie) {
return document.cookie.split(';').reduce(function(prev, c) {
var arr = c.split('=');
return (arr[0].trim() === cookie) ? arr[1] : prev;
}, undefined);
}
Jonathan from the ExcelCentral forums suggests:
=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1
This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:
=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1
For weeks beginning on Tuesday, use:
=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1
etc.
I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).
Use .height()
like this:
var result = $("#myDiv").height();
There's also .innerHeight()
and .outerHeight()
depending on exactly what you want.
You can test it here, play with the padding/margins/content to see how it changes around.
Try this method to get path of original
image captured by camera.
public String getOriginalImagePath() {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
return cursor.getString(column_index_data);
}
This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.
For sending a mail with attachment..
public class SendAttachment{
public static void main(String [] args){
//to address
String to="[email protected]";//change accordingly
//from address
final String user="[email protected]";//change accordingly
final String password="password";//change accordingly
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
//1) get the session object
Properties properties = System.getProperties();
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
//2) compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Hii");
//3) create MimeBodyPart object and set your message content
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("How is This");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
//Location of file to be attached
String filename = Environment.getExternalStorageDirectory().getPath()+"/R2832.zip";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName("Hello");
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
//7) send message
Transport.send(message);
System.out.println("MESSAGE SENT....");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
->> works for me.
postgres version:
<postgres.version>11.6</postgres.version>
Query:
select object_details->'valuationDate' as asofJson, object_details->>'valuationDate' as asofText from MyJsonbTable;
Output:
asofJson asofText
"2020-06-26" 2020-06-26
"2020-06-25" 2020-06-25
"2020-06-25" 2020-06-25
"2020-06-25" 2020-06-25
The <f:viewParam>
manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>
, but then for GET parameters.
The following example
<f:metadata>
<f:viewParam name="id" value="#{bean.id}" />
</f:metadata>
does basically the following:
id
.required
, validator
and converter
attributes and nest a <f:converter>
and <f:validator>
in it like as with <h:inputText>
)#{bean.id}
value, or if the value
attribute is absent, then set it as request attribtue on name id
so that it's available by #{id}
in the view.So when you open the page as foo.xhtml?id=10
then the parameter value 10
get set in the bean this way, right before the view is rendered.
As to validation, the following example sets the param to required="true"
and allows only values between 10 and 20. Any validation failure will result in a message being displayed.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
</f:metadata>
<h:message for="id" />
You can use the <f:viewAction>
for this.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
<f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />
with
public void onload() {
// ...
}
The <f:viewAction>
is however new since JSF 2.2 (the <f:viewParam>
already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event>
instead.
<f:event type="preRenderView" listener="#{bean.onload}" />
This is however invoked on every request. You need to explicitly check if the request isn't a postback:
public void onload() {
if (!FacesContext.getCurrentInstance().isPostback()) {
// ...
}
}
When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:
public void onload() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
// ...
}
}
Using <f:event>
this way is in essence a workaround/hack, that's exactly why the <f:viewAction>
was introduced in JSF 2.2.
You can "pass-through" the view parameters in navigation links by setting includeViewParams
attribute to true
or by adding includeViewParams=true
request parameter.
<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">
which generates with the above <f:metadata>
example basically the following link
<a href="next.xhtml?id=10">
with the original parameter value.
This approach only requires that next.xhtml
has also a <f:viewParam>
on the very same parameter, otherwise it won't be passed through.
The <f:viewParam>
can also be used in combination with "plain HTML" GET forms.
<f:metadata>
<f:viewParam id="query" name="query" value="#{bean.query}" />
<f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
<label for="query">Query</label>
<input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
<input type="submit" value="Search" />
<h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
...
</h:dataTable>
With basically this @RequestScoped
bean:
private String query;
private List<Result> results;
public void search() {
results = service.search(query);
}
Note that the <h:message>
is for the <f:viewParam>
, not the plain HTML <input type="text">
! Also note that the input value displays #{param.query}
when #{bean.query}
is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).
maybe problem with margin?
width:auto;
padding: 0px;
margin: 0px
You could build a Column/Row with Flexible or Expanded children that have flex values that add up to the percentages you want.
You may also find the AspectRatio widget useful.
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
The defer attribute is only for external scripts (should only be used if the src attribute is present).
Every write to the database has lots of potential side effects.
Delete: a row must be removed, indexes updated, foreign keys checked and possibly cascade-deleted, etc. Insert: a row must be allocated - this might be in place of a deleted row, might not be; indexes must be updated, foreign keys checked, etc. Update: one or more values must be updated; perhaps the row's data no longer fits into that block of the database so more space must be allocated, which may cascade into multiple blocks being re-written, or lead to fragmented blocks; if the value has foreign key constraints they must be checked, etc.
For a very small number of columns or if the whole row is updated Delete+insert might be faster, but the FK constraint problem is a big one. Sure, maybe you have no FK constraints now, but will that always be true? And if you have a trigger it's easier to write code that handles updates if the update operation is truly an update.
Another issue to think about is that sometimes inserting and deleting hold different locks than updating. The DB might lock the entire table while you are inserting or deleting, as opposed to just locking a single record while you are updating that record.
In the end, I'd suggest just updating a record if you mean to update it. Then check your DB's performance statistics and the statistics for that table to see if there are performance improvements to be made. Anything else is premature.
An example from the ecommerce system I work on: We were storing credit-card transaction data in the database in a two-step approach: first, write a partial transaction to indicate that we've started the process. Then, when the authorization data is returned from the bank update the record. We COULD have deleted then re-inserted the record but instead we just used update. Our DBA told us that the table was fragmented because the DB was only allocating a small amount of space for each row, and the update caused block-chaining since it added a lot of data. However, rather than switch to DELETE+INSERT we just tuned the database to always allocate the whole row, this means the update could use the pre-allocated empty space with no problems. No code change required, and the code remains simple and easy to understand.
JavaScript has a RegExp
object which does what you want. The String
object has a match()
function that will help you out.
var matches = text.match(/price\[(\d+)\]\[(\d+)\]/);
var productId = matches[1];
var shopId = matches[2];
IEEE 754 defines 1.0 / 0.0
as Infinity and -1.0 / 0.0
as -Infinity and 0.0 / 0.0
as NaN.
By the way, floating point values also have -0.0
and so 1.0/ -0.0
is -Infinity
.
Integer arithmetic doesn't have any of these values and throws an Exception instead.
To check for all possible values (e.g. NaN, 0.0, -0.0) which could produce a non finite number you can do the following.
if (Math.abs(tab[i] = 1 / tab[i]) < Double.POSITIVE_INFINITY)
throw new ArithmeticException("Not finite");
You have name spaces so you can have globally unique elements. However, 99% of the time this doesn't really matter, but when you put it in the perspective of The Semantic Web, it starts to become important.
For example, you could make an XML mash-up of different schemes just by using the appropriate xmlns
. For example, mash up friend of a friend with vCard, etc.
I ran into this issue when I was using pycharm to create and run a virtual environment - I clicked the "inherit global site packages" checkbox - deleting and recreating the venv solved the issue for me. If you used another means for creating your venv, make sure it IS NOT INHERITING global packages!
If iframe is not in the same domain such that you cannot get access to its internals from the parent but you can modify the source code of the iframe then you can modify the page displayed by the iframe to send messages to the parent window, which allows you to share information between the pages. Some sources:
You can tie it to button or on load of the page.
window.print();
Change the project interpreter to ~/anaconda2/python/bin
by going to File -> Settings -> Project -> Project Interpreter
. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations
. This makes PyCharm
use Anaconda
instead of the default Python interpreter under usr/bin/python27
.
If you will change the ID then Toggle will not working same problem was with me i just change
<div class="collapse navbar-collapse" id="defaultNavbar1">
<ul class="nav navbar-nav">
id="defaultNavbar1" then toggle is working
from torial: If you use winsock, here's a way: http://tangentsoft.net/wskfaq/examples/ipaddr.html
As for the subnet portion of the question; there is not platform agnostic way to retrieve the subnet mask as the POSIX socket API (which all modern operating systems implement) does not specify this. So you will have to use whatever method is available on the platform you are using.
If you are looking for psql command-line mode
like me, here is the syntax --pset expanded=auto
Quoted it here
psql command-line options:
-P expanded=auto
--pset expanded=auto
-x
--expanded
Another 2nd way is -q
option ref
You can download in the current directory with a .
:
cd # by default, goes to $HOME
scp me@host:/path/to/file .
or in you HOME
directly with :
scp me@host:/path/to/file ~
You can prefer quick-json parser to meet your requirement...
quick-json parser is very straight forward, flexible, very fast and customizable. Try this out
[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -
Compliant with JSON specification (RFC4627)
High-Performance JSON parser
Supports Flexible/Configurable parsing approach
Configurable validation of key/value pairs of any JSON Heirarchy
Easy to use # Very Less foot print
Raises developer friendly and easy to trace exceptions
Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered
Validating and Non-Validating parser support
Support for two types of configuration (JSON/XML) for using quick-json validating parser
Require JDK 1.5 # No dependency on external libraries
Support for Json Generation through object serialization
Support for collection type selection during parsing process
For e.g.
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.
//To align it to the left
p.add(b, BorderLayout.WEST);
//To align it to the right
p.add(b, BorderLayout.EAST);
//To align it at the top
p.add(b, BorderLayout.NORTH);
//To align it to the bottom
p.add(b, BorderLayout.SOUTH);
//To align it to the center
p.add(b, BorderLayout.CENTER);
Don't forget to import it as well by typing:
import java.awt.BorderLayout;
There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!
You can use the .update()
method if you don't need the original d2
any more:
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return
None
.
E.g.:
>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'b': 1, 'c': 3}
>>> d2.update(d1)
>>> d2
{'a': 1, 'c': 3, 'b': 2}
Update:
Of course you can copy the dictionary first in order to create a new merged one. This might or might not be necessary. In case you have compound objects (objects that contain other objects, like lists or class instances) in your dictionary, copy.deepcopy
should also be considered.
You can just edit your file on host and quickly copy it into and run it inside the container. Here is my one-line shortcut to copy and run a Python file:
docker cp main.py my-container:/data/scripts/ ; docker exec -it my-container python /data/scripts/main.py
Do ls -la
to know the user and group of /var/log/mongodb.
Then do sudo chown -R user:group /data/db
Now run sudo service mongodb start
.
Check the status with sudo service mongodb status
Structure packing is only done when you tell your compiler explicitly to pack the structure. Padding is what you're seeing. Your 32-bit system is padding each field to word alignment. If you had told your compiler to pack the structures, they'd be 6 and 5 bytes, respectively. Don't do that though. It's not portable and makes compilers generate much slower (and sometimes even buggy) code.
You can change your the Build Target for your project at any time:
Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.
Edit the following elements in the AndroidManifest.xml file (it is in your project root directory)
In this case, that will be:
<uses-sdk android:minSdkVersion="3" />
<uses-sdk android:targetSdkVersion="8" />
Save it
Rebuild your project.
Click the Project on the menu bar, select Clean...
Now, run the project again.
Right Click Project name, move on Run as, and select Android Application
By the way, reviewing Managing Projects from Eclipse with ADT will be helpful. Especially the part called Creating an Android Project.
I find this method to be most friendly.
var b = BigInteger.valueOf(x).toByteArray();
var l = new BigInteger(b);
Use stat
like this:
#include <sys/stat.h> // stat
#include <stdbool.h> // bool type
bool file_exists (char *filename) {
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
and call it like this:
#include <stdio.h> // printf
int main(int ac, char **av) {
if (ac != 2)
return 1;
if (file_exists(av[1]))
printf("%s exists\n", av[1]);
else
printf("%s does not exist\n", av[1]);
return 0;
}
It has something to do with your link and content. Try the following two links:
String path="http://www.ted.com/talks/download/video/8584/talk/761";
String path1="http://commonsware.com/misc/test2.3gp";
Uri uri=Uri.parse(path1);
VideoView video=(VideoView)findViewById(R.id.VideoView01);
video.setVideoURI(uri);
video.start();
Start with "path1", it is a small light weight video stream and then try the "path", it is a higher resolution than "path1", a perfect high resolution for the mobile phone.
(new Date()).toLocaleString()
Will output the date and time using your local format. For example: "5/1/2020, 10:35:41 AM"
Yeah Regex is cool, but there are other alternative.
This allows you to edit multiple lines at once. Now you can add *Quotes (") or anything * at start and end of each lines.
The answer is simple. Just divide string by 1. Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
Very easy and fastest method is using ng2-file-upload.
Install ng2-file-upload via npm. npm i ng2-file-upload --save
At first import module in your module.
import { FileUploadModule } from 'ng2-file-upload';
Add it to [imports] under @NgModule:
imports: [ ... FileUploadModule, ... ]
Markup:
<input ng2FileSelect type="file" accept=".xml" [uploader]="uploader"/>
In your commponent ts:
import { FileUploader } from 'ng2-file-upload';
...
uploader: FileUploader = new FileUploader({ url: "api/your_upload", removeAfterUpload: false, autoUpload: true });
It`is simplest usage of this. To know all power of this see demo
You can remove non numeric characters using regex
onTextChanged (text) {
this.setState({
myNumber: text.replace(/\D/g, ''),
});
}
DateFormatter
has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:
extension Date {
func asString(style: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
}
This gives you the following styles:
short, medium, long, full
Example usage:
let myDate = Date()
myDate.asString(style: .full) // Wednesday, January 10, 2018
myDate.asString(style: .long) // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short) // 1/10/18
Here are 3 different methods to check this
<?php
//Method 1
if(!empty($_GET))
echo "exist";
else
echo "do not exist";
//Method 2
echo "<br>";
if($_GET)
echo "exist";
else
echo "do not exist";
//Method 3
if(count($_GET))
echo "exist";
else
echo "do not exist";
?>
The NA can actually be due to 2 reasons. One is that there is a NA in your data. Another one is due to there being one of the values being constant. This results in standard deviation being equal to zero and hence the cor function returns NA.
Like this:
sleep(num_secs)
The num_secs
value can be an integer or float.
Also, if you're writing this within a Rails app, or have included the ActiveSupport library in your project, you can construct longer intervals using the following convenience syntax:
sleep(4.minutes)
# or, even longer...
sleep(2.hours); sleep(3.days) # etc., etc.
# or shorter
sleep(0.5) # half a second
If you want to revert the file to its state in master
:
git checkout origin/master [filename]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>
<style type="text/css"><!--
.class1 A:link {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 4px solid #333333; border-right: 4px solid #333333; border-top: 3px solid #333333; border-bottom: 4px solid #333333;}
.class1 A:visited {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 4px solid #333333; border-right: 4px solid #333333; border-top: 3px solid #333333; border-bottom: 4px solid #333333;}
.class1 A:hover {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #0000FF; border-right: 3px solid #0000FF; border-top: 2px solid #0000FF; border-bottom: 2px solid #0000FF;}
.class1 A:active {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #0000FF; border-right: 3px solid #0000FF; border-top: 2px solid #0000FF; border-bottom: 2px solid #0000FF;}
#nav_menu .current {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #FF0000; border-right: 3px solid #FF0000; border-top: 2px solid #FF0000; border-bottom: 2px solid #FF0000;}
a:link {text-decoration:none;}
a:visited {text-decoration:none;}
a:hover {text-decoration:none;}
a:active {text-decoration:none;}
--></style>
</head>
<body style="background:#000000 url('...../images/bg.jpg') repeat-y top center fixed; width="100%" align="center">
<table style="table-layout:fixed; border:0px" width=100% height=100% border=0 cellspacing=0 cellpadding=0 align=center><tr>
<td style="background: url(...../images/menu_bg-menu.jpg) center no-repeat;" "border:0px" width="100%" height="100%" align="center" valign="middle">
<span class="class1" id="nav_menu">
<a href="http://Yourhomepage-url.com/" ***class="current"*** target="_parent"><font face="Georgia" color="#0000FF" size="2"><b> Home </b></font></a>
<a href="http://Yourhomepage-url.com/yourfaqspage-url.php_or_.html" target="_parent"><font face="Georgia" color="#0000FF" size="2"><b> FAQs page </b></font></a>
<a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" target="_parent"><font face="Georgia" color="#0000FF" size="2"><b> About </b></font></a>
<a href="http://Yourhomepage-url.com/yourcontactpage-url.php_or_.html" target="_parent"><font face="Georgia" color="#0000FF" size="2"><b> Contact </b></font></a>
</span>
</td></tr></table></body></html>
Note: the style goes in between the head tag (<head> .... </head>
) and the class="class1" and the id="nav_menu" goes in the ie: (-- <span class="class1" id="nav_menu">
--).
Then the last class attribute (class="current") goes in the hyper-link code of the link in the page that you want the active current link to correspond to.
Example: You want the link tab to stay active or highlighted when it's correspondent page is whats currently in view, go to that page itself and place the class="current" attribute by it's link's html code. Only in the page that corresponds to the link so that when ever that page is at view, the tab will stay highlighted or stand out different from the rest of the tabs.
For the Home page, go to the home page and place the class in it. example: <a href="http://Yourhomepage-url.com/" class="current" target="_parent">
For the About page, go to the about page and place the class in it. example: <a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">
For the Contact page, go to the contact page and place the class in it. example: <a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">
etc ......
Notice the example Table above;- Lets assume this was the Home page, so on this page, only the Home url link section has the class="current"
Sorry for any meaning-less error, am not a prof. but this worked for me and displays fine in almost all the browsers tested, including ipad, and smart phones. Hope this will help some-one out here because is very frustrating to want to and not able to. I had tried so had to get to this, and so far it's good for me.
As of requests
version 2.10.0, released on 2016-04-29, requests
supports SOCKS.
It requires PySocks, which can be installed with pip install pysocks
.
Example usage:
import requests
proxies = {'http': "socks5://myproxy:9191"}
requests.get('http://example.org', proxies=proxies)
1st Step: Go to the form where datagridview is added
2nd step: click on the datagridview at the top right side there will be displayed a small button of like play icon or arrow to edit the datagridview.
3rd step: click on that button and select edit columns now click the attributes you want to increase font size.
4th step: on the right side of the property menu the first on the list column named defaultcellstyle click on its property a new window will open to change the font and font size.
The usage of org.apache.commons.httpclient.URI
is not strictly an issue; what is an issue is that you target the wrong constructor, which is depreciated.
Using just
new URI( [string] );
Will indeed flag it as depreciated. What is needed is to provide at minimum one additional argument (the first, below), and ideally two:
escaped
: true if URI character sequence is in escaped form. false otherwise.charset
: the charset string to do escape encoding, if
requiredThis will target a non-depreciated constructor within that class. So an ideal usage would be as such:
new URI( [string], true, StandardCharsets.UTF_8.toString() );
A bit crazy-late in the game (a hair over 11 years later - egad!), but I hope this helps someone else, especially if the method at the far end is still expecting a URI, such as org.apache.commons.httpclient.setURI()
.
above application.properties worked amazing for me:
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com
I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.
To see the file size of your containers, you can use the --size
argument of docker ps
:
docker ps --size
ANOTHER REASON
for a white screen without error messages might be fragmentation of the APC cache.
Use phpinfo() to find out if it is used by your page (we had issues with PHP 5.4 + APC 3.1.13) and if so see what happens when you either
php_flag apc.cache_by_default off
apc_clear_cache();
(no solution but good to see if the APC is the problem)If you do have the APC and it is the problem, then you could
One addition: It should be noted that, in case "/tmp" is the directory where the session data is stored (which seems to be the default value), the sessions will not persist after reboot of that web server, as "/tmp" is often purged during reboot. The concept of a client-wise persistence stands and falls with the persistence of the storage on the server - which might fail if the "/tmp" directory is used for session data.
Actually I don't see any nulls:
given:
static void Main()
{
string[] testArray = new string[]
{
"aa",
"ab",
"ac",
"ad",
"ab",
"af"
};
Array.Sort(testArray, StringComparer.InvariantCulture);
Array.ForEach(testArray, x => Console.WriteLine(x));
}
I obtained:
change this line
for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){
to
for(int a = 0, b = 1; a<cards.length-1, b=a+1; a++){
Use this approach to sum the list of BigDecimal:
List<BigDecimal> values = ... // List of BigDecimal objects
BigDecimal sum = values.stream().reduce((x, y) -> x.add(y)).get();
This approach maps each BigDecimal as a BigDecimal only and reduces them by summing them, which is then returned using the get()
method.
Here's another simple way to do the same summing:
List<BigDecimal> values = ... // List of BigDecimal objects
BigDecimal sum = values.stream().reduce(BigDecimal::add).get();
Update
If I were to write the class and lambda expression in the edited question, I would have written it as follows:
import java.math.BigDecimal;
import java.util.LinkedList;
public class Demo
{
public static void main(String[] args)
{
LinkedList<Invoice> invoices = new LinkedList<>();
invoices.add(new Invoice("C1", "I-001", BigDecimal.valueOf(.1), BigDecimal.valueOf(10)));
invoices.add(new Invoice("C2", "I-002", BigDecimal.valueOf(.7), BigDecimal.valueOf(13)));
invoices.add(new Invoice("C3", "I-003", BigDecimal.valueOf(2.3), BigDecimal.valueOf(8)));
invoices.add(new Invoice("C4", "I-004", BigDecimal.valueOf(1.2), BigDecimal.valueOf(7)));
// Java 8 approach, using Method Reference for mapping purposes.
invoices.stream().map(Invoice::total).forEach(System.out::println);
System.out.println("Sum = " + invoices.stream().map(Invoice::total).reduce((x, y) -> x.add(y)).get());
}
// This is just my style of writing classes. Yours can differ.
static class Invoice
{
private String company;
private String number;
private BigDecimal unitPrice;
private BigDecimal quantity;
public Invoice()
{
unitPrice = quantity = BigDecimal.ZERO;
}
public Invoice(String company, String number, BigDecimal unitPrice, BigDecimal quantity)
{
setCompany(company);
setNumber(number);
setUnitPrice(unitPrice);
setQuantity(quantity);
}
public BigDecimal total()
{
return unitPrice.multiply(quantity);
}
public String getCompany()
{
return company;
}
public void setCompany(String company)
{
this.company = company;
}
public String getNumber()
{
return number;
}
public void setNumber(String number)
{
this.number = number;
}
public BigDecimal getUnitPrice()
{
return unitPrice;
}
public void setUnitPrice(BigDecimal unitPrice)
{
this.unitPrice = unitPrice;
}
public BigDecimal getQuantity()
{
return quantity;
}
public void setQuantity(BigDecimal quantity)
{
this.quantity = quantity;
}
}
}
Something that is not explicitly said in the documentation or in the answers on this page (even though implied by @Naruto), is that FragmentPagerAdapter
will not update the Fragments if the data in the Fragment changes because it keeps the Fragment in memory.
So even if you have a limited number of Fragments to display, if you want to be able to refresh your fragments (say for example you re-run the query to update the listView in the Fragment), you need to use FragmentStatePagerAdapter.
My whole point here is that the number of Fragments and whether or not they are similar is not always the key aspect to consider. Whether or not your fragments are dynamic is also key.
This image displayed below gives a clear understanding and shows the exact difference between .append()
, .prepend()
, .after()
and .before()
You can see from the image that .append()
and .prepend()
adds the new elements as child elements (brown colored) to the target.
And .after()
and .before()
adds the new elements as sibling elements (black colored) to the target.
Here is a DEMO for better understanding.
EDIT: the flipped versions of those functions:
Using this code:
var $target = $('.target');
$target.append('<div class="child">1. append</div>');
$target.prepend('<div class="child">2. prepend</div>');
$target.before('<div class="sibling">3. before</div>');
$target.after('<div class="sibling">4. after</div>');
$('<div class="child flipped">or appendTo</div>').appendTo($target);
$('<div class="child flipped">or prependTo</div>').prependTo($target);
$('<div class="sibling flipped">or insertBefore</div>').insertBefore($target);
$('<div class="sibling flipped">or insertAfter</div>').insertAfter($target);
on this target:
<div class="target">
This is the target div to which new elements are associated using jQuery
</div>
So although these functions flip the parameter order, each creates the same element nesting:
var $div = $('<div>').append($('<img>'));
var $img = $('<img>').appendTo($('<div>'))
...but they return a different element. This matters for method chaining.
I ran into the same issues the other day and it took me days to make it work. The error message was "Could not find the main class", but I can run the executable jar exported from Eclipse in other Windows machines without any problem.
The solution was to install both x64 and x86 version of the same version of JRE. The path environment variable was pointed to the x64 version. No idea why, but it worked for me.
In addition:
AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location
If you only want to sort only on the 5th field then use -k5,5
.
Also, use the -t
command line switch to specify the delimiter to tab
. Try this:
sort -k5,5 -r -n -t \t filename
or if the above doesn't work (with the tab
) this:
sort -k5,5 -r -n -t $'\t' filename
The man page for sort states:
-t, --field-separator=SEP use SEP instead of non-blank to blank transition
Finally, this SO question Unix Sort with Tab Delimiter might be helpful.
Try zoom
property
<img src="..." style="zoom: 0.5" />
Edit: Apparently, FireFox doesn't support zoom
property. You should use;
-moz-transform: scale(0.5);
for FireFox.
I got here searching for the same error, but from Node.js native driver. The answer for me was combination of answers by campeterson and Prabhat.
The issue is that readPreference
setting defaults to primary
, which then somehow leads to the confusing slaveOk
error. My problem is that I just wan to read from my replica set from any node. I don't even connect to it as to replicaset. I just connect to any node to read from it.
Setting readPreference
to primaryPreferred
(or better to the ReadPreference.PRIMARY_PREFERRED
constant) solved it for me. Just pass it as an option to MongoClient.connect()
or to client.db()
or to any find()
, aggregate()
or other function.
const { MongoClient, ReadPreference } = require('mongodb');
const client = await MongoClient.connect(MONGODB_CONNECTIONSTRING, { readPreference: ReadPreference.PRIMARY_PREFERRED });
This is not possible with css, but I have used one css trick in one of my website, please check if this works for you.
The trick is: wrap the input box with a div and make it relative, place a transparent image inside the div and make it absolute over the input text box, so that no one can edit it.
css
.txtBox{
width:250px;
height:25px;
position:relative;
}
.txtBox input{
width:250px;
height:25px;
}
.txtBox img{
position:absolute;
top:0;
left:0
}
html
<div class="txtBox">
<input name="" type="text" value="Text Box" />
<img src="http://dev.w3.org/2007/mobileok-ref/test/data/ROOT/GraphicsForSpacingTest/1/largeTransparent.gif" width="250" height="25" alt="" />
</div>
With Java 8, there are more elegant and functional ways to solve this.
LCM:
private static int lcm(int numberOne, int numberTwo) {
final int bigger = Math.max(numberOne, numberTwo);
final int smaller = Math.min(numberOne, numberTwo);
return IntStream.rangeClosed(1,smaller)
.filter(factor -> (factor * bigger) % smaller == 0)
.map(factor -> Math.abs(factor * bigger))
.findFirst()
.getAsInt();
}
GCD:
private static int gcd(int numberOne, int numberTwo) {
return (numberTwo == 0) ? numberOne : gcd(numberTwo, numberOne % numberTwo);
}
Of course if one argument is 0, both methods will not work.
XMLHttpRequest is a built-in object in web browsers.
It is not distributed with Node; you have to install it separately,
Install it with npm,
npm install xmlhttprequest
Now you can require
it in your code.
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
That said, the http module is the built-in tool for making HTTP requests from Node.
Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.
I don't meet the problem as you. But I get the same ERROR Message. So I mark it down here for others' convience.
Check the charset of two table if the column type is char
or varchar
. I use a charset=gbk
, but I create a new table whose default charset=utf8
. So the charset is not the same.
ERROR 1215 (HY000): Cannot add foreign key constraint
To solve it is to use the same charset. For example utf8
.
Failed to find: com.android.support:appcompat-v7:22.0.0
The "I literally tried everything else" answer:
This problem will also occur if you don't have an upto date Android Support Library and Android Support Repository. Just install using the SDK manager.
I wrote a C++
class using timeb
.
#include <sys/timeb.h>
class msTimer
{
public:
msTimer();
void restart();
float elapsedMs();
private:
timeb t_start;
};
Member functions:
msTimer::msTimer()
{
restart();
}
void msTimer::restart()
{
ftime(&t_start);
}
float msTimer::elapsedMs()
{
timeb t_now;
ftime(&t_now);
return (float)(t_now.time - t_start.time) * 1000.0f +
(float)(t_now.millitm - t_start.millitm);
}
Example of use:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
msTimer t;
for (int i = 0; i < 5000000; i++)
;
std::cout << t.elapsedMs() << endl;
return 0;
}
Output on my computer is '19'.
Accuracy of the msTimer
class is of the order of milliseconds. In the usage example above, the total time of execution taken up by the for
-loop is tracked. This time included the operating system switching in and out the execution context of main()
due to multitasking.
The exec function executes a system command and never returns-- use system instead of exec if you want it to return
Does exactly the same thing as exec LIST , except that a fork is done first, and the parent process waits for the child process to complete.
In contrast to exec and system, backticks don't give you the return value but the collected STDOUT.
A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected.
In more complex scenarios, where you want to fetch STDOUT, STDERR or the return code, you can use well known standard modules like IPC::Open2 and IPC::Open3.
Example:
use IPC::Open2;
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some', 'cmd', 'and', 'args');
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;
Finally, IPC::Run from the CPAN is also worth looking at…
If you are using RemoteDriver things are different. From http://element34.ca/blog/iedriverserver-webdriver-and-python :
You will need to start the server using a line like
java -jar selenium-server-standalone-2.26.0.jar -Dwebdriver.ie.driver=C:\Temp\IEDriverServer.exe
I found that if the IEDriverServer.exe was in C:\Windows\System32\
or its subfolders, it couldn't be found automatically (even though System32 was in the %PATH%
) or explicitly using the -D flag.
The following solutions are applicable since spark 1.5 :
For lower than :
// filter data where the date is lesser than 2015-03-14
data.filter(data("date").lt(lit("2015-03-14")))
For greater than :
// filter data where the date is greater than 2015-03-14
data.filter(data("date").gt(lit("2015-03-14")))
For equality, you can use either equalTo
or ===
:
data.filter(data("date") === lit("2015-03-14"))
If your DataFrame
date column is of type StringType
, you can convert it using the to_date
function :
// filter data where the date is greater than 2015-03-14
data.filter(to_date(data("date")).gt(lit("2015-03-14")))
You can also filter according to a year using the year
function :
// filter data where year is greater or equal to 2016
data.filter(year($"date").geq(lit(2016)))
Object Serialization uses the Serializable and Externalizable interfaces. A Java object is only serializable. if a class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable. Most of the java class are serializable.
NotSerializableException
: packageName.ClassName
« To participate a Class Object in serialization process, The class must implement either Serializable or Externalizable interface.Object Serialization produces a stream with information about the Java classes for the objects which are being saved. For serializable objects, sufficient information is kept to restore those objects even if a different (but compatible) version of the implementation of the class is present. The Serializable interface is defined to identify classes which implement the serializable protocol:
package java.io;
public interface Serializable {};
InvalidClassException
« In deserialization process, if local class serialVersionUID value is different from the corresponding sender's class. then result's in conflict as
java.io.InvalidClassException: com.github.objects.User; local class incompatible: stream classdesc serialVersionUID = 5081877, local class serialVersionUID = 50818771
For Externalizable objects, only the identity of the class of the object is saved by the container; the class must save and restore the contents. The Externalizable interface is defined as follows:
package java.io;
public interface Externalizable extends Serializable
{
public void writeExternal(ObjectOutput out)
throws IOException;
public void readExternal(ObjectInput in)
throws IOException, java.lang.ClassNotFoundException;
}
OptionalDataException
« The fields MUST BE IN THE SAME ORDER AND TYPE as we wrote them out. If there is any mismatch of type from the stream it throws OptionalDataException.
@Override public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt( id );
out.writeUTF( role );
out.writeObject(address);
}
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.id = in.readInt();
this.address = (Address) in.readObject();
this.role = in.readUTF();
}
The instance fields of the class which written (exposed) to ObjectOutput
get serialized.
Example « implements Serializable
class Role {
String role;
}
class User extends Role implements Serializable {
private static final long serialVersionUID = 5081877L;
Integer id;
Address address;
public User() {
System.out.println("Default Constructor get executed.");
}
public User( String role ) {
this.role = role;
System.out.println("Parametarised Constructor.");
}
}
class Address implements Serializable {
private static final long serialVersionUID = 5081877L;
String country;
}
Example « implements Externalizable
class User extends Role implements Externalizable {
Integer id;
Address address;
// mandatory public no-arg constructor
public User() {
System.out.println("Default Constructor get executed.");
}
public User( String role ) {
this.role = role;
System.out.println("Parametarised Constructor.");
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt( id );
out.writeUTF( role );
out.writeObject(address);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.id = in.readInt();
this.address = (Address) in.readObject();
this.role = in.readUTF();
}
}
Example
public class CustomClass_Serialization {
static String serFilename = "D:/serializable_CustomClass.ser";
public static void main(String[] args) throws IOException {
Address add = new Address();
add.country = "IND";
User obj = new User("SE");
obj.id = 7;
obj.address = add;
// Serialization
objects_serialize(obj, serFilename);
objects_deserialize(obj, serFilename);
// Externalization
objects_WriteRead_External(obj, serFilename);
}
public static void objects_serialize( User obj, String serFilename ) throws IOException{
FileOutputStream fos = new FileOutputStream( new File( serFilename ) );
ObjectOutputStream objectOut = new ObjectOutputStream( fos );
// java.io.NotSerializableException: com.github.objects.Address
objectOut.writeObject( obj );
objectOut.flush();
objectOut.close();
fos.close();
System.out.println("Data Stored in to a file");
}
public static void objects_deserialize( User obj, String serFilename ) throws IOException{
try {
FileInputStream fis = new FileInputStream( new File( serFilename ) );
ObjectInputStream ois = new ObjectInputStream( fis );
Object readObject;
readObject = ois.readObject();
String calssName = readObject.getClass().getName();
System.out.println("Restoring Class Name : "+ calssName); // InvalidClassException
User user = (User) readObject;
System.out.format("Obj[Id:%d, Role:%s] \n", user.id, user.role);
Address add = (Address) user.address;
System.out.println("Inner Obj : "+ add.country );
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void objects_WriteRead_External( User obj, String serFilename ) throws IOException {
FileOutputStream fos = new FileOutputStream(new File( serFilename ));
ObjectOutputStream objectOut = new ObjectOutputStream( fos );
obj.writeExternal( objectOut );
objectOut.flush();
fos.close();
System.out.println("Data Stored in to a file");
try {
// create a new instance and read the assign the contents from stream.
User user = new User();
FileInputStream fis = new FileInputStream(new File( serFilename ));
ObjectInputStream ois = new ObjectInputStream( fis );
user.readExternal(ois);
System.out.format("Obj[Id:%d, Role:%s] \n", user.id, user.role);
Address add = (Address) user.address;
System.out.println("Inner Obj : "+ add.country );
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
@see
sklearn.tree.export_graphviz
doesn't return anything, and so by default returns None
.
By doing dotfile = tree.export_graphviz(...)
you overwrite your open file object, which had been previously assigned to dotfile
, so you get an error when you try to close the file (as it's now None
).
To fix it change your code to
...
dotfile = open("D:/dtree2.dot", 'w')
tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
dotfile.close()
...
In all honesty, why so much overengineering...
I consider it really a bad practice to write active code for generating passive code.
My solution: most editors have block select mode. Just use it to add # to all lines you want to comment out. What's the big deal...
Notepad example:
To create: Alt - mousedrag down, press #.
To delete: Alt-mousedrag down, shift-right arrow, delete.
The only difference between innerText
and innerHTML
is that innerText
insert string as it is into the element, while innerHTML
run it as html content.
const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';_x000D_
document.getElementById('innertext').innerText = ourstring;_x000D_
document.getElementById('innerhtml').innerHTML = ourstring;
_x000D_
.name{_x000D_
color:red;_x000D_
}
_x000D_
<h3>Inner text below. It inject string as it is into the element.</h3>_x000D_
<div id="innertext"></div>_x000D_
<br />_x000D_
<h3>Inner html below. It renders the string into the element and treat as part of html document.</h3>_x000D_
<div id="innerhtml"></div>
_x000D_
If you use the ino command line:
ino upload
it can be because you use the arduino software at the same time, try to kill it.
In my case, it was the comment line that was messing up the COPY command
I removed the comment after the COPY command and placed it to a dedicated line above the command. Surprisingly it resolved the issue.
Faulty Dockerfile command
COPY qt-downloader . # https://github.com/engnr/qt-downloader -> contains the script to auto download qt for different architectures and versions
Working Dockerfile command
# https://github.com/engnr/qt-downloader -> contains the script to auto download qt for different architectures and versions
COPY qt-downloader .
Hope it helps someone.
\w
is not a word boundary, it matches any word character, including underscores: [a-zA-Z0-9_]
. \b
is a word boundary, that is, it matches the position between a word and a non-alphanumeric character: \W
or [^\w]
.
These implementations may vary from language to language though.
If you're using Xamarin, I found a guide on their official forum explaining how to do this:
Hereafter, you might also need to update the Google Play Services from the Google Play Store.
Hope this helps for anyone else who has troubles finding the documentation.
On SQL Server 2012, you can use the following stored procedure:
sp_columns '<table name>'
For example, given a database table named users:
sp_columns 'users'
You may want to use
location.reload(forceGet)
forceGet
is a boolean and optional.
The default is false which reloads the page from the cache.
Set this parameter to true if you want to force the browser to get the page from the server to get rid of the cache as well.
Or just
location.reload()
if you want quick and easy with caching.
$(this).find(".bgHeaderH2").html();
or
$(this).find(".bgHeaderH2").text();
You could use very easily reflection to list all properties, methods and values.
For Gecko based browsers you can use the .toSource() method:
var data = new Object();
data["firstname"] = "John";
data["lastname"] = "Smith";
data["age"] = 21;
alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})"
But since you use Firebug, why not just use console.log?
The 'go to bracket' shortcut takes cursor before the bracket, unlike the 'end' key which takes after the bracket. WASDMap VSCode extension is very helpful for navigating and selecting text using WASD keys.
You could use the timeout
setting in the ajax options like this:
$.ajax({
url: "test.html",
timeout: 3000,
error: function(){
//do something
},
success: function(){
//do something
}
});
Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/
Remember that when a timeout occurs, the error
handler is triggered and not the success
handler :)
If I'm not mistaken it is:
MyArray.SetValue(ArrayElement, PositionInArray)
You are missing a 'b' I think?
sudo service mongod start
should be
sudo service mongodb start
I think this is the case?
import pandas as pd
data = pd.read_csv("data.csv")
cols = data.columns
Similar to above, using filter
from dplyr
:
filter(df, fct %in% vc)
To expand upon Alex's answer, I have an example with variable arguments and promises. I wanted to load images via ajax and display them on the page after they all loaded.
To do that, I used the following:
let urlCreator = window.URL || window.webkitURL;
// Helper function for making ajax requests
let fetch = function(url) {
return $.ajax({
type: "get",
xhrFields: {
responseType: "blob"
},
url: url,
});
};
// Map the array of urls to an array of ajax requests
let urls = ["https://placekitten.com/200/250", "https://placekitten.com/300/250"];
let files = urls.map(url => fetch(url));
// Use the spread operator to wait for all requests
$.when(...files).then(function() {
// If we have multiple urls, then loop through
if(urls.length > 1) {
// Create image urls and tags for each result
Array.from(arguments).forEach(data => {
let imageUrl = urlCreator.createObjectURL(data[0]);
let img = `<img src=${imageUrl}>`;
$("#image_container").append(img);
});
}
else {
// Create image source and tag for result
let imageUrl = urlCreator.createObjectURL(arguments[0]);
let img = `<img src=${imageUrl}>`;
$("#image_container").append(img);
}
});
Updated to work for either single or multiple urls: https://jsfiddle.net/euypj5w9/
concurency: multiple execution flows with the potential to share resources
Ex: two threads competing for a I/O port.
paralelism: splitting a problem in multiple similar chunks.
Ex: parsing a big file by running two processes on every half of the file.
In your IDE right click on the file you want to read and choose "copy path" then paste it into your code.
Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"
Gson 1.6 now includes a low-level streaming API and a new parser which is actually faster than Jackson.
Try this Once go to the Programs and Features window->, hit the "Turn Windows Features on or off" in the left pane.
Now scroll down through the tree and find:
Internet Information Services World Wide Web Services Application Development Features ...and then check all the relevant features you require. I chose .NET 3.5 and 4.6.
and if does not work then go to Let it do its work and then you should be back to happy-development-land in VS before you know it. If not, then it could actually be a bug in Visual Studio. Please check the following patches for your version of VS: VS2010, VS2012 or VS2013. This will surely help you out.
Check out Typekit, a commercial option (they have a free package available too).
It uses different techniques depending on which browser is being used (@font-face
vs. EOT
format), and they take care of all the font licensing issues for you also. It supports everything down to IE6.
Here's some more info about how Typekit works:
There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. The process of converting source code into native executable code is called "compilation", and it's not supported by scripting languages like VBScript.
Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a self-extracting archive is that decompression software (like WinZip) is not required on the end user's computer to be able to extract or "decompress" the file. If it isn't compressed in the first place, this is a moot point.
Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.
In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be compiled. Visual Basic 6 (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild.
Alternatively, you could go ahead and make the jump to Visual Basic .NET, which remains somewhat similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some huge differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.
You can also use firstOrCreate
OR firstOrNew
// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]);
// update record
$post->title = "Updated title";
$post->save();
Hope it will help you :)
You mention the most commonly implemented, which is Adjacency List: https://blogs.msdn.microsoft.com/mvpawardprogram/2012/06/25/hierarchies-convert-adjacency-list-to-nested-sets
There are other models as well, including materialized path and nested sets: http://communities.bmc.com/communities/docs/DOC-9902
Joe Celko has written a book on this subject, which is a good reference from a general SQL perspective (it is mentioned in the nested set article link above).
Also, Itzik Ben-Gann has a good overview of the most common options in his book "Inside Microsoft SQL Server 2005: T-SQL Querying".
The main things to consider when choosing a model are:
1) Frequency of structure change - how frequently does the actual structure of the tree change. Some models provide better structure update characteristics. It is important to separate structure changes from other data changes however. For example, you may want to model a company's organizational chart. Some people will model this as an adjacency list, using the employee ID to link an employee to their supervisor. This is usually a sub-optimal approach. An approach that often works better is to model the org structure separate from employees themselves, and maintain the employee as an attribute of the structure. This way, when an employee leaves the company, the organizational structure itself does not need to be changes, just the association with the employee that left.
2) Is the tree write-heavy or read-heavy - some structures work very well when reading the structure, but incur additional overhead when writing to the structure.
3) What types of information do you need to obtain from the structure - some structures excel at providing certain kinds of information about the structure. Examples include finding a node and all its children, finding a node and all its parents, finding the count of child nodes meeting certain conditions, etc. You need to know what information will be needed from the structure to determine the structure that will best fit your needs.
Also we can change a little example from ipr101
Object.prototype.toType = function() {
return ({}).toString.call(this).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
and call as
"aaa".toType(); // 'string'
You can open a command prompt and do a
route print
and see your current routing table.
You can modify it by
route add d.d.d.d mask m.m.m.m g.g.g.g
route delete d.d.d.d mask m.m.m.m g.g.g.g
route change d.d.d.d mask m.m.m.m g.g.g.g
these seem to work
I run a ping d.d.d.d -t change the route and it changes. (my test involved routing to a dead route and the ping stopped)
openjdk-6
is a Java runtime, not a JDK (development kit which contains javac
, for example). Install openjdk-6-jdk
.
Maven also needs the JDK.
[EDIT] When the JDK is installed, use /usr/lib/jvm/java-6-openjdk
for JAVA_HOME
(i.e. without the jre
part).
Here's another way to do it instead of using foreach loops for looking inside EntityValidationErrors. Of course you can format the message to your own liking :
try {
// your code goes here...
}
catch (DbEntityValidationException ex)
{
Console.Write($"Validation errors: {string.Join(Environment.NewLine, ex.EntityValidationErrors.SelectMany(vr => vr.ValidationErrors.Select(err => $"{err.PropertyName} - {err.ErrorMessage}")))}", ex);
throw;
}
Make sure you have %JAVA_HOME%
set by typing echo %JAVA_HOME%
in Command Prompt. If you don't have that set, then you need to go add your Java path to Window's Environmental Variables.
In case you have one identity (Id
) and one common (Type
) columns:
UPDATE #Table1
SET [Type] = (SELECT TOP 1 [Type]
FROM #Table1 t
WHERE t.[Type] IS NOT NULL AND
b.[Id] > t.[Id]
ORDER BY t.[Id] DESC)
FROM #Table1 b
WHERE b.[Type] IS NULL
Looks like a combination of componentDidMount
and componentDidUpdate
will get the job done. The first is called after the initial rendering, when the DOM is available, the second is called after any subsequent renderings, once the updated DOM is available. In my case, I both have them delegate to a common function to do the same thing.
In case you want to chain a lot of querysets, try this:
from itertools import chain
result = list(chain(*docs))
where: docs is a list of querysets
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
You could use PHP's file_get_contents();
<?php
$script = file_get_contents('javascriptFile.js');
echo "<script>".$script."</script>";
?>
For more information on the function:
You can provide a file-like object to the stdin
argument of subprocess.call()
.
The documentation for the Popen
object applies here.
To capture the output, you should instead use subprocess.check_output()
, which takes similar arguments. From the documentation:
>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'
It might help you to understand.
import * as Rx from 'rxjs';
const subject1 = new Rx.Subject();
subject1.next(1);
subject1.subscribe(x => console.log(x)); // will print nothing -> because we subscribed after the emission and it does not hold the value.
const subject2 = new Rx.Subject();
subject2.subscribe(x => console.log(x)); // print 1 -> because the emission happend after the subscription.
subject2.next(1);
const behavSubject1 = new Rx.BehaviorSubject(1);
behavSubject1.next(2);
behavSubject1.subscribe(x => console.log(x)); // print 2 -> because it holds the value.
const behavSubject2 = new Rx.BehaviorSubject(1);
behavSubject2.subscribe(x => console.log('val:', x)); // print 1 -> default value
behavSubject2.next(2) // just because of next emission will print 2
The directions state:
- Download the appropriate Instant Client packages for your platform. All installations REQUIRE the Basic package.
- Unzip the packages into a single directory such as "instantclient".
- Set the library loading path in your environment to the directory in Step 2 ("instantclient"). On many UNIX platforms, LD_LIBRARY_PATH is the appropriate environment variable. On Windows, PATH should be used.
- Start your application and enjoy.
Suggest extracting/unzipping into a new directory. They've suggested instantclient
, but you can name the directory anything you like. Name it C:\OracleInstantClient\
if you choose.
Then in Step 3, open a Windows Command Prompt. Type:
PATH C:\OracleInstantClient; %PATH%`
That's all there is to it!
You could add the user to the Database Level Role db_datareader.
Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.
See Books Online for reference:
http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx
You can add a database user to a database role using the following query:
EXEC sp_addrolemember N'db_datareader', N'userName'
Sub HighlightSpecificValue()
'PURPOSE: Highlight all cells containing a specified values
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
'What value do you want to find?
fnd = InputBox("I want to hightlight cells containing...", "Highlight")
'End Macro if Cancel Button is Clicked or no Text is Entered
If fnd = vbNullString Then Exit Sub
Set myRange = ActiveSheet.UsedRange
Set LastCell = myRange.Cells(myRange.Cells.Count)
enter code here
Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)
'Test to see if anything was found
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Else
GoTo NothingFound
End If
Set rng = FoundCell
'Loop until cycled through all unique finds
Do Until FoundCell Is Nothing
'Find next cell with fnd value
Set FoundCell = myRange.FindNext(after:=FoundCell)
'Add found cell to rng range variable
Set rng = Union(rng, FoundCell)
'Test to see if cycled through to first found cell
If FoundCell.Address = FirstFound Then Exit Do
Loop
'Highlight Found cells yellow
rng.Interior.Color = RGB(255, 255, 0)
Dim fnd1 As String
fnd1 = "Rah"
'Condition highlighting
Set FoundCell = myRange.FindNext(after:=FoundCell)
If FoundCell.Value("rah") Then
rng.Interior.Color = RGB(255, 0, 0)
ElseIf FoundCell.Value("Nav") Then
rng.Interior.Color = RGB(0, 0, 255)
End If
'Report Out Message
MsgBox rng.Cells.Count & " cell(s) were found containing: " & fnd
Exit Sub
'Error Handler
NothingFound:
MsgBox "No cells containing: " & fnd & " were found in this worksheet"
End Sub
But to make sure that your new row is accessible in the new table, you need to close the table:
DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);
The rationale behind not using the new keyword, is simple:
By not using it at all, you avoid the pitfall that comes with accidentally omitting it. The construction pattern that YUI uses, is an example of how you can avoid the new keyword altogether"
var foo = function () {
var pub= { };
return pub;
}
var bar = foo();
Alternatively you could so this:
function foo() { }
var bar = new foo();
But by doing so you run risk of someone forgetting to use the new keyword, and the this operator being all fubar. AFAIK there is no advantage to doing this (other than you are used to it).
At The End Of The Day: It's about being defensive. Can you use the new statement? Yes. Does it make your code more dangerous? Yes.
If you have ever written C++, it's akin to setting pointers to NULL after you delete them.
I want to add, who needs full custom header functionality
function addSearchControls(json) {
$("#tblCalls thead").append($("#tblCalls thead tr:first").clone());
$("#tblCalls thead tr:eq(1) th").each(function (index) {
// For text inputs
if (index != 1 && index != 2) {
$(this).replaceWith('<th><input type="text" placeholder=" ' + $(this).html() + ' ara"></input></th>');
var searchControl = $("#tblCalls thead tr:eq(1) th:eq(" + index + ") input");
searchControl.on("keyup", function () {
table.column(index).search(searchControl.val()).draw();
})
}
// For DatePicker inputs
else if (index == 1) {
$(this).replaceWith('<th><input type="text" id="datepicker" placeholder="' + $(this).html() + ' ara" class="tblCalls-search-date datepicker" /></th>');
$('.tblCalls-search-date').on('keyup click change', function () {
var i = $(this).attr('id'); // getting column index
var v = $(this).val(); // getting search input value
table.columns(index).search(v).draw();
});
$(".datepicker").datepicker({
dateFormat: "dd-mm-yy",
altFieldTimeOnly: false,
altFormat: "yy-mm-dd",
altTimeFormat: "h:m",
altField: "#tarih-db",
monthNames: ["Ocak", "Subat", "Mart", "Nisan", "Mayis", "Haziran", "Temmuz", "Agustos", "Eylül", "Ekim", "Kasim", "Aralik"],
dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
firstDay: 1,
dateFormat: "yy-mm-dd",
showOn: "button",
showAnim: 'slideDown',
showButtonPanel: true,
autoSize: true,
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
buttonImageOnly: false,
buttonText: "Tarih Seçiniz",
closeText: "Temizle"
});
$(document).on("click", ".ui-datepicker-close", function () {
$('.datepicker').val("");
table.columns(5).search("").draw();
});
}
// For DropDown inputs
else if (index == 2) {
$(this).replaceWith('<th><select id="filter_comparator" class="styled-select yellow rounded"><option value="select">Seç</option><option value="eq">=</option><option value="gt">>=</option><option value="lt"><=</option><option value="ne">!=</option></select><input type="text" id="filter_value"></th>');
var selectedOperator;
$('#filter_comparator').on('change', function () {
var i = $(this).attr('id'); // getting column index
var v = $(this).val(); // getting search input value
selectedOperator = v;
if(v=="select")
table.columns(index).search('select|0').draw();
$('#filter_value').val("");
});
$('#filter_value').on('keyup click change', function () {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
var i = $(this).attr('id'); // getting column index
var v = $(this).val(); // getting search input value
table.columns(index).search(selectedOperator + '|' + v).draw();
}
});
}
})
}
I needed to use raw sql because I failed at getting composite_primary_keys to function with activerecord 2.3.8. So in order to access the sqlserver 2000 table with a composite primary key, raw sql was required.
sql = "update [db].[dbo].[#{Contacts.table_name}] " +
"set [COLUMN] = 0 " +
"where [CLIENT_ID] = '#{contact.CLIENT_ID}' and CONTACT_ID = '#{contact.CONTACT_ID}'"
st = ActiveRecord::Base.connection.raw_connection.prepare(sql)
st.execute
If a better solution is available, please share.
I deleted the obj folder and then the project loaded as expected.
I'd have a class in your CSS like this:
.no-transition {
-webkit-transition: none;
-moz-transition: none;
-o-transition: none;
-ms-transition: none;
transition: none;
}
and then in your jQuery:
$('#elem').addClass('no-transition'); //will disable it
$('#elem').removeClass('no-transition'); //will enable it
The Heap is divided into young and old generations as follows :
Young Generation: It is a place where an object lived for a short period and it is divided into two spaces:
Old Generation: This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from the Young Generation.
Explanation
Let's imagine our application has just started.
So at this point all three of these spaces are empty (Eden, S0, S1).
Whenever a new object is created it is placed in the Eden space.
When the Eden space gets full then the garbage collection process (minor GC) will take place on the Eden space and any surviving objects are moved into S0.
Our application then continues running add new objects are created in the Eden space the next time that the garbage collection process runs it looks at everything in the Eden space and in S0 and any objects that survive get moved into S1.
PS: Based on the configuration that how much time object should survive in Survivor space, the object may also move back and forth to S0 and S1 and then reaching the threshold objects will be moved to old generation heap space.
If you want to assign dynamic bitmap image to bitmap variables
Example for kotlin
backgroundImage = Glide.with(applicationContext).asBitmap().load(PresignedUrl().getUrl(items!![position].img)).into(100, 100).get();
The above answers did not work for me
.asBitmap
should be before the .load("http://....")
There is one little catch with the third approach. Since aggregate POMs (myproject/pom.xml) usually don't have parent at all, they do not share configuration. That means all those aggregate POMs will have only default repositories.
That is not a problem if you only use plugins from Central, however, this will fail if you run plugin using the plugin:goal format from your internal repository. For example, you can have foo-maven-plugin
with the groupId of org.example
providing goal generate-foo
. If you try to run it from the project root using command like mvn org.example:foo-maven-plugin:generate-foo
, it will fail to run on the aggregate modules (see compatibility note).
Several solutions are possible:
You can set a bucket policy as detailed in this blog post:
http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/
As per @robbyt's suggestion, create a bucket policy with the following JSON:
{
"Version": "2008-10-17",
"Statement": [{
"Sid": "AllowPublicRead",
"Effect": "Allow",
"Principal": { "AWS": "*" },
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::bucket/*" ]
}]
}
Important: replace bucket
in the Resource
line with the name of your bucket.
$(":button").click(function () {
$("#anchor_google")[0].click();
});
You can use the syntax of ${arrayName[@]}
#!/bin/bash
# declare an array called files, that contains 3 values
files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
for i in "${files[@]}"
do
echo "$i"
done
The simplest and best way to get yesterday's date is:
subdate(current_date, 1)
Your query would be:
SELECT
url as LINK,
count(*) as timesExisted,
sum(DateVisited between UNIX_TIMESTAMP(subdate(current_date, 1)) and
UNIX_TIMESTAMP(current_date)) as timesVisitedYesterday
FROM mytable
GROUP BY 1
For the curious, the reason that sum(condition)
gives you the count of rows that satisfy the condition, which would otherwise require a cumbersome and wordy case
statement, is that in mysql boolean values are 1
for true and 0
for false, so summing a condition effectively counts how many times it's true. Using this pattern can neaten up your SQL code.
Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0
first, then cd %~dp0
. This will change the directory to the batch file's drive, then change to its folder.
For #oneLinerLovers, cd /d %~dp0
will change both the drive and directory :)
Hope this helps someone.
If I understand your request correctly, you have to do the following:
public class Section
{
public String Head
{
get
{
return SubHead.LastOrDefault();
}
set
{
SubHead.Add(value);
}
public List<string> SubHead { get; private set; }
public List<string> Content { get; private set; }
}
You use it like this:
var section = new Section();
section.Head = "Test string";
Now "Test string" is added to the subHeads collection and will be available through the getter:
var last = section.Head; // last will be "Test string"
Hope I understood you correctly.
I advise you to go with Scanner
instead of DataInputStream
. Scanner
is specifically designed for this purpose and introduced in Java 5. See the following links to know how to use Scanner
.
Example
Scanner s = new Scanner(System.in);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
try the following as there will be no varchar conversion
SELECT Subject, CAST(DeliveryDate AS DATE)
from Email_Administration
where MerchantId =@ MerchantID
How about using the ExecutorService.shutDownNow()
method as described in http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html? It seems to be the simplest solution.