If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.
try {
//Dangerous code: could throw an error
} catch (Exception e) {
//Cleanup: make sure that this methods variables and such are in the desired state
throw e;
}
This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.
An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.
If you do throw an exception from a constructor, keep in mind that you need to use the function try/catch syntax if you need to catch that exception in a constructor initializer list.
e.g.
func::func() : foo()
{
try {...}
catch (...) // will NOT catch exceptions thrown from foo constructor
{ ... }
}
vs.
func::func()
try : foo() {...}
catch (...) // will catch exceptions thrown from foo constructor
{ ... }
This is expected behavior for an uncaught exception with display_errors off.
Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.
ini_set("display_errors", 1);
or
try{
// code that may throw an exception
} catch(Exception $e){
echo $e->getMessage();
}
If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).
Another option for you would be to use set_exception_handler to set a default error handler for your script.
function default_exception_handler(Exception $e){
// show something to the user letting them know we fell down
echo "<h2>Something Bad Happened</h2>";
echo "<p>We fill find the person responsible and have them shot</p>";
// do some logging for the exception and call the kill_programmer function.
}
set_exception_handler("default_exception_handler");
you can throw
as object
throw ({message: 'This Failed'})
then for example in your try/catch
try {
//
} catch(e) {
console.log(e); //{message: 'This Failed'}
console.log(e.message); //This Failed
}
or just throw a string error
throw ('Your error')
try {
//
} catch(e) {
console.log(e); //Your error
}
throw new Error //only accept a string
Since asked and answered by the same person, I'll add a npm link as an alternative.
from docs:
This is handy for installing your own stuff, so that you can work on it and test it iteratively without having to continually rebuild.
cd ~/projects/node-bloggy # go into the dir of your main project
npm link ../node-redis # link the dir of your dependency
[Edit] As of NPM 2.0, you can declare local dependencies in package.json
"dependencies": {
"bar": "file:../foo/bar"
}
Path.GetFullPath()
does not work with relative paths.
Here's the solution that works with both relative + absolute paths. It works on both Linux + Windows and it keeps the ..
as expected in the beginning of the text (at rest they will be normalized). The solution still relies on Path.GetFullPath
to do the fix with a small workaround.
It's an extension method so use it like text.Canonicalize()
/// <summary>
/// Fixes "../.." etc
/// </summary>
public static string Canonicalize(this string path)
{
if (path.IsAbsolutePath())
return Path.GetFullPath(path);
var fakeRoot = Environment.CurrentDirectory; // Gives us a cross platform full path
var combined = Path.Combine(fakeRoot, path);
combined = Path.GetFullPath(combined);
return combined.RelativeTo(fakeRoot);
}
private static bool IsAbsolutePath(this string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
return
Path.IsPathRooted(path)
&& !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)
&& !Path.GetPathRoot(path).Equals(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal);
}
private static string RelativeTo(this string filespec, string folder)
{
var pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) folder += Path.DirectorySeparatorChar;
var folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString()
.Replace('/', Path.DirectorySeparatorChar));
}
The only way I can think of doing this is by doing something like alert('you have a new message') when the message is received. This will flash the taskbar if the window is minimized, but it will also open a dialog box, which you may not want.
you can also try this trick:
ps aux | grep puma
sample output:
myname 77921 0.0 0.0 2433828 1972 s000 R+ 11:17AM 0:00.00 grep puma
myname 67661 0.0 2.3 2680504 191204 s002 S+ 11:00AM 0:18.38 puma 3.11.2 (tcp://localhost:3000) [my_proj]
then:
kill -9 67661
declare @T table(id int)
insert into @T values
(1),
(2),
(12),
(123),
(1234)
select right('0000'+convert(varchar(4), id), 4)
from @T
Result
----
0001
0002
0012
0123
1234
Here are the different ways in which you can create an array of booleans in typescript:
let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();
let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();
let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];
let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();
let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();
You can access them using the index:
console.log(arr[5]);
and you add elements using push:
arr.push(true);
When creating the array you can supply the initial values:
let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);
Checkout the tutorial from Ourcodeworld Ourcodeworld - encode and decode html entities with javascript
Most importantly, the he library example
he.encode('foo © bar ? baz ???? qux');
// ? 'foo © bar ≠ baz 𝌆 qux'
// Passing an `options` object to `encode`, to explicitly encode all symbols:
he.encode('foo © bar ? baz ???? qux', {
'encodeEverything': true
});
he.decode('foo © bar ≠ baz 𝌆 qux');
// ? 'foo © bar ? baz ???? qux'
This library would probably make your coding easier and better managed. It is popular, regularly updated and follows the HTML spec. It itself has no dependencies, as can be seen in the package.json
When you use strace (on Linux) to run your binary, it will output the returns from system calls and what the error number means. This may sometimes be useful to you.
SQLyog is GUI based solution to the problem of data search across all columns, tables and databases. One can customize search restricting it to field, table and databases.
In its Data Search
feature one can search for strings just like one uses Google.
There is likely whitespace outside of your php tags.
var Animal = function(options) {
var name = options.name;
var animal = {};
animal.getName = function() {
return name;
};
var somePrivateMethod = function() {
};
return animal;
};
// usage
var cat = Animal({name: 'tiger'});
1.
long date = curDateFld.getDate();
//convert long to string
String str = String.valueOf(date);
//convert string to long
date = Long.valueOf(str);
2.
//convert long to string just concat long with empty string
String str = ""+date;
//convert string to long
date = Long.valueOf(str);
The trap
shell builtin allows catching signals, and other useful conditions, including failed command execution (i.e., a non-zero return status). So if you don't want to explicitly test return status of every single command you can say trap "your shell code" ERR
and the shell code will be executed any time a command returns a non-zero status. For example:
trap "echo script failed; exit 1" ERR
Note that as with other cases of catching failed commands, pipelines need special treatment; the above won't catch false | true
.
Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.
If you happen to be using Microsoft IIS server, in addition to the php.ini settings mentioned by others, you may need to increase the execution timeout settings for the PHP FastCGI application in the IIS Server Manager:
Step 1) Open the IIS Server Manager (usually under Server Manager in the Start Menu, then Tools / Internet Information Services (IIS) Manager).
Step 2) Click on the main connection (not specific to any particular domain).
Step 3) Under the IIS section, find FastCGI Settings (shown below).
Step 4) Therein, right-click the PHP application and select Edit....
Step 5) Check the timeouts (shown below).
In my case, the default timeouts here were 70 and 90 seconds; the former of which was causing a 500 Internal Server Error on PHP scripts that took longer than 70 seconds.
"SP25 work on Visual Studio 2019" is an exaggeration. It is extremely unreliable and should be avoided at all costs. I currently have to maintain a second development environment with V2015 for report development.
Your server might not be running. This can have 2 issus IMO:
I had the problem that the permissions were not set on the postgres folders and so the service was not able to start. I have no idea why that happend but giving proper permissions on the root postges folder and subfolders did the trick. If I recall it correctly, postgres is also installed as a service so you should find it in the Service List
To start the server, you have a startcommand in your Startmenu. Somewhere at Start -> PostgreSQL -> Start Service/Server/... (haven't used it on Windows for a long time but it should be there).
Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length
returns undefined rather than 5.
This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.
Implemented in JavaScript (ES6):
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
Usage:
const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
function draw( x, y ){
ctx.clearRect( 0, 0, canvas.width, canvas.height );
ctx.beginPath();
ctx.strokeStyle = "orange";
ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
ctx.lineWidth = 3;
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "indigo";
ctx.arc( x, y, 6, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
let angle = 0; // In degrees
setInterval(function(){
const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
console.log( x, y );
draw( x, y );
document.querySelector("#degrees").innerHTML = angle + "°";
document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();
}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
It's important to understand what the =
operator in JavaScript does and does not do.
The =
operator does not make a copy of the data.
The =
operator creates a new reference to the same data.
After you run your original code:
var a = $('#some_hidden_var').val(),
b = a;
a
and b
are now two different names for the same object.
Any change you make to the contents of this object will be seen identically whether you reference it through the a
variable or the b
variable. They are the same object.
So, when you later try to "revert" b
to the original a
object with this code:
b = a;
The code actually does nothing at all, because a
and b
are the exact same thing. The code is the same as if you'd written:
b = b;
which obviously won't do anything.
Why does your new code work?
b = { key1: a.key1, key2: a.key2 };
Here you are creating a brand new object with the {...}
object literal. This new object is not the same as your old object. So you are now setting b
as a reference to this new object, which does what you want.
To handle any arbitrary object, you can use an object cloning function such as the one listed in Armand's answer, or since you're using jQuery just use the $.extend()
function. This function will make either a shallow copy or a deep copy of an object. (Don't confuse this with the $().clone()
method which is for copying DOM elements, not objects.)
For a shallow copy:
b = $.extend( {}, a );
Or a deep copy:
b = $.extend( true, {}, a );
What's the difference between a shallow copy and a deep copy? A shallow copy is similar to your code that creates a new object with an object literal. It creates a new top-level object containing references to the same properties as the original object.
If your object contains only primitive types like numbers and strings, a deep copy and shallow copy will do exactly the same thing. But if your object contains other objects or arrays nested inside it, then a shallow copy doesn't copy those nested objects, it merely creates references to them. So you could have the same problem with nested objects that you had with your top-level object. For example, given this object:
var obj = {
w: 123,
x: {
y: 456,
z: 789
}
};
If you do a shallow copy of that object, then the x
property of your new object is the same x
object from the original:
var copy = $.extend( {}, obj );
copy.w = 321;
copy.x.y = 654;
Now your objects will look like this:
// copy looks as expected
var copy = {
w: 321,
x: {
y: 654,
z: 789
}
};
// But changing copy.x.y also changed obj.x.y!
var obj = {
w: 123, // changing copy.w didn't affect obj.w
x: {
y: 654, // changing copy.x.y also changed obj.x.y
z: 789
}
};
You can avoid this with a deep copy. The deep copy recurses into every nested object and array (and Date in Armand's code) to make copies of those objects in the same way it made a copy of the top-level object. So changing copy.x.y
wouldn't affect obj.x.y
.
Short answer: If in doubt, you probably want a deep copy.
this is simple way to do push notification for all browser https://pushjs.org
Push.create("Hello world!", {
body: "How's it hangin'?",
icon: '/icon.png',
timeout: 4000,
onClick: function () {
window.focus();
this.close();
}
});
Those are "non-client" areas and are controlled by Windows. Here is the MSDN docs on the subject (the pertinent info is at the top).
Basically, you set your Window's WindowStyle="None", then build your own window interface. (similar question on SO)
Here is the solution I found: On the project tree "app", right click mouse button to get the context menu. Select "open module setting", on the tree "app" - "properties" tab, select the existing "build tools version" you have. The gradle will start to build.
In the HTML which you have shared:
<div id="a">This is some
<div id="b">text</div>
</div>
The text This is some
is within a text node. To depict the text node in a structured way:
<div id="a">
This is some
<div id="b">text</div>
</div>
To extract and print the text This is some
from the text node using Selenium's python client you have 2 ways as follows:
Using splitlines()
: You can identify the parent element i.e. <div id="a">
, extract the innerHTML
and then use splitlines()
as follows:
using xpath:
print(driver.find_element_by_xpath("//div[@id='a']").get_attribute("innerHTML").splitlines()[0])
using xpath:
print(driver.find_element_by_css_selector("div#a").get_attribute("innerHTML").splitlines()[0])
Using execute_script()
: You can also use the execute_script()
method which can synchronously execute JavaScript in the current window/frame as follows:
using xpath and firstChild:
parent_element = driver.find_element_by_xpath("//div[@id='a']")
print(driver.execute_script('return arguments[0].firstChild.textContent;', parent_element).strip())
using xpath and childNodes[n]:
parent_element = driver.find_element_by_xpath("//div[@id='a']")
print(driver.execute_script('return arguments[0].childNodes[1].textContent;', parent_element).strip())
I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True)
. You can also disable buffering by setting the PYTHONUNBUFFERED
environment variable (to any non-empty string).
An operator for a conditional expression in Python was added in 2006 as part of Python Enhancement Proposal 308. Its form differ from common ?:
operator and it's:
<expression1> if <condition> else <expression2>
which is equivalent to:
if <condition>: <expression1> else: <expression2>
Here is an example:
result = x if a > b else y
Another syntax which can be used (compatible with versions before 2.5):
result = (lambda:y, lambda:x)[a > b]()
where operands are lazily evaluated.
Another way is by indexing a tuple (which isn't consistent with the conditional operator of most other languages):
result = (y, x)[a > b]
or explicitly constructed dictionary:
result = {True: x, False: y}[a > b]
Another (less reliable), but simpler method is to use and
and or
operators:
result = (a > b) and x or y
however this won't work if x
would be False
.
A possible workaround is to make x
and y
lists or tuples as in the following:
result = ((a > b) and [x] or [y])[0]
or:
result = ((a > b) and (x,) or (y,))[0]
If you're working with dictionaries, instead of using a ternary conditional, you can take advantage of get(key, default)
, for example:
shell = os.environ.get('SHELL', "/bin/sh")
Source: ?: in Python at Wikipedia
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
Job done :)
In openCV whenever you try to display an oversized image or image bigger than your display resolution you get the cropped display. It's a default behaviour.
In order to view the image in the window of your choice openCV encourages to use named window. Please refer to namedWindow documentation
The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
cv.namedWindow(name, flags=CV_WINDOW_AUTOSIZE)
where each window is related to image container by the name arg, make sure to use same name
eg:
import cv2
frame = cv2.imread('1.jpg')
cv2.namedWindow("Display 1")
cv2.resizeWindow("Display 1", 300, 300)
cv2.imshow("Display 1", frame)
I prefer use an extension for that. Besides, this url http://emailregex.com can help you to test if regex is correct. In fact, the site offers differents implementations for some programming languages. I share my implementation for Swift 3.
extension String {
func validateEmail() -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
}
}
time.time()
will do the job.
import time
start = time.time()
# run your code
end = time.time()
elapsed = end - start
You may want to look at this question, but I don't think it will be necessary.
If your reason for iterating trough the Map
, is to do an operation on the value and write to a resulting Map
. I recommend using the transform
-methods in the Google Guava Maps
class.
import com.google.common.collect.Maps;
After you have added the Maps
to your imports, you can use Maps.transformValues
and Maps.transformEntries
on your maps, like this:
public void transformMap(){
Map<String, Integer> map = new HashMap<>();
map.put("a", 2);
map.put("b", 4);
Map<String, Integer> result = Maps.transformValues(map, num -> num * 2);
result.forEach((key, val) -> print(key, Integer.toString(val)));
// key=a,value=4
// key=b,value=8
Map<String, String> result2 = Maps.transformEntries(map, (key, value) -> value + "[" + key + "]");
result2.forEach(this::print);
// key=a,value=2[a]
// key=b,value=4[b]
}
private void print(String key, String val){
System.out.println("key=" + key + ",value=" + val);
}
That's because at the time of installation you have selected the default radio button to use "Git" with the "Git bash" only. If you would have chosen "Git and command line tool" than this would not be an issue.
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
For iOS you need to use the touchmove event as well as the scroll event like this:
document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);
function ScrollStart() {
//start of scroll event for iOS
}
function Scroll() {
//end of scroll event for iOS
//and
//start/end of scroll event for other browsers
}
From the HashSet<T>
page on MSDN:
The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
(emphasis mine)
intersect_all <- function(a,b,...){
all_data <- c(a,b,...)
require(plyr)
count_data<- length(list(a,b,...))
freq_dist <- count(all_data)
intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
intersect_data
}
intersect_all(a,b,c)
UPDATE EDIT A simpler code
intersect_all <- function(a,b,...){
Reduce(intersect, list(a,b,...))
}
intersect_all(a,b,c)
At the first glance, I missed, that my "web" service didn't actually start, so that's why nginx couldn't find any host
web_1 | python3: can't open file '/var/www/app/app/app.py': [Errno 2] No such file or directory
web_1 exited with code 2
nginx_1 | [emerg] 1#1: host not found in upstream "web:4044" in /etc/nginx/conf.d/nginx.conf:2
2018 Update - Might be helpful for future readers:
I am not sure when this was originally introduced in Chrome. But another (easy) way this can be done now in Chrome is via console commands.
For example: (in chrome console type)
getEventListeners($0)
Whereas $0 is the selected element in the DOM.
https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#0_-_4
How about:
df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x
To do all these operations in one-liner:
setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))
#[1] name age gender
#<0 rows> (or 0-length row.names)
Or
data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))
This is an odd solution, but it worked for me.
I wanted to uninstall Visual Studio 2015 and do a clean install afterwards, but when I tried to remove it through the Control Panel, it was giving me a generic error.
I fixed it by deleting the Visual Studio 2015 folder in Program Files (x86). After that, the Control Panel uninstall worked fine.
This is how I would write using more functional way
. Here is the code:
new List<Money>()
{
new Money() { Amount = 10, Type = "US"},
new Money() { Amount = 20, Type = "US"}
}
.ForEach(money =>
{
Console.WriteLine($"amount is {money.Amount}, and type is {money.Type}");
});
For right menu you can do it:
public static Drawable setTintDrawable(Drawable drawable, @ColorInt int color) {
drawable.clearColorFilter();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawable.invalidateSelf();
Drawable wrapDrawable = DrawableCompat.wrap(drawable).mutate();
DrawableCompat.setTint(wrapDrawable, color);
return wrapDrawable;
}
And in your activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_profile, menu);
Drawable send = menu.findItem(R.id.send);
Drawable msg = menu.findItem(R.id.message);
DrawableUtils.setTintDrawable(send.getIcon(), Color.WHITE);
DrawableUtils.setTintDrawable(msg.getIcon(), Color.WHITE);
return true;
}
This is the result:
I just had a similar issue with a field like that which I solved a different way. My use case was needing to take those ids in a comma separated list for use in a join.
I was able to solve it using a like, but it was made easier because in addition to the comma delimiter the ids were also quoted like so:
keys
"1","2","6","12"
Because of that, I was able to do a LIKE
SELECT twwf.id, jtwi.id joined_id
FROM table_with_weird_field twwf
INNER JOIN join_table_with_ids jtwi
ON twwf.delimited_field LIKE CONCAT("%\"", jtwi.id, "\"%")
This basically just looks to see if the id from the table you're trying to join appears in the set and at that point you can join on it easily enough and return your records. You could also just create a view from something like this.
It worked well for my use case where I was dealing with a Wordpress plugin that managed relations in the way described. The quotes really help though because otherwise you run the risk of partial matches (aka - id 1 within 18, etc).
The /P
switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
Two ways I've used it... first:
SET /P variable=
When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.
And second:
SET /P variable=<%temp%\filename.txt
Will set variable to contents (the first line) of the txt file. This method won't work unless the /P
is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.
Here's how to do it:
var myVideo = document.getElementById("my-video")
myVideo.controls = false;
Working example: https://jsfiddle.net/otnfccgu/2/
See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp
It flushes the internal buffer, which is supposed to cause the OS to write out the buffer to the file.[1] Python uses the OS's default buffering unless you configure it do otherwise.
But sometimes the OS still chooses not to cooperate. Especially with wonderful things like write-delays in Windows/NTFS. Basically the internal buffer is flushed, but the OS buffer is still holding on to it. So you have to tell the OS to write it to disk with os.fsync()
in those cases.
I think it would be easier using this CLR Stored procedure SQL-APIConsumer:
exec [dbo].[APICaller_POST]
@URL = 'http://localhost:5000/api/auth/login'
,@BodyJson = '{"Username":"gdiaz","Password":"password"}'
It has multiple procedures that allows you calling API that required a parameters and even passing multiples headers and tokens authentications.
GET/PUT is idempotent PATCH can be sometimes idempotent
What is idempotent - It means if we fire the query multiple times it should not afftect the result of it.(same output.Suppose a cow is pregnant and if we breed it again then it cannot be pregnent multiple times)
get
:-simple get. Get the data from server and show it to user
{
id:1
name:parth
email:[email protected]
}
post
:-create new resource at Database. It means it adds new data. Its not idempotent.
put
:-Create new resource otherwise add to existing. Idempotent because it will update the same resource everytime and output will be the same. ex. - initial data
{
id:1
name:parth
email:[email protected]
}
{
id:1
email:[email protected]
}
patch
so now came patch request PATCH can be sometimes idempotent
id:1
name:parth
email:[email protected]
}
patch name:w
{
id:1
name:w
email:[email protected]
}
HTTP Method GET yes POST no PUT yes PATCH no* OPTIONS yes HEAD yes DELETE yes
Resources : Idempotent -- What is Idempotency?
As mentioned by Tom, background-color: rgba(229,229,229, 0.85)
can do the trick.
Place that on the style of the parent element and child wont be affected.
Add a nodemon.json
configuration file in your root folder and specify ignore patterns for example:
nodemon.json
{
"ignore": [
"*.test.js",
"dist/*"
]
}
.git
, node_modules
, bower_components
, .nyc_output
, coverage
and .sass-cache
are ignored so you don't need to add them to your configuration.Explanation: This error happens because you exceeded the max number of watchers allowed by your system (i.e. nodemon
has no more disk space to watch all the files - which probably means you are watching not important files). So you ignore non-important files that you don't care about changes in them for example the build output or the test cases.
Using the appropriate VerificationMode:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");
One of the best ways I find for approximating the complexity of the recursive algorithm is drawing the recursion tree. Once you have the recursive tree:
Complexity = length of tree from root node to leaf node * number of leaf nodes
n
and number of leaf node 1
so complexity will be n*1 = n
The second function will have the length of n/5
and number of leaf nodes again 1
so complexity will be n/5 * 1 = n/5
. It should be approximated to n
For the third function, since n
is being divided by 5 on every recursive call, length of recursive tree will be log(n)(base 5)
, and number of leaf nodes again 1 so complexity will be log(n)(base 5) * 1 = log(n)(base 5)
For the fourth function since every node will have two child nodes, the number of leaf nodes will be equal to (2^n)
and length of the recursive tree will be n
so complexity will be (2^n) * n
. But since n
is insignificant in front of (2^n)
, it can be ignored and complexity can be only said to be (2^n)
.
For the fifth function, there are two elements introducing the complexity. Complexity introduced by recursive nature of function and complexity introduced by for
loop in each function. Doing the above calculation, the complexity introduced by recursive nature of function will be ~ n
and complexity due to for loop n
. Total complexity will be n*n
.
Note: This is a quick and dirty way of calculating complexity(nothing official!). Would love to hear feedback on this. Thanks.
If you are after 2D array for google charts, the best way to do it is
var finalData = [];
[["key",value], ["2013-8-5", 13.5], ["2013-7-29",19.7]...]
referring to Not a valid 2d array google chart
Using trap is not always an option. For example, if you're writing some kind of re-usable function that needs error handling and that can be called from any script (after sourcing the file with helper functions), that function cannot assume anything about exit time of the outer script, which makes using traps very difficult. Another disadvantage of using traps is bad composability, as you risk overwriting previous trap that might be set earlier up in the caller chain.
There is a little trick that can be used to do proper error handling without traps. As you may already know from other answers, set -e
doesn't work inside commands if you use ||
operator after them, even if you run them in a subshell; e.g., this wouldn't work:
#!/bin/sh
# prints:
#
# --> outer
# --> inner
# ./so_1.sh: line 16: some_failed_command: command not found
# <-- inner
# <-- outer
set -e
outer() {
echo '--> outer'
(inner) || {
exit_code=$?
echo '--> cleanup'
return $exit_code
}
echo '<-- outer'
}
inner() {
set -e
echo '--> inner'
some_failed_command
echo '<-- inner'
}
outer
But ||
operator is needed to prevent returning from the outer function before cleanup. The trick is to run the inner command in background, and then immediately wait for it. The wait
builtin will return the exit code of the inner command, and now you're using ||
after wait
, not the inner function, so set -e
works properly inside the latter:
#!/bin/sh
# prints:
#
# --> outer
# --> inner
# ./so_2.sh: line 27: some_failed_command: command not found
# --> cleanup
set -e
outer() {
echo '--> outer'
inner &
wait $! || {
exit_code=$?
echo '--> cleanup'
return $exit_code
}
echo '<-- outer'
}
inner() {
set -e
echo '--> inner'
some_failed_command
echo '<-- inner'
}
outer
Here is the generic function that builds upon this idea. It should work in all POSIX-compatible shells if you remove local
keywords, i.e. replace all local x=y
with just x=y
:
# [CLEANUP=cleanup_cmd] run cmd [args...]
#
# `cmd` and `args...` A command to run and its arguments.
#
# `cleanup_cmd` A command that is called after cmd has exited,
# and gets passed the same arguments as cmd. Additionally, the
# following environment variables are available to that command:
#
# - `RUN_CMD` contains the `cmd` that was passed to `run`;
# - `RUN_EXIT_CODE` contains the exit code of the command.
#
# If `cleanup_cmd` is set, `run` will return the exit code of that
# command. Otherwise, it will return the exit code of `cmd`.
#
run() {
local cmd="$1"; shift
local exit_code=0
local e_was_set=1; if ! is_shell_attribute_set e; then
set -e
e_was_set=0
fi
"$cmd" "$@" &
wait $! || {
exit_code=$?
}
if [ "$e_was_set" = 0 ] && is_shell_attribute_set e; then
set +e
fi
if [ -n "$CLEANUP" ]; then
RUN_CMD="$cmd" RUN_EXIT_CODE="$exit_code" "$CLEANUP" "$@"
return $?
fi
return $exit_code
}
is_shell_attribute_set() { # attribute, like "x"
case "$-" in
*"$1"*) return 0 ;;
*) return 1 ;;
esac
}
Example of usage:
#!/bin/sh
set -e
# Source the file with the definition of `run` (previous code snippet).
# Alternatively, you may paste that code directly here and comment the next line.
. ./utils.sh
main() {
echo "--> main: $@"
CLEANUP=cleanup run inner "$@"
echo "<-- main"
}
inner() {
echo "--> inner: $@"
sleep 0.5; if [ "$1" = 'fail' ]; then
oh_my_god_look_at_this
fi
echo "<-- inner"
}
cleanup() {
echo "--> cleanup: $@"
echo " RUN_CMD = '$RUN_CMD'"
echo " RUN_EXIT_CODE = $RUN_EXIT_CODE"
sleep 0.3
echo '<-- cleanup'
return $RUN_EXIT_CODE
}
main "$@"
Running the example:
$ ./so_3 fail; echo "exit code: $?"
--> main: fail
--> inner: fail
./so_3: line 15: oh_my_god_look_at_this: command not found
--> cleanup: fail
RUN_CMD = 'inner'
RUN_EXIT_CODE = 127
<-- cleanup
exit code: 127
$ ./so_3 pass; echo "exit code: $?"
--> main: pass
--> inner: pass
<-- inner
--> cleanup: pass
RUN_CMD = 'inner'
RUN_EXIT_CODE = 0
<-- cleanup
<-- main
exit code: 0
The only thing that you need to be aware of when using this method is that all modifications of Shell variables done from the command you pass to run
will not propagate to the calling function, because the command runs in a subshell.
NULL
is not a keyword. It's an identifier defined in some standard headers. You can include
#include <cstddef>
To have it in scope, including some other basics, like std::size_t
.
If you want to return IHttpActionResult
you can do it like this:
[HttpGet]
public IHttpActionResult Test()
{
var stream = new MemoryStream();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "test.pdf"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var response = ResponseMessage(result);
return response;
}
Try this..
#!/usr/bin/env python
import gtk.gdk
import time
import random
while 1 :
# generate a random time between 120 and 300 sec
random_time = random.randrange(120,300)
# wait between 120 and 300 seconds (or between 2 and 5 minutes)
print "Next picture in: %.2f minutes" % (float(random_time) / 60)
time.sleep(random_time)
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
ts = time.time()
filename = "screenshot"
filename += str(ts)
filename += ".png"
if (pb != None):
pb.save(filename,"png")
print "Screenshot saved to "+filename
else:
print "Unable to get the screenshot."
What type of LayoutManager are you using for the panel you're adding the JTextField to?
Different layout managers approach sizing elements on them in different ways, some respect SetPreferredSize(), while others will scale the compoenents to fit their container.
See: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
ps. this has nothing to do with eclipse, its java.
Visual Studio Code: Version: 1.53.2
If you are looking for the answer in 2021 (like I was), the answer is here on the Microsoft website but honestly hard to follow.
Go to Edit > Replace in Files
From there it is similar to the search funtionality for a single file.
I changed the name of a class I was using across files and this worked perfectly.
Note: If you cannot find the Replace in Files option, first click on the Search icon (magnifying glass) and then it will appear.
Either use
<embed src="file.pdf" />
if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff
Marked anwser is perfect but it misses character 127(DEL) which is also a non-printable character
my answer would be
$string = preg_replace('/[\x00-\x1F\x7f-\xFF]/', '', $string);
What's wrong with using 'key_name'
instead, even if it is a variable?
This is really obscure but works. 7za.exe is standalone version of 7zip and is available with install package.
# get files to be send
$logFiles = Get-ChildItem C:\Logging\*.* -Include *.log | where {$_.Name -match $yesterday}
foreach ($logFile in $logFiles)
{
Write-Host ("Processing " + $logFile.FullName)
# compress file
& ./7za.exe a -mmt=off ($logFile.FullName + ".7z") $logFile.FullName
}
I had this problem after enabling a new service API on the Google console and trying to use the previously made credentials.
To fix the problem, I had to go back to the credential page, clicking on the credential name, and clicking "Save" again. After that, I could authenticate just fine.
I had a similar problem when I needed to make multiple sql queries. The problem was that some queries did not return the result and I wanted to print that result. And there was a mistake. As already written, there are several solutions.
if cursor.description is None:
# No recordset for INSERT, UPDATE, CREATE, etc
pass
else:
# Recordset for SELECT
As well as:
exist = cursor.fetchone()
if exist is None:
... # does not exist
else:
... # exists
One of the solutions is:
The try
and except
block lets you handle the error
/exceptions
. The finally
block lets you execute code, regardless of the result of the try
and except
blocks.
So the presented problem can be solved by using it.
s = """ set current query acceleration = enable;
set current GET_ACCEL_ARCHIVE = yes;
SELECT * FROM TABLE_NAME;"""
query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
print(f"Executing SQL statements ====> {sql} <=====")
cursor.execute(sql)
print(f"SQL ====> {sql} <===== was executed successfully")
try:
print("\n****************** RESULT ***********************")
for result in cursor.fetchall():
print(result)
print("****************** END RESULT ***********************\n")
except Exception as e:
print(f"SQL: ====> {sql} <==== doesn't have output!\n")
# print(str(e))
output:
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!
Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!
Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====
****************** RESULT ***********************
---------- DATA ----------
****************** END RESULT ***********************
The example above only presents a simple use as an idea that could help with your solution. Of course, you should also pay attention to other errors, such as the correctness of the query, etc.
For debugging purposes, you could use print(repr(data))
.
To display text, always print Unicode. Don't hardcode the character encoding of your environment such as Cp850 inside your script. To decode the HTTP response, see A good way to get the charset/encoding of an HTTP response in Python.
To print Unicode to Windows console, you could use win-unicode-console
package.
When managing the actual files, things can get out of sync pretty easily unless you're really vigilant. So we've launched a (beta) free service called String which allows you to keep track of your language files easily, and collaborate with translators.
You can either import existing language files (in PHP array, PHP Define, ini, po or .strings formats) or create your own sections from scratch and add content directly through the system.
String is totally free so please check it out and tell us what you think.
It's actually built on Codeigniter too! Check out the beta at http://mygengo.com/string
If using GitHub on Windows:
This is why, before you start making changes of your own, that you should create a branch for each set of changes you plan to put into a pull request. That way, once you make the pull request, you can then make another branch and continue work on some other task/feature/bugfix without affecting the previous pull request.
By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.
Assuming that you meant to state 'Class Diagram' instead of 'Project Hierarchy', I've used the following Eclipse plug-ins to generate Class Diagrams at various points in my professional career:
Obligatory links
The listed tools will not generate class diagrams from source code, or atleast when I used them quite a few years back. You can use them to handcraft class diagrams though.
Related questions on StackOverflow
Except for ObjectAid and a few other mentions, most of the Eclipse plug-ins mentioned in the listed questions may no longer be available, or would work only against older versions of Eclipse.
If your table is MyISAM
:
SELECT *
FROM pages
WHERE MATCH(title, content) AGAINST ('keyword' IN BOOLEAN MODE)
This will be much faster if you create a FULLTEXT
index on your columns:
CREATE FULLTEXT INDEX fx_pages_title_content ON pages (title, content)
, but will work even without the index.
Based on the excellent answer by trincot, I wrote a reusable function that accepts a handler to run over each item in an array. The function itself returns a promise that allows you to wait until the loop has finished and the handler function that you pass may also return a promise.
It took me some time to get it right, but I believe the following code will be usable in a lot of promise-looping situations.
Copy-paste ready code:
// SEE https://stackoverflow.com/a/46295049/286685
const loop = (arr, fn, busy, err, i=0) => {
const body = (ok,er) => {
try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}
catch(e) {er(e)}
}
const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)
const run = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()
return busy ? run(busy,err) : new Promise(run)
}
To use it, call it with the array to loop over as the first argument and the handler function as the second. Do not pass parameters for the third, fourth and fifth arguments, they are used internally.
const loop = (arr, fn, busy, err, i=0) => {_x000D_
const body = (ok,er) => {_x000D_
try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
catch(e) {er(e)}_x000D_
}_x000D_
const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
const run = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const items = ['one', 'two', 'three']_x000D_
_x000D_
loop(items, item => {_x000D_
console.info(item)_x000D_
})_x000D_
.then(() => console.info('Done!'))
_x000D_
Let's look at the handler function, nested loops and error handling.
The handler gets passed 3 arguments. The current item, the index of the current item and the complete array being looped over. If the handler function needs to do async work, it can return a promise and the loop function will wait for the promise to resolve before starting the next iteration. You can nest loop invocations and all works as expected.
const loop = (arr, fn, busy, err, i=0) => {_x000D_
const body = (ok,er) => {_x000D_
try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
catch(e) {er(e)}_x000D_
}_x000D_
const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
const run = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
[],_x000D_
['one', 'two'],_x000D_
['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
console.info('Performing test ' + idx)_x000D_
return loop(test, (testCase) => {_x000D_
console.info(testCase)_x000D_
})_x000D_
.then(testNext)_x000D_
.catch(testFailed)_x000D_
}))_x000D_
.then(() => console.info('All tests done'))
_x000D_
Many promise-looping examples I looked at break down when an exception occurs. Getting this function to do the right thing was pretty tricky, but as far as I can tell it is working now. Make sure to add a catch handler to any inner loops and invoke the rejection function when it happens. E.g.:
const loop = (arr, fn, busy, err, i=0) => {_x000D_
const body = (ok,er) => {_x000D_
try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
catch(e) {er(e)}_x000D_
}_x000D_
const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
const run = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
[],_x000D_
['one', 'two'],_x000D_
['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
console.info('Performing test ' + idx)_x000D_
loop(test, (testCase) => {_x000D_
if (idx == 2) throw new Error()_x000D_
console.info(testCase)_x000D_
})_x000D_
.then(testNext)_x000D_
.catch(testFailed) // <--- DON'T FORGET!!_x000D_
}))_x000D_
.then(() => console.error('Oops, test should have failed'))_x000D_
.catch(e => console.info('Succesfully caught error: ', e))_x000D_
.then(() => console.info('All tests done'))
_x000D_
Since writing this answer, I turned the above code in an NPM package.
npm install --save for-async
var forAsync = require('for-async'); // Common JS, or
import forAsync from 'for-async';
var arr = ['some', 'cool', 'array'];
forAsync(arr, function(item, idx){
return new Promise(function(resolve){
setTimeout(function(){
console.info(item, idx);
// Logs 3 lines: `some 0`, `cool 1`, `array 2`
resolve(); // <-- signals that this iteration is complete
}, 25); // delay 25 ms to make async
})
})
See the package readme for more details.
Other answers work, but
To get the full/default price:
$product->get_price_html();
I added "\Anaconda3_64\" and "\Anaconda3_64\Scripts\" to the PATH variable. Then I can use conda from powershell or command prompt.
The syntax is:
=GOOGLEFINANCE(ticker, [attribute], [start_date], [num_days|end_date], [interval])
=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
=GOOGLEFINANCE("GOOG","price",TODAY()-30,TODAY())
=GOOGLEFINANCE(A2,A3)
=117.80*Index(GOOGLEFINANCE("CURRENCY:EURGBP", "close", DATE(2014,1,1)), 2, 2)
For instance if you'd like to convert the rate on specific date, here is some more advanced example:
=IF($C2 = "GBP", "", Index(GoogleFinance(CONCATENATE("CURRENCY:", C2, "GBP"), "close", DATE(year($A2), month($A2), day($A2)), DATE(year($A2), month($A2), day($A2)+1), "DAILY"), 2))
where $A2
is your date (e.g. 01/01/2015
) and C2
is your currency (e.g. EUR
).
See more samples at Docs editors Help at Google.
You should check if it's not defined using if (!Array.prototype.indexOf)
.
Also, your implementation of indexOf
is not correct. You must use ===
instead of ==
in your if (this[i] == obj)
statement, otherwise [4,"5"].indexOf(5)
would be 1 according to your implementation, which is incorrect.
I recommend you use the implementation on MDC.
However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
Use mysql_fetch_assoc instead of mysql_fetch_array
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
I modified some thing that were poping up error for me and end up with this which worked great to extract the data as I needed:
Sub get_data_web()
Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")
With appIE
.navigate "https://finance.yahoo.com/quote/NQ%3DF/futures?p=NQ%3DF"
.Visible = True
End With
Do While appIE.Busy
DoEvents
Loop
Set allRowofData = appIE.document.getElementsByClassName("Ta(end) BdT Bdc($c-fuji-grey-c) H(36px)")
Dim i As Long
Dim myValue As String
Count = 1
For Each itm In allRowofData
For i = 0 To 4
myValue = itm.Cells(i).innerText
ActiveSheet.Cells(Count, i + 1).Value = myValue
Next
Count = Count + 1
Next
appIE.Quit
Set appIE = Nothing
End Sub
What you can do is use a pixmap as an icon and then put this icon onto the button.
To make sure the size of the button will be correct, you have to reisze the icon according to the pixmap size.
Something like this should work :
QPixmap pixmap("image_path");
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
Very easy:
var stringArr = dataTable.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();
Where DataRow.ItemArray
property is an array of objects containing the values of the row for each columns of the data table.
You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.
However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).
EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:
expires_in
)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.There is also an API that returns the remaining lifetime of the access_token:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
This will return a json array that will contain an expires_in
parameter, which is the number of seconds left in the lifetime of the token.
You can reset by update sequence after deleted rows in your-table
UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';
Based on http://html5-demos.appspot.com/static/a.download.html:
var fileContent = "My epic novel that I don't want to lose.";
var bb = new Blob([fileContent ], { type: 'text/plain' });
var a = document.createElement('a');
a.download = 'download.txt';
a.href = window.URL.createObjectURL(bb);
a.click();
Modified the original fiddle: http://jsfiddle.net/9av2mfjx/
on linux ctrl+m should work but it doesn't for solving the problem click on the (...) (its extended controls) and then close that window.now you can open menu by ctrl+m. then:
click on the (...) (its extended controls)
close extended controls
ctrl+m
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
Update
There has been recent improvements in datetime API with JSR-310.
Instant now = Instant.now();
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println(now);
System.out.println(yesterday);
Outdated answer
You are subtracting the wrong number:
Use Calendar
instead:
private Date yesterday() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
Then, modify your method to the following:
private String getYesterdayDateString() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return dateFormat.format(yesterday());
}
See
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
I don't think it is a bug, Try adding the MIME type to your .htaccess file For instance, put or add the following content to your .htaccess file (which should be in the same place of your .js or above folders)
#JavaScript
AddType application/x-javascript .js
This solved my tree "Resource interpreted as other but transfered ... " warnings. Everytime you have that kind of warning it means you don't have enough info in your .htaccess file.
BTW1: Since you are modifying .htaccess file, make sure you restart your server.
BTW2: I also could clear same warnings for GIF files in Safari 4 with this:
#GIF
AddType image/gif .gif
BTW3: For other file types: see w3schools list or htaccess-guide
seperate your page from nav bar.
pageOne.php:
$page="one";
include("navigation.php");
navigation.php
if($page=="one"){$oneIsActive = 'class="active"';}else{ $oneIsActive=""; }
if($page=="two"){$twoIsActive = 'class="active"';}else{ $twoIsActive=""; }
if($page=="three"){$threeIsActive = 'class="active"';}else{ $threeIsActive=""; }
<ul class="nav">
<li <?php echo $oneIsActive; ?>><a href="pageOne.php">One</a></li>
<li <?php echo $twoIsActive; ?>><a href="pageTwo.php"><a href="#">Page 2</a></li>
<li <?php echo $threeIsActive; ?>><a href="pageThree.php"><a href="#">Page 3</a></li>
</ul>
I found that I could also set the title of my pages with this method as well.
$page="one";
$title="This is page one."
include("navigation.php");
and just grab the $title var and put it in between the "title" tags. Though I am sending it to my header page above my nav bar.
FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:
ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg
Let's explain the options:
-i input file the path to the input file
-ss 01:23:45 seek the position to the specified timestamp
-vframes 1 only handle one video frame
output.jpg output filename, should have a well-known extension
The -ss
parameter accepts a value in the form HH:MM:SS[.xxx]
or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.
You can simply use value_counts
with sort
option set to False
. This will preserve ordering of the categories
df['colour'].value_counts(sort=False).plot.bar(rot=0)
Use xml drawable like this:
Save the following contents as round_button.xml
in drawable
folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape android:shape="oval">
<solid android:color="#fa09ad"/>
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="oval">
<solid android:color="#c20586"/>
</shape>
</item>
</selector>
Android Material Effect: Although FloatingActionButton
is a better option, If you want to do it using xml selector, create a folder drawable-v21
in res
and save another round_button.xml
there with following xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#c20586">
<item>
<shape android:shape="oval">
<solid android:color="#fa09ad"/>
</shape>
</item>
</ripple>
And set it as background of Button
in xml like this:
<Button
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/round_button"
android:gravity="center_vertical|center_horizontal"
android:text="hello"
android:textColor="#fff" />
Important:
Remove warnings.filterwarnings and add:
numpy.seterr(all='raise')
Try this:
String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
trimmedArray[i] = array[i].trim();
Now trimmedArray
contains the same strings as array
, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:
for (int i = 0; i < array.length; i++)
array[i] = array[i].trim();
What login are you connecting to SQL Server as? You need to connect with a login that has sufficient privileges to create a database. Network Service is probably not good enough, unless you go into SQL Server and add them as a login with sufficient rights.
As long as there are no identity columns you can just
INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]
You should use val
instead of value
.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('input[name="testing"]').val('Work!');
});
</script>
You have the button tag
http://www.w3schools.com/tags/tag_button.asp
<button>What ever you want</button>
With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.
You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/
exit(X)
, where X is a number (according to the doc) should work.
But it is not recommended by Apple and won't be accepted by the AppStore.
Why? Because of these guidelines (one of my app got rejected):
We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.
Please refer to the attached screenshot/s for reference.
The iOS Human Interface Guidelines specify,
"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:
Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.
Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."
> It would be appropriate to remove any mechanisms for quitting your app.
Plus, if you try to hide that function, it would be understood by the user as a crash.
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
In json strict mode, you'll have to keep the order:
{
"dt": {
"$gte": {
"$date": "2013-10-01T00:00:00.000Z"
}
}
}
Only thing which worked to define my search queries on mlab.com.
Rather than defining contact_email
within app.config
, define it in a parameters
entry:
parameters:
contact_email: [email protected]
You should find the call you are making within your controller now works.
@Francisco Goldenstein, just a minor correction. The COMMIT must be used after you set the variable, otherwise the WHILE will be executed just once:
DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;
WHILE (@Deleted_Rows > 0)
BEGIN
BEGIN TRANSACTION
-- Delete some small number of rows at a time
DELETE TOP (10000) LargeTable
WHERE readTime < dateadd(MONTH,-7,GETDATE())
SET @Deleted_Rows = @@ROWCOUNT;
COMMIT TRANSACTION
CHECKPOINT -- for simple recovery model
END
Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue
annotation using IDENTITY.
@Entity
@Table(name = "client")
data class Client(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)
GL
You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:
solution 1: call alpha's alphaMethod1()
from beta's alphaMethod1()
class Beta extends Alpha
{
public void alphaMethod1()
{
super.alphaMethod1();
}
}
or from any other method of Beta like:
class Beta extends Alpha
{
public void foo()
{
super.alphaMethod1();
}
}
class Test extends Beta
{
public static void main(String[] args)
{
Beta beta = new Beta();
beta.foo();
}
}
solution 2: create alpha's object and call alpha's alphaMethod1()
class Test extends Beta
{
public static void main(String[] args)
{
Alpha alpha = new Alpha();
alpha.alphaMethod1();
}
}
You don't have a validator on the page. Add something like this to show the validation message.
@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.Number = 12;
MyDynamic.MyMethod = new Func<int>(() =>
{
return 55;
});
Console.WriteLine(MyDynamic.MyMethod());
Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.
Assuming you understand the consequences of using the MEMORY engine as mentioned in comments, and here, as well as some others you'll find by searching about (no transaction safety, locking issues, etc) - you can proceed as follows:
MEMORY tables are stored differently than InnoDB, so you'll need to use an export/import strategy. First dump each table separately to a file using SELECT * FROM tablename INTO OUTFILE 'table_filename'
. Create the MEMORY database and recreate the tables you'll be using with this syntax: CREATE TABLE tablename (...) ENGINE = MEMORY;
. You can then import your data using LOAD DATA INFILE 'table_filename' INTO TABLE tablename
for each table.
You probably don't need this anymore, but this is what I did for a similar problem. (It looks longer than it is because of the comments.)
itemList = ['hi', 'hi', 'hello', 'bye']
counter = {}
maxItemCount = 0
for item in itemList:
try:
# Referencing this will cause a KeyError exception
# if it doesn't already exist
counter[item]
# ... meaning if we get this far it didn't happen so
# we'll increment
counter[item] += 1
except KeyError:
# If we got a KeyError we need to create the
# dictionary key
counter[item] = 1
# Keep overwriting maxItemCount with the latest number,
# if it's higher than the existing itemCount
if counter[item] > maxItemCount:
maxItemCount = counter[item]
mostPopularItem = item
print mostPopularItem
If you are fond of functional programming style, here is a useful function, self-documented and tested code using doctest.
def decompose(a_list):
"""Turns a list into a set of all elements and a set of duplicated elements.
Returns a pair of sets. The first one contains elements
that are found at least once in the list. The second one
contains elements that appear more than once.
>>> decompose([1,2,3,5,3,2,6])
(set([1, 2, 3, 5, 6]), set([2, 3]))
"""
return reduce(
lambda (u, d), o : (u.union([o]), d.union(u.intersection([o]))),
a_list,
(set(), set()))
if __name__ == "__main__":
import doctest
doctest.testmod()
From there you can test unicity by checking whether the second element of the returned pair is empty:
def is_set(l):
"""Test if there is no duplicate element in l.
>>> is_set([1,2,3])
True
>>> is_set([1,2,1])
False
>>> is_set([])
True
"""
return not decompose(l)[1]
Note that this is not efficient since you are explicitly constructing the decomposition. But along the line of using reduce, you can come up to something equivalent (but slightly less efficient) to answer 5:
def is_set(l):
try:
def func(s, o):
if o in s:
raise Exception
return s.union([o])
reduce(func, l, set())
return True
except:
return False
What worked for me was
<WebBrowser Source="pack://siteoforigin:,,,/StartPage.html" />
from here. I copied StartPage.html to the same output directory as the xaml-file and it loaded it from that relative path.
I use the following steps to solve the problem:
First, Make sure
“Run this program in compatibality mode for: Windows XP (Service Pack 3)” and “Run this program as an administrator” are ENABLED.
Run in Command Prompt
C:\Users\{yourusernamehere}\Documents\Downloads\netbeans-6.5-ml-windows.exe –-javahome "C:\Program Files (x86)\Java\jdk1.6.0_18"
This code:
$("#yourFileInput")[0].files[0].size;
Returns the file size for an form input.
On FF 3.6 and later this code should be:
$("#yourFileInput")[0].files[0].fileSize;
This could be a CORS issue. try enabling CORS for you api.
For WebApi
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
you should write var element = [];
in javascript {}
is an empty object and []
is an empty array.
You have more static resources that the cache has room for. You can do one of the following:
For more details see the documentation for these configuration options.
The simplest solution may be to add HINTS
to each find_*
request.
For example:
find_library(CURL_LIBRARY
NAMES curl curllib libcurl_imp curllib_static
HINTS "${CMAKE_PREFIX_PATH}/curl/lib"
)
For Boost I would strongly recommend using the FindBoost standard module and setting the BOOST_DIR
variable to point to your Boost libraries.
Why not just check which element was clicked? If you click on something, window.event.target
is assigned to the element which was clicked, and the clicked element can also be passed as an argument.
If the target and element aren't equal, it was an event that propagated up.
function myfunc(el){
if (window.event.target === el){
// perform action
}
}
<div onclick="myfunc(this)" />
There is one more way, i got the same situation in my project. i solved this way
List<Object[]> list = HQL.list();
In above hibernate query language i know at which place what are my objects so what i did is :
for(Object[] obj : list){
String val = String.valueOf(obj[1]);
int code =Integer.parseint(String.valueof(obj[0]));
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
import traceback
traceback.print_stack()
Through trial and error, it seems if the user was originally created "without login" then this query
select * from sys.database_principals
will show authentication_type = 0 (NONE).
Apparently these users cannot be re-linked to any login (pre-existing or new, SQL or Windows) since this command:
alter user [TempUser] with login [TempLogin]
responds with the Remap Error "Msg 33016" shown in the question.
Also these users do not show up in classic (deprecating) SP report:
exec sp_change_users_login 'Report'
If anyone knows a way around this or how to change authentication_type, please comment.
It should wait until get request completed. After that I'll return get request body from where function is called.
function foo() {
var jqXHR = $.ajax({
url: url,
type: 'GET',
async: false,
});
return JSON.parse(jqXHR.responseText);
}
You can get that error if you have an object with the same name as the schema. For example:
create sequence s2;
begin
s2.a;
end;
/
ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored
When you refer to S2.MY_FUNC2
the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2
there is no confusion, so it works.
The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.
It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.
select owner, object_type, object_name
from all_objects
where object_name = 'S2';
I will explain you this with a practical example and no theory stuff:
A developer writes the code. No GUI is implemented yet. The testing at this level verifies that the functions work correctly and the data types are correct. This phase of testing is called Unit testing.
When a GUI is developed, and application is assigned to a tester, he verifies business requirements with a client and executes the different scenarios. This is called functional testing. Here we are mapping the client requirements with application flows.
Integration testing: let's say our application has two modules: HR and Finance. HR module was delivered and tested previously. Now Finance is developed and is available to test. The interdependent features are also available now, so in this phase, you will test communication points between the two and will verify they are working as requested in requirements.
Regression testing is another important phase, which is done after any new development or bug fixes. Its aim is to verify previously working functions.
SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.
As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.
More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.
To make sure it will work, you need to validate it.
function mmIsDate(str) {
if (str == undefined) { return false; }
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2], 10);
if (yyyy < 1900) { return false; }
var mm = parseInt(parms[1], 10);
if (mm < 1 || mm > 12) { return false; }
var dd = parseInt(parms[0], 10);
if (dd < 1 || dd > 31) { return false; }
var dateCheck = new Date(yyyy, mm - 1, dd);
return (dateCheck.getDate() === dd && (dateCheck.getMonth() === mm - 1) && dateCheck.getFullYear() === yyyy);
};
Here's a case-insensitive trivial solution:
function hasClass(element, classNameToTestFor) {
var classNames = element.className.split(' ');
for (var i = 0; i < classNames.length; i++) {
if (classNames[i].toLowerCase() == classNameToTestFor.toLowerCase()) {
return true;
}
}
return false;
}
There is actually a really easy way to do this with GitHub Desktop now that I don't believe was a feature before.
All you need to do is switch to the new branch in GitHub Desktop, and it will prompt you to leave your changes on the current branch (which will be stashed), or to bring your changes with you to the new branch. Just choose the second option, to bring the changes to the new branch. You can then commit as usual.
You have to use the escaped unicode :
Like
.breadcrumbs a:before {
content: '\0000a0';
}
More info on : http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/
I like the idea to override default options, this seems like a good solution.
However, if you are up to extending the Http
class. Make sure to read this through!
Some answers here are actually showing incorrect overloading of request()
method, which could lead to a hard-to-catch errors and weird behavior. I've stumbled upon this myself.
This solution is based on request()
method implementation in Angular 4.2.x
, but should be future-compatible:
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {
ConnectionBackend, Headers,
Http as NgHttp,
Request,
RequestOptions,
RequestOptionsArgs,
Response,
XHRBackend
} from '@angular/http';
import {AuthenticationStateService} from '../authentication/authentication-state.service';
@Injectable()
export class Http extends NgHttp {
constructor (
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private authenticationStateService: AuthenticationStateService
) {
super(backend, defaultOptions);
}
request (url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
if ('string' === typeof url) {
url = this.rewriteUrl(url);
options = (options || new RequestOptions());
options.headers = this.updateHeaders(options.headers);
return super.request(url, options);
} else if (url instanceof Request) {
const request = url;
request.url = this.rewriteUrl(request.url);
request.headers = this.updateHeaders(request.headers);
return super.request(request);
} else {
throw new Error('First argument must be a url string or Request instance');
}
}
private rewriteUrl (url: string) {
return environment.backendBaseUrl + url;
}
private updateHeaders (headers?: Headers) {
headers = headers || new Headers();
// Authenticating the request.
if (this.authenticationStateService.isAuthenticated() && !headers.has('Authorization')) {
headers.append('Authorization', 'Bearer ' + this.authenticationStateService.getToken());
}
return headers;
}
}
Notice that I'm importing original class this way import { Http as NgHttp } from '@angular/http';
in order to prevent name clashes.
The problem addressed here is that
request()
method has two different call signatures. WhenRequest
object is passed instead of the URLstring
, theoptions
argument is ignored by Angular. So both cases must be properly handled.
And here's the example of how to register this overridden class with DI container:
export const httpProvider = {
provide: NgHttp,
useFactory: httpFactory,
deps: [XHRBackend, RequestOptions, AuthenticationStateService]
};
export function httpFactory (
xhrBackend: XHRBackend,
requestOptions: RequestOptions,
authenticationStateService: AuthenticationStateService
): Http {
return new Http(
xhrBackend,
requestOptions,
authenticationStateService
);
}
With such approach you can inject Http
class normally, but your overridden class will be magically injected instead. This allows you to integrate your solution easily without changing other parts of the application (polymorphism in action).
Just add httpProvider
to the providers
property of your module metadata.
The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.
A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY
@COUNTRY VARCHAR(20)
AS
SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY
GO
The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
The above code passing country parameter to the stored procedure from C# application.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPCOUNTRY";
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
}
connection.Close();
}
}
}
The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions.
For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.
You might also use a module when you have shared methods across multiple apps (again, the library model is good here).
Moving tables:
First run:
SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
FROM ALL_OBJECTS
WHERE OWNER = '<schema_name>'
AND OBJECT_TYPE = 'TABLE' <> '<TABLESPACE_NAME>';
-- Or suggested in the comments (did not test it myself)
SELECT 'ALTER TABLE <SCHEMA>.' || TABLE_NAME ||' MOVE TABLESPACE '||' TABLESPACE_NAME>; '
FROM dba_tables
WHERE OWNER = '<SCHEMA>'
AND TABLESPACE_NAME <> '<TABLESPACE_NAME>
Where <schema_name>
is the name of the user.
And <tablespace_name>
is the destination tablespace.
As a result you get lines like:
ALTER TABLE SCOT.PARTS MOVE TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Moving indexes:
First run:
SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;'
FROM ALL_INDEXES
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';
The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.
As a result you should get something like:
ALTER INDEX SCOT.PARTS_NO_PK REBUILD TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Last but not least, moving LOBs:
First run:
SELECT 'ALTER TABLE <schema_name>.'||LOWER(TABLE_NAME)||' MOVE LOB('||LOWER(COLUMN_NAME)||') STORE AS (TABLESPACE <table_space>);'
FROM DBA_TAB_COLS
WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';
This moves the LOB objects to the other tablespace.
As a result you should get something like:
ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);
Paste the results in a script or in a oracle sql developer like application and run it.
O and there is one more thing:
For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.
Indeed, if you sorted out the iterator then buffering could now be your problem. You could tell the python in the sub-process not to buffer its output.
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
becomes
proc = subprocess.Popen(['python','-u', 'fake_utility.py'],stdout=subprocess.PIPE)
I have needed this when calling python from within python.
May be this will help some one. I have my proxy setup in python script but keep getting the error mentioned in the question.
Below is the piece of block which will take my username and password as a constant in the beginning.
if (use_proxy):
proxy = req.ProxyHandler({'https': proxy_url})
auth = req.HTTPBasicAuthHandler()
opener = req.build_opener(proxy, auth, req.HTTPHandler)
req.install_opener(opener)
If you are using corporate laptop and if you did not connect to Direct Access or office VPN then the above block will throw error. All you need to do is to connect to your org VPN and then execute your python script.
Thanks
>>> line = "abc#@!?efg12;:?"
>>> ''.join( c for c in line if c not in '?:!/;' )
'abc#@efg12'
IEnumerable and IEnumerator (and their generic counterparts IEnumerable<T> and IEnumerator<T>) are base interfaces of iterator implementations in .Net Framework Class Libray collections.
IEnumerable is the most common interface you would see in the majority of the code out there. It enables the foreach loop, generators (think yield) and because of its tiny interface, it's used to create tight abstractions. IEnumerable depends on IEnumerator.
IEnumerator, on the other hand, provides a slightly lower level iteration interface. It's referred to as the explicit iterator which gives the programmer more control over the iteration cycle.
IEnumerable is a standard interface that enables iterating over collections that supports it (in fact, all collection types I can think of today implements IEnumerable). Compiler support allows language features like foreach
. In general terms, it enables this implicit iterator implementation.
foreach (var value in list)
Console.WriteLine(value);
I think foreach
loop is one of the main reasons for using IEnumerable interfaces. foreach
has a very succinct syntax and very easy to understand compared to classic C style for loops where you need to check the various variables to see what it was doing.
Probably a lesser known feature is that IEnumerable also enables generators in C# with the use of yield return
and yield break
statements.
IEnumerable<Thing> GetThings() {
if (isNotReady) yield break;
while (thereIsMore)
yield return GetOneMoreThing();
}
Another common scenario in practice is using IEnumerable to provide minimalistic abstractions. Because it is a minuscule and read-only interface, you are encouraged to expose your collections as IEnumerable (rather than List for example). That way you are free to change your implementation without breaking your client's code (change List to a LinkedList for instance).
One behaviour to be aware of is that in streaming implementations (e.g. retrieving data row by row from a database, instead of loading all the results in memory first) you cannot iterate over the collection more than once. This is in contrast to in-memory collections like List, where you can iterate multiple times without problems. ReSharper, for example, has a code inspection for Possible multiple enumeration of IEnumerable.
IEnumerator, on the other hand, is the behind the scenes interface which makes IEnumerble-foreach-magic work. Strictly speaking, it enables explicit iterators.
var iter = list.GetEnumerator();
while (iter.MoveNext())
Console.WriteLine(iter.Current);
In my experience IEnumerator is rarely used in common scenarios due to its more verbose syntax and slightly confusing semantics (at least to me; e.g. MoveNext() returns a value as well, which the name doesn't suggest at all).
I only used IEnumerator in particular (slightly lower level) libraries and frameworks where I was providing IEnumerable interfaces. One example is a data stream processing library which provided series of objects in a foreach
loop even though behind the scenes data was collected using various file streams and serialisations.
Client code
foreach(var item in feed.GetItems())
Console.WriteLine(item);
Library
IEnumerable GetItems() {
return new FeedIterator(_fileNames)
}
class FeedIterator: IEnumerable {
IEnumerator GetEnumerator() {
return new FeedExplicitIterator(_stream);
}
}
class FeedExplicitIterator: IEnumerator {
DataItem _current;
bool MoveNext() {
_current = ReadMoreFromStream();
return _current != null;
}
DataItem Current() {
return _current;
}
}
select a.orgName,b.duplicate, a.id
from organizations a
inner join (
SELECT orgName, COUNT(*) AS duplicate
FROM organizations
GROUP BY orgName
HAVING COUNT(*) > 1
) b on o.orgName = oc.orgName
group by a.orgName,a.id
How do I invoke a maven task without leaving vi?
Maven is no different than any other shell command:
:!mvn
You can :set makeprg=mvn
if you already have a favourite key mapping for :make
.
Can I get code completion?
Yes, eclim is great, a bridge between vim's editing efficiency and Eclipse's Java language-specific awareness.
<C-n>
and <C-p>
are not-so-great, but amazingly helpful.
How's the syntax highlighting?
More than good enough for a regex-based highligher.
You may want to consider tools for other vim+java purposes, like code templates (snippetEmu—default snippets suck, but customizability shines), searching for usages and going to declarations (eclim, grep, ctags), generating getters and setters (java_getset, or eclim), automatic imports (eclim). You might also need a java shell for quick experiments (the BeanShell, a.k.a. bsh
).
This advice was great. I had the same problem, but my solution was different, because I was so stupid, that I have renamed directory where XAMPP was located and since I had installed a lot of another programs I couldn't rename it back.
In my case there was original directory C:\Programs\Xampp and renamed it to C:\PROGRAMS_\Xampp and that was the mistake.
The solution was to find all references on C:\Programs and rename them C:\PROGRAMS_ in the XAMPP directory, because for some reason during the installation it writes absolute paths, not relative. Of course, there are some references in the registry too.
Try this:
$NameRegex = "chalmw-dm"
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}
I believe the best way to store Lat/Lng in MySQL is to have a POINT column (2D datatype) with a SPATIAL index.
CREATE TABLE `cities` (
`zip` varchar(8) NOT NULL,
`country` varchar (2) GENERATED ALWAYS AS (SUBSTRING(`zip`, 1, 2)) STORED,
`city` varchar(30) NOT NULL,
`centre` point NOT NULL,
PRIMARY KEY (`zip`),
KEY `country` (`country`),
KEY `city` (`city`),
SPATIAL KEY `centre` (`centre`)
) ENGINE=InnoDB;
INSERT INTO `cities` (`zip`, `city`, `centre`) VALUES
('CZ-10000', 'Prague', POINT(50.0755381, 14.4378005));
If any of your components are Strong Named (signed), then all need to be. If you, as I did, add a project and reference it from a Strong Named project/component, neglecting to sign your new component, debugging will be as if your new component is an external one and you will not be able to step into it. So make sure all your components are signed, or none.
From C++ Templates The Complete Guide:
Member function templates cannot be declared virtual. This constraint is imposed because the usual implementation of the virtual function call mechanism uses a fixed-size table with one entry per virtual function. However, the number of instantiations of a member function template is not fixed until the entire program has been translated. Hence, supporting virtual member function templates would require support for a whole new kind of mechanism in C++ compilers and linkers. In contrast, the ordinary members of class templates can be virtual because their number is fixed when a class is instantiated
Simpler way you can go array.myitem(0) in VB code
my full answer here parse and stringify (serialize)
Use the 'this' object in js
ScriptEngine.AddCode "Object.prototype.myitem=function( i ) { return this[i] } ; "
Then you can go array.myitem(0)
Private ScriptEngine As ScriptControl
Public Sub InitScriptEngine()
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "Object.prototype.myitem=function( i ) { return this[i] } ; "
Set foo = ScriptEngine.Eval("(" + "[ 1234, 2345 ]" + ")") ' JSON array
Debug.Print foo.myitem(1) ' method case sensitive!
Set foo = ScriptEngine.Eval("(" + "{ ""key1"":23 , ""key2"":2345 }" + ")") ' JSON key value
Debug.Print foo.myitem("key1") ' WTF
End Sub
The existing answers (pass the data in the Intent
passed to startActivity()
) show the normal way to solve this problem. There is another solution that can be used in the odd case where you're creating an Activity that will be started by another app (for example, one of the edit activities in a Tasker plugin) and therefore do not control the Intent
which launches the Activity
.
You can create a base-class Activity
that has a constructor with a parameter, then a derived class that has a default constructor which calls the base-class constructor with a value, as so:
class BaseActivity extends Activity
{
public BaseActivity(String param)
{
// Do something with param
}
}
class DerivedActivity extends BaseActivity
{
public DerivedActivity()
{
super("parameter");
}
}
If you need to generate the parameter to pass to the base-class constructor, simply replace the hard-coded value with a function call that returns the correct value to pass.
For a simple way, use system()
:
#include <stdlib.h>
...
int status = system("./foo 1 2 3");
system()
will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode: int exitcode = status / 256
).
The manpage for wait()
(in section 2, man 2 wait
on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would be WIFEXITED
and WEXITSTATUS
.
Alternatively, if you need to read foo's standard output, use popen(3)
, which returns a file pointer (FILE *
); interacting with the command's standard input/output is then the same as reading from or writing to a file.
Try this: Have a button/link which opens a webpage (in a new window) with just the pdf file embedded in it, and print the webpage.
In head of the main page:
<script type="text/javascript">
function printpdf()
{
myWindow=window.open("pdfwebpage.html");
myWindow.close; //optional, to close the new window as soon as it opens
//this ensures user doesn't have to close the pop-up manually
}
</script>
And in body of the main page:
<a href="printpdf()">Click to Print the PDF</a>
Inside pdfwebpage.html:
<html>
<head>
</head>
<body onload="window.print()">
<embed src="pdfhere.pdf"/>
</body>
</html>
NOBODY above explained/clarified terms to a novice user. They get confused by the terms
.hg/hgrc -- this file is used for Repository, at local/workspace location / in actual repository's .hg folder.
~/.hgrc -- this file is different than the below one. this file resides at ~ or home directory.
myremote.xxxx=..... bb.xxxx=......
This is one of the lines under [auth] section/directive, while using mercurial keyring extension. Make sure the server name you put there, matches with what you use while doing "hg clone" otherwise keyring will say, user not found. bb or myremote in the line below, are "alias name" that you MUST give while doing "hg clone http:/.../../repo1 bb or myremote" otherwise, it wont work or you have to make sure your local repository's .hg/hgrc file contain same alias, ie (what you gave while doing hg clone .. as last parameter).
PS the following links for clear details, sorry for quickly written grammar.
ex: If inside ~/.hgrc (user's home directory in Linux/Unix) or mercurial.ini in Windows at user's home directory, contains, the following line and if you do
`"hg clone http://.../.../reponame myremote"`
, then you'll never be prompted for user credentials more than once per http repo link. In ~/.hgrc under [extensions] a line for "mercurial_keyring = " or "hgext.mercurial_keyring = /path/to/your/mercurial_keyring.py" .. one of these lines should be there.
[auth]
myremote.schemes = http https
myremote.prefix = thsusncdnvm99/hg
myremote.username = c123456
I'm trying to find out how to set the PREFIX property so that user can clone or perform any Hg operations without username/password prompts and without worrying about what he mentioned in the http://..../... for servername while using the Hg repo link. It can be IP, servername or server's FQDN
@laconbass's answer helped me and is probably most correct.
I came here because I was using spawn incorrectly. As a simple example:
this is incorrect:
const s = cp.spawn('npm install -D suman', [], {
cwd: root
});
this is incorrect:
const s = cp.spawn('npm', ['install -D suman'], {
cwd: root
});
this is correct:
const s = cp.spawn('npm', ['install','-D','suman'], {
cwd: root
});
however, I recommend doing it this way:
const s = cp.spawn('bash');
s.stdin.end(`cd "${root}" && npm install -D suman`);
s.once('exit', code => {
// exit
});
this is because then the cp.on('exit', fn)
event will always fire, as long as bash is installed, otherwise, the cp.on('error', fn)
event might fire first, if we use it the first way, if we launch 'npm' directly.
You could create a user form:
It sounds like you need an OR instead:
<button type="submit" [disabled]="!validate || !SAForm.valid">Add</button>
This will disable the button if not validate or if not SAForm.valid.
I've built upon Ð?c Thanh Nguy?n's fantastic answer to allow this method to work with 64-bit versions of Excel. I'm running Excel 2010 64-Bit on 64-Bit Windows 7.
Create a new xlsm file and store this code in Module1
Option Explicit
Private Const PAGE_EXECUTE_READWRITE = &H40
Private Declare PtrSafe Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As LongPtr, Source As LongPtr, ByVal Length As LongPtr)
Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As LongPtr, _
ByVal dwSize As LongPtr, ByVal flNewProtect As LongPtr, lpflOldProtect As LongPtr) As LongPtr
Private Declare PtrSafe Function GetModuleHandleA Lib "kernel32" (ByVal lpModuleName As String) As LongPtr
Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, _
ByVal lpProcName As String) As LongPtr
Private Declare PtrSafe Function DialogBoxParam Lib "user32" Alias "DialogBoxParamA" (ByVal hInstance As LongPtr, _
ByVal pTemplateName As LongPtr, ByVal hWndParent As LongPtr, _
ByVal lpDialogFunc As LongPtr, ByVal dwInitParam As LongPtr) As Integer
Dim HookBytes(0 To 5) As Byte
Dim OriginBytes(0 To 5) As Byte
Dim pFunc As LongPtr
Dim Flag As Boolean
Private Function GetPtr(ByVal Value As LongPtr) As LongPtr
GetPtr = Value
End Function
Public Sub RecoverBytes()
If Flag Then MoveMemory ByVal pFunc, ByVal VarPtr(OriginBytes(0)), 6
End Sub
Public Function Hook() As Boolean
Dim TmpBytes(0 To 5) As Byte
Dim p As LongPtr
Dim OriginProtect As LongPtr
Hook = False
pFunc = GetProcAddress(GetModuleHandleA("user32.dll"), "DialogBoxParamA")
If VirtualProtect(ByVal pFunc, 6, PAGE_EXECUTE_READWRITE, OriginProtect) <> 0 Then
MoveMemory ByVal VarPtr(TmpBytes(0)), ByVal pFunc, 6
If TmpBytes(0) <> &H68 Then
MoveMemory ByVal VarPtr(OriginBytes(0)), ByVal pFunc, 6
p = GetPtr(AddressOf MyDialogBoxParam)
HookBytes(0) = &H68
MoveMemory ByVal VarPtr(HookBytes(1)), ByVal VarPtr(p), 4
HookBytes(5) = &HC3
MoveMemory ByVal pFunc, ByVal VarPtr(HookBytes(0)), 6
Flag = True
Hook = True
End If
End If
End Function
Private Function MyDialogBoxParam(ByVal hInstance As LongPtr, _
ByVal pTemplateName As LongPtr, ByVal hWndParent As LongPtr, _
ByVal lpDialogFunc As LongPtr, ByVal dwInitParam As LongPtr) As Integer
If pTemplateName = 4070 Then
MyDialogBoxParam = 1
Else
RecoverBytes
MyDialogBoxParam = DialogBoxParam(hInstance, pTemplateName, _
hWndParent, lpDialogFunc, dwInitParam)
Hook
End If
End Function
Paste this code in Module2 and run it
Sub unprotected()
If Hook Then
MsgBox "VBA Project is unprotected!", vbInformation, "*****"
End If
End Sub
DISCLAIMER This worked for me and I have documented it here in the hope it will help someone out. I have not fully tested it. Please be sure to save all open files before proceeding with this option.
Shortest Yet!
<button onclick="history.go(-1);">Go back</button>
I prefer the .go(-number)
method as then, for 1 or many 'backs' there's only 1 method to use/remember/update/search for, etc.
Also, using a tag for a back button seems more appropriate than tags with names and types...
If you get this from a Webserver, check out jQuery. You can load it, using the Ajax load function and select the node or text you want, using Selectors.
If you don't want to do this in a http environment or avoid using jQuery, please explain in greater detail.
If you've got tags (and you should), you can open a file from the command line just by the name of the class or method or c function, with "vim -t DBPlaylist", and within vim with ":tag ShowList".
You may also need to make database containing table active
use [dbname]
otherwise you may get error (even if you specify database i.e. dbname.table )
FAILED Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter partition. Unable to alter partitions because table or database does not exist.
Thanks for the plug of Simpl.css!
remember to wrap all your columns in ColumnWrapper
like so.
<div class="ColumnWrapper">
<div class="ColumnOneHalf">Tree</div>
<div class="ColumnOneHalf">View</div>
</div>
I am about to release version 1.0 of Simpl.css so help spread the word!
The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.
To test this fact:
// file: test.php
sleep(10);
die("alert('Done!');");
// HTML file:
<script type="text/javascript" src="test.php"></script>
Dynamically added scripts are executed as soon as they are appended to the document.
To test this fact:
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
var s = document.createElement('script');
s.type = "text/javascript";
s.src = "link.js"; // file contains alert("hello!");
document.body.appendChild(s);
alert("appended");
</script>
<script type="text/javascript">
alert("final");
</script>
</body>
</html>
Order of alerts is "appended" -> "hello!" -> "final"
If in a script you attempt to access an element that hasn't been reached yet (example: <script>do something with #blah</script><div id="blah"></div>
) then you will get an error.
Overall, yes you can include external scripts and then access their functions and variables, but only if you exit the current <script>
tag and start a new one.
In SQL you need to use GETDATE()
:
UPDATE table SET date = GETDATE();
There is no NOW()
function.
To answer your question:
In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.
So, if your requirement is to set it all to the same date I would do something like this (untested):
DECLARE @currDate DATETIME;
SET @currDate = GETDATE();
UPDATE table SET date = @currDate;
It is possible that you compiled your binary with incompatible architecture settings on your build host vs. your execution host. Can you please have a look at the enabled target settings via
g++ {all-your-build-flags-here} -Q -v --help=target
on your build host? In particular, the COLLECT_GCC_OPTIONS
variable may give you valuable debug info. Then have a look at the CPU capabilities on your execution host via
cat /proc/cpuinfo | grep -m1 flags
Look out for mismatches such as -msse4.2 [enabled]
on your build host but a missing sse4_2
flag in the CPU capabilities.
If that doesn't help, please provide the output of ldd commonKT
on both build and execution host.
Try changing to this line:
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, i, 0);
I had this problem as well and thought I'd share since I can't find my problem above.
This was my code
return RedirectToAction("Overview", model.Id);
Calling this ActionResult:
public ActionResult Overview(int id)
I assumed it would be smart enough to figure out that the value I pass it is the id paramter for Overview, but it's not. This fixed it:
return RedirectToAction("Overview", new {id = model.Id});
This problem started when I did 'Remove Unused References'. The website still worked on my local machine, but did not worked on the server after publishing.
I fixed this problem by doing the following,
Because Test discovery seems to be a complete subject, there is some dedicated framework to test discovery :
More reading here : https://wiki.python.org/moin/PythonTestingToolsTaxonomy
for me "I" was capital in "Images". which also angular-cli didn't like. so it is also case sensitive.
Some web servers like IIS don't have problem with that, if angular application is hosted in IIS, case sensitive is not a problem.
Android NDK official hello-libs
CMake example
Just worked for me on Ubuntu 17.10 host, Android Studio 3, Android SDK 26, so I strongly recommend that you base your project on it.
The shared library is called libgperf
, the key code parts are:
hello-libs/app/src/main/cpp/CMakeLists.txt:
// -L
add_library(lib_gperf SHARED IMPORTED)
set_target_properties(lib_gperf PROPERTIES IMPORTED_LOCATION
${distribution_DIR}/gperf/lib/${ANDROID_ABI}/libgperf.so)
// -I
target_include_directories(hello-libs PRIVATE
${distribution_DIR}/gperf/include)
// -lgperf
target_link_libraries(hello-libs
lib_gperf)
android {
sourceSets {
main {
// let gradle pack the shared library into apk
jniLibs.srcDirs = ['../distribution/gperf/lib']
Then, if you look under /data/app
on the device, libgperf.so
will be there as well.
on C++ code, use: #include <gperf.h>
header location: hello-libs/distribution/gperf/include/gperf.h
lib location: distribution/gperf/lib/arm64-v8a/libgperf.so
If you only support some architectures, see: Gradle Build NDK target only ARM
The example git tracks the prebuilt shared libraries, but it also contains the build system to actually build them as well: https://github.com/googlesamples/android-ndk/tree/840858984e1bb8a7fab37c1b7c571efbe7d6eb75/hello-libs/gen-libs
I think that myString is not a string but an array of strings. Here is what you need to do:
String myNewString = join(myString, "")
if (!myNewString.equals(""))
{
//Do something
}
You can use IndexOf()
like this:
string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
// The string exists in the original
}
Since 0 (zero) can be an index, you check against -1.
The zero-based index position of value if that string is found, or -1 if it is not. If value is String.Empty, the return value is 0.
static void Main(string[] args)
{
foreach (int value in Enum.GetValues(typeof(DaysOfWeek)))
{
Console.WriteLine(((DaysOfWeek)value).ToString());
}
foreach (string value in Enum.GetNames(typeof(DaysOfWeek)))
{
Console.WriteLine(value);
}
Console.ReadLine();
}
public enum DaysOfWeek
{
monday,
tuesday,
wednesday
}
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
Not sure what is the difference between .cfg & .cnf
In my server I couldn't find .cfg or .cnf
I had created a new file for the same and placed it in the following folder /usr/local/ssl/bin
executed the
.\openssl genrsa -des3 -out <key name>.key 2048
went great..
input { float: right; clear: both; }
If you want to find out how to set-up a non-native cross compile, I found this useful:
On the target machine,
% gcc -march=native -Q --help=target | grep march
-march= core-avx-i
Then use this on the build machine:
% gcc -march=core-avx-i ...
You can try this click event
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
Eid_txt.Text = row.Cells["Employee ID"].Value.ToString();
Name_txt.Text = row.Cells["First Name"].Value.ToString();
Surname_txt.Text = row.Cells["Last Name"].Value.ToString();
In order to restrict you just need to set the single line option on "true".
android:singleLine="true"
I had a similar issue which i solved by making two changes
added below entry in application.yaml file
spring:
jackson:
serialization.write_dates_as_timestamps: false
add below two annotations in pojo
sample example
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class Customer {
//your fields ...
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
protected LocalDate birthdate;
}
then the following json requests worked for me
{
"birthdate": "2019-11-28"
}
{
"birthdate":[2019,11,18]
}
Hope it helps!!
to switchto a frame:
driver.switchTo.frame("Frame_ID");
to switch to the default again.
driver.switchTo().defaultContent();
I know this is older, but wanted to contribute another possibly solution.
If you want to keep the project location, as I did, I found that copying the .project file from another project into the project's directory, then editing the .project file to name it properly, then choosing the Import Existing Projects into Workspace option worked for me.
In Windows, I used a file monitor to see what Eclipse was doing, and it was simply erroring out for some unknown reason when trying to create the .project file. So, I did that manually and it worked for me.
In Spring MVC, all incoming requests go through a single servlet. This servlet - DispatcherServlet
- is the front controller. Front controller is a typical design pattern in the web applications development. In this case, a single servlet receives all requests and transfers them to all other components of the application.
The task of the DispatcherServlet
is to send request to the specific Spring MVC controller.
Usually we have a lot of controllers and DispatcherServlet
refers to one of the following mappers in order to determine the target controller:
BeanNameUrlHandlerMapping
;ControllerBeanNameHandlerMapping
;ControllerClassNameHandlerMapping
;DefaultAnnotationHandlerMapping
;SimpleUrlHandlerMapping
.If no configuration is performed, the DispatcherServlet
uses BeanNameUrlHandlerMapping
and DefaultAnnotationHandlerMapping
by default.
When the target controller is identified, the DispatcherServlet
sends request to it. The controller performs some work according to the request
(or delegate it to the other objects), and returns back to the DispatcherServlet
with the Model and the name of the View.
The name of the View is only a logical name. This logical name is then used to search for the actual View (to avoid coupling with the controller and specific View). Then DispatcherServlet
refers to the ViewResolver
and maps the logical name of the View to the specific implementation of the View.
Some possible Implementations of the ViewResolver
are:
BeanNameViewResolver
;ContentNegotiatingViewResolver
;FreeMarkerViewResolver
;InternalResourceViewResolver
;JasperReportsViewResolver
;ResourceBundleViewResolver
;TilesViewResolver
;UrlBasedViewResolver
;VelocityLayoutViewResolver
;VelocityViewResolver
;XmlViewResolver
;XsltViewResolver
.When the DispatcherServlet
determines the view that will display the results it will be rendered as the response.
Finally, the DispatcherServlet
returns the Response
object back to the client.
I realize this is a belated answer, but looking through developer.android.com, it seems that the Toggle button would be ideal for your situation.
http://developer.android.com/guide/topics/ui/controls/togglebutton.html
And of course you can still use the other suggestions for having a background drawable to get a custom look you want.
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_button_background"
android:textOn="On"
android:textOff="Off"
/>
Now if you want to go with your final edit and have a "halo" effect around your buttons, you can use another custom selector to do just that.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" > <!-- selected -->
<shape>
<solid
android:color="@android:color/white" />
<stroke
android:width="3px"
android:color="@android:color/holo_blue_bright" />
<corners
android:radius="5dp" />
</shape>
</item>
<item> <!-- default -->
<shape>
<solid
android:color="@android:color/white" />
<stroke
android:width="1px"
android:color="@android:color/darker_gray" />
<corners
android:radius="5dp" />
</shape>
</item>
</selector>
Small performance test comparision for three solutions:
$(".link").prop('href',"https://example.com")
$(".link").attr('href',"https://example.com")
document.querySelector(".link").href="https://example.com";
Here you can perform test by yourself https://jsperf.com/a-href-js-change
We can read href values in following ways
let href = $(selector).prop('href');
let href = $(selector).attr('href');
let href = document.querySelector(".link").href;
Here you can perform test by yourself https://jsperf.com/a-href-js-read
gcc -dumpversion
-dumpversion
Print the compiler version (for example,3.0
) — and don't do anything else.
The same works for following compilers/aliases:
cc -dumpversion
g++ -dumpversion
clang -dumpversion
tcc -dumpversion
Be careful with automate parsing the GCC output:
--version
might be localized (e.g. to Russian, Chinese, etc.)--version
output will contain something like Android (5220042 based on r346389c) clang version 8.0.7
(it's real version string)Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
Nowadays with flexbox you can greatly simplify your code and only adjust 1 parameter as needed:
.pdflink:after {
content: url('/images/pdf.png');
display: inline-flex;
width: 10px;
}
Now you can just adjust the width of the element and the height will automatically adjust, increase/decrease the width until the height of the element is at the number you need.
Please add Settings under Properties for the Project and make use of them this way you have clean and easy configurable settings that can be configured as default
How To: Create a New Setting at Design Time
Update: after comments below
- Right + Click on project
- Add New Item
- Under Visual C# Items -> General
- Select Settings File
If my compiler is set to 32 bit, size_t
is nothing other than a typedef for unsigned int
. If my compiler is set to 64 bit, size_t
is nothing other than a typedef for unsigned long long
.
To rename a directory or file (I don't know much about complex cases, so there might be some caveats):
git filter-repo --path-rename OLD_NAME:NEW_NAME
To rename a directory in files that mention it (it's possible to use callbacks, but I don't know how):
git filter-repo --replace-text expressions.txt
expressions.txt
is a file filled with lines like literal:OLD_NAME==>NEW_NAME
(it's possible to use Python's RE with regex:
or glob with glob:
).
To rename a directory in messages of commits:
git-filter-repo --message-callback 'return message.replace(b"OLD_NAME", b"NEW_NAME")'
Python's regular expressions are also supported, but they must be written in Python, manually.
If the repository is original, without remote, you will have to add --force
to force a rewrite. (You may want to create a backup of your repository before doing this.)
If you do not want to preserve refs (they will be displayed in the branch history of Git GUI), you will have to add --replace-refs delete-no-add
.
math.log10 is fast but gives problem when your number is greater than 999999999999997. This is because the float have too many .9s, causing the result to round up.
The solution is to use a while counter method for numbers above that threshold.
To make this even faster, create 10^16, 10^17 so on so forth and store as variables in a list. That way, it is like a table lookup.
def getIntegerPlaces(theNumber):
if theNumber <= 999999999999997:
return int(math.log10(theNumber)) + 1
else:
counter = 15
while theNumber >= 10**counter:
counter += 1
return counter
If anyone came here looking for a simple method to scale/resize an image in Python, without using additional libraries, here's a very simple image resize function:
#simple image scaling to (nR x nC) size
def scale(im, nR, nC):
nR0 = len(im) # source number of rows
nC0 = len(im[0]) # source number of columns
return [[ im[int(nR0 * r / nR)][int(nC0 * c / nC)]
for c in range(nC)] for r in range(nR)]
Example usage: resizing a (30 x 30) image to (100 x 200):
import matplotlib.pyplot as plt
def sqr(x):
return x*x
def f(r, c, nR, nC):
return 1.0 if sqr(c - nC/2) + sqr(r - nR/2) < sqr(nC/4) else 0.0
# a red circle on a canvas of size (nR x nC)
def circ(nR, nC):
return [[ [f(r, c, nR, nC), 0, 0]
for c in range(nC)] for r in range(nR)]
plt.imshow(scale(circ(30, 30), 100, 200))
This works to shrink/scale images, and works fine with numpy arrays.
You can use a WScript
object and call the Sleep
method on it:
Set WScript = CreateObject("WScript.Shell")
WScript.Sleep 2000 'Sleeps for 2 seconds
Another option is to import and use the WinAPI function directly (only works in VBA, thanks @Helen):
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 2000
Made it.
from datetime import datetime
dateNow = datetime.now().strftime('%Y%m%d')
PHP Manual said :
w Numeric representation of the day of the week
You can therefore construct a date with mktime, and use in it date("w", $yourTime);
I encountered the same issue recently and I tried different values for "gcm_sender_id" based on the project ID. However, the "gcm_sender_id" value must be set to the "Project Number".
You can find this value under: Menu > IAM & Admin > Settings.
See screenshot: GCM Project Number
How about just > Format only cells that contain - in the drop down box select Blanks