Follow these tools: From cmd: C:\> netstat -anob
with Administrator privileges.
All from sysinternals.com.
If you just want to know process running and threads under each process, I recommend learning about wmic
. It is a wonderful command-line tool, which gives you much more than you can know.
Example:
c:\> wmic process list brief /every:5
The above command will show an all process list in brief every 5 seconds. To know more, you can just go with /?
command of windows , for example,
c:\> wmic /?
c:\> wmic process /?
c:\> wmic prcess list /?
And so on and so forth. :)
Yet another cause: if your namespace has a hyphen ("-"), then it will build and run correctly, but the resource won't be accessible. Namespaces (identifiers) aren't supposed to have hyphens, but this doesn't appear to be enforced anywhere except in loading resources. This has burned me twice over the decade.
For retrieving the screen resolution, you're going to want to use the System.Windows.Forms.Screen
class. The Screen.AllScreens
property can be used to access a collection of all of the displays on the system, or you can use the Screen.PrimaryScreen
property to access the primary display.
The Screen
class has a property called Bounds
, which you can use to determine the resolution of the current instance of the class. For example, to determine the resolution of the current screen:
Rectangle resolution = Screen.PrimaryScreen.Bounds;
For changing the resolution, things get a little more complicated. This article (or this one) provides a detailed implementation and explanation. Hope this helps.
As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.
Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash
is incorrect and should have been callbackOnLocationHash
(note the mis-spelling of "Location").
This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.
Example:
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'
There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes
Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v
or v as T
) do not check for extra properties, so you can use them in place of a type annotation:
interface Options {
x?: string;
y?: number;
}
// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;
Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking
Before
interface Model {
name: string;
}
function createModel(x: Model) { ... }
// Error
createModel({name: 'hello', length: 100});
After
interface Model {
name: string;
[others: string]: any;
}
function createModel(x: Model) { ... }
// OK
createModel({name: 'hello', length: 100});
interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }
let x: Animal;
if(...) {
x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
x = { move: 'catwalk', meow: 'mrar' };
} else {
x = { move: 'gallop', neigh: 'wilbur' };
}
Two good solutions come to mind here
Specify a closed set for x
// Removes all errors
let x: Dog|Cat|Horse;
or Type assert each thing
// For each initialization
x = { move: 'doggy paddle', woof: 'bark' } as Dog;
A clean solution to the "data model" problem using intersection types:
interface DataModelOptions {
name?: string;
id?: number;
}
interface UserProperties {
[key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
/* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
/* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });
See also https://github.com/Microsoft/TypeScript/issues/3755
try this which is working for me in my test demo
<script>
$(document).ready(function(){
$('#dropdown').change(function()
{
// var selectedValue = parseInt(jQuery(this).val());
var text = $('#dropdown').val();
//alert("text");
//Depend on Value i.e. 0 or 1 respective function gets called.
switch(text){
case 'Reporting':
// alert("hello1");
$("#td1").hide();
break;
case 'Buyer':
//alert("hello");
$("#td1").show();
break;
//etc...
default:
alert("catch default");
break;
}
});
});
</script>
SELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias
Or more idiomatic:
SELECT coalesce(field, 'Empty') AS field_alias
Use Lookupstage to decide whether to insert or update. Check this link for more info - http://beingoyen.blogspot.com/2010/03/ssis-how-to-update-instead-of-insert.html
Steps to do update:
Under Custom properties select SQLCOMMAND and insert update command ex:
UPDATE table1 SET col1 = ?, col2 = ? where id = ?
map columns in exact order from source to output as in update command
import time
from datetime import datetime
now = datetime.now()
# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6
(Sorry, it wouldn't let me comment on existing answer)
You could try either of these. They are not giving me errors.
It is also the suggested method from typescript for array declaration.
By using the Array<Thing>
it is making use of the generics in typescript. It is similar to asking for a List<T>
in c# code.
// Declare with default value
private _possessions: Array<Thing> = new Array<Thing>();
// or
private _possessions: Array<Thing> = [];
// or -> prefered by ts-lint
private _possessions: Thing[] = [];
or
// declare
private _possessions: Array<Thing>;
// or -> preferd by ts-lint
private _possessions: Thing[];
constructor(){
//assign
this._possessions = new Array<Thing>();
//or
this._possessions = [];
}
Be careful, you're unwittingly asking "where the date is greater than one divided by nine, divided by two thousand and eight".
Put #
signs around the date, like this #1/09/2008#
Looks like you are missing the printer name, driver, and port - in that order. Your final command should resemble:
AcroRd32.exe /t <file.pdf> <printer_name> <printer_driver> <printer_port>
For example:
"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" /t "C:\Folder\File.pdf" "Brother MFC-7820N USB Printer" "Brother MFC-7820N USB Printer" "IP_192.168.10.110"
Note: To find the printer information, right click your printer and choose properties. In my case shown above, the printer name and driver name matched - but your information may differ.
From the documentation I get the impression that in your example it would be intended to use:
@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)
Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:
BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types
The problem with these answers is that, with every Xcode update, menus and locations will change.
Just go to /Applications/Xcode.app/Contents/Developer/Platforms
and delete what you don't need. Xcode will start fine. If you're at all concerned then you can simply restore from Trash.
var arr=[{"username":"sai","email":"[email protected],"}]
localStorage.setItem('logInArr', JSON.stringfy(arr))
The solution is isblank(cell)=false
/.*/
works great if there are no line breaks. If it has to match line breaks, here are some solutions:
Solution | Description |
---|---|
/.*/s |
/s (dot all flag) makes . (wildcard character) match anything, including line breaks. Throw in an * (asterisk), and it will match everything. Read more. |
/[\s\S]*/ |
\s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character. * (asterisk) will match all occurrences of the character set (Encapsulated by [] ). Read more. |
I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().
If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.
It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return
statement. When the code goes down that path, the function ends with no value returned, and so returns None
.
Updated: It sounds like your code looks like this:
def b(self, p, data):
current = p
if current.data == data:
return True
elif current.data == 1:
return False
else:
self.b(current.next, data)
That else clause is your None
path. You need to return the value that the recursive call returns:
else:
return self.b(current.next, data)
BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.
The most efficient way is to call the very same function that has been registered with addEventListener
directly.
You can also trigger a fake event with CustomEvent
and co.
Finally some elements such as <input type="file">
support a .click()
method.
Here is a slight variation on Shimmy's one for collection of classes that already implement the well-known IComparable<T>
interface. In this case, the "order by" selector is implicit.
public class SortedObservableCollection<T> : ObservableCollection<T> where T : IComparable<T>
{
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);
if (e.Action != NotifyCollectionChangedAction.Reset &&
e.Action != NotifyCollectionChangedAction.Move &&
e.Action != NotifyCollectionChangedAction.Remove)
{
var query = this.Select((item, index) => (Item: item, Index: index)).OrderBy(tuple => tuple.Item, Comparer.Default);
var map = query.Select((tuple, index) => (OldIndex: tuple.Index, NewIndex: index)).Where(o => o.OldIndex != o.NewIndex);
using (var enumerator = map.GetEnumerator())
{
if (enumerator.MoveNext())
{
base.MoveItem(enumerator.Current.OldIndex, enumerator.Current.NewIndex);
}
}
}
}
// (optional) user is not allowed to move items in a sorted collection
protected override void MoveItem(int oldIndex, int newIndex) => throw new InvalidOperationException();
protected override void SetItem(int index, T item) => throw new InvalidOperationException();
private class Comparer : IComparer<T>
{
public static readonly Comparer Default = new Comparer();
public int Compare(T x, T y) => x.CompareTo(y);
}
// explicit sort; sometimes needed.
public virtual void Sort()
{
if (Items.Count <= 1)
return;
var items = Items.ToList();
Items.Clear();
items.Sort();
foreach (var item in items)
{
Items.Add(item);
}
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
On bootstrap 3, make sure the white-space is not set as 'nowrap'.
div {
width: 200px;
word-break: break-all;
white-space: normal;
}
Here is a function that works with jQuery (for height only, not width):
function setHeight(jq_in){
jq_in.each(function(index, elem){
// This line will work with pure Javascript (taken from NicB's answer):
elem.style.height = elem.scrollHeight+'px';
});
}
setHeight($('<put selector here>'));
Note: The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.
Use "\n"
instead of '\n'
If you like to avoid both changes()=0
and INSERT OR IGNORE
even if you cannot afford deleting the row - You can use this logic;
First, insert (if not exists) and then update by filtering with the unique key.
-- Table structure
CREATE TABLE players (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name VARCHAR (255) NOT NULL
UNIQUE,
age INTEGER NOT NULL
);
-- Insert if NOT exists
INSERT INTO players (user_name, age)
SELECT 'johnny', 20
WHERE NOT EXISTS (SELECT 1 FROM players WHERE user_name='johnny' AND age=20);
-- Update (will affect row, only if found)
-- no point to update user_name to 'johnny' since it's unique, and we filter by it as well
UPDATE players
SET age=20
WHERE user_name='johnny';
Notice: I haven't tested it to see the which triggers are being called, but I assume the following:
in this way you can have a single SQL command
-- Table structure
CREATE TABLE players (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name VARCHAR (255) NOT NULL
UNIQUE,
age INTEGER NOT NULL
);
-- Single command to insert or update
INSERT OR REPLACE INTO players
(id, user_name, age)
VALUES ((SELECT id from players WHERE user_name='johnny' AND age=20),
'johnny',
20);
Edit: added option 2.
try this just insert before
<script async='async' src='https://cdn.jsdelivr.net/ga-lite/latest/ga-lite.min.js'></script> <script>var galite=galite||{};galite.UA="xx-xxxxxxx-x";</script>
Please change xx-xxxxxxx-x to your code, please check to implementation here http://www.gee.web.id/2016/11/how-to-leverage-browser-caching-for-google-analitycs.html
This is an error message you see whenever you have a situation like the following:
char* pointer_to_nonconst = "string literal";
Why? Well, C and C++ differ in the type of the string literal. In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction but more of a type safety thing. A conversion from const char*
to char*
is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to a char*
and gives you a warning about this conversion being deprecated.
So, somewhere you are missing one or more const
s in your program for const correctness. But the code you showed to us is not the problem as it does not do this kind of deprecated conversion. The warning must have come from some other place.
Make a timer, that activates whatever code you want to when it ticks. Make sure the first line in the timer's code is:
timer.enabled = false
Replace timer with whatever you named your timer.
Then use this in your code:
WebBrowser1.Document.Window.DomWindow.execscript("checkPasswordConfirm();","JavaScript")
timer.enabled = true
Dim allelements As HtmlElementCollection = WebBrowser1.Document.All
For Each webpageelement As HtmlElement In allelements
If webpageelement.InnerText = "Sign Up" Then
webpageelement.InvokeMember("click")
End If
Next
ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,)
from telephone number:
var str = "+(48) 123-456-789".replace(/[-+()\s]/g, ''); // result: "48123456789"
We use regular expression [-+()\s]
where we put unwanted characters between [
and ]
(the "\s
" is 'space' character escape - for more info google 'character escapes in in regexp')
To expand Hitesh's answer if you want to drop rows where 'x' specifically is nan, you can use the subset parameter. His answer will drop rows where other columns have nans as well
dat.dropna(subset=['x'])
All the examples are great, but I figure I'd add one more to show how working in a "tidy" format simplifies things. Right now the data frame is in "wide" format meaning the variables "a" through "d" are represented in columns. To get to a "tidy" (or long) format, you can use gather()
from the tidyr
package which shifts the variables in columns "a" through "d" into rows. Then you use the group_by()
and summarize()
functions to get the mean of each group. If you want to present the data in a wide format, just tack on an additional call to the spread()
function.
library(tidyverse)
# Create reproducible df
set.seed(101)
df <- tibble(a = sample(1:5, 10, replace=T),
b = sample(1:5, 10, replace=T),
c = sample(1:5, 10, replace=T),
d = sample(1:5, 10, replace=T),
grp = sample(1:3, 10, replace=T))
# Convert to tidy format using gather
df %>%
gather(key = variable, value = value, a:d) %>%
group_by(grp, variable) %>%
summarize(mean = mean(value)) %>%
spread(variable, mean)
#> Source: local data frame [3 x 5]
#> Groups: grp [3]
#>
#> grp a b c d
#> * <int> <dbl> <dbl> <dbl> <dbl>
#> 1 1 3.000000 3.5 3.250000 3.250000
#> 2 2 1.666667 4.0 4.666667 2.666667
#> 3 3 3.333333 3.0 2.333333 2.333333
Prefix you literal with 0b
like in
int i = 0b11111111;
See here.
This is my way of doing this, i use setTimeout:
var timer = {
running: false,
iv: 5000,
timeout: false,
cb : function(){},
start : function(cb,iv){
var elm = this;
clearInterval(this.timeout);
this.running = true;
if(cb) this.cb = cb;
if(iv) this.iv = iv;
this.timeout = setTimeout(function(){elm.execute(elm)}, this.iv);
},
execute : function(e){
if(!e.running) return false;
e.cb();
e.start();
},
stop : function(){
this.running = false;
},
set_interval : function(iv){
clearInterval(this.timeout);
this.start(false, iv);
}
};
Usage:
timer.start(function(){
console.debug('go');
}, 2000);
timer.set_interval(500);
timer.stop();
I am including this answer in case someone comes to this page for the same reason I did. I just wasted an embarrassing amount of time trying to track the problem down. I was calling:
unset($_SESSION['myVar']);
from a logout script. Then navigating to a page that required login, and the server still thought I was logged in. The problem was that the logout script was not calling:
session_start();
Unsetting a session var DOES NOT WORK unless you start the session first.
In addition to the answer of "dasblinkenlight" I think an example could help. I will only use 8 bits for a better understanding.
x & 1
produces a value that is either1
or0
, depending on the least significant bit ofx
: if the last bit is1
, the result ofx & 1
is1
; otherwise, it is0
. This is a bitwise AND operation.
This is because 1
will be represented in bits as 00000001
. Only the last bit is set to 1
. Let's assume x
is 185
which will be represented in bits as 10111001
. If you apply a bitwise AND operation on x
with 1
this will be the result:
00000001
10111001
--------
00000001
The first seven bits of the operation result will be 0
after the operation and will carry no information in this case (see Logical AND operation). Because whatever the first seven bits of the operand x
were before, after the operation they will be 0
. But the last bit of the operand 1
is 1
and it will reveal if the last bit of operand x
was 0
or 1
. So in this example the result of the bitwise AND operation will be 1
because our last bit of x
is 1
. If the last bit would have been 0
, then the result would have been also 0
, indicating that the last bit of operand x
is 0
:
00000001
10111000
--------
00000000
x >>= 1
means "setx
to itself shifted by one bit to the right". The expression evaluates to the new value ofx
after the shift
Let's pick the example from above. For x >>= 1
this would be:
10111001
--------
01011100
And for left shift x <<= 1
it would be:
10111001
--------
01110010
Please pay attention to the note of user "dasblinkenlight" in regard to shifts.
Goto App.config
Find
<setting name="RunAsWindowsService" serializeAs="String">
<value>True</value>
</setting>
Set to False
Jquery Select Box Validation.You can Alert Message via alert or Put message in Div as per your requirements.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="message"></div>_x000D_
<form method="post">_x000D_
<select name="year" id="year">_x000D_
<option value="0">Year</option>_x000D_
<option value="1">1919</option>_x000D_
<option value="2">1920</option>_x000D_
<option value="3">1921</option>_x000D_
<option value="4">1922</option>_x000D_
</select>_x000D_
<button id="clickme">Click</button>_x000D_
</form>_x000D_
<script>_x000D_
$("#clickme").click(function(){_x000D_
_x000D_
if( $("#year option:selected").val()=='0'){_x000D_
_x000D_
alert("Please select one option at least");_x000D_
_x000D_
$("#message").html("Select At least one option");_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
</script>
_x000D_
I usually add to index changes I don't want to stash and then stash with --keep-index
option.
git add app/controllers/cart_controller.php
git stash --keep-index
git reset
Last step is optional, but usually you want it. It removes changes from index.
Warning
As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index
just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.
Tried and tested approach.
public static ArrayList<String> listToArrayList(List<Object> myList) {
ArrayList<String> arl = new ArrayList<String>();
for (Object object : myList) {
arl.add((String) object);
}
return arl;
}
Name: net/sf/jasperreports/engine/util/xml/JaxenXPathExecuterFactory.c lass SHA-256-Digest: q3B5wW+hLX/+lP2+L0/6wRVXRHq1mISBo1dkixT6Vxc=
An alternative in Java 8 is:
static final Random random = new Random(); // Or SecureRandom
static final int startChar = (int) '!';
static final int endChar = (int) '~';
static String randomString(final int maxLength) {
final int length = random.nextInt(maxLength + 1);
return random.ints(length, startChar, endChar + 1)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
I'd like to add df.values.tolist()
. (as long as you don't mind to get a column of lists rather than tuples)
import pandas as pd
import numpy as np
size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)})
%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Any Image is a collection of signals of various frequencies. The higher frequencies control the edges and the lower frequencies control the image content. Edges are formed when there is a sharp transition from one pixel value to the other pixel value like 0 and 255 in adjacent cell. Obviously there is a sharp change and hence the edge and high frequency. For sharpening an image these transitions can be enhanced further.
One way is to convolve a self made filter kernel with the image.
import cv2
import numpy as np
image = cv2.imread('images/input.jpg')
kernel = np.array([[-1,-1,-1],
[-1, 9,-1],
[-1,-1,-1]])
sharpened = cv2.filter2D(image, -1, kernel) # applying the sharpening kernel to the input image & displaying it.
cv2.imshow('Image Sharpening', sharpened)
cv2.waitKey(0)
cv2.destroyAllWindows()
There is another method of subtracting a blurred version of image from bright version of it. This helps sharpening the image. But should be done with caution as we are just increasing the pixel values. Imagine a grayscale pixel value 190, which if multiplied by a weight of 2 makes if 380, but is trimmed of at 255 due to the maximum allowable pixel range. This is information loss and leads to washed out image.
addWeighted(frame, 1.5, image, -0.5, 0, image);
Figured out my own problem. The solution ended up being based in interpolators.
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
fadeIn.setDuration(1000);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
fadeOut.setStartOffset(1000);
fadeOut.setDuration(1000);
AnimationSet animation = new AnimationSet(false); //change to false
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
this.setAnimation(animation);
val fadeIn = AlphaAnimation(0f, 1f)
fadeIn.interpolator = DecelerateInterpolator() //add this
fadeIn.duration = 1000
val fadeOut = AlphaAnimation(1f, 0f)
fadeOut.interpolator = AccelerateInterpolator() //and this
fadeOut.startOffset = 1000
fadeOut.duration = 1000
val animation = AnimationSet(false) //change to false
animation.addAnimation(fadeIn)
animation.addAnimation(fadeOut)
this.setAnimation(animation)
ULIMIT configuration:
Make Below entry
website soft nofile 8192
website hard nofile 8192
website soft nproc 4096
website hard nproc 8192
website soft core unlimited
website hard core unlimited
Make Below entry for ALL USER
* soft nofile 8192
* hard nofile 8192
* soft nproc 4096
* hard nproc 8192
* soft core unlimited
* hard core unlimited
After modifying the file, user need to logoff and login again to see the new values.
Select is a simple one-to-one projection from source element to a result element. Select- Many is used when there are multiple from clauses in a query expression: each element in the original sequence is used to generate a new sequence.
add this in the parent div at the bottom
<div style="clear:both"></div>
In Visual Studio 2019 (Xamarin):
This worked for me. Add a call to clearChart, at the top oF your updateChart()
`function clearChart() {
event.preventDefault();
var parent = document.getElementById('parent-canvas');
var child = document.getElementById('myChart');
parent.removeChild(child);
parent.innerHTML ='<canvas id="myChart" width="350" height="99" ></canvas>';
return;
}`
This response isn't about macro war, but producing error if no matching platform is found.
#ifdef LINUX_KEY_WORD
... // linux code goes here.
#elif WINDOWS_KEY_WORD
... // windows code goes here.
#else
#error Platform not supported
#endif
If #error
is not supported, you may use static_assert (C++0x) keyword. Or you may implement custom STATIC_ASSERT, or just declare an array of size 0, or have switch that has duplicate cases. In short, produce error at compile time and not at runtime
Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild
ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers
parameter. Then each process will start 25 threads determined by ThreadsPerChild
parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit
parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients
is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients
. This also means that if I set MaxClients
to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient
parameter. In this case, we need to also increase ServerLimit
to 1000/25 i.e. MaxClients/ThreadsPerChild=40
So this is the optmized configuration to server 1000 clients
<IfModule mpm_worker_module>
ServerLimit 40
StartServers 2
MaxClients 1000
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestsPerChild 0
</IfModule>
The following function will return an array containing all the siblings of the given element.
function getSiblings(elem) {
return [...elem.parentNode.children].filter(item => item !== elem);
}
Just pass the selected element into the getSiblings()
function as it's only parameter.
The other answers should probably do the trick, but this one is simpler and does not require jQuery:
document.head.querySelector("[property~=video][content]").content;
The original question used an RDFa tag with a property=""
attribute. For the normal HTML <meta name="" …>
tags you could use something like:
document.querySelector('meta[name="description"]').content
You can also "WAITFOR" a "TIME":
RAISERROR('Im about to wait for a certain time...', 0, 1) WITH NOWAIT
WAITFOR TIME '16:43:30.000'
RAISERROR('I waited!', 0, 1) WITH NOWAIT
I found a solution, which works, but does result in a Warning
(WARN/Resources(268): Converting to float: TypedValue{t=0x3/d=0x4d "1.2" a=2 r=0x7f06000a}
) in LogCat.
<resources>
<string name="text_line_spacing">1.2</string>
</resources>
<android:lineSpacingMultiplier="@string/text_line_spacing"/>
I recently had a similar experience (sql server 2012). I did not have the luxury of controlling the input, I just had a requirement to report on it. Luckily the dates were entered with leading 3 character alpha month abbreviations, so this made it simple & quick:
TRY_CONVERT(DATETIME,REPLACE(obs.DateValueText,SUBSTRING(obs.DateValueText,1,3),CHARINDEX(SUBSTRING(obs.DateValueText,1,3),'...JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC')/4))
It worked for 12 hour:
Feb-14-2015 5:00:00 PM 2015-02-14 17:00:00.000
and 24 hour times:
Sep-27-2013 22:45 2013-09-27 22:45:00.000
(thanks ryanyuyu)
I had the same issue! I was unable to change/set the ID attribute of elements. It worked in all other browsers but not IE. It probably isn't relevant to your problem but here is what I ended up doing:
Background
I was building an MVC site with jquery tabs. I wanted to create tabs dynamically and do an AJAX postback to the server saving the tab in the database. I wanted to use a unique identifier, in the form of an int, for the tabs so I wouldn't get in to trouble if a user created two tabs with the same name. I then used the unique ID to identify the tabs like:
<ul>
<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove List</span></li>
<ul>
When I then implemented the remove functions on the tabs the callback uses the index, witch is 0 based. Then I had no way to sending back the unique ID to the server to trash the DB entry. The callback for the tabremove event gives the jquery event and ui parameters. With one line of code I could get the ID of the span:
var dbIndex = event.currentTarget.id;
The problem was that the span tag didn't have any ID. So in the create callback I tried to set the ID buy extracting the ID from the a href like this:
ui.tab.parentNode.id = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);
That worked fine in FireFox but not in IE. So I tried a few other:
//ui.tab.parentNode.setAttribute('id', ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6));
//$(ui.tab.parentNode).attr({'id':ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6)});
//ui.tab.parentNode.id.value = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);
None of them worked! So after a few hours of test and Googeling I gave up and draw the conclusion that IE cant set the ID attribute of an element dynamically.
As I sad this is probably not relevant to your issue but I thought I would share.
Solution
And for all of you who found this by Googleing on the tabs issue I had here is what I ended up doing in the tabsremove callback to solve the issue:
var dbIndex = event.currentTarget.offsetParent.childNodes[0].href.substring(event.currentTarget.offsetParent.childNodes[0].href.indexOf('#list-') + 6);
Probably not the sexiest solution but hey it solved the issue. If anyone have any input please share...
The documentation for START_STICKY
and START_NOT_STICKY
is quite straightforward.
If this service's process is killed while it is started (after returning from
onStartCommand(Intent, int, int))
, then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to callonStartCommand(Intent, int, int)
after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.
Example: Local Service Sample
If this service's process is killed while it is started (after returning from
onStartCommand(Intent, int, int))
, and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call toContext.startService(Intent)
. The service will not receive aonStartCommand(Intent, int, int)
call with anull
Intent because it will not be re-started if there are no pending Intents to deliver.This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every
N
minutes by having the alarm start its service. When itsonStartCommand(Intent, int, int)
is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.
Example: ServiceStartArguments.java
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
With jQuery:
$("#fileRequest").click(function() {
// // hope the server sets Content-Disposition: attachment!
window.location = 'file.doc';
});
Try with setPreferredSize
instead of setSize
.
UPDATE: GridLayout
take up all space in its container, and BoxLayout
seams to take up all the width in its container, so I added some glue-panels that are invisible and just take up space when the user stretches the window. I have just done this horizontally, and not vertically, but you could implement that in the same way if you want it.
Since GridLayout
make all cells in the same size, it doesn't matter if they have a specified size. You have to specify a size for its container instead, as I have done.
import javax.swing.*;
import java.awt.*;
public class PanelModel {
public static void main(String[] args) {
JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel(new GridLayout(4, 4));
firstPanel.setPreferredSize(new Dimension(4*100, 4*100));
for (int i=1; i<=4; i++) {
for (int j=1; j<=4; j++) {
firstPanel.add(new JButton());
}
}
JPanel firstGluePanel = new JPanel(new BorderLayout());
firstGluePanel.add(firstPanel, BorderLayout.WEST);
firstGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
firstGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);
JPanel secondPanel = new JPanel(new GridLayout(13, 5));
secondPanel.setPreferredSize(new Dimension(5*40, 13*40));
for (int i=1; i<=5; i++) {
for (int j=1; j<=13; j++) {
secondPanel.add(new JButton());
}
}
JPanel secondGluePanel = new JPanel(new BorderLayout());
secondGluePanel.add(secondPanel, BorderLayout.WEST);
secondGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
secondGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);
mainPanel.add(firstGluePanel);
mainPanel.add(secondGluePanel);
frame.getContentPane().add(mainPanel);
//frame.setSize(400,600);
frame.pack();
frame.setVisible(true);
}
}
If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing.
var canvas = document.getElementById("myCanvas");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var ctx = canvas.getContext("2d");
var canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
// That's how you define the value of a pixel //
function drawPixel (x, y, r, g, b, a) {
var index = (x + y * canvasWidth) * 4;
canvasData.data[index + 0] = r;
canvasData.data[index + 1] = g;
canvasData.data[index + 2] = b;
canvasData.data[index + 3] = a;
}
// That's how you update the canvas, so that your //
// modification are taken in consideration //
function updateCanvas() {
ctx.putImageData(canvasData, 0, 0);
}
Then, you can use it in this way :
drawPixel(1, 1, 255, 0, 0, 255);
drawPixel(1, 2, 255, 0, 0, 255);
drawPixel(1, 3, 255, 0, 0, 255);
updateCanvas();
For more information, you can take a look at this Mozilla blog post : http://hacks.mozilla.org/2009/06/pushing-pixels-with-canvas/
I know it's been quite some time since the question was asked. However, if it helps anyone this worked for me.
$(function() {
$('.datetimepicker').datetimepicker({
format: 'MM-DD-YYYY HH:mm '
});
});
STATICFILES_DIRS
: You can keep the static files for your project here e.g. the ones used by your templates.
STATIC_ROOT
: leave this empty, when you do manage.py collectstatic
, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.
--------Edit----------------
As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
or
STATIC_ROOT = '/opt/web/project/static_files'
--------End Edit -----------------
STATIC_URL
: '/static/' is usually fine, it's just a prefix for static files.
To view your iOS device's console in Safari on your Mac (Mac only apparently):
Safari's Inspector will appear showing a console for your iOS device.
This works:
sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"
Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)
Just keep in mind that:
obj= "foo"
is correct; obj="foo"
is not.You need to first find iframe
. You can do so using following statement.
WebElement iFrame= driver.findElement(By.tagName("iframe"));
Then, you can swith to it using switchTo
method on you WebDriver
object.
driver.switchTo().frame(iFrame);
And to move back to the parent frame, you can either use switchTo().parentFrame()
or if you want to get back to the main (or most parent) frame, you can use switchTo().defaultContent();
.
driver.switchTo().parentFrame(); // to move back to parent frame
driver.switchTo().defaultContent(); // to move back to most parent or main frame
Hope it helps.
Sean it works fine i've just used this code
$content = preg_replace("/<img[^>]+\>/i", " ", $content);
echo $content;
//the result it's only the plain text. It works!!!
This code works fine with me
<script type="text/javascript">
$(document).ready(function(){
$("#select_all").change(function(){
$(".checkbox_class").prop("checked", $(this).prop("checked"));
});
});
</script>
you only need to add class checkbox_class to all checkbox
Easy and simple :D
You could use the heapq module:
>>> el = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]
>>> import heapq
>>> heapq.nlargest(2, el)
[90.8, 74]
And go from there...
The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
You can keep your CONTACT parameter with the following approach:
using (var stream = new MemoryStream())
{
var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
context.Request.InputStream.Seek(0, SeekOrigin.Begin);
context.Request.InputStream.CopyTo(stream);
string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}
Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.
Found as accepted answer here
If you need to give a distance between two rows use this tag
margin-top: 10px !important;
yield
is like a return element for a function. The difference is, that the yield
element turns a function into a generator. A generator behaves just like a function until something is 'yielded'. The generator stops until it is next called, and continues from exactly the same point as it started. You can get a sequence of all the 'yielded' values in one, by calling list(generator())
.
you can use angular's filter
https://docs.angularjs.org/api/ng/filter/filter
in your controller:
$filter('filter')(myArray, {'id':73})
or in your HTML
{{ myArray | filter : {'id':73} }}
If you also want to block Sundays (or other days) as well as the array of dates, I use this code:
jQuery(function($){
var disabledDays = [
"27-4-2016", "25-12-2016", "26-12-2016",
"4-4-2017", "5-4-2017", "6-4-2017", "6-4-2016", "7-4-2017", "8-4-2017", "9-4-2017"
];
//replace these with the id's of your datepickers
$("#id-of-first-datepicker,#id-of-second-datepicker").datepicker({
beforeShowDay: function(date){
var day = date.getDay();
var string = jQuery.datepicker.formatDate('d-m-yy', date);
var isDisabled = ($.inArray(string, disabledDays) != -1);
//day != 0 disables all Sundays
return [day != 0 && !isDisabled];
}
});
});
On RHEL systems, the /etc/rc.d/init.d/functions
script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.
The specific function provided to help with this is daemon
. If you are intending to use it to start a daemon-like program, a simple usage would be:
daemon --user=username command
If that is too heavy-handed for what you need, there is runuser
(see man runuser
for full info; some versions may need -u
prior to the username):
/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"
I had the same problem and I could solve it by adding the entity into persistence.xml. The problem was caused due to the fact that the entity was not added to the persistence config. Edit your persistence file:
<persistence-unit name="MY_PU" transaction-type="RESOURCE_LOCAL">
<provider>`enter code here`
org.hibernate.jpa.HibernatePersistenceProvider
</provider>
<class>mypackage.MyEntity</class>
...
Using @joran's sample data,
ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")
note that the default position of geom_histogram
is "stack."
see "position adjustment" of this page:
try:
thevariable
except NameError:
print("well, it WASN'T defined after all!")
else:
print("sure, it was defined.")
If you have already installed 2.2.5 and set as current ruby version, but still showing the same error even if the Ruby version 2.3.0 is not even installed, then just install the bundler.
gem install bundler
and then:
bundle install
An inner class cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?".
as u said here inner class cannot be static... i found the below code which is being given static....reason? or which is correct....
Yes, there is nothing in the semantics of a static nested type that would stop you from doing that. This snippet runs fine.
public class MultipleInner {
static class Inner {
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Inner();
}
}
}
this is a code posted in this website...
for the question---> Can a Static Nested Class be Instantiated Multiple Times?
answer was--->
Now, of course the nested type can do its own instance control (e.g. private constructors, singleton pattern, etc) but that has nothing to do with the fact that it's a nested type. Also, if the nested type is a static enum, of course you can't instantiate it at all.
But in general, yes, a static nested type can be instantiated multiple times.
Note that technically, a static nested type is not an "inner" type.
The issue appears with parsing the JSON from request body, tipical for an invalid JSON. If you're using curl on windows, try escaping the json like -d "{"name":"value"}"
or even -d "{"""name""":"value"""}"
On the other hand you can ommit the content-type header in which case whetewer is sent will be converted to your String argument
That URL will points to your own server-side file upload action. The documentation doesn't go into much detail, but fortunately Don Jones fills in some of the blanks here:
How can you integrate a custom file browser/uploader with CKEditor?
See also:
http://zerokspot.com/weblog/2009/09/09/custom-filebrowser-callbacks-ckeditor/
As of the latest version:
PhpStorm > Preferences.. > Editor > General > Appearance > Show line numbers
im attach my vb.net code based on brian reference
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Public Class PinvokeWindowsNetworking
Const NO_ERROR As Integer = 0
Private Structure ErrorClass
Public num As Integer
Public message As String
Public Sub New(ByVal num As Integer, ByVal message As String)
Me.num = num
Me.message = message
End Sub
End Structure
Private Shared ERROR_LIST As ErrorClass() = New ErrorClass() {
New ErrorClass(5, "Error: Access Denied"),
New ErrorClass(85, "Error: Already Assigned"),
New ErrorClass(1200, "Error: Bad Device"),
New ErrorClass(67, "Error: Bad Net Name"),
New ErrorClass(1204, "Error: Bad Provider"),
New ErrorClass(1223, "Error: Cancelled"),
New ErrorClass(1208, "Error: Extended Error"),
New ErrorClass(487, "Error: Invalid Address"),
New ErrorClass(87, "Error: Invalid Parameter"),
New ErrorClass(1216, "Error: Invalid Password"),
New ErrorClass(234, "Error: More Data"),
New ErrorClass(259, "Error: No More Items"),
New ErrorClass(1203, "Error: No Net Or Bad Path"),
New ErrorClass(1222, "Error: No Network"),
New ErrorClass(1206, "Error: Bad Profile"),
New ErrorClass(1205, "Error: Cannot Open Profile"),
New ErrorClass(2404, "Error: Device In Use"),
New ErrorClass(2250, "Error: Not Connected"),
New ErrorClass(2401, "Error: Open Files")}
Private Shared Function getErrorForNumber(ByVal errNum As Integer) As String
For Each er As ErrorClass In ERROR_LIST
If er.num = errNum Then Return er.message
Next
Try
Throw New Win32Exception(errNum)
Catch ex As Exception
Return "Error: Unknown, " & errNum & " " & ex.Message
End Try
Return "Error: Unknown, " & errNum
End Function
<DllImport("Mpr.dll")>
Private Shared Function WNetUseConnection(ByVal hwndOwner As IntPtr, ByVal lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUserID As String, ByVal dwFlags As Integer, ByVal lpAccessName As String, ByVal lpBufferSize As String, ByVal lpResult As String) As Integer
End Function
<DllImport("Mpr.dll")>
Private Shared Function WNetCancelConnection2(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Boolean) As Integer
End Function
<StructLayout(LayoutKind.Sequential)>
Private Class NETRESOURCE
Public dwScope As Integer = 0
Public dwType As Integer = 0
Public dwDisplayType As Integer = 0
Public dwUsage As Integer = 0
Public lpLocalName As String = ""
Public lpRemoteName As String = ""
Public lpComment As String = ""
Public lpProvider As String = ""
End Class
Public Shared Function connectToRemote(ByVal remoteUNC As String, ByVal username As String, ByVal password As String) As String
Return connectToRemote(remoteUNC, username, password, False)
End Function
Public Shared Function connectToRemote(ByVal remoteUNC As String, ByVal username As String, ByVal password As String, ByVal promptUser As Boolean) As String
Dim nr As NETRESOURCE = New NETRESOURCE()
nr.dwType = ResourceTypes.Disk
nr.lpRemoteName = remoteUNC
Dim ret As Integer
If promptUser Then
ret = WNetUseConnection(IntPtr.Zero, nr, "", "", Connects.Interactive Or Connects.Prompt, Nothing, Nothing, Nothing)
Else
ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, Nothing, Nothing, Nothing)
End If
If ret = NO_ERROR Then Return Nothing
Return getErrorForNumber(ret)
End Function
Public Shared Function disconnectRemote(ByVal remoteUNC As String) As String
Dim ret As Integer = WNetCancelConnection2(remoteUNC, Connects.UpdateProfile, False)
If ret = NO_ERROR Then Return Nothing
Return getErrorForNumber(ret)
End Function
Enum Resources As Integer
Connected = &H1
GlobalNet = &H2
Remembered = &H3
End Enum
Enum ResourceTypes As Integer
Any = &H0
Disk = &H1
Print = &H2
End Enum
Enum ResourceDisplayTypes As Integer
Generic = &H0
Domain = &H1
Server = &H2
Share = &H3
File = &H4
Group = &H5
End Enum
Enum ResourceUsages As Integer
Connectable = &H1
Container = &H2
End Enum
Enum Connects As Integer
Interactive = &H8
Prompt = &H10
Redirect = &H80
UpdateProfile = &H1
CommandLine = &H800
CmdSaveCred = &H1000
LocalDrive = &H100
End Enum
End Class
how to use it
Dim login = PinvokeWindowsNetworking.connectToRemote("\\ComputerName", "ComputerName\UserName", "Password")
If IsNothing(login) Then
'do your thing on the shared folder
PinvokeWindowsNetworking.disconnectRemote("\\ComputerName")
End If
If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer
parameter can be used with a RestTemplateBuilder
:
String accessToken= "<the oauth 2 token>";
RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("Authorization", "Bearer "+accessToken);
return execution.execute(request, body);
})).build();
You may use Chocolatey on Windows. It's very easy to use and useful for keeping you updated with other applications too.
Also, you can just simply download the latest version from https://nodejs.org and install it.
If width:100%
works in any cases, just use that, otherwise you can use vw
in this case which is relative to 1% of the width of the viewport.
That means if you want to cover off the width, just use 100vw
.
Look at the image I draw for you here:
Try the snippet I created for you as below:
.full-width {_x000D_
width: 100vw;_x000D_
height: 100px;_x000D_
margin-bottom: 40px;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.one-vw-width {_x000D_
width: 1vw;_x000D_
height: 100px;_x000D_
background-color: red;_x000D_
}
_x000D_
<div class="full-width"></div>_x000D_
<div class="one-vw-width"></div>
_x000D_
If you also have documents that don't have the key, you can use:
ME.find({ pictures: { $exists: true, $not: {$size: 0} } })
MongoDB don't use indexes if $size is involved, so here is a better solution:
ME.find({ pictures: { $exists: true, $ne: [] } })
Since MongoDB 2.6 release, you can compare with the operator $gt
but could lead to unexpected results (you can find a detailled explanation in this answer):
ME.find({ pictures: { $gt: [] } })
Like Nathan, I often want to dump the results of a sqlalchemy or sqlsoup Query into a Pandas data frame. My own solution for this is:
query = session.query(tbl.Field1, tbl.Field2)
DataFrame(query.all(), columns=[column['name'] for column in query.column_descriptions])
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
If you are going to use a collection that you don't know the size of in advance, there are better options than arrays.
Use a List<string>
instead - it will allow you to add as many items as you need and if you need to return an array, call ToArray()
on the variable.
var listOfStrings = new List<string>();
// do stuff...
string[] arrayOfStrings = listOfStrings.ToArray();
If you must create an empty array you can do this:
string[] emptyStringArray = new string[0];
the following procedure worked for me:
As @Nakilon said, their is a comparing tool built in github if that's what you use.
To use it, append the url of the repo with "/compare".
You need to add target for that button.
myButton.addTarget(self, action: #selector(ClassName.FunctionName(_:), forControlEvents: .TouchUpInside)
FunctionName: connected // for example
And of course you need to set tag of that button since you are using it.
myButton.tag = indexPath.row
You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.
To get the tag in the connected function:
func connected(sender: UIButton) {
let buttonTag = sender.tag
// Do any additional setup
}
I prefer This One
document.forms['idOfTheForm'].nameOfTheInputFiled.value;
What you probably want is dir()
.
The catch is that classes are able to override the special __dir__
method, which causes dir()
to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__
, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__
or be able to provide a comprehensive list of attributes via __dir__
: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.
In the short run, if dir()
isn't sufficient, you could write a function which traverses __dict__
for an object, then __dict__
for all the classes in obj.__class__.__mro__
; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .feathers
.
This sounds like a permissions issue - is it possible you had two windows open, executing with separate rights? Perhaps check ownership of the .git folder.
Perhaps check to see if there is an outstanding file lock open, maybe use lsof to check, or the equivalent for your OS.
Here is the formula I'm using
=IF( ISNUMBER(FIND(".",A1)), LEN(A1) - FIND(".",A1), 0 )
The default, unnamed instance always gets port 1433 for TCP. UDP port 1434 is used by the SQL Browser service to allow named instances to be located. In SQL Server 2000 the first instance to be started took this role.
Non-default instances get their own dynamically-allocated port, by default. If necessary, for example to configure a firewall, you can set them explicitly. If you don't want to enable or allow access to SQL Browser, you have to either include the instance's port number in the connection string, or set it up with the Alias tab in cliconfg
(SQL Server Client Network Utility) on each client machine.
For more information see SQL Server Browser Service on MSDN.
So, answering my own question here. We ultimately determined that we were seeing 502 and 503 errors in the load balancer due to Tomcat threads timing out. In the short term we increased the timeout. In the longer term, we fixed the app problems that were causing the timeouts in the first place. Why Tomcat timeouts were being perceived as 502 and 503 errors at the load balancer is still a bit of a mystery.
You can simply use base64.urlsafe_b64decode(data)
if you are trying to decode a web image. It will automatically take care of the padding.
Founder a simple solution here:
https://stackoverflow.com/a/47132808/9656339
pd.concat([df1, df2]).loc[df1.index.symmetric_difference(df2.index)]
".*[^(\\.inc)]\\.ftl$"
In Java this will find all files ending in ".ftl" but not ending in ".inc.ftl", which is exactly what I wanted.
This is a exact same of zero323's answer but in SQL query way.
Assuming that dataframe is created and registered as
df.createOrReplaceTempView("table")
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|0 |cat26 |30.9 |
//|0 |cat13 |22.1 |
//|0 |cat95 |19.6 |
//|0 |cat105 |1.3 |
//|1 |cat67 |28.5 |
//|1 |cat4 |26.8 |
//|1 |cat13 |12.6 |
//|1 |cat23 |5.3 |
//|2 |cat56 |39.6 |
//|2 |cat40 |29.7 |
//|2 |cat187 |27.9 |
//|2 |cat68 |9.8 |
//|3 |cat8 |35.6 |
//+----+--------+----------+
Window function :
sqlContext.sql("select Hour, Category, TotalValue from (select *, row_number() OVER (PARTITION BY Hour ORDER BY TotalValue DESC) as rn FROM table) tmp where rn = 1").show(false)
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|1 |cat67 |28.5 |
//|3 |cat8 |35.6 |
//|2 |cat56 |39.6 |
//|0 |cat26 |30.9 |
//+----+--------+----------+
Plain SQL aggregation followed by join:
sqlContext.sql("select Hour, first(Category) as Category, first(TotalValue) as TotalValue from " +
"(select Hour, Category, TotalValue from table tmp1 " +
"join " +
"(select Hour as max_hour, max(TotalValue) as max_value from table group by Hour) tmp2 " +
"on " +
"tmp1.Hour = tmp2.max_hour and tmp1.TotalValue = tmp2.max_value) tmp3 " +
"group by tmp3.Hour")
.show(false)
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|1 |cat67 |28.5 |
//|3 |cat8 |35.6 |
//|2 |cat56 |39.6 |
//|0 |cat26 |30.9 |
//+----+--------+----------+
Using ordering over structs:
sqlContext.sql("select Hour, vs.Category, vs.TotalValue from (select Hour, max(struct(TotalValue, Category)) as vs from table group by Hour)").show(false)
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|1 |cat67 |28.5 |
//|3 |cat8 |35.6 |
//|2 |cat56 |39.6 |
//|0 |cat26 |30.9 |
//+----+--------+----------+
DataSets way and don't dos are same as in original answer
Now we know what the actual error is can formulate an answer.
Not allowed to load local resource
is a Security exception built into Chrome and other modern browsers. The wording may be different but in some way shape or form they all have security exceptions in place to deal with this scenario.
In the past you could override certain settings or apply certain flags such as
--disable-web-security --allow-file-access-from-files --allow-file-access
in Chrome (See https://stackoverflow.com/a/22027002/692942)
It's there for a reason
At this point though it's worth pointing out that these security exceptions exist for good reason and trying to circumvent them isn't the best idea.
As you have access to Classic ASP already you could always build a intermediary page that serves the network based files. You do this using a combination of the ADODB.Stream
object and the Response.BinaryWrite()
method. Doing this ensures your network file locations are never exposed to the client and due to the flexibility of the script it can be used to load resources from multiple locations and multiple file types.
Here is a basic example (getfile.asp
);
<%
Option Explicit
Dim s, id, bin, file, filename, mime
id = Request.QueryString("id")
'id can be anything just use it as a key to identify the
'file to return. It could be a simple Case statement like this
'or even pulled from a database.
Select Case id
Case "TESTFILE1"
'The file, mime and filename can be built-up anyway they don't
'have to be hard coded.
file = "\\server\share\Projecten\Protocollen\346\Uitvoeringsoverzicht.xls"
mime = "application/vnd.ms-excel"
'Filename you want to display when downloading the resource.
filename = "Uitvoeringsoverzicht.xls"
'Assuming other files
Case ...
End Select
If Len(file & "") > 0 Then
Set s = Server.CreateObject("ADODB.Stream")
s.Type = adTypeBinary 'adTypeBinary = 1 See "Useful Links"
Call s.Open()
Call s.LoadFromFile(file)
bin = s.Read()
'Clean-up the stream and free memory
Call s.Close()
Set s = Nothing
'Set content type header based on mime variable
Response.ContentType = mime
'Control how the content is returned using the
'Content-Disposition HTTP Header. Using "attachment" forces the resource
'to prompt the client to download while "inline" allows the resource to
'download and display in the client (useful for returning images
'as the "src" of a <img> tag).
Call Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
Call Response.BinaryWrite(bin)
Else
'Return a 404 if there's no file.
Response.Status = "404 Not Found"
End If
%>
This example is pseudo coded and as such is untested.
This script can then be used in <a>
like this to return the resource;
<a href="/getfile.asp?id=TESTFILE1">Click Here</a>
The could take this approach further and consider (especially for larger files) reading the file in chunks using Response.IsConnected
to check whether the client is still there and s.EOS
property to check for the end of the stream while the chunks are being read. You could also add to the querystring parameters to set whether you want the file to return in-line or prompt to be downloaded.
Using METADATA
to Import DLL Constants - If you are having trouble getting adTypeBinary
to be recongnised, always better then just hard coding 1
.
Content-Disposition:What are the differences between “inline” and “attachment”? - Useful information about how Content-Disposition
behaves on the client.
Use this command:
GRANT ALL ON yourdatabasename.* TO root@'%' IDENTIFIED BY 'yourRootPassword';
Then:
FLUSH PRIVILEGES;
Then comment out the below line in file "/etc/mysql/mysql.conf.d/mysqld.cnf" (is required!):
bind-address = 127.0.0.1
Works for me!
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
Here's a really simple API that I created for reading simple XML files in Java. It's incredibly simple and easy to use. Hope it's useful for you.
Try to create an AVD with the monitor.bat
in the tools-folder
, that worked out for me!
yes, by using css styles white-space: pre-wrap; in the .dropdown class of the bootstrap by overriding it. Earlier it is white-space: nowrap; so it makes the dropdown wrapped into one line. pre-wrap makes it as according to the width.
This code work fine for me, Here i contvert array to string with ~ sign
<input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>
You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.
Sub dedupe_abcd()
Dim icol As Long
With Sheets("Sheet1") '<-set this worksheet reference properly!
icol = Application.Match("abcd", .Rows(1), 0)
With .Cells(1, 1).CurrentRegion
.RemoveDuplicates Columns:=icol, Header:=xlYes
End With
End With
End Sub
Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.
In some case you can use this:
$('.myInput').get(0).checked = true
For toggle you can use if else with function
Plenty of workable solutions here, but as I like saying, "if it's worth doing once, it's worth doing again." I did upvote the sugestion to use (tab)(tab), but as some have noted, you may not have completion support, or, if you have many include files, you may want an easier way to know where a target is defined.
I have not tested the below with sub-makes...I think it wouldn't work. As we know, recursive makes considered harmful.
.PHONY: list ls
ls list :
@# search all include files for targets.
@# ... excluding special targets, and output dynamic rule definitions unresolved.
@for inc in $(MAKEFILE_LIST); do \
echo ' =' $$inc '= '; \
grep -Eo '^[^\.#[:blank:]]+.*:.*' $$inc | grep -v ':=' | \
cut -f 1 | sort | sed 's/.*/ &/' | sed -n 's/:.*$$//p' | \
tr $$ \\\ | tr $(open_paren) % | tr $(close_paren) % \
; done
# to get around escaping limitations:
open_paren := \(
close_paren := \)
= Makefile =
includes
ls list
= util/kiss/snapshots.mk =
rotate-db-snapshots
rotate-file-snapshots
snap-db
snap-files
snapshot
= util/kiss/main.mk =
dirs
install
%MK_DIR_PREFIX%env-config.php
%MK_DIR_PREFIX%../srdb
SELECT a AS current_a, COUNT(*) AS b,
(SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
from t group by a order by b desc
This was already a month ago, but oh well.
I could be wrong, but for your question I get the feeling that bind_param
isn't really the problem here. You always need to define some conditions, be it directly in the query string itself, of using bind_param
to set the ?
placeholders. That's not really an issue.
The problem I had using MySQLi SELECT *
queries is the bind_result
part. That's where it gets interesting. I came across this post from Jeffrey Way: http://jeff-way.com/2009/05/27/tricky-prepared-statements/(This link is no longer active). The script basically loops through the results and returns them as an array — no need to know how many columns there are, and you can still use prepared statements.
In this case it would look something like this:
$stmt = $mysqli->prepare(
'SELECT * FROM tablename WHERE field1 = ? AND field2 = ?');
$stmt->bind_param('ss', $value, $value2);
$stmt->execute();
Then use the snippet from the site:
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
And $results
now contains all the info from SELECT *
. So far I found this to be an ideal solution.
Since getText()
is non-static you cannot call it from a static method.
To understand why, you have to understand the difference between the two.
Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:
SomeClass myObject = new SomeClass();
To call an instance method, you call it on the instance (myObject
):
myObject.getText(...)
However a static method/field can be called only on the type directly, say like this:
The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod()
but this is discouraged because it does not make it clear that they are class variables.
... = SomeClass.final
And the two cannot work together as they operate on different data spaces (instance data and class data)
Let me try and explain. Consider this class (psuedocode):
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = "0";
}
Now I have the following use case:
Test item1 = new Test();
item1.somedata = "200";
Test item2 = new Test();
Test.TTT = "1";
What are the values?
Well
in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99
In other words, TTT
is a datum that is shared by all the instances of the type. So it make no sense to say
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = getText(); // error there is is no somedata at this point
}
So the question is why is TTT static or why is getText() not static?
Remove the static
and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText()
that require it to be non-static?
class Test extends Thread
{
public void run(){
try{
Thread.sleep(10000);
}catch(InterruptedException e){
System.out.println("test1");
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]){
Test t1=new Test1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){
System.out.println("test2");
System.out.println("Exception handled "+e);
}
}
}
Its output doesn't contain test2 , so its not handling runtime exception. @jon skeet, @Jan Zyka
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "yourcustomaddress/bundles/andreistatistics/css/like.css"
});
css_link.appendTo('head');
If you (or a helpful admin) runs Set-ExecutionPolicy
as administrator, the policy will be set for all users. (I would suggest "remoteSigned" rather than "unrestricted" as a safety measure.)
NB.: On a 64-bit OS you need to run Set-ExecutionPolicy
for 32-bit and 64-bit PowerShell separately.
I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.
try this approach if you know your object client name ( it is not important that it is Button or TextBox )
$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');
try this ones if you want add onClick event to a server object with JQuery
$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');
The csv.writer
writerow
method takes an iterable as an argument. Your result set has to be a list (rows) of lists (columns).
csvwriter.writerow(row)
Write the row parameter to the writer’s file object, formatted according to the current dialect.
Do either:
import csv
RESULTS = [
['apple','cherry','orange','pineapple','strawberry']
]
with open('output.csv','wb') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerows(RESULTS)
or:
import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open('output.csv','wb') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerow(RESULT)
Common Table Expressions let you define what are essentially views that last only within the scope of your select, insert, update and delete statements. Depending on what you need to do they can be terribly useful.
On most distributions you have the possibility to install another gcc and g++ version beside a most recent compiler like gcc-4.7. In addition most build systems are aware of the CC
and CXX
environment variables, which let specify you other C and C++ compilers respectively. SO I suggest something like:
CC=gcc-4.4 CXX=g++-4.4 cmake path/to/your/CMakeLists.txt
For Makefiles there should be a similar way. I do not recommend setting custom symlinks within /usr/local unless you know what you are doing.
Spark 2.2+
Spark 2.2 introduces typedLit
to support Seq
, Map
, and Tuples
(SPARK-19254) and following calls should be supported (Scala):
import org.apache.spark.sql.functions.typedLit
df.withColumn("some_array", typedLit(Seq(1, 2, 3)))
df.withColumn("some_struct", typedLit(("foo", 1, 0.3)))
df.withColumn("some_map", typedLit(Map("key1" -> 1, "key2" -> 2)))
Spark 1.3+ (lit
), 1.4+ (array
, struct
), 2.0+ (map
):
The second argument for DataFrame.withColumn
should be a Column
so you have to use a literal:
from pyspark.sql.functions import lit
df.withColumn('new_column', lit(10))
If you need complex columns you can build these using blocks like array
:
from pyspark.sql.functions import array, create_map, struct
df.withColumn("some_array", array(lit(1), lit(2), lit(3)))
df.withColumn("some_struct", struct(lit("foo"), lit(1), lit(.3)))
df.withColumn("some_map", create_map(lit("key1"), lit(1), lit("key2"), lit(2)))
Exactly the same methods can be used in Scala.
import org.apache.spark.sql.functions.{array, lit, map, struct}
df.withColumn("new_column", lit(10))
df.withColumn("map", map(lit("key1"), lit(1), lit("key2"), lit(2)))
To provide names for structs
use either alias
on each field:
df.withColumn(
"some_struct",
struct(lit("foo").alias("x"), lit(1).alias("y"), lit(0.3).alias("z"))
)
or cast
on the whole object
df.withColumn(
"some_struct",
struct(lit("foo"), lit(1), lit(0.3)).cast("struct<x: string, y: integer, z: double>")
)
It is also possible, although slower, to use an UDF.
Note:
The same constructs can be used to pass constant arguments to UDFs or SQL functions.
I got pretty good results with my HTML mailing list by using the following:
p { margin-bottom: 0; }
ul { margin-top: 0; }
This does not reset all margin values but only those that create such a gap before ordered list, and still doesn't assume anything about default margin values.
I've just put together what you may be looking for: http://www.graphdracula.net
It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:
var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");
I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!
You may want to have a look at other projects, too! Below are two meta-comparisons:
SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.
DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":
Here's a list of similar projects (some have been already mentioned here):
vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks.
Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below) with help from several universities and other organizations.
The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010.
D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery.
Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API.
sigma.js Lightweight but powerful library for drawing graphs
jsPlumb jQuery plug-in for creating interactive connected graphs
Springy - a force-directed graph layout algorithm
Processing.js Javascript port of the Processing library by John Resig
JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.
RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.
JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package
mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io.
GoJS Interactive graph drawing and layout library
yFiles for HTML Commercial graph drawing and layout library
KeyLines Commercial JS network visualization toolkit
ZoomCharts Commercial multi-purpose visualization library
Syncfusion JavaScript Diagram Commercial diagram library for drawing and visualization.
Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)
Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013.
arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist.
jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.
jsdot Client side graph drawing application. Abandoned in 2011.
Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3.
Moo Wheel Interactive JS representation for connections and relations (2008)
JSViz 2007-era graph visualization script
dagre Graph layout for JavaScript
Graphviz Sophisticated graph visualization language
Flare Beautiful and powerful Flash based graph drawing
NodeBox Python Graph Visualization
Just Add AjaxControlToolkit.dll to your Reference folder.
On your Project Solution
Right Click on Reference Folder > Add Reference > browse AjaxControlToolkit.dll .
Then build.
Regards
On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.
If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.
You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.
Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.
Let's make it simple as hell. If you want a single number for the number of dimensions like 2, 3, 4, etc.,
then just use tf.rank()
. But, if you want the exact shape of the tensor then use tensor.get_shape()
with tf.Session() as sess:
arr = tf.random_normal(shape=(10, 32, 32, 128))
a = tf.random_gamma(shape=(3, 3, 1), alpha=0.1)
print(sess.run([tf.rank(arr), tf.rank(a)]))
print(arr.get_shape(), ", ", a.get_shape())
# for tf.rank()
[4, 3]
# for tf.get_shape()
Output: (10, 32, 32, 128) , (3, 3, 1)
My solution was to use the "-OutBuffer 2147483647" parameter in my query, which is part of the Common Parameters. PS C:> Get-Help about_CommonParameters -Full
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
I strongly recommend you learn how to use layout managers to get the layout you want to see. null
layouts are fragile, and cause no end of trouble.
Try this source & check the comments.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class VolumeCalculator extends JFrame implements ActionListener {
private JTabbedPane jtabbedPane;
private JPanel options;
JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
myTitle;
JTextArea labelTubStatus;
public VolumeCalculator(){
setSize(400, 250);
setVisible(true);
setSize(400, 250);
setVisible(true);
setTitle("Volume Calculator");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createOptions();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Options", options);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
/* CREATE OPTIONS */
public void createOptions(){
options = new JPanel();
//options.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
options.add(labelOptions);
JTextField newTitle = new JTextField("Some Title");
//newTitle.setBounds(80, 40, 225, 20);
options.add(newTitle);
myTitle = new JTextField(20);
// myTitle WAS NEVER ADDED to the GUI!
options.add(myTitle);
//myTitle.setBounds(80, 40, 225, 20);
//myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
//newName.setBounds(60, 80, 150, 20);
newName.addActionListener(this);
options.add(newName);
JButton Exit = new JButton("Exit");
//Exit.setBounds(250, 80, 80, 20);
Exit.addActionListener(this);
options.add(Exit);
}
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
String buttonLabel = button.getText();
if ("Exit".equalsIgnoreCase(buttonLabel)){
Exit_pressed();
return;
}
if ("Set New Name".equalsIgnoreCase(buttonLabel)){
New_Name();
return;
}
}
private void Exit_pressed(){
System.exit(0);
}
private void New_Name(){
System.out.println("'" + myTitle.getText() + "'");
this.setTitle(myTitle.getText());
}
private void Options(){
}
public static void main(String[] args){
JFrame frame = new VolumeCalculator();
frame.pack();
frame.setSize(380, 350);
frame.setVisible(true);
}
}
I faced the exact same problem that java would work but javac would not on a cmd prompt in Windows 8.
The problem occured because I forgot to remove '>'
at the end of the path name, i.e., it was like this:
C:\Program Files\Java\jdk*\bin>
where it was suppose to be like this:
C:\Program Files\Java\jdk*\bin
Perhaps use this:
[a[i] for i in (1,2,5)]
# [11, 12, 15]
Try this:
$('#form').submit(function(eventObj) {
$(this).append('<input type="hidden" name="field_name" value="value" /> ');
return true;
});
XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:
XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);
I use something like this
>>> import datetime
>>> regex = datetime.datetime.strptime
>>>
>>> # TEST
>>> assert regex('2020-08-03', '%Y-%m-%d')
>>>
>>> assert regex('2020-08', '%Y-%m-%d')
ValueError: time data '2020-08' does not match format '%Y-%m-%d'
>>> assert regex('08/03/20', '%m/%d/%y')
>>>
>>> assert regex('08-03-2020', '%m/%d/%y')
ValueError: time data '08-03-2020' does not match format '%m/%d/%y'
For Tomcat 8, I had to add the following line to tomcat/conf/logging.properties
for the jars scanned by Tomcat to show up in the logs:
org.apache.jasper.servlet.TldScanner.level = FINE
The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}
Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport
struct over time.
I just want to add that this nearly identical post provides the very useful alternative of using an echo pipe if no force or quiet switch is available. For instance, I think it's the only way to bypass the Y/N prompt in this example.
Echo y|NETDOM COMPUTERNAME WorkComp /Add:Work-Comp
In a general sense you should first look at your command switches for /f, /q, or some variant thereof (for example, Netdom RenameComputer uses /Force, not /f). If there is no switch available, then use an echo pipe.
myvariable=$(mysql database -u $user -p$password | SELECT A, B, C FROM table_a)
without the blank space after -p
. Its trivial, but without don't work.
I am using those two collectors:
public static <T> Collector<T, ?, Optional<T>> zeroOrOne() {
return Collectors.reducing((a, b) -> {
throw new IllegalStateException("More than one value was returned");
});
}
public static <T> Collector<T, ?, T> onlyOne() {
return Collectors.collectingAndThen(zeroOrOne(), Optional::get);
}
Beware that in Mysql, the utf8
character set is only a subset of the real UTF8 character set. In order to save one byte of storage, the Mysql team decided to store only three bytes of a UTF8 characters instead of the full four-bytes. That means that some east asian language and emoji aren't fully supported. To make sure you can store all UTF8 characters, use the utf8mb4
data type, and utf8mb4_bin
or utf8mb4_general_ci
in Mysql.
@Baxter's is mostly correct but it is missing one important Windows-specific detail.
Subversion's runtime configuration area is stored in the %APPDATA%\Subversion\
directory. The files are config
and servers
.
However, in addition to text-based configuration files, Subversion clients can use Windows Registry to store the client settings. It makes it possible to modify the settings with PowerShell in a convenient manner, and also distribute these settings to user workstations in Active Directory environment via AD Group Policy. See SVNBook | Configuration and the Windows Registry (you can find examples and a sample *.reg
file there).
Call it like this:
foo(*ob);
Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.
Simple Explanation:
bind() create a new function, a new reference at a function it returns to you.
In parameter after this keyword, you pass in the parameter you want to preconfigure. Actually it does not execute immediately, just prepares for execution.
You can preconfigure as many parameters as you want.
Simple Example to understand bind:
function calculate(operation) {
if (operation === 'ADD') {
alert('The Operation is Addition');
} else if (operation === 'SUBTRACT') {
alert('The Operation is Subtraction');
}
}
addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));
Another way to do this is to use "Copy Database" feature:
Find by right clicking the source database > "Tasks" > "Copy Database".
You can copy the database to a lower version of SQL Server Instance. This worked for me from a SQL Server 2008 R2 (SP1) - 10.50.2789.0 to Microsoft SQL Server 2008 (SP2) - 10.0.3798.0
This question is confusing. A regular object, {}
doesn't have a length
property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in
statement on the object, since length
is not set, and increment a counter.
I'm confused as to why you need the length
. Are you manually setting 0
on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';
. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length
is already set.
Not difficult, check this.
<button @click="disabled = !disabled">Toggle Enable</button>
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="disabled">
One hex digit = 1 nibble (four-bits)
Two hex digits = 1 byte (eight-bits)
MD5 = 32 hex digits
32 hex digits = 16 bytes ( 32 / 2)
16 bytes = 128 bits (16 * 8)
The same applies to SHA-1 except it's 40 hex digits long.
I hope this helps.
Yes, there is.
Surprising, huh? You can get a specific value from a multiple return using a simple mute
function:
package main
import "fmt"
import "strings"
func µ(a ...interface{}) []interface{} {
return a
}
type A struct {
B string
C func()(string)
}
func main() {
a := A {
B:strings.TrimSpace(µ(E())[1].(string)),
C:µ(G())[0].(func()(string)),
}
fmt.Printf ("%s says %s\n", a.B, a.C())
}
func E() (bool, string) {
return false, "F"
}
func G() (func()(string), bool) {
return func() string { return "Hello" }, true
}
https://play.golang.org/p/IwqmoKwVm-
Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.
You can read more about the science behind that from this article. Credits to the author.
I got the exact same problem. After viewing this reference: http://zetcode.com/springboot/requestparam/
My problem solved by changing
method = RequestMethod.GET, produces = "application/json;charset=UTF-8"
to
method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE
and don't forget to add the library:
import org.springframework.http.MediaType;
it works on both postman or regular browser.
Drop it in and you're good to go:
*proerty can be set in IB, and if no highlighted background is set, background will not change when pressed
private var highlightedBackgroundColors = [UIButton:UIColor]()
private var unhighlightedBackgroundColors = [UIButton:UIColor]()
extension UIButton {
@IBInspectable var highlightedBackgroundColor: UIColor? {
get {
return highlightedBackgroundColors[self]
}
set {
highlightedBackgroundColors[self] = newValue
}
}
override open var backgroundColor: UIColor? {
get {
return super.backgroundColor
}
set {
unhighlightedBackgroundColors[self] = newValue
super.backgroundColor = newValue
}
}
override open var isHighlighted: Bool {
get {
return super.isHighlighted
}
set {
if highlightedBackgroundColor != nil {
super.backgroundColor = newValue ? highlightedBackgroundColor : unhighlightedBackgroundColors[self]
}
super.isHighlighted = newValue
}
}
}
#define return if (std::random(1000) < 2) throw std::exception(); else return
this is just so evil. It's random, which means it fires in different places all the time, it changes return statement, which usually have some code on it that could fail all by itself, it changes innocent looking keyword that you won't ever get suspicious over and it uses exception from std space so you won't try to search through your sources to find it's source. Just brilliant.
I believe in Oracle it means order by column #1
$.fn.scrollEnd = function(callback, timeout) {
$(this).scroll(function(){
var $this = $(this);
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
$this.data('scrollTimeout', setTimeout(callback,timeout));
});
};
$(window).scroll(function(){
$('.main').fadeOut();
});
$(window).scrollEnd(function(){
$('.main').fadeIn();
}, 700);
That should do the Trick!
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:
Under Conditional Formatting > Manage Rules:
$A2<$B2
$B$2:$B$100
(assuming you have 100 rows)This worked for me in Excel 2016.
All of the current answers on this thread must have been a bit dated. As of pandas
version 0.24.0, the .to_flat_index()
does what you need.
From panda's own documentation:
MultiIndex.to_flat_index()
Convert a MultiIndex to an Index of Tuples containing the level values.
A simple example from its documentation:
import pandas as pd
print(pd.__version__) # '0.23.4'
index = pd.MultiIndex.from_product(
[['foo', 'bar'], ['baz', 'qux']],
names=['a', 'b'])
print(index)
# MultiIndex(levels=[['bar', 'foo'], ['baz', 'qux']],
# codes=[[1, 1, 0, 0], [0, 1, 0, 1]],
# names=['a', 'b'])
Applying to_flat_index()
:
index.to_flat_index()
# Index([('foo', 'baz'), ('foo', 'qux'), ('bar', 'baz'), ('bar', 'qux')], dtype='object')
pandas
columnAn example of how you'd use it on dat
, which is a DataFrame with a MultiIndex
column:
dat = df.loc[:,['name','workshop_period','class_size']].groupby(['name','workshop_period']).describe()
print(dat.columns)
# MultiIndex(levels=[['class_size'], ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max']],
# codes=[[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7]])
dat.columns = dat.columns.to_flat_index()
print(dat.columns)
# Index([('class_size', 'count'), ('class_size', 'mean'),
# ('class_size', 'std'), ('class_size', 'min'),
# ('class_size', '25%'), ('class_size', '50%'),
# ('class_size', '75%'), ('class_size', 'max')],
# dtype='object')
Try this:
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
There are more methods available, e.g. see here: http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html
At least on the current maven version you need to add the switch -DreResolve=false if you intend to remove the dependencies from your local repo without re-downloading them.
mvn dependency:purge-local-repository -DreResolve=false
removes the dependencies without downloading them again.
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
So, this is all you need:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
$(function(){
$('.easy_editor').css('border','9px solid red');
});
On Linux try these:
set wrap off
set trimout ON
set trimspool on
set serveroutput on
set pagesize 0
set long 20000000
set longchunksize 20000000
set linesize 4000
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
You could add a static method in your enum that accepts an int
as a parameter and returns a PcapLinkType
.
public static PcapLinkType of(int linkType) {
switch (linkType) {
case -1: return DLT_UNKNOWN
case 0: return DLT_NULL;
//ETC....
default: return null;
}
}
i have resolved this by following steps.
1) Go to customise icon in the top right corner chrome.
2) click on
more tools option.
3) Click task manager.
4) Kill/end process GPU process
This has resolved my issue of black screen in chrome.
You may also have to use it in onPause
or onDestroy
of Activity
Life Cycle:
//you may call the cancel() method but if it is not handled in doInBackground() method
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
loginTask.cancel(true);
where loginTask
is object of your AsyncTask
Thank you.
Be Careful, Follow these steps and save your time
Right Click on your Project Explorer.
Select New-> Project -> Android Application Project from Existing Code
Browse upto this path only - "C:\Users**your path**\Local\Android\android-sdk\extras\google\google_play_services"
Be careful brose only upto - google_play_services and not upto google_play_services_lib
And this way you are able to import the google play service lib.
Let me know if you have any queries regarding the same.
Thanks
One main difference is the Local
part of LocalDateTime
. If you live in Germany and create a LocalDateTime
instance and someone else lives in USA and creates another instance at the very same moment (provided the clocks are properly set) - the value of those objects would actually be different. This does not apply to Instant
, which is calculated independently from time zone.
LocalDateTime
stores date and time without timezone, but it's initial value is timezone dependent. Instant
's is not.
Moreover, LocalDateTime
provides methods for manipulating date components like days, hours, months. An Instant
does not.
apart from the nanosecond precision advantage of Instant and the time-zone part of LocalDateTime
Both classes have the same precision. LocalDateTime
does not store timezone. Read javadocs thoroughly, because you may make a big mistake with such invalid assumptions: Instant and LocalDateTime.
Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.
Taken from the angular docs:
So you'd need to change your code to:
$http.get(dataUrl)
.success(function (data){
$scope.data.products = data;
})
.error(function (error, status){
$scope.data.error = { message: error, status: status};
console.log($scope.data.error.status);
});
Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.
The other answers are the easiest, however it's a bit annoying that the random.shuffle
method doesn't actually return anything - it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:
import random
def my_shuffle(array):
random.shuffle(array)
return array
Then you can do lines like:
for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']):
You can go through all the answers above to understand why the .add()
is restricted to '<?>'
, '<? extends>'
, and partly to '<? super>'
.
But here's the conclusion of it all if you want to remember it, and dont want to go exploring the answer every time:
List<? extends A>
means this will accept any List
of A
and subclass of A
.
But you cannot add anything to this list. Not even objects of type A
.
List<? super A>
means this will accept any list of A
and superclass of A
.
You can add objects of type A
and its subclasses.
More recent and much cleaner: use event.key
. No more arbitrary number codes!
note.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace") {
// Do something
}
});
This work crossbrowser for me (IE11, EDGE, CHROME, FIREFOX, OPERA), use https://www.icoconverter.com/ to create .ico file
<link data-senna-track="temporary" href="${favicon_url}" rel="Shortcut Icon" />
<link rel="icon" href="${favicon_url}" type="image/x-icon" />
<link rel="shortcut icon" href="${favicon_url}" type="image/x-icon" />
If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.
First way is floor rounding the float value:
float myFloat = 3.14f;
int myInteger = (int)myFloat;
The output of this code will be 3, even if the myFloat value is closer to 4.
The second way is ceil rounding the float value:
float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);
The output of this code will be 4, because the rounding mode is always looking for the highest value.
Looks like some changes to SASS have made possible what you've initially tried doing:
@import "../subdir/common";
We even got this to work for some totally unrelated folder located in c:\projects\sass
:
@import "../../../../../../../../../../projects/sass/common";
Just add enough ../
to be sure you'll end up at the drive root and you're good to go.
Of course, this solution is far from pretty, but I couldn't get an import from a totally different folder to work, neither using I c:\projects\sass
nor setting the environment variable SASS_PATH
(from: :load_paths reference) to that same value.
Using .multiply() (ufunc multiply)
a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0
np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])
increase the response.getBufferSize() get the buffer size and compare with the bytes you want to transfer !
Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE
environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.
node('label'){
// now you are on slave labeled with 'label'
def workspace = WORKSPACE
// ${workspace} will now contain an absolute path to job workspace on slave
workspace = env.WORKSPACE
// ${workspace} will still contain an absolute path to job workspace on slave
// When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
echo "Current workspace is ${env.WORKSPACE}"
// the current Jenkins instances will support the short syntax, too:
echo "Current workspace is $WORKSPACE"
}
You can do it with the HTMLWorker
class (deprecated) like this:
import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
String k = "<html><body> This is my Project </body></html>";
OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(k));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
or using the XMLWorker
, (download from this jar) using this code:
import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
String k = "<html><body> This is my Project </body></html>";
OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
InputStream is = new ByteArrayInputStream(k.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) {
was returning an invalid character error because it was trying to watch the value of attrs.dynamic
which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
Anyone over here who wants his image to fit in full screen without any crop (in both portrait and landscape mode), use this:
image: {
flex: 1,
width: '100%',
height: '100%',
resizeMode: 'contain',
},
Try to run Your XAMPP Control Panel as Run as administrator
, then install Apache and MySQL.
When XAMPP opens, ensure that Apache and MySQL services are stopped.
Now just check/tick on Apache and Mysql service module.
Now Apache and MySQL will be added to window services. You can set these services to start when Windows boots.
In Visual Studio 2012
Go to
Edit -> Advanced -> View White Spaces
Or
Press Ctrl+R, Ctrl+W
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap
object and draw into that using the Graphics.CopyFromScreen
method.
Sample code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.
SET @rownum = 0;
SELECT sub.*, sub.rank as Rank
FROM
(
SELECT *, (@rownum := @rownum + 1) as rank
FROM msgtable
WHERE cdate = '18/07/2012'
) sub
WHERE rank BETWEEN ((@PageNum - 1) * @PageSize + 1)
AND (@PageNum * @PageSize)
Every time you pass the parameters @PageNum
and the @PageSize
to get the specific page you want. For exmple the first 10 rows would be @PageNum = 1 and @PageSize = 10
_x000D_
_x000D_
let myArr = [_x000D_
{ name: "john", age: 23 },_x000D_
{ name: "john", age: 43 },_x000D_
{ name: "jim", age: 101 },_x000D_
{ name: "bob", age: 67 },_x000D_
];_x000D_
_x000D_
let list = _.filter(myArr, item => item.name === "john");
_x000D_
_x000D_
_x000D_
What you are looking for is this:
SHOW VARIABLES;
You can modify it further like any query:
SHOW VARIABLES LIKE '%max%';
Your problem comes from the 32/64 bit version of your JDK/JRE... Your shared lib is searched for a 32 bit version.
Your default JDK is a 32 bit version. Try to install a 64 bit one by default and relaunch your `.sh file.
try changing the connection port to 8012
open xampp as administrator
Mysql config => my.ini change the port from 3306 to 8012
close and run it again I hope it will work.
import UIKit
import SafariServices
let url = URL(string: "https://sprotechs.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)
int sum=0;
for(int i:A)
sum+=i;
The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
Another "finally" block emulation using C++11 lambda functions
template <typename TCode, typename TFinallyCode>
inline void with_finally(const TCode &code, const TFinallyCode &finally_code)
{
try
{
code();
}
catch (...)
{
try
{
finally_code();
}
catch (...) // Maybe stupid check that finally_code mustn't throw.
{
std::terminate();
}
throw;
}
finally_code();
}
Let's hope the compiler will optimize the code above.
Now we can write code like this:
with_finally(
[&]()
{
try
{
// Doing some stuff that may throw an exception
}
catch (const exception1 &)
{
// Handling first class of exceptions
}
catch (const exception2 &)
{
// Handling another class of exceptions
}
// Some classes of exceptions can be still unhandled
},
[&]() // finally
{
// This code will be executed in all three cases:
// 1) exception was not thrown at all
// 2) exception was handled by one of the "catch" blocks above
// 3) exception was not handled by any of the "catch" block above
}
);
If you wish you can wrap this idiom into "try - finally" macros:
// Please never throw exception below. It is needed to avoid a compilation error
// in the case when we use "begin_try ... finally" without any "catch" block.
class never_thrown_exception {};
#define begin_try with_finally([&](){ try
#define finally catch(never_thrown_exception){throw;} },[&]()
#define end_try ) // sorry for "pascalish" style :(
Now "finally" block is available in C++11:
begin_try
{
// A code that may throw
}
catch (const some_exception &)
{
// Handling some exceptions
}
finally
{
// A code that is always executed
}
end_try; // Sorry again for this ugly thing
Personally I don't like the "macro" version of "finally" idiom and would prefer to use pure "with_finally" function even though a syntax is more bulky in that case.
You can test the code above here: http://coliru.stacked-crooked.com/a/1d88f64cb27b3813
PS
If you need a finally block in your code, then scoped guards or ON_FINALLY/ON_EXCEPTION macros will probably better fit your needs.
Here is short example of usage ON_FINALLY/ON_EXCEPTION:
void function(std::vector<const char*> &vector)
{
int *arr1 = (int*)malloc(800*sizeof(int));
if (!arr1) { throw "cannot malloc arr1"; }
ON_FINALLY({ free(arr1); });
int *arr2 = (int*)malloc(900*sizeof(int));
if (!arr2) { throw "cannot malloc arr2"; }
ON_FINALLY({ free(arr2); });
vector.push_back("good");
ON_EXCEPTION({ vector.pop_back(); });
...