In Cygwin, you can activate such feature by right-clicking the window. In the pop-up window, select Options... -> Mouse -> activate Clicks place command line cursor -> Apply.
From now on, simply clicking the left mouse button at some position within the command line will place the cursor there.
Thanks for your answers. I didn't understand what type of object "MyTable" was (in your answers) and the following code gave me the error shown below.
DataTable dt = ds.Tables[0];
var name = from r in dt
where r.ID == 0
select r.Name;
Could not find an implementation of the query pattern for source type 'System.Data.DataTable'. 'Where' not found
So I continued my googling and found something that does work:
var rowColl = ds.Tables[0].AsEnumerable();
string name = (from r in rowColl
where r.Field<int>("ID") == 0
select r.Field<string>("NAME")).First<string>();
What do you think?
None of the above worked for me. This is what finally worked for me:
1) Start Services (Type services in your start > search)
2) Look for Apache services.It was disabled in my case. Enabling it worked for me.
Some people have also reported duplicate listing of Apache services which has prevented it from starting. If that is the case, delete/disable one of the Apache services which corresponds to the wrong path.
A restart of XAMPP might be required.
You use the datetime.datetime.date()
method:
datetime.datetime.now().date()
Obviously, the expression above can (and should IMHO :) be written as:
datetime.date.today()
I had this same issue - I had just added the font-awesome cdn links - commenting out the bootstrap one below solved my issue.. didnt really troubleshoot it as the font awesome still worked -
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
Quick example:
On Ubuntu, if you are interested, for instance, in Gmail then open the Terminal and type:
nslookup -q=mx gmail.com
As well as the Require-Bundle form of dependency management (most similar to Maven's pom dependencies), it's also possible to have Import-Package dependencies. It's much easier to introduce circular dependencies with Import-Package than Require-Bundle, but YMMV.
Also, Eclipse projects have a 'project references' which says which other projects it depends on. Eclipse uses this at a high level to decide what projects to build, and in which order, so it's quite possible that your Manifest.MF lists everything correctly but the project references are out of whack. Right click on a project and then go to properties - you'll see which projects you depend on. If you're a text kind of person, open up the .project files and see which ones you depend on there - it's probable that a project cyclic link is being defined at that level instead (often caused when you have an A-B dependency and then flipped from B-A but without updating the .project references).
You can set triangle with position see this code for reference
.top-left-corner {
width: 0px;
height: 0px;
border-top: 0px solid transparent;
border-bottom: 55px solid transparent;
border-left: 55px solid #289006;
position: absolute;
left: 0px;
top: 0px;
}
your code compiles here fine (even with that line uncommented. had to change it to
num3 = 100000000000000000000;
to start getting the warning.
Had the same problem a few minutes ago, I was missing the 'Maven depencendies' library in my Deployment Assembly. I added it through the section 'Web Deployment Assembly' in Eclipse
You can do it by using below CSS:
table {
width: 100%;
table-layout: fixed;
}
th, td {
overflow: hidden;
width: 200px;
text-overflow: ellipsis;
white-space: nowrap;
}
Here is a StackBlitz Example
with Sample Data
You can specify how many times you want the previous item to match by using {min,max}
.
{[0-9]{1,3}:[0-9]{1,3}}
Also, you can use \d
for digits instead of [0-9]
for most regex flavors:
{\d{1,3}:\d{1,3}}
You may also want to consider escaping the outer {
and }
, just to make it clear that they are not part of a repetition definition.
If you want to return some value then wrap your statement in function
function my_function(){
return my_thing;
}
Problem is with the statement on the 1st line if you are trying to use PHP
var ask = confirm ('".$message."');
IF you are trying to use PHP you should use
var ask = confirm (<?php echo "'".$message."'" ?>); //now message with be the javascript string!!
You can cast datetime to time
select CAST(GETDATE() as time)
If you want a hh:mm format
select cast(CAST(GETDATE() as time) as varchar(5))
As far as I know you will need to give the domain account the proper "User Rights" such as "Log on as a Batch Job". You can check that in your Local Policies. Also, you might have a Domain GPO which is overwriting your local policies. I bet if you add this Domain Account into the local admin group of that machine, your problem will go away. A few articles for you to check:
http://social.technet.microsoft.com/Forums/en/windowsserver2008r2general/thread/9edcb63a-d133-45a0-9e8c-f1b774765531 http://social.technet.microsoft.com/Forums/lv/winservergen/thread/68019b24-78a5-4db0-a150-ada921930924 http://sqlsolace.blogspot.com/2009/08/task-scheduler-task-does-not-run-error.html?m=1 http://technet.microsoft.com/en-us/library/cc722152.aspx
Disable the button with setEnabled(false)
until it is safe for the user to click it again.
I'm surprised nobody has thought of using iter
's two-argument form:
from itertools import islice
def chunk(it, size):
it = iter(it)
return iter(lambda: tuple(islice(it, size)), ())
Demo:
>>> list(chunk(range(14), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13)]
This works with any iterable and produces output lazily. It returns tuples rather than iterators, but I think it has a certain elegance nonetheless. It also doesn't pad; if you want padding, a simple variation on the above will suffice:
from itertools import islice, chain, repeat
def chunk_pad(it, size, padval=None):
it = chain(iter(it), repeat(padval))
return iter(lambda: tuple(islice(it, size)), (padval,) * size)
Demo:
>>> list(chunk_pad(range(14), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, None)]
>>> list(chunk_pad(range(14), 3, 'a'))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 'a')]
Like the izip_longest
-based solutions, the above always pads. As far as I know, there's no one- or two-line itertools recipe for a function that optionally pads. By combining the above two approaches, this one comes pretty close:
_no_padding = object()
def chunk(it, size, padval=_no_padding):
if padval == _no_padding:
it = iter(it)
sentinel = ()
else:
it = chain(iter(it), repeat(padval))
sentinel = (padval,) * size
return iter(lambda: tuple(islice(it, size)), sentinel)
Demo:
>>> list(chunk(range(14), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13)]
>>> list(chunk(range(14), 3, None))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, None)]
>>> list(chunk(range(14), 3, 'a'))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 'a')]
I believe this is the shortest chunker proposed that offers optional padding.
As Tomasz Gandor observed, the two padding chunkers will stop unexpectedly if they encounter a long sequence of pad values. Here's a final variation that works around that problem in a reasonable way:
_no_padding = object()
def chunk(it, size, padval=_no_padding):
it = iter(it)
chunker = iter(lambda: tuple(islice(it, size)), ())
if padval == _no_padding:
yield from chunker
else:
for ch in chunker:
yield ch if len(ch) == size else ch + (padval,) * (size - len(ch))
Demo:
>>> list(chunk([1, 2, (), (), 5], 2))
[(1, 2), ((), ()), (5,)]
>>> list(chunk([1, 2, None, None, 5], 2, None))
[(1, 2), (None, None), (5, None)]
use
path_to_exe >> log_file
to see the output of your command also errors can be redirected with
path_to_exe &> log_file
also you can use
crontab -l
to check if your edits were saved.
Ctrl+Alt+? / ? add cursors above and below the current line. Still nowhere near as good as sublime or brackets though. I can't see anything equivalent to Ctrl+D in sublime in the keyboard shortcuts file.
Use namespace
using System.Collections.Specialized;
Make instance of DataContext
Class
LinqToSqlDataContext dc = new LinqToSqlDataContext();
Use
OrderedDictionary dict = dc.TableName.ToDictionary(d => d.key, d => d.value);
In order to retrieve the values use namespace
using System.Collections;
ICollection keyCollections = dict.Keys;
ICOllection valueCollections = dict.Values;
String[] myKeys = new String[dict.Count];
String[] myValues = new String[dict.Count];
keyCollections.CopyTo(myKeys,0);
valueCollections.CopyTo(myValues,0);
for(int i=0; i<dict.Count; i++)
{
Console.WriteLine("Key: " + myKeys[i] + "Value: " + myValues[i]);
}
Console.ReadKey();
If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before
//HTML
<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
<div class="morph-button morph-button-overlay morph-button-fixed">
<button id="user-interface" type="button">MORE INFO</button>
<!--a id="user-interface" href="javascript:void(0)">popup</a-->
<div class="morph-content">
<div>
<div class="content-style-overlay">
<span class="icon icon-close">Close the overlay</span>
<h2>About Parsley</h2>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
</div>
</div>
</div>
</div>
</div>
//CSS
/* Blur - doesn't work on IE */
.blur-on, .blur-element {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
-webkit-transition: all 5s linear;
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
.blur-off {
-webkit-filter: blur(0px) !important;
-moz-filter : blur(0px) !important;
-o-filter : blur(0px) !important;
-ms-filter : blur(0px) !important;
filter : blur(0px) !important;
}
.blur-bgimage:before {
content: "";
position: absolute;
height: 20%; width: 20%;
background-size: cover;
background: inherit;
z-index: -1;
transform: scale(5);
transform-origin: top left;
filter: blur(2px);
-moz-transform: scale(5);
-moz-transform-origin: top left;
-moz-filter: blur(2px);
-webkit-transform: scale(5);
-webkit-transform-origin: top left;
-webkit-filter: blur(2px);
-o-transform: scale(5);
-o-transform-origin: top left;
-o-filter: blur(2px);
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
//Javascript
function blurBehindPopup() {
if(blurredElements.length == 0) {
for(var i=0; i < document.body.children.length; i++) {
var element = document.body.children[i];
if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
classie.addClass( element, 'blur-element' );
blurredElements.push(element);
}
}
} else {
for(var i=0; i < blurredElements.length; i++) {
classie.addClass( blurredElements[i], 'blur-element' );
}
}
}
function unblurBehindPopup() {
for(var i=0; i < blurredElements.length; i++) {
classie.removeClass( blurredElements[i], 'blur-element' );
}
}
Knowledge of high level programming languages (C/C++, Java, PHP, Python, Perl, etc.) would suggest to the layman that Bourne Again Shell (Bash) functions should work like they do in those other languages.
Instead, Bash functions work like shell commands and expect arguments to be passed to them in the same way one might pass an option to a shell command (e.g. ls -l
). In effect, function arguments in Bash are treated as positional parameters ($1, $2..$9, ${10}, ${11}
, and so on). This is no surprise considering how getopts
works. Do not use parentheses to call a function in Bash.
(Note: I happen to be working on OpenSolaris at the moment.)
# Bash style declaration for all you PHP/JavaScript junkies. :-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
function backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# sh style declaration for the purist in you. ;-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# In the actual shell script
# $0 $1 $2
backupWebRoot ~/public/www/ webSite.tar.zip
Want to use names for variables? Just do something this.
local filename=$1 # The keyword declare can be used, but local is semantically more specific.
Be careful, though. If an argument to a function has a space in it, you may want to do this instead! Otherwise, $1
might not be what you think it is.
local filename="$1" # Just to be on the safe side. Although, if $1 was an integer, then what? Is that even possible? Humm.
Want to pass an array to a function?
callingSomeFunction "${someArray[@]}" # Expands to all array elements.
Inside the function, handle the arguments like this.
function callingSomeFunction ()
{
for value in "$@" # You want to use "$@" here, not "$*" !!!!!
do
:
done
}
Need to pass a value and an array, but still use "$@" inside the function?
function linearSearch ()
{
local myVar="$1"
shift 1 # Removes $1 from the parameter list
for value in "$@" # Represents the remaining parameters.
do
if [[ $value == $myVar ]]
then
echo -e "Found it!\t... after a while."
return 0
fi
done
return 1
}
linearSearch $someStringValue "${someArray[@]}"
Go for the second option, Edit the project to agree with the latest JDK
It's simple .First you should clear your collection and after clear list like this code :
yourCollection.clear();
setListAdapter(null);
mime-types starting with x-
are not standardized. In case of javascript it's kind of outdated.
Additional the second code snippet
<?Header('Content-Type: text/javascript');?>
requires short_open_tags
to be enabled. you should avoid it.
<?php Header('Content-Type: text/javascript');?>
However, the completely correct mime-type for javascript is
application/javascript
http://www.iana.org/assignments/media-types/application/index.html
You can use this.setResizable(false);
or frameObject.setResizable(false);
In Linux,
edit .bashrc
file and add the ANDROID_HOME
and PATH
variable,
export ANDROID_HOME=/usr/local/android-sdk-linux/
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platforms-tools
After saving .bashrc
file, run
source ~/.bashrc
then in type
android
in a terminal
if it will run, ANDROID_HOME
and PATH
is set,
if you get this message,
bash: /src/android-sdk/tools/android: Permission denied
then run
sudo chmod a+x /usr/local/android-sdk-linux/tools/android
otherwise you will get same error message
Error: Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.
NB: Use your android sdk installation path instead of /usr/local/android-sdk-linux/
If you have div next each other like this
<div id="1" style="float:left; margin-right:5px">
</div>
<div id="2" style="float:left">
</div>
This should work!
You can use length
:
if($("#one").length) { // 0 == false; >0 == true
alert('yes');
}
Using nodejs natively
var fs = require('fs')
var oldPath = 'old/path/file.txt'
var newPath = 'new/path/file.txt'
fs.rename(oldPath, newPath, function (err) {
if (err) throw err
console.log('Successfully renamed - AKA moved!')
})
(NOTE: "This will not work if you are crossing partitions or using a virtual filesystem not supporting moving files. [...]" – Flavien Volken Sep 2 '15 at 12:50")
In case anyone arrives looking for how to generate a relative path from the rails console
ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"
Or the controller
include ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"
This might help..!!!
SQLCMD -S SERVERNAME -E
Try this to Convert from Decimal to Hex
#include<stdio.h>
#include<conio.h>
int main(void)
{
int count=0,digit,n,i=0;
int hex[5];
clrscr();
printf("enter a number ");
scanf("%d",&n);
if(n<10)
{
printf("%d",n);
}
switch(n)
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("B");
break;
case 13:
printf("C");
break;
case 14:
printf("D");
break;
case 15:
printf("E");
break;
case 16:
printf("F");
break;
default:;
}
while(n>16)
{
digit=n%16;
hex[i]=digit;
i++;
count++;
n=n/16;
}
hex[i]=n;
for(i=count;i>=0;i--)
{
switch(hex[i])
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");
break;
case 15:
printf("F");
break;
default:
printf("%d",hex[i]);
}
}
getch();
return 0;
}
Synchronized normal method
equivalent to
Synchronized statement
(use this)
class A {
public synchronized void methodA() {
// all function code
}
equivalent to
public void methodA() {
synchronized(this) {
// all function code
}
}
}
Synchronized static method
equivalent to Synchronized statement
(use class)
class A {
public static synchronized void methodA() {
// all function code
}
equivalent to
public void methodA() {
synchronized(A.class) {
// all function code
}
}
}
Synchronized statement (using variable)
class A {
private Object lock1 = new Object();
public void methodA() {
synchronized(lock1 ) {
// all function code
}
}
}
For synchronized
, we have both Synchronized Methods
and Synchronized Statements
. However, Synchronized Methods
is similar to Synchronized Statements
so we just need to understand Synchronized Statements
.
=> Basically, we will have
synchronized(object or class) { // object/class use to provides the intrinsic lock
// code
}
Here is 2 think that help understanding synchronized
intrinsic lock
associated with it.synchronized statement
, it automatically acquires the intrinsic lock
for that synchronized statement's
object and releases it when the method returns. As long as a thread owns an intrinsic lock
, NO other thread can acquire the SAME lock => thread safe.=>
When a thread A
invokes synchronized(this){// code 1}
=> all the block code (inside class) where have synchronized(this)
and all synchronized normal method
(inside class) is locked because SAME lock. It will execute after thread A
unlock ("// code 1" finished).
This behavior is similar to synchronized(a variable){// code 1}
or synchronized(class)
.
SAME LOCK => lock (not depend on which method? or which statements?)
I prefer synchronized statements
because it is more extendable. Example, in future, you only need synchronized a part of method. Example, you have 2 synchronized method and it don't have any relevant to each other, however when a thread run a method, it will block the other method (it can prevent by use synchronized(a variable)
).
However, apply synchronized method is simple and the code look simple. For some class, there only 1 synchronized method, or all synchronized methods in the class in relevant to each other => we can use synchronized method
to make code shorter and easy to understand
(it not relevant to much to synchronized
, it is the different between object and class or none-static and static).
synchronized
or normal method or synchronized(this)
or synchronized(non-static variable)
it will synchronized base on each object instance. synchronized
or static method or synchronized(class)
or synchronized(static variable)
it will synchronized base on classhttps://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
Hope it help
There is no way you could do this 100% (i would say maybe 1-5% would be plausible) with nowdays knowledge. You would get much better result (than those 1-5%) just checking the image-names for sex-related-words :).
@SO Troll: So true.
According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:
{% if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') ) %}
<li>some text</li>
{% endif %}
Edit: Using line_statement_prefix = '#'
* the code would look like this:
# if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') )
<li>some text</li>
# endif
*Here's an example of how you'd specify the line_statement_prefix
in the Environment
:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml']),
line_statement_prefix='#'
)
Or using Flask:
from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'
Yes, you can. There are two options with comparing items, the Comparable interface, and the Comparator interface.
Both of these interfaces allow for different behavior. Comparable allows you to make the object act like you just described Strings (in fact, String implements Comparable). The second, Comparator, allows you to do what you are asking to do. You would do it like this:
Collections.sort(myArrayList, new MyComparator());
That will cause the Collections.sort method to use your comparator for it's sorting mechanism. If the objects in the ArrayList implement comparable, you can instead do something like this:
Collections.sort(myArrayList);
The Collections class contains a number of these useful, common tools.
Have you looked into querying INFORMATION_SCHEMA.Tables? As in
SELECT ic.Table_Name,
ic.Column_Name,
ic.data_Type,
IFNULL(Character_Maximum_Length,'') AS `Max`,
ic.Numeric_precision as `Precision`,
ic.numeric_scale as Scale,
ic.Character_Maximum_Length as VarCharSize,
ic.is_nullable as Nulls,
ic.ordinal_position as OrdinalPos,
ic.column_default as ColDefault,
ku.ordinal_position as PK,
kcu.constraint_name,
kcu.ordinal_position,
tc.constraint_type
FROM INFORMATION_SCHEMA.COLUMNS ic
left outer join INFORMATION_SCHEMA.key_column_usage ku
on ku.table_name = ic.table_name
and ku.column_name = ic.column_name
left outer join information_schema.key_column_usage kcu
on kcu.column_name = ic.column_name
and kcu.table_name = ic.table_name
left outer join information_schema.table_constraints tc
on kcu.constraint_name = tc.constraint_name
order by ic.table_name, ic.ordinal_position;
There are many great answers already on this question, but a lot of great libraries have come out since those answers were posted. This is intended as a kind of newbie-guide.
I will cover several use cases for performing network operations and a solution or two for each.
Typically Json, can be XML or something else
Let's say you are writing an app that lets users track stock prices, interest rates and currecy exchange rates. You find an Json API that looks something like this:
http://api.example.com/stocks //ResponseWrapper<String> object containing a list of Srings with ticker symbols
http://api.example.com/stocks/$symbol //Stock object
http://api.example.com/stocks/$symbol/prices //PriceHistory<Stock> object
http://api.example.com/currencies //ResponseWrapper<String> object containing a list of currency abbreviation
http://api.example.com/currencies/$currency //Currency object
http://api.example.com/currencies/$id1/values/$id2 //PriceHistory<Currency> object comparing the prices of the first currency (id1) to the second (id2)
This is an excellent choice for an API with multiple endpoints and allows you to declare the ReST endpoints instead of having to code them individually as with other libraries like ion or Volley. (website: http://square.github.io/retrofit/)
How do you use it with the finances API?
build.gradle
Add these lines to your Module level buid.gradle:
implementation 'com.squareup.retrofit2:retrofit:2.3.0' //retrofit library, current as of September 21, 2017
implementation 'com.squareup.retrofit2:converter-gson:2.3.0' //gson serialization and deserialization support for retrofit, version must match retrofit version
FinancesApi.java
public interface FinancesApi {
@GET("stocks")
Call<ResponseWrapper<String>> listStocks();
@GET("stocks/{symbol}")
Call<Stock> getStock(@Path("symbol")String tickerSymbol);
@GET("stocks/{symbol}/prices")
Call<PriceHistory<Stock>> getPriceHistory(@Path("symbol")String tickerSymbol);
@GET("currencies")
Call<ResponseWrapper<String>> listCurrencies();
@GET("currencies/{symbol}")
Call<Currency> getCurrency(@Path("symbol")String currencySymbol);
@GET("currencies/{symbol}/values/{compare_symbol}")
Call<PriceHistory<Currency>> getComparativeHistory(@Path("symbol")String currency, @Path("compare_symbol")String currencyToPriceAgainst);
}
FinancesApiBuilder
public class FinancesApiBuilder {
public static FinancesApi build(String baseUrl){
return new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(FinancesApi.class);
}
}
FinancesFragment snippet
FinancesApi api = FinancesApiBuilder.build("http://api.example.com/"); //trailing '/' required for predictable behavior
api.getStock("INTC").enqueue(new Callback<Stock>(){
@Override
public void onResponse(Call<Stock> stockCall, Response<Stock> stockResponse){
Stock stock = stockCall.body();
//do something with the stock
}
@Override
public void onResponse(Call<Stock> stockCall, Throwable t){
//something bad happened
}
}
If your API requires an API Key or other header like a user token, etc. to be sent, Retrofit makes this easy (see this awesome answer for details: https://stackoverflow.com/a/42899766/1024412).
Let's say you're building a "mood weather" app that looks up the users GPS location and checks the current temperature in that area and tells them the mood. This type of app doesn't need to declare API endpoints; it just needs to be able to access one API endpoint.
This is a great library for this type of access.
Please read msysmilu's great answer (https://stackoverflow.com/a/28559884/1024412)
Volley can also be used for ReST APIs, but due to the more complicated setup required I prefer to use Retrofit from Square as above (http://square.github.io/retrofit/)
Let's say you are building a social networking app and want to load profile pictures of friends.
build.gradle
Add this line to your Module level buid.gradle:
implementation 'com.android.volley:volley:1.0.0'
ImageFetch.java
Volley requires more setup than Retrofit. You will need to create a class like this to setup a RequestQueue, an ImageLoader and an ImageCache, but it's not too bad:
public class ImageFetch {
private static ImageLoader imageLoader = null;
private static RequestQueue imageQueue = null;
public static ImageLoader getImageLoader(Context ctx){
if(imageLoader == null){
if(imageQueue == null){
imageQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
imageLoader = new ImageLoader(imageQueue, new ImageLoader.ImageCache() {
Map<String, Bitmap> cache = new HashMap<String, Bitmap>();
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
return imageLoader;
}
}
user_view_dialog.xml
Add the following to your layout xml file to add an image:
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/profile_picture"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:srcCompat="@android:drawable/spinner_background"/>
UserViewDialog.java
Add the following code to the onCreate method (Fragment, Activity) or the constructor (Dialog):
NetworkImageView profilePicture = view.findViewById(R.id.profile_picture);
profilePicture.setImageUrl("http://example.com/users/images/profile.jpg", ImageFetch.getImageLoader(getContext());
Another excellent library from Square. Please see the site for some great examples: http://square.github.io/picasso/
myOptions = {
center: myLatlng,
minZoom: 6,
maxZoom: 9,
styles: customStyles,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
You have to use a negative lookahead assertion.
(?!^ABC$)
You could for example use the following.
(?!^ABC$)(^.*$)
If this does not work in your editor, try this. It is tested to work in ruby and javascript:
^((?!ABC).)*$
You can use:
npm show {pkg} version
(so npm show express version
will return now 3.0.0rc3
).
Check for session is new.
HttpSession session = request.getSession(false);
if (!session.isNew()) {
// Session is valid
}
else {
//Session has expired - redirect to login.jsp
}
The easiest way to accomplish this on android is by adding the following code to your custom style :
@android:color/transparent
If you need to insert into a specific position in the array, you can do this:
case ADD_ITEM :
return {
...state,
arr: [
...state.arr.slice(0, action.pos),
action.newItem,
...state.arr.slice(action.pos),
],
}
try this in javascript
document.getElementById("22IdMObileFull").text ="itsClicked"
The STAThreadAttribute
is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.
MSDN explains the reason in slightly more detail:
STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.
This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).
You need to use the square brackets notation to have values sent as an array:
<form method='post' id='userform' action='thisform.php'>
<tr>
<td>Trouble Type</td>
<td>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
</td>
</tr>
</table>
<input type='submit' class='buttons'>
</form>
Please note though, that only the values of only checked checkboxes will be sent.
((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\.[a-zA-Z]+
check here:- https://www.freeformatter.com/java-regex-tester.html#ad-output
It sorts out theses entries correctly
There are 2 ways to run Selenium python tests in Google Chrome. I'm considering Windows (Windows 10 in my case):
Prerequisite: Download the latest Chrome Driver from: https://sites.google.com/a/chromium.org/chromedriver/downloads
Way 1:
i) Extract the downloaded zip file in a directory/location of your choice
ii) Set the executable path in your code as below:
self.driver = webdriver.Chrome(executable_path='D:\Selenium_RiponAlWasim\Drivers\chromedriver_win32\chromedriver.exe')
Way 2:
i) Simply paste the chromedriver.exe under /Python/Scripts/ (In my case the folder was: C:\Python36\Scripts)
ii) Now write the simple code as below:
self.driver = webdriver.Chrome()
Hijacking a bit to add what ended up working for me:
Go into the Maven Projects
sidebar on the right edge of the IDE, and verify that your dependencies are listed correctly under your module there. Assuming they are, just ask IDEA to reimport then (the first button at the top, looks like two blue arrows forming a counter-clockwise circle).
Once I did that, and let IDEA reload the project for me, all my dependencies were magically understood.
For reference: this was with IDEA 13.1.2
You can also disable the menu items through the backend, without having to touch any code. Go into:
System > Configuration > Advanced
You'll be presented with a long list of options. Here are some of the key modules to set to 'Disabled' :
Mage_Downloadable -> My Downloadable Products
Mage_Newsletter -> My Newsletter
Mage_Review -> My Reviews
Mage_Tag -> My Tags
Mage_Wishlist -> My Wishlist
I also disabled Mage_Poll, as it has a tendency to show up in other page templates and can be annoying if you're not using it.
From definition of IGrouping :
IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable
you can just iterate through elements like this:
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}
As @qiao said, you can't use __dirname
in the node repl. However, if you need need this value in the console, you can use path.resolve()
or path.dirname()
. Although, path.dirname()
will just give you a "." so, probably not that helpful. Be sure to require('path')
.
Using interface
as message constant is generally a bad idea. It will leak into client program permanently as part of exported API. Who knows, that later client programmers might parse that error messages(public) as part of their program.
You will be locked forever to support this, as changes in string format will/may break client program.
If you are using ES6 syntax you can use the spread operator to add new items to an existing array as a one liner.
// Append an array
const newArr = [1,2,3,4]
this.setState(prevState => ({
arr: [...prevState.arr, ...newArr]
}));
// Append a single item
this.setState(prevState => ({
arr: [...prevState.arr, 'new item']
}));
You need to add that folder to your Windows Path:
https://docs.python.org/2/using/windows.html Taken from this question.
This code works very well
function isUndefined(array, index) {
return ((String(array[index]) == "undefined") ? "Yes" : "No");
}
As Michael said:
and
Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).
It is not an issue it is because of caching...
To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products')
.
After timestamp it should be axios.get(/api/products?${Date.now()}
.
It will resolve your 304 status code.
git stash save
is deprecated as of 2.15.x/2.16, instead you can use git stash push -m "message"
You can use it like this:
git stash push -m "message"
where "message" is your note for that stash.
In order to retrieve the stash you can use: git stash list
. This will output a list like this, for example:
stash@{0}: On develop: perf-spike
stash@{1}: On develop: node v10
Then you simply use apply
giving it the stash@{index}
:
git stash apply stash@{1}
References git stash man page
MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.
INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct,
t.inact, t.inadur, t.inadist,
t.smlct, t.smldur, t.smldist,
t.larct, t.lardur, t.lardist,
t.emptyct, t.emptydur
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...
your initial request is "I have a large PDF file that is a floor map for a building. "
I am afraid to tell you this might be harder than you guess.
Cause the last known lib everyones use to parse pdf is smalot, and this one is known to encounter issue regarding large file.
Here too, Lookig for a real php lib to parse pdf, without any memory peak that need a php configuration to disable memory limit as lot of "developers" does (which I guess is really not advisable).
see this post for more details about smalot performance : https://github.com/smalot/pdfparser/issues/163
Change
int wordLength = wordLengthFunction(string word);
to
int wordLength = wordLengthFunction(word);
make sure you're using the newest jquery, and problem solved
I met this problem with this code:
<script src="/scripts/plugins/jquery/jquery-1.6.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>
After change it to this:
<script src="/scripts/plugins/jquery/jquery-1.7.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>
It works fine
@kit's answer is okay, but remember to add ROUTER_PROVIDERS
to providers in the component. Then you can redirect to another page within ngOnInit
method:
import {Component, OnInit} from 'angular2/core';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'
@Component({
selector: 'loginForm',
templateUrl: 'login.html',
providers: [ROUTER_PROVIDERS]
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.navigate(['./SomewhereElse']);
}
}
To check if a folder exists or not, you can simply use the exists()
method:
// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )
// If it doesn't exist
if( !folder.exists() ) {
// Create all folders up-to and including B
folder.mkdirs()
}
// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
w << "Some text\n"
}
As the others said, you can use Firebug, and that will sort you out no worries on Firefox. Chrome & Safari both have a built-in developer console which has an almost identical interface to Firebug's console, so your code should be portable across those browsers. For other browsers, there's Firebug Lite.
If Firebug isn't an option for you, then try this simple script:
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
I'd recommend against alerting each individual property: some objects have a LOT of properties and you'll be there all day clicking "OK", "OK", "OK", "O... dammit that was the property I was looking for".
children()
only looks at the immediate children of the node, while find()
traverses the entire DOM below the node, so children()
should be faster given equivalent implementations. However, find()
uses native browser methods, while children()
uses JavaScript interpreted in the browser. In my experiments there isn't much performance difference in typical cases.
Which to use depends on whether you only want to consider the immediate descendants or all nodes below this one in the DOM, i.e., choose the appropriate method based on the results you desire, not the speed of the method. If performance is truly an issue, then experiment to find the best solution and use that (or see some of the benchmarks in the other answers here).
You can use WebClient to download the html for any url. Once you have the html, you can use a third-party library like HtmlAgilityPack to lookup values in the html as in below code -
public static string GetInnerHtmlFromDiv(string url)
{
string HTML;
using (var wc = new WebClient())
{
HTML = wc.DownloadString(url);
}
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(HTML);
HtmlNode element = doc.DocumentNode.SelectSingleNode("//div[@id='<div id here>']");
if (element != null)
{
return element.InnerHtml.ToString();
}
return null;
}
Use break?
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
I use this function htmlentities($string):
$msg = "<script>alert("hello")</script> <h1> Hello World </h1>" $msg = htmlentities($msg); echo $msg;
It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.
This is the code for the character you posted in your question: 
But that's not a checkbox character...
To call a specific exception such as FileNotFoundException use this format
if (-not (Test-Path $file))
{
throw [System.IO.FileNotFoundException] "$file not found."
}
To throw a general exception use the throw command followed by a string.
throw "Error trying to do a task"
When used inside a catch, you can provide additional information about what triggered the error
Use 0 for true and 1 for false.
Sample:
#!/bin/bash
isdirectory() {
if [ -d "$1" ]
then
# 0 = true
return 0
else
# 1 = false
return 1
fi
}
if isdirectory $1; then echo "is directory"; else echo "nopes"; fi
Edit
From @amichair's comment, these are also possible
isdirectory() {
if [ -d "$1" ]
then
true
else
false
fi
}
isdirectory() {
[ -d "$1" ]
}
The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. You may use them, but if you must you need to have whitespace between them.
Alternatively:
while [ $stats -gt 300 ] || [ $stats -eq 0 ]
On small device : 4 columns x 3 (= 12) ==> col-sm-3
On extra small : 3 columns x 4 (= 12) ==> col-xs-4
<footer class="row">
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 1</li>
<li>Text 2</li>
<li>Text 3</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 4</li>
<li>Text 5</li>
<li>Text 6</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 7</li>
<li>Text 8</li>
<li>Text 9</li>
</ul>
</nav>
<nav class="hidden-xs col-sm-3">
<ul class="list-unstyled">
<li>Text 10</li>
<li>Text 11</li>
<li>Text 12</li>
</ul>
</nav>
</footer>
As you say, hidden-xs is not enough, you have to combine xs and sm class.
Here is links to the official doc about available responsive classes and about the grid system.
Have in head :
onclick
propertySuppose you added your click event inline, like this :
<button id="myButton" onclick="alert('test')">Married</button>
Then, you can remove the event like this :
$("#myButton").prop('onclick', null); // Removes 'onclick' property if found
click
event listenersSuppose you added your click event by defining an event listener, like this :
$("button").on("click", function() { alert("clicked!"); });
... or like this:
$("button").click(function() { alert("clicked!"); });
Then, you can remove the event like this :
$("#myButton").off('click'); // Removes other events if found
If you're uncertain how your event has been added, you can combine both, like this :
$("#myButton").prop('onclick', null) // Removes 'onclick' property if found
.off('click'); // Removes other events if found
Know your host ip address on your lan Open cmd and type ipconfig and the if xampp the default listen port would be 80 Then for instance if 10.0.0.5 is your host ip address Type 10.0.0.5:80 from your mobile's web browser Make sure that both are connected to the same LAN However the default port that webaddress tries is 80.
The files managed by git are shown by git ls-files
. Check out its manual page.
On a related note: the java compiler uses int to represent boolean since JVM has a limited support for the boolean type.See Section 3.3.4 The boolean type.
In JVM, the integer zero represents false, and any non-zero integer represents true (Source : Inside Java Virtual Machine by Bill Venners)
Don't go inside mysql
, just open Command prompt and directly type this:
mysqldump -u [uname] -p[pass] db_name > db_backup.sql
You could write this as a psql script, e.g.,
START TRANSACTION;
CREATE TABLE ...
CREATE TABLE ...
COMMIT;
\echo 'Task completed sucessfully.'
and run with
psql -f somefile.sql
Raising errors with parameters isn't possible in PostgreSQL directly. When porting such code, some people encode the necessary information in the error string and parse it out if necessary.
It all works a bit differently, so be prepared to relearn/rethink/rewrite a lot of things.
In a SQL Server trigger you have available two psdeuotables called inserted and deleted. These contain the old and new values of the record.
So within the trigger (you can look up the create trigger parts easily) you would do something like this:
Insert table2 (user_id, user_name)
select user_id, user_name from inserted i
left join table2 t on i.user_id = t.userid
where t.user_id is null
When writing triggers remember they act once on the whole batch of information, they do not process row-by-row. So account for multiple row inserts in your code.
That really depends on if you expect to find the object, or not. If you follow the school of thought that exceptions should be used for indicating something, well, err, exceptional has occured then:
Otherwise, return null.
Easy:
print "$_ $h{$_}\n" for (keys %h);
Elegant, but actually 30% slower (!):
while (my ($k,$v)=each %h){print "$k $v\n"}
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.Use Array list http://developer.android.com/reference/java/util/ArrayList.html
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyClass
{
public static void main(String args[])
{
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
String dateInString = "Wed Mar 14 15:30:00 EET 2018";
SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatterOut.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
here is your Date object date and the output is :
Wed Mar 14 13:30:00 UTC 2018
14 Mar 2018
<!--
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:[email protected])
CREATE TABLE `images` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`image` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB ;
-->
<!-- this form is user to store images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />
<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>
<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
mysql_connect("", "", "") OR DIE (mysql_error());
mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
header("location:search.php");
}
//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
$name=$_POST['image_name'];
$email=$_POST['mail'];
$fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
}
// our sql query
$sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
mysql_query($sql) or die("Error in Query insert: " . mysql_error());
}
?>
<?php
//SEARCH.PHP PAGE
//connect to database.db name = images
mysql_connect("localhost", "root", "") OR DIE (mysql_error());
mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database
$msg="";
$sql="select * from images";
if(mysql_query($sql))
{
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$id=$row['id'];
$name=$row['name'];
$image=$row['image'];
$msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " /> </a>';
}
}
else
$msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>
In my case, another developer had removed some of the tables from the underlying database. When I realised this, and removed these tables from the entity, the problem was solved. Wasn't as obvious as it sounds.
Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:
window.parent.$("#serverMsg")
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?
) as the request body.
This requires Content-Type
and Content-Length
headers, so the receiving server knows how to interpret the incoming data. (*)
var querystring = require('querystring');
var http = require('http');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded
for the traditional format that a standard HTML form would use.
It's easy to send JSON (application/json
) in exactly the same manner; just JSON.stringify()
the data beforehand.
URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.
The bottom line is: The server must be able to interpret the content type in question. It could be text/plain
or anything else; there is no need to convert data if the receiving server understands it as it is.
Add a charset parameter (e.g. application/json; charset=Windows-1252
) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.
The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY
property value of the BindingProvider
(every proxy implements javax.xml.ws.BindingProvider
interface):
...
EchoService service = new EchoService();
Echo port = service.getEchoPort();
/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
System.out.println("Server said: " + echo.echo(args[0]));
...
The drawback is that this only works when the original WSDL is still accessible. Not recommended.
The second option is to get the endpoint URL from the WSDL.
...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService");
EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();
System.out.println("Server said: " + echo.echo(args[0]));
...
Not all HTML and CSS is supported by Microsoft Office products, Outlook in particular; take a look here for reference on supported elements for what you can and can't use in Outlook when rendering HTML.
Specifically, from that link it doesn't state the background
CSS property is supported for div
elements. You might have to use an img
and do some hacky layering.
Note that in your second example you have a quote mismatch, which won't help any.
Lastly and something I just came across at the link provided is the Outlook HTML and CSS Validator tool - you could try running that against your newsletter markup and see if it gives you any suggestions/alternatives.
We cant connect to iPhones normally by bluetooth.it is so difficult.so,please try any other file transfers like zapya,xender.it seems good
For Oracle:
select EXTRACT(month from DATE_CREATED), sum(Num_of_Pictures)
from pictures_table
group by EXTRACT(month from DATE_CREATED);
Let's call keys
the list/iterator of keys that you are given to remove. I'd do this:
keys_to_remove = set(keys).intersection(set(mydict.keys()))
for key in keys_to_remove:
del mydict[key]
You calculate up front all the affected items and operate on them.
I prefer to create a new dictionary over mutating an existing one, so I would probably also consider this:
keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: v for k, v in mydict.iteritems() if k in keys_to_keep}
or:
keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: mydict[k] for k in keys_to_keep}
I solve this issues looking for the name that I passed on my request
I was sending on body:
{thumbbail: <myimg>}
and I was expect to:
upload.single('thumbnail')
so, I fix the name that a send on request
I had this issue with sites running on XAMPP with private hostnames. Not so private, it turns out! They were all domain.dev
, which Google has now registered as a private gTLD, and is forcing HSTS at the domain level. Changed every virtual host to .devel
(eugh), restarted Apache and all is now well.
I created a little library functionality to solve these problems:
Instead of:
public T DifficultCalculation<T>(T a, T b)
{
T result = a * b + a; // <== WILL NOT COMPILE!
return result;
}
Console.WriteLine(DifficultCalculation(2, 3)); // Should result in 8.
You could write:
public T DifficultCalculation<T>(Number<T> a, Number<T> b)
{
Number<T> result = a * b + a;
return (T)result;
}
Console.WriteLine(DifficultCalculation(2, 3)); // Results in 8.
You can find the source code here: https://codereview.stackexchange.com/questions/26022/improvement-requested-for-generic-calculator-and-generic-number
Here is a sample for ISO-8859-9;
protected void btnKaydet_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformatsofficedocument.wordprocessingml.documet";
Response.AddHeader("Content-Disposition", "attachment; filename=XXXX.doc");
Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-9");
Response.Charset = "ISO-8859-9";
EnableViewState = false;
StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);
form1.RenderControl(html);
byte[] bytesInStream = Encoding.GetEncoding("iso-8859-9").GetBytes(writer.ToString());
MemoryStream memoryStream = new MemoryStream(bytesInStream);
string msgBody = "";
string Email = "[email protected]";
SmtpClient client = new SmtpClient("mail.xxxxx.org");
MailMessage message = new MailMessage(Email, "[email protected]", "ONLINE APP FORM WITH WORD DOC", msgBody);
Attachment att = new Attachment(memoryStream, "XXXX.doc", "application/vnd.openxmlformatsofficedocument.wordprocessingml.documet");
message.Attachments.Add(att);
message.BodyEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
client.Send(message);}
Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.
Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.
Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.
Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.
export default function useGoogleMapMarker(props) {
const [marker, setMarker] = useState();
useEffect(() => {
// ...code
const marker = new maps.Marker({ position, map, title, icon });
// ...code
setMarker(marker);
return () => marker.setMap(null); // to remove markers when unmounts
}, []);
return marker;
}
Hey is better than Apache Bench, has fewer issues with SSL
./hey https://google.com -more
Summary:
Total: 3.0960 secs
Slowest: 1.6052 secs
Fastest: 0.4063 secs
Average: 0.6773 secs
Requests/sec: 64.5992
Response time histogram:
0.406 [1] |
0.526 [142] |????????????????????????????????????????
0.646 [1] |
0.766 [6] |??
0.886 [0] |
1.006 [0] |
1.126 [0] |
1.246 [12] |???
1.365 [32] |?????????
1.485 [5] |?
1.605 [1] |
Latency distribution:
10% in 0.4265 secs
25% in 0.4505 secs
50% in 0.4838 secs
75% in 1.2181 secs
90% in 1.2869 secs
95% in 1.3384 secs
99% in 1.4085 secs
Details (average, fastest, slowest):
DNS+dialup: 0.1150 secs, 0.0000 secs, 0.4849 secs
DNS-lookup: 0.0032 secs, 0.0000 secs, 0.0319 secs
req write: 0.0001 secs, 0.0000 secs, 0.0007 secs
resp wait: 0.2068 secs, 0.1690 secs, 0.4906 secs
resp read: 0.0117 secs, 0.0011 secs, 0.2375 secs
Status code distribution:
[200] 200 responses
Working demo:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
onload = function(){
var divg = document.createElement("div");
divg.appendChild(document.createTextNode("New DIV"));
document.body.appendChild(divg);
};
</script>
</head>
<body>
</body>
</html>
This exact question is answered on mySql workbench-faq:
Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.
That means hover over an acronym in the mySql Workbench table editor.
If you're looking for just the instance variables in the object, this might be useful:
obj.instance_variables.map do |var|
puts [var, obj.instance_variable_get(var)].join(":")
end
or as a one-liner for copy and pasting:
obj.instance_variables.map{|var| puts [var, obj.instance_variable_get(var)].join(":")}
var wordCount =
from word in words
group word by word into g
select new { g.Key, Count = g.Count() };
This is taken from one of the examples in the linqpad
numpy.append
is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append
is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:
import numpy
old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]
I think you might be able to achieve your goal by doing something like:
result = numpy.zeros((10,))
result[0:2] = [1, 2]
# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]
Update:
If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:
import numpy as np
a = np.array([0., 1.])
b = np.array([2., 3.])
temp = []
while True:
rnd = random.randint(0, 100)
if rnd > 50:
temp.append(a)
else:
temp.append(b)
if rnd == 0:
break
result = np.array(temp)
In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.
new update
The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b)
the shapes of a
and b
need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.
Another option altogether is to detach the database via Management Studio. Then simply delete the log file, or rename it and delete later.
Back in Management Studio attach the database again. In the attach window remove the log file from list of files.
The DB attaches and creates a new empty log file. After you check everything is all right, you can delete the renamed log file.
You probably ought not use this for production databases.
You could try this code:
private float GetBrightestColor(float r, float g, float b) {
if (r > g && r > b) {
return r;
} else if (g > r && g > b) {
return g;
} else if (b > r && b > g) {
return b;
}
}
Use this:
echo "${@:2}"
The following syntax:
echo "${*:2}"
would work as well, but is not recommended, because as @Gordon already explained, that using *
, it runs all of the arguments together as a single argument with spaces, while @
preserves the breaks between them (even if some of the arguments themselves contain spaces). It doesn't make the difference with echo
, but it matters for many other commands.
On centos 7, I just do
sudo yum install java-sdk
I assume you have most common repo already. Centos just finds the correct SDK with the -devel sufix.
Quick and easy:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
Or, if you want a jQuery plugin:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();
Some explanation ignore a condition about the retain cycle [If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from outside the group.] For more information, read the document
If you want to ensure only that class will match then use getClass() ==
. If you want to match subclasses then instanceof
is needed.
Also, instanceof will not match against a null but is safe to compare against a null. So you don't have to null check it.
if ( ! (obj instanceof MyClass) ) { return false; }
// on your branch that holds the commit you want to pass
$ git log
// copy the commit hash found
$ git checkout [branch that will copy the commit]
$ git reset --hard [hash of the commit you want to copy from the other branch]
// remove the [brackets]
Other more useful commands here with explanation: Git Guide
I have MinGW and also mingw32-make.exe in my bin in the C:\MinGW\bin . same other I add bin path to my windows path. After that I change it's name to make.exe . Now I can Just write command "make" in my Makefile direction and execute my Makefile same as Linux.
My way to go (when there is no appropiate way to insert special chars) via CSS:
-ms-word-break: break-all;
word-break: break-all;
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;
As found here: http://kenneth.io/blog/2012/03/04/word-wrapping-hypernation-using-css/ with some additional research to be found there.
command to remove cordova and ionic
sudo npm uninstall -g ionic
you would need to first open your file in read format, save it to a variable, then open the second file in write format where you would write or append the variable using a the [::-1] slice, completely reversing the file. You can also use readlines() to make it into a list of lines, which you can manipulate
def copy_and_reverse(filename, newfile):
with open(filename) as file:
text = file.read()
with open(newfile, "w") as file2:
file2.write(text[::-1])
Including the implementation file (test.c
) causes it to be prepended to your main.c and complied there and then again separately. So, the function test
has two definitions -- one in the object code of main.c
and once in that of test.c
, which gives you a ODR violation. You need to create a header file containing the declaration of test
and include it in main.c
:
/* test.h */
#ifndef TEST_H
#define TEST_H
void test(); /* declaration */
#endif /* TEST_H */
One thing you might want to look at is the Commons DBCP project. It provides a BasicDataSource that is configured fairly similarly to your example. To use that you need the database vendor's JDBC JAR in your classpath and you have to specify the vendor's driver class name and the database URL in the proper format.
Edit:
If you want to configure a BasicDataSource
for MySQL, you would do something like this:
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");
Code that needs a DataSource
can then use that.
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
Check this plugin WP Media Folder at Joomunited, you can:
Since the last months they add a lot of must use features.
This is a paid plugin but it worth the money, I install it now by default on all my customers websites.
Another option is to use a multi-stage docker build to ensure that your SSH keys are not included in the final image.
As described in my post you can prepare your intermediate image with the required dependencies to git clone and then COPY
the required files into your final image.
Additionally if we LABEL
our intermediate layers, we can even delete them from the machine when finished.
# Choose and name our temporary image.
FROM alpine as intermediate
# Add metadata identifying these images as our build containers (this will be useful later!)
LABEL stage=intermediate
# Take an SSH key as a build argument.
ARG SSH_KEY
# Install dependencies required to git clone.
RUN apk update && \
apk add --update git && \
apk add --update openssh
# 1. Create the SSH directory.
# 2. Populate the private key file.
# 3. Set the required permissions.
# 4. Add github to our list of known hosts for ssh.
RUN mkdir -p /root/.ssh/ && \
echo "$SSH_KEY" > /root/.ssh/id_rsa && \
chmod -R 600 /root/.ssh/ && \
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
# Clone a repository (my website in this case)
RUN git clone [email protected]:janakerman/janakerman.git
# Choose the base image for our final image
FROM alpine
# Copy across the files from our `intermediate` container
RUN mkdir files
COPY --from=intermediate /janakerman/README.md /files/README.md
We can then build:
MY_KEY=$(cat ~/.ssh/id_rsa)
docker build --build-arg SSH_KEY="$MY_KEY" --tag clone-example .
Prove our SSH keys are gone:
docker run -ti --rm clone-example cat /root/.ssh/id_rsa
Clean intermediate images from the build machine:
docker rmi -f $(docker images -q --filter label=stage=intermediate)
Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository
in your settings.xml
or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.
A workaround is as follows. In the value:
releases::default::https://YOUR_NEXUS_URL/releases
you need to remove the default
section, making it:
releases::https://YOUR_NEXUS_URL/releases
The prior version 2.8.2 does not have this bug.
Wrap your all statements in !IsPostBack
condition on page load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// all statements
}
}
This will fix your issue.
You can use new Date().getTimezoneOffset()/60
for the timezone. There is also a toLocaleString()
method for displaying a date using the user's locale.
Here's the whole list: Working with Dates
Put it in a TRY/CATCH
.
When RAISERROR is run with a severity of 11 or higher in a TRY block, it transfers control to the associated CATCH block
Reference: MSDN.
EDIT: This works for MSSQL 2005+, but I see that you now have clarified that you are working on MSSQL 2000. I'll leave this here for reference.
remote server> cd /home/ec2-user
remote server> git init --bare --shared test
add ssh pub key to remote server
local> git remote add aws ssh://ec2-user@<hostorip>:/home/ec2-user/dev/test
local> git push aws master
A good resource start off point would be MSDN as your looking into a microsoft product
You can not post to Facebook walls automatically without creating an application and using the templated feed publisher as Frank pointed out.
The only thing you can do is use the 'share' widgets that they provide, which require user interaction.
String formattedStr=unformattedStr;
formattedStr=formattedStr.trim().replaceAll("\\s+", " ");
You can use a combination of other LINQ methods to handle not matching condition:
var res = dictionary.Where(x => x.Value.ID == someID)
.Select(x => x.Value.DisplayName)
.DefaultIfEmpty("Unknown")
.First();
you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"')
,if you want to know more detail, please refer to $sce
Better to use:
DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key
start it with hover of body than It will start when the mouse first moves on the screen, which is mostly within a second after arrival, the problem here is that it will reverse when out of the screen.
html:hover #animateelementid, body:hover #animateelementid {rotate ....}
thats the best thing I can think of: http://jsfiddle.net/faVLX/
fullscreen: http://jsfiddle.net/faVLX/embedded/result/
Edit see comments below:
This will not work on any touchscreen device because there is no hover, so the user won't see the content unless they tap it. – Rich Bradshaw
Return false
to prevent the keystroke from continuing.
Could it be a problem with past preview versions of Android Studio ? nowadays "beta" has replaced the "preview". I try it out step by step debugging while using Memory Monitor at same time by Android Studio (Beta) 0.8.11 on OSX 10.9.5 without any problems.
The tutorial Debugging with Android Studio also helps, specially this paragraph :
Here a couple of screenshot while debugging step by step on a breakpoint a monitoring the memory on the emulator:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
works. I am using Python 3.7 and tensorflow 2.0.
The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on
SELECT column_name, position
FROM all_cons_columns
WHERE constraint_name = <<name of constraint from the error message>>
AND owner = <<owner of the table>>
AND table_name = <<name of the table>>
Once you know what column(s) are affected, you can compare the data you're trying to INSERT
or UPDATE
against the data already in the table to determine why the constraint is being violated.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double num;
int result;
cout<<"Enter a number to find the number of digits, not including decimal places: ";
cin>>num;
result = ((num<=1)? 1 : log10(num)+1);
cout<<"Number of digits "<<result<<endl;
return 0;
}
This is probably the simplest way of solving your problem, assuming you only care about digits before the decimal and assuming anything less than 10 is just 1 digit.
I know this is an older question, but I wanted to post an answer for users with the same question:
curl -H 'Cache-Control: no-cache' http://www.example.com
This curl command servers in its header request to return non-cached data from the web server.
You may also try this, anaconda http://continuum.io/downloads
But you need to modify your environment variable PATH, so that the anaconda folder is before the original Python folder.
Renders a view and sends the rendered HTML string to the client.
res.render('index');
Or
res.render('index', function(err, html) {
if(err) {...}
res.send(html);
});
DOCS HERE: https://expressjs.com/en/api.html#res.render
Well, if you want to do it using an algorithm. There are a plethora of sorting algorithms out there. If you aren't concerned too much about efficiency and more about readability and understandability. I recommend Insertion Sort. Here is the psudo code, it is trivial to translate this into java.
begin
for i := 1 to length(A)-1 do
begin
value := A[i];
j := i - 1;
done := false;
repeat
{ To sort in descending order simply reverse
the operator i.e. A[j] < value }
if A[j] > value then
begin
A[j + 1] := A[j];
j := j - 1;
if j < 0 then
done := true;
end
else
done := true;
until done;
A[j + 1] := value;
end;
end;
Try writting the lambda with the same conditions as the delegate. like this:
List<AnalysisObject> analysisObjects =
analysisObjectRepository.FindAll().Where(
(x =>
(x.ID == packageId)
|| (x.Parent != null && x.Parent.ID == packageId)
|| (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
).ToList();
#define MAXSPACE 25
string line = "test one two three.";
string arr[MAXSPACE];
string search = " ";
int spacePos;
int currPos = 0;
int k = 0;
int prevPos = 0;
do
{
spacePos = line.find(search,currPos);
if(spacePos >= 0)
{
currPos = spacePos;
arr[k] = line.substr(prevPos, currPos - prevPos);
currPos++;
prevPos = currPos;
k++;
}
}while( spacePos >= 0);
arr[k] = line.substr(prevPos,line.length());
for(int i = 0; i < k; i++)
{
cout << arr[i] << endl;
}
If you're happy using JQuery then remove the disabled attribute when submitting the form:
$("form").submit(function() {
$("input").removeAttr("disabled");
});
Late to the party - here as a pure java solution for those when JNI is not an option.JTransforms
select substring( field, 1, 5 ) from sometable
var isArray=function(value){
if(Array.isArray){
return Array.isArray(value);
}else{
return Object.prototype.toString.call(value)==='[object Array]';
}
}
var isObject=function(value){
return value !== null&&!isArray(value) && typeof value === 'object';
}
var _val=new Date;
console.log(isObject(_val));//true
console.log(Object.prototype.toString.call(_val)==='[object Object]');//false
Here's an example:
I'm writing a C# program that interfaces with a high-speed camera. The camera has its own driver that acquires images and loads them into the computer's memory for me automatically.
So when I'm ready to bring the latest image into my program to work with, the camera driver provides me with an IntPtr to where the image is ALREADY stored in physical memory, so I don't have to waste time/resources creating another block of memory to store an image that's in memory already. The IntPtr just shows me where the image already is.
I just wanted to add my version of IE detection. It's based on a snippet found at http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/ and exteded to also support ie10 and ie11. It detects IE 5 to 11.
All you need to do is add it somewhere and then you can always check with a simple condition. The global var isIE
will be undefined if it's not an IE, or otherwise it will be the version number. So you can easily add things like if (isIE && isIE < 10)
or alike.
var isIe = (function(){
if (!(window.ActiveXObject) && "ActiveXObject" in window) { return 11; /* IE11 */ }
if (Function('/*@cc_on return /^10/.test(@_jscript_version) @*/')()) { return 10; /* IE10 */ }
var undef,
v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}());
This kind of operation is covered under hierarchical indexing. Check out the examples here
When you groupby, you're making new indices. If you also pass a list through .agg(). you'll get multiple columns. I was trying to figure this out and found this thread via google.
It turns out if you pass a tuple corresponding to the exact column you want sorted on.
Try this:
# generate toy data
ex = pd.DataFrame(np.random.randint(1,10,size=(100,3)), columns=['features', 'AUC', 'recall'])
# pass a tuple corresponding to which specific col you want sorted. In this case, 'mean' or 'AUC' alone are not unique.
ex.groupby('features').agg(['mean','std']).sort_values(('AUC', 'mean'))
This will output a df sorted by the AUC-mean column only.
A more detailed example with support of HTTP code not defined in C# HttpStatusCode
.
public class MyController : ApiController
{
public IHttpActionResult Get()
{
HttpStatusCode codeNotDefined = (HttpStatusCode)429;
return Content(codeNotDefined, "message to be sent in response body");
}
}
Content
is a virtual method defined in abstract class ApiController
, the base of the controller. See the declaration as below:
protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value);
To expand one what CheeseConQueso is saying, here are the entire steps to update a view using PHPMyAdmin:
SHOW CREATE VIEW your_view_name
CREATE VIEW
... syntax) to make sure it runs as you expect it to.CREATE VIEW...
syntax).I hope that helps somebody. Special thanks to CheesConQueso for his/her insightful answer.
Solution for Android Studio 3.6:
yourSwitch.setTextColor(getResources().getColor(R.color.yourColor));
Changes the text color of a in the color XML file defined value (yourColor).
Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.
A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId
attribute set to True
, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show
without creating a new instance of the class.
Step away from this, and treat your form as an object instead - expose Property Get
members and abstract away the form's controls - the calling code doesn't care about controls anyway:
Option Explicit
Private cancelling As Boolean
Public Property Get UserId() As String
UserId = txtUserId.Text
End Property
Public Property Get Password() As String
Password = txtPassword.Text
End Property
Public Property Get IsCancelled() As Boolean
IsCancelled = cancelling
End Property
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub CancelButton_Click()
cancelling = True
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
cancelling = True
Cancel = True
Me.Hide
End If
End Sub
Now the calling code can do this (assuming the UserForm was named LoginPrompt
):
With New LoginPrompt
.Show vbModal
If .IsCancelled Then Exit Sub
DoSomething .UserId, .Password
End With
Where DoSomething
would be some procedure that requires the two string parameters:
Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
'work with the parameter values, regardless of where they came from
End Sub
std::list<Object> l;
std::list<Object>::iterator ptr;
int i;
for( i = 0 , ptr = l.begin() ; i < N && ptr != l.end() ; i++ , ptr++ );
if( ptr == l.end() ) {
// list too short
} else {
// 'ptr' points to N-th element of list
}
The most simple and the correct way is to use Record type Record<string, string>
const myVar : Record<string, string> = {
key1: 'val1',
key2: 'val2',
}
Traditionally PHP has been tolerant to bad practice and failures in code,
which makes debugging quite hard.
The problem in this specific case is that both mysqli and PDO
by default don't tell you, when a query failed and just return FALSE
.
(I will not talk about the depricated mysql extention.
The support for prepared statements is reason anough to switch either to PDO or mysqli.)
But you can change the default behavior of PHP to always throw exceptions when a query fails.
For PDO: Use $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
error_reporting(E_ALL);
$pdo = new PDO("mysql:host=localhost;dbname=test", "test","");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->query('select emal from users');
$data = $result->fetchAll();
This will show you the following:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\pdo.php on line 8
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\pdo.php on line 8
As you see, it tells you exactly, what is wrong with the query, and where to fix it in your code.
Without $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
you will get
Fatal error: Call to a member function fetchAll() on boolean in E:\htdocs\test\mysql_errors\pdo.php on line 9
For mysqli: Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'test', '', 'test');
$result = $mysqli->query('select emal from users');
$data = $result->fetch_all();
You will get
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'emal' in 'field list'' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
mysqli_sql_exception: Unknown column 'emal' in 'field list' in E:\htdocs\test\mysql_errors\mysqli.php on line 8
Without mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
you only get
Fatal error: Call to a member function fetch_all() on boolean in E:\htdocs\test\mysql_errors\mysqli.php on line 10
Of course, you could manually check the MySQL errors. But I would go crazy if I had to do that every time I made a typo - or worse - every time I want to query the database.
You first need to uninstall the ruby installed by Ubuntu with something like sudo apt-get remove ruby
.
Then reinstall ruby using rbenv and ruby-build according to their docs:
cd $HOME
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL
rbenv install 2.3.1
rbenv global 2.3.1
ruby -v
The last step is to install Bundler:
gem install bundler
rbenv rehash
Then enjoy!
Derek
For SQL Server 2014:
http://www.microsoft.com/en-us/download/confirmation.aspx?id=42295
Select SharedManagementObjects.msi for your architectur
$('input.abc').not(':checked').length > 0
You can check wether an arrow key is pressed by:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41)
alert( "arrowkey pressed" );
});
In SQL Server 2017 STRING_AGG is added:
SELECT t.name,STRING_AGG (c.name, ',') AS csv
FROM sys.tables t
JOIN sys.columns c on t.object_id = c.object_id
GROUP BY t.name
ORDER BY 1
Also, STRING_SPLIT is usefull for the opposite case and available in SQL Server 2016
While you can't directly recover a MySQL password without bruteforcing, there might be another way - if you've used MySQL Workbench to connect to the database, and have saved the credentials to the "vault", you're golden.
On Windows, the credentials are stored in %APPDATA%\MySQL\Workbench\workbench_user_data.dat - encrypted with CryptProtectData (without any additional entropy). Decrypting is easy peasy:
std::vector<unsigned char> decrypt(BYTE *input, size_t length) {
DATA_BLOB inblob { length, input };
DATA_BLOB outblob;
if (!CryptUnprotectData(&inblob, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &outblob)) {
throw std::runtime_error("Couldn't decrypt");
}
std::vector<unsigned char> output(length);
memcpy(&output[0], outblob.pbData, outblob.cbData);
return output;
}
Or you can check out this DonationCoder thread for source + executable of a quick-and-dirty implementation.
Hi to use the thread pool in Python you can use this library :
from multiprocessing.dummy import Pool as ThreadPool
and then for use, this library do like that :
pool = ThreadPool(threads)
results = pool.map(service, tasks)
pool.close()
pool.join()
return results
The threads are the number of threads that you want and tasks are a list of task that most map to the service.
Setting background-blend-mode
to darken
would be the most direct and shortest way to achieve the purpose however you must set a background-color
first for the blend mode to work.
This is also the best way if you need to manipulate the values in javascript later on.
background: rgba(0, 0, 0, .65) url('http://fc02.deviantart.net/fs71/i/2011/274/6/f/ocean__sky__stars__and_you_by_muddymelly-d4bg1ub.png');
background-blend-mode: darken;
you can test this expression:
^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$
Description:
validates a yyyy-mm-dd, yyyy mm dd, or yyyy/mm/dd date
makes sure day is within valid range for the month - does NOT validate Feb. 29 on a leap year, only that Feb. Can have 29 days
Matches (tested) : 0001-12-31 | 9999 09 30 | 2002/03/03
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
For me it worked:
df['id'].convert_dtypes()
see the documentation here:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.convert_dtypes.html
I was able to list all untracked files reported by svn st
in bash by doing:
echo $(svn st | grep -P "^\?" | cut -c 9-)
If you are feeling lucky, you could replace echo
with rm
to delete untracked files. Or copy the files you want to delete by hand, if you are feeling a less lucky.
(I used @abe-voelker 's answer to revert the remaining files: https://stackoverflow.com/a/6204601/1695680)
For a production system, you can use this configuration :
--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT CONNECT ON DATABASE nova TO user;
--ACCESS SCHEMA
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO user;
--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL ON ALL TABLES IN SCHEMA public TO admin ;
To account for milliseconds and the user's time zone, use the following:
var _userOffset = _date.getTimezoneOffset()*60*1000; // user's offset time
var _centralOffset = 6*60*60*1000; // 6 for central time - use whatever you need
_date = new Date(_date.getTime() - _userOffset + _centralOffset); // redefine variable
Craiglist is pretty stingy with their data , they even go out of their way to block scraping. If you use ruby here is a gem I wrote to help scrape craiglist data you can search through multiple cities , calculate average price ect...
When the browser puts something in its cache, it also stores the Last-Modified
or ETag
header from the server.
The browser then sends a request with the If-Modified-Since
or If-None-Match
header, telling the server to send a 304 if the content still has that date or ETag.
The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.
If your input is already sorted, then there may be a simpler way to do it:
from operator import itemgetter
from itertools import groupby
unique_list = list(map(itemgetter(0), groupby(yourList)))
I took another try at it, using the DataContractJsonSerializer class. This solves it:
The code looks like this:
using System.Runtime.Serialization;
[DataContract]
public class DataObject
{
[DataMember(Name = "user_id")]
public int UserId { get; set; }
[DataMember(Name = "detail_level")]
public string DetailLevel { get; set; }
}
And the test is:
using System.Runtime.Serialization.Json;
[TestMethod]
public void DataObjectSimpleParseTest()
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataObject));
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonData));
DataObject dataObject = serializer.ReadObject(ms) as DataObject;
Assert.IsNotNull(dataObject);
Assert.AreEqual("low", dataObject.DetailLevel);
Assert.AreEqual(1234, dataObject.UserId);
}
The only drawback is that I had to change DetailLevel from an enum to a string - if you keep the enum type in place, the DataContractJsonSerializer expects to read a numeric value and fails. See DataContractJsonSerializer and Enums for further details.
In my opinion this is quite poor, especially as JavaScriptSerializer handles it correctly. This is the exception that you get trying to parse a string into an enum:
System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type DataObject. The value 'low' cannot be parsed as the type 'Int64'. --->
System.Xml.XmlException: The value 'low' cannot be parsed as the type 'Int64'. --->
System.FormatException: Input string was not in a correct format
And marking up the enum like this does not change this behaviour:
[DataContract]
public enum DetailLevel
{
[EnumMember(Value = "low")]
Low,
...
}
This also seems to work in Silverlight.
The on-heap store refers to objects that will be present in the Java heap (and also subject to GC). On the other hand, the off-heap store refers to (serialized) objects that are managed by EHCache, but stored outside the heap (and also not subject to GC). As the off-heap store continues to be managed in memory, it is slightly slower than the on-heap store, but still faster than the disk store.
The internal details involved in management and usage of the off-heap store aren't very evident in the link posted in the question, so it would be wise to check out the details of Terracotta BigMemory, which is used to manage the off-disk store. BigMemory (the off-heap store) is to be used to avoid the overhead of GC on a heap that is several Megabytes or Gigabytes large. BigMemory uses the memory address space of the JVM process, via direct ByteBuffers that are not subject to GC unlike other native Java objects.
There's also the approach some shops take of using some of C++'s features in a C-like way, but avoiding ones that are objectionable. For example, using classes and class methods and function overloading (which are usually easy for even C diehards to cope with), but not the STL, stream operators, and Boost (which are harder to learn and can have bad memory characteristics).
Try to move:
apply plugin: 'com.google.gms.google-services'
just below:
apply plugin: 'com.android.application'
In your module Gradle file, then make sure all Google service's have the version 9.0.0
.
Make sure that only this build tools is used:
classpath 'com.android.tools.build:gradle:2.1.0'
Make sure in gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
After all above is correct, then make menu File -> Invalidate caches and restart.
This funny solution works really good actually!
public static int countLines(File input) throws IOException {
try (InputStream is = new FileInputStream(input)) {
int count = 1;
for (int aChar = 0; aChar != -1;aChar = is.read())
count += aChar == '\n' ? 1 : 0;
return count;
}
}
While the pattern for testing multiple values
>>> 2 in {1, 2, 3}
True
>>> 5 in {1, 2, 3}
False
is very readable and is working in many situation, there is one pitfall:
>>> 0 in {True, False}
True
But we want to have
>>> (0 is True) or (0 is False)
False
One generalization of the previous expression is based on the answer from ytpillai:
>>> any([0 is True, 0 is False])
False
which can be written as
>>> any(0 is item for item in (True, False))
False
While this expression returns the right result it is not as readable as the first expression :-(
Not with primitive arrays. You'll need to use a List or some other data structure:
List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));
From documentation at https://pip.pypa.io/en/latest/reference/pip_install.html#caching:
Starting with v6.0, pip provides an on-by-default cache which functions similarly to that of a web browser. While the cache is on by default and is designed do the right thing by default you can disable the cache and always access PyPI by utilizing the
--no-cache-dir
option.
Because you have multiple versions of NumPy installed.
Try pip uninstall numpy
and pip list | grep numpy
several times, until you see no output from pip list | grep numpy
.
Then pip install numpy
will get you the newest version of NumPy.
return Deal::with(["redeem" => function($q){
$q->where('user_id', '=', 1);
}])->get();
this worked for me