Have you tried int 21h
service 2? DL
is the character to print.
mov dl,'A' ; print 'A'
mov ah,2
int 21h
To print the integer value, you'll have to write a loop to decompose the integer to individual characters. If you're okay with printing the value in hex, this is pretty trivial.
If you can't rely on DOS services, you might also be able to use the BIOS int 10h
with AL
set to 0Eh
or 0Ah
.
Following is a sample of five different ways to summate values. The first is a naive way to perform the summation (and fails). The second attempts to use sprintf()
, but it too fails. The third uses sprintf()
successfully while the final two (4th & 5th) use floor($value + 0.5)
.
use strict;
use warnings;
use POSIX;
my @values = (26.67,62.51,62.51,62.51,68.82,79.39,79.39);
my $total1 = 0.00;
my $total2 = 0;
my $total3 = 0;
my $total4 = 0.00;
my $total5 = 0;
my $value1;
my $value2;
my $value3;
my $value4;
my $value5;
foreach $value1 (@values)
{
$value2 = $value1;
$value3 = $value1;
$value4 = $value1;
$value5 = $value1;
$total1 += $value1;
$total2 += sprintf('%d', $value2 * 100);
$value3 = sprintf('%1.2f', $value3);
$value3 =~ s/\.//;
$total3 += $value3;
$total4 += $value4;
$total5 += floor(($value5 * 100.0) + 0.5);
}
$total1 *= 100;
$total4 = floor(($total4 * 100.0) + 0.5);
print '$total1: '.sprintf('%011d', $total1)."\n";
print '$total2: '.sprintf('%011d', $total2)."\n";
print '$total3: '.sprintf('%011d', $total3)."\n";
print '$total4: '.sprintf('%011d', $total4)."\n";
print '$total5: '.sprintf('%011d', $total5)."\n";
exit(0);
#$total1: 00000044179
#$total2: 00000044179
#$total3: 00000044180
#$total4: 00000044180
#$total5: 00000044180
Note that floor($value + 0.5)
can be replaced with int($value + 0.5)
to remove the dependency on POSIX
.
You can turn off foreign key checks:
SET FOREIGN_KEY_CHECKS = 0;
/* DO WHAT YOU NEED HERE */
SET FOREIGN_KEY_CHECKS = 1;
Please make sure to NOT use this on production and have a backup.
This is a very old post, I know, but this is also a common problem. All of the suggested methods are very nice but they will always point to a process, and there are many chances that we already know that our site is making problems, but we just want to know what specific page is spending too much time in processing. The most precise and simple tool in my opinion is IIS itself.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.
i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.
Notice that static vars can also be used to share information across all instances
I know this is an old thread but thought I should mention that the extern
keyword. I've recently ran into this issue and solved as follows
Helper.h
namespace DX
{
extern inline void ThrowIfFailed(HRESULT hr);
}
Helper.cpp
namespace DX
{
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
std::stringstream ss;
ss << "#" << hr;
throw std::exception(ss.str().c_str());
}
}
}
for a pure shell solution without calling external program:
NL=$'\n' # define a variable to reference 'newline'
testVar=${testVar%$NL} # removes trailing 'NL' from string
I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:
Go to folder:
C:\AppServ\MySQL
Right click and Run as Administrator these files:
mysql_servicefix.bat
mysql_serviceinstall.bat
mysql_servicestart.bat
Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.
So this is ancient, but there's a much better modern solution. Not sure what version of c#/.NET is required, but this is how I do it:
... Other method code not relevant to the question.
// a token source that will timeout at the specified interval, or if cancelled outside of this scope
using var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, timeoutTokenSource.Token);
async Task<MessageResource> FetchAsync()
{
try
{
return await MessageResource.FetchAsync(m.Sid);
} catch (TaskCanceledException e)
{
if (timeoutTokenSource.IsCancellationRequested)
throw new TimeoutException("Timeout", e);
throw;
}
}
return await Task.Run(FetchAsync, linkedTokenSource.Token);
the CancellationTokenSource
constructor takes a TimeSpan
parameter which will cause that token to cancel after that interval has elapsed. You can then wrap your async (or syncronous, for that matter) code in another call to Task.Run
, passing the timeout token.
This assumes you're passing in a cancellation token (the token
variable). If you don't have a need to cancel the task separately from the timeout, you can just use timeoutTokenSource
directly. Otherwise, you create linkedTokenSource
, which will cancel if the timeout ocurrs, or if it's otherwise cancelled.
We then just catch OperationCancelledException
and check which token threw the exception, and throw a TimeoutException
if a timeout caused this to raise. Otherwise, we rethrow.
Also, I'm using local functions here, which were introduced in C# 7, but you could easily use lambda or actual functions to the same affect. Similarly, c# 8 introduced a simpler syntax for using statements, but those are easy enough to rewrite.
Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.
Using Functional Components and React Hooks
const [array,setArray] = useState([]);
Push value at the end:
setArray(oldArray => [...oldArray,newValue] );
Push value at the begging:
setArray(oldArray => [newValue,...oldArrays] );
What about something like this.
<div id="movie_item">
<div class="movie_item_poster">
<img src="..." style="max-width: 100%; max-height: 100%;">
</div>
<div id="movie_item_content">
<div class="movie_item_content_year">year</div>
<div class="movie_item_content_title">title</div>
<div class="movie_item_content_plot">plot</div>
</div>
<div class="movie_item_toolbar">
Lorem Ipsum...
</div>
</div>
You don't have to float both movie_item_poster
AND movie_item_content
. Just float one of them...
#movie_item {
position: relative;
margin-top: 10px;
height: 175px;
}
.movie_item_poster {
float: left;
height: 150px;
width: 100px;
}
.movie_item_content {
position: relative;
}
.movie_item_content_title {
}
.movie_item_content_year {
float: right;
}
.movie_item_content_plot {
}
.movie_item_toolbar {
clear: both;
vertical-align: bottom;
width: 100%;
height: 25px;
}
I would suggest this one:
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
wl.acquire();
The flag ACQUIRE_CAUSES_WAKEUP is explained like that:
Normal wake locks don't actually turn on the illumination. Instead, they cause the illumination to remain on once it turns on (e.g. from user activity). This flag will force the screen and/or keyboard to turn on immediately, when the WakeLock is acquired. A typical use would be for notifications which are important for the user to see immediately.
Also, make sure you have the following permission in the AndroidManifewst.xml file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().
however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.
Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
temp.add(i+1);
s.clear();
s.addAll(temp);
if you declare it as float or any decimal format it will display
0
only
E.g :
declare @weight float;
SET @weight= 47 / 638; PRINT @weight
Output : 0
If you want the output as
0.073667712
E.g
declare @weight float;
SET @weight= 47.000000000 / 638.000000000; PRINT @weight
This works with our libraries running GIT v1.7.1, where we have a DEV package repo and LIVE package repo. The repositories themselves are nothing but a shell to package the assets for a project. all submodules.
The LIVE is never updated intentionally, however cache files or accidents can occur, leaving the repo dirty. New submodules added to the DEV must be initialized within LIVE as well.
Package Repository in DEV
Here we want to pull all upstream changes that we are not yet aware of, then we will update our package repository.
# Recursively reset to the last HEAD
git submodule foreach --recursive git reset --hard
# Recursively cleanup all files and directories
git submodule foreach --recursive git clean -fd
# Recursively pull the upstream master
git submodule foreach --recursive git pull origin master
# Add / Commit / Push all updates to the package repo
git add .
git commit -m "Updates submodules"
git push
Package Repository in LIVE
Here we want to pull the changes that are committed to the DEV repository, but not unknown upstream changes.
# Pull changes
git pull
# Pull status (this is required for the submodule update to work)
git status
# Initialize / Update
git submodule update --init --recursive
Works perfect in Swift 2.0
@IBOutlet var theImage: UIImageView! //you can replace this with any UIObject eg: label etc
override func viewDidLoad() {
super.viewDidLoad()
//Make sure the width and height are same
self.theImage.layer.cornerRadius = self.theImage.frame.size.width / 2
self.theImage.layer.borderWidth = 2.0
self.theImage.layer.borderColor = UIColor.whiteColor().CGColor
self.theImage.clipsToBounds = true
}
Thanks guys, this really saved my day too. I antecedently pressed on skip break points, if you did the same this will result on break point appearing with a backslash icon on them.
To bring it back to normal:
To confirm, try putting break point on any line, and it should appear normally.
Only this regex worked for me:
sed 's/\\0//g'
So as you get your data do this: $ get_data | sed 's/\\0//g'
which will output your data without 0x00
Probably you need an array?
var Game = {
status: [
["val", "val","val"],
["val", "val", "val"]
]
}
alert(Game.status[0][0]);
Just loop...
foreach(var table in DataSet1.Tables) {
foreach(var col in table.Columns) {
...
}
foreach(var row in table.Rows) {
object[] values = row.ItemArray;
...
}
}
You have to add Button to excel sheet(say sheet1
) from which you can go to another sheet(say sheet2
).
Button can be added from Developer tab in excel. If developer tab is not there follow below steps to enable.
GOTO file -> options -> Customize Ribbon -> enable checkbox of developer on right panel -> Done.
To Add button :-
Developer Tab -> Insert -> choose first item button -> choose location of button-> Done.
To give name for button :-
Right click on button -> edit text.
To add code for going to sheet2 :-
Right click on button -> Assign Macro -> New -> (microsoft visual basic will open to code for button) -> paste below code
Worksheets("Sheet2").Visible = True
Worksheets("Sheet2").Activate
Save the file using 'Excel Macro Enable Template(*.xltm)' By which the code is appended with excel sheet.
(Jun-Nov 2016) The question and its answers are now out-of-date as: 1) GData APIs are the previous generation of Google APIs. While not all GData APIs have been deprecated, all the latest Google APIs do not use the Google Data Protocol; and 2) there is a new Google Sheets API v4 (also not GData).
Moving forward from here, you need to get the Google APIs Client Library for .NET and use the latest Sheets API, which is much more powerful and flexible than any previous API. Here's a C# code sample to help get you started. Also check the .NET reference docs for the Sheets API and the .NET Google APIs Client Library developers guide.
If you're not allergic to Python (if you are, just pretend it's pseudocode ;) ), I made several videos with slightly longer, more "real-world" examples of using the API you can learn from and migrate to C# if desired:
there is the class I mentioned in the comment we had with Sean Patrick Floyd : I did it with a peculiar use which needs WeakReference, but you can change it by any object with ease.
Hoping this can help someone someday :)
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
/**
*
* @author leBenj
*/
public class Array2DWeakRefsBuffered<T>
{
private final WeakReference<T>[][] _array;
private final Queue<T> _buffer;
private final int _width;
private final int _height;
private final int _bufferSize;
@SuppressWarnings( "unchecked" )
public Array2DWeakRefsBuffered( int w , int h , int bufferSize )
{
_width = w;
_height = h;
_bufferSize = bufferSize;
_array = new WeakReference[_width][_height];
_buffer = new LinkedList<T>();
}
/**
* Tests the existence of the encapsulated object
* /!\ This DOES NOT ensure that the object will be available on next call !
* @param x
* @param y
* @return
* @throws IndexOutOfBoundsException
*/public boolean exists( int x , int y ) throws IndexOutOfBoundsException
{
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
}
if( _array[x][y] != null )
{
T elem = _array[x][y].get();
if( elem != null )
{
return true;
}
}
return false;
}
/**
* Gets the encapsulated object
* @param x
* @param y
* @return
* @throws IndexOutOfBoundsException
* @throws NoSuchElementException
*/
public T get( int x , int y ) throws IndexOutOfBoundsException , NoSuchElementException
{
T retour = null;
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
}
if( _array[x][y] != null )
{
retour = _array[x][y].get();
if( retour == null )
{
throw new NoSuchElementException( "Dereferenced WeakReference element at [ " + x + " ; " + y + "]" );
}
}
else
{
throw new NoSuchElementException( "No WeakReference element at [ " + x + " ; " + y + "]" );
}
return retour;
}
/**
* Add/replace an object
* @param o
* @param x
* @param y
* @throws IndexOutOfBoundsException
*/
public void set( T o , int x , int y ) throws IndexOutOfBoundsException
{
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ y = " + y + "]" );
}
_array[x][y] = new WeakReference<T>( o );
// store local "visible" references : avoids deletion, works in FIFO mode
_buffer.add( o );
if(_buffer.size() > _bufferSize)
{
_buffer.poll();
}
}
}
Example of how to use it :
// a 5x5 array, with at most 10 elements "bufferized" -> the last 10 elements will not be taken by GC process
Array2DWeakRefsBuffered<Image> myArray = new Array2DWeakRefsBuffered<Image>(5,5,10);
Image img = myArray.set(anImage,0,0);
if(myArray.exists(3,3))
{
System.out.println("Image at 3,3 is still in memory");
}
Your sub-query is just incomplete, that's all. See the query below with my addictions:
INSERT INTO customers ( customer_id, firstname, surname )
VALUES ((SELECT MAX( customer_id ) FROM customers) +1), 'jim', 'sock')
You should create a new project in Code::Blocks, and make sure it's 'Console Application'.
Add your .cpp files into the project so they are all compiled and linked together.
$timestamp = strtotime('today midnight');
You might want to take a look what PHP has to offer: http://php.net/datetime
Use the menu selection Navigate -> Test, or Ctrl+Shift+T (Shift+?+T on Mac). This will go to the existing test class, or offer to generate it for you through a little wizard.
You can checkup for the special variable __name__
with this simple example:
create file1.py
if __name__ == "__main__":
print("file1 is being run directly")
else:
print("file1 is being imported")
create file2.py
import file1 as f1
print("__name__ from file1: {}".format(f1.__name__))
print("__name__ from file2: {}".format(__name__))
if __name__ == "__main__":
print("file2 is being run directly")
else:
print("file2 is being imported")
Execute file2.py
output:
file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly
Try this :
open the terminal and type this command : sudo gedit /etc/mysql/my.cnf
Paste the line in my.cnf file: set-variable=max_connections=500
The modern way to do it that maintains the order is:
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(lseparatedOrbList))
as discussed by Raymond Hettinger (python core dev) in this answer. In python 3.5 and above this is also the fastest way - see the linked answer for details. However the keys must be hashable (as is the case in your list I think)
Yes you should, As it locks the version of each and every package which you are using in your app and when you run npm install
it install the exact same version in your node_modules folder. This is important becasue let say you are using bootstrap 3 in your application and if there is no package-lock.json file in your project then npm install
will install bootstrap 4 which is the latest and you whole app ui will break due to version mismatch.
this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.
to check either a pointer is initialized or not you can try something like
Class *pointer = new Class();
if(pointer!=nullptr){
pointer->myFunction();
}
check if the array is null first so you would avoid a null pointer exception
logic in any language: if array is null or is empty :do ....
Download visual studio c++ express version 2006,2010 etc. then goto create new project and create c++ project select cmd project check empty rename cc with c extension file name
Note that in .NET 4.0 there are (supposedly) iterator-based (rather than array-based) file functions built in:
foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
{
Console.WriteLine(file);
}
At the moment I'd use something like below; the inbuilt recursive method breaks too easily if you don't have access to a single sub-dir...; the Queue<string>
usage avoids too much call-stack recursion, and the iterator block avoids us having a huge array.
static void Main() {
foreach (string file in GetFiles(SOME_PATH)) {
Console.WriteLine(file);
}
}
static IEnumerable<string> GetFiles(string path) {
Queue<string> queue = new Queue<string>();
queue.Enqueue(path);
while (queue.Count > 0) {
path = queue.Dequeue();
try {
foreach (string subDir in Directory.GetDirectories(path)) {
queue.Enqueue(subDir);
}
}
catch(Exception ex) {
Console.Error.WriteLine(ex);
}
string[] files = null;
try {
files = Directory.GetFiles(path);
}
catch (Exception ex) {
Console.Error.WriteLine(ex);
}
if (files != null) {
for(int i = 0 ; i < files.Length ; i++) {
yield return files[i];
}
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void Decimal2Binary(long value,char *b,int len)
{
if(value>0)
{
do
{
if(value==1)
{
*(b+len-1)='1';
break;
}
else
{
*(b+len-1)=(value%2)+48;
value=value/2;
len--;
}
}while(1);
}
}
long Binary2Decimal(char *b,int len)
{
int i=0;
int j=0;
long value=0;
for(i=(len-1);i>=0;i--)
{
if(*(b+i)==49)
{
value+=pow(2,j);
}
j++;
}
return value;
}
int main()
{
char data[11];//????BIT????????
long value=1023;
memset(data,'0',sizeof(data));
data[10]='\0';//????
Decimal2Binary(value,data,10);
printf("%d->%s\n",value,data);
value=Binary2Decimal(data,10);
printf("%s->%d",data,value);
return 0;
}
This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:
'since the file name and path were used several times in code
'variables were made public
Public FName As Variant, Filename As String, Path As String
Sub xxx()
...
If Not GetFileName = 1 Then Exit Sub '
...
End Sub
Private Function GetFileName()
GetFileName = 0 'used for error handling at call point in case user cancels
FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
Filename = Split(FName, "\")(UBound(Split(FName, "\"))) 'results in file name
Path = Left(FName, InStrRev(FName, "\")) 'results in path
End Function
You must use plt.show()
at the end in order to see the plot
Here's a solution that handles errors in requests and calls a callback after the file is written:
request(opts)
.on('error', function(err){ return callback(err)})
.pipe(fs.createWriteStream(filename))
.on('finish', function (err) {
return callback(err);
});
If you are using a database that supports map-reduce, like couchdb, storing tags in a plain text field or list field is indeed the best way. Example:
tagcloud: {
map: function(doc){
for(tag in doc.tags){
emit(doc.tags[tag],1)
}
}
reduce: function(keys,values){
return values.length
}
}
Running this with group=true will group the results by tag name, and even return a count of the number of times that tag was encountered. It's very similar to counting the occurrences of a word in text.
How about this:
(my_list and my_list[0]) or None
Note: This should work fine for lists of objects but it might return incorrect answer in case of number or string list per the comments below.
For the parent:
display: flex;
You should add some prefixes http://css-tricks.com/using-flexbox/
Edit: Only drawback is IE as usual, IE9 does not support flex. http://caniuse.com/flexbox
Edit 2: As @toddsby noted, align items is for parent, and its default value actually is stretch. If you want a different value for child, there is align-self property.
Edit 3: jsFiddle: https://jsfiddle.net/bv71tms5/2/
A robust solution is to delegate counting to a subroutine invoked with call
; the subroutine uses goto
statements to emulate a loop in which shift
is used to consume the (subroutine-only) arguments iteratively:
@echo off
setlocal
:: Call the argument-counting subroutine with all arguments received,
:: without interfering with the ability to reference the arguments
:: with %1, ... later.
call :count_args %*
:: Print the result.
echo %ReturnValue% argument(s) received.
:: Exit the batch file.
exit /b
:: Subroutine that counts the arguments given.
:: Returns the count in %ReturnValue%
:count_args
set /a ReturnValue = 0
:count_args_for
if %1.==. goto :eof
set /a ReturnValue += 1
shift
goto count_args_for
Well, Seems like there was a bug when creating custom post types in the function.php file of the theme... which bugged that.
As we have well established here, writelines
does not append the newlines for you. But, what everyone seems to be missing, is that it doesn't have to when used as a direct "counterpart" for readlines()
and the initial read persevered the newlines!
When you open a file for reading in binary mode (via 'rb'
), then use readlines()
to fetch the file contents into memory, split by line, the newlines remain attached to the end of your lines! So, if you then subsequently write them back, you don't likely want writelines
to append anything!
So if, you do something like:
with open('test.txt','rb') as f: lines=f.readlines()
with open('test.txt','wb') as f: f.writelines(lines)
You should end up with the same file content you started with.
In addition to this answer, note that in Node.js if you access JSON with the array syntax []
all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']
You can use the .tostring() method with datetime format specifiers to format to whatever you need:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013
Linked list is guaranteed to act in sequential order.
From the documentation
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
iterator() Returns an iterator over the elements in this list in proper sequence.
I adapted @mVchr's answer and inverted it to use for sticky ad positioning: if you need it absolutely positioned (scrolling) until the header junk is off screen but then need it to stay fixied/visible on screen after that:
$.fn.followTo = function (pos) {
var stickyAd = $(this),
theWindow = $(window);
$(window).scroll(function (e) {
if ($(window).scrollTop() > pos) {
stickyAd.css({'position': 'fixed','top': '0'});
} else {
stickyAd.css({'position': 'absolute','top': pos});
}
});
};
$('#sticky-ad').followTo(740);
CSS:
#sticky-ad {
float: left;
display: block;
position: absolute;
top: 740px;
left: -664px;
margin-left: 50%;
z-index: 9999;
}
This should work
<a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>
You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block
Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
You've got to do some extra massaging if you want the ticks (not labels) to show up on the top and bottom (not just the top). The only way I could do this is with a minor change to unutbu's code:
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.xaxis.set_ticks_position('both') # THIS IS THE ONLY CHANGE
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()
Output:
This answer works for me in c#:
using System.IO;
string fileName = Path.GetFileName("C:\Hello\AnotherFolder\The File Name.PDF");
import regex
text = 'ask her to call Mary back when she comes back'
p = r'(?i)(?s)call(.*?)back'
for match in regex.finditer(p, str(text)):
print (match.group(1))
Output: Mary
It doesn't appear that iframes display and scroll properly. You can use an object tag to replace an iframe and the contents will be scrollable with 2 fingers. Here's a simple example:
<html>
<head>
<meta name="viewport" content="minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;"/>
</head>
<body>
<div>HEADER - use 2 fingers to scroll contents:</div>
<div id="scrollee" style="height:75%;" >
<object id="object" height="90%" width="100%" type="text/html" data="http://en.wikipedia.org/"></object>
</div>
<div>FOOTER</div>
</body>
</html>
For debugging you can also use a "Java Decompiler" such as: JAD and decompile source on the fly (although the generated source is never the same as the original). Then install JAD as a plugin in Eclipse or your favorite IDE.
In the solution below I used python3.4
as binary, but it's safe to use with any version or binary of python. it works fine on windows too (except the downloading pip with wget
obviously but just save the file locally and run it with python).
This is great if you have multiple versions of python installed, so you can manage external libraries per python version.
So first, I'd recommend get-pip.py
, it's great to install pip :
wget https://bootstrap.pypa.io/get-pip.py
Then you need to install pip for your version of python, I have python3.4
so for me this is the command :
python3.4 get-pip.py
Now pip is installed for python3.4
and in order to get libraries for python3.4
one need to call it within this version, like this :
python3.4 -m pip
So if you want to install numpy you would use :
python3.4 -m pip install numpy
Note that numpy
is quite the heavy library. I thought my system was hanging and failing.
But using the verbose option, you can see that the system is fine :
python3.4 -m pip install numpy -v
This may tell you that you lack python.h but you can easily get it :
On RHEL (Red hat, CentOS, Fedora) it would be something like this :
yum install python34-devel
On debian-like (Debian, Ubuntu, Kali, ...) :
apt-get install python34-dev
Then rerun this :
python3.4 -m pip install numpy -v
here is what I used
.ui-autocomplete { max-height: 200px; overflow-y: auto; overflow-x: hidden;}
The overflow auto so the scroll bar will not show when it's not supposed to.
Assuming your regular expression is correct:
inside your script tags
function validateEmail(emailField){
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false)
{
alert('Invalid Email Address');
return false;
}
return true;
}
in your textfield:
<input type="text" onblur="validateEmail(this);" />
Your else statement should look like this (note the ^
):
{{^avatar}}
...
{{/avatar}}
In mustache this is called 'Inverted sections'.
Here is a permissively-licensed C library with a variety of different FFT implementations, each of which is in its own self-contained C-file.
Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.
It worked for me so here's hoping it helps someone else, too.
What do you thing about this approach?
with open(filename) as data:
datalines = (line.rstrip('\r\n') for line in data)
for line in datalines:
...do something awesome...
Generator expression avoids loading whole file into memory and with
ensures closing the file
The normal layout for a maven multi module project is:
parent
+-- pom.xml
+-- module
+-- pom.xml
Check that you use this layout.
Additionally:
the relativePath
looks strange. Instead of '..'
<relativePath>..</relativePath>
try '../' instead:
<relativePath>../</relativePath>
You can also remove relativePath
if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.
The module path may be wrong. In the parent you define the module as:
<module>junitcategorizer.cutdetection</module>
You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection
is not the name of the folder than change it accordingly.
Hope that helps..
EDIT have a look at the other post, I answered there.
C99 standard on c >= '0' && c <= '9'
c >= '0' && c <= '9'
(mentioned in another answer) works because C99 N1256 standard draft 5.2.1 "Character sets" says:
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
ASCII is not guaranteed however.
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
=============== and for post
$.ajax({ type: 'post',
must be met with
app.post('/', function(req, res) {
You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA
class ClassA {
public function getName() {
echo $this->name;
}
}
class ClassB extends ClassA {
public function getName() {
parent::getName();
}
}
Without inheritance or an instance method, you'd need ClassA to have a static method
class ClassA {
public static function getName() {
echo "Rawkode";
}
}
--- other file ---
echo ClassA::getName();
If you're just looking to call the method from an instance of the class:
class ClassA {
public function getName() {
echo "Rawkode";
}
}
--- other file ---
$a = new ClassA();
echo $a->getName();
Regardless of the solution you choose, require 'ClassA.php
is needed.
I like the solution using the -eq
test, because it's basically a one-liner.
My own solution was to use parameter expansion to throw away all the numerals and see if there was anything left. (I'm still using 3.0, haven't used [[
or expr
before, but glad to meet them.)
if [ "${INPUT_STRING//[0-9]}" = "" ]; then
# yes, natural number
else
# no, has non-numeral chars
fi
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
Also, we use them for managing inheritance.
class Super( object ):
def __init__( self, this, that ):
self.this = this
self.that = that
class Sub( Super ):
def __init__( self, myStuff, *args, **kw ):
super( Sub, self ).__init__( *args, **kw )
self.myStuff= myStuff
x= Super( 2.7, 3.1 )
y= Sub( "green", 7, 6 )
This way Sub doesn't really know (or care) what the superclass initialization is. Should you realize that you need to change the superclass, you can fix things without having to sweat the details in each subclass.
In fact you cannot do it easily right now (at the time I am writing this message). I will try to explain why.
First of all, the glibc is no more, it has been subsumed by the eglibc project. And, the Debian distribution switched to eglibc some time ago (see here and there and even on the glibc source package page). So, you should consider installing the eglibc package through this kind of command:
apt-get install libc6-amd64 libc6-dev libc6-dbg
Replace amd64
by the kind of architecture you want (look at the package list here).
Unfortunately, the eglibc package version is only up to 2.13 in unstable
and testing
. Only the experimental
is providing a 2.17 version of this library. So, if you really want to have it in 2.15 or more, you need to install the package from the experimental version (which is not recommended). Here are the steps to achieve as root:
Add the following line to the file /etc/apt/sources.list
:
deb http://ftp.debian.org/debian experimental main
Update your package database:
apt-get update
Install the eglibc package:
apt-get -t experimental install libc6-amd64 libc6-dev libc6-dbg
Pray...
Well, that's all folks.
The application/x-www-form-urlencoded
Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:
curl -X DELETE "http://localhost:5000/locations?id=3"
or
curl -X GET "http://localhost:5000/locations?id=3"
The other answers here are excellent and accurate. In the interest of adding to the list of things to try:
Double and triple-check that your app is using the right application ID and secret key. In my case, after trying many other things, I checked the application ID and secret key and found that I was using our production settings on our development system. Doh!
Using the correct application ID and secret key fixed the problem.
If you simply want to replace the entire text inside the text editing controller, then the other answers here work. However, if you want to programmatically insert, replace a selection, or delete, then you need to have a little more code.
Making your own custom keyboard is one use case for this. All of the inserts and deletions below are done programmatically:
The _controller
here is a TextEditingController
for the TextField
.
void _insertText(String myText) {
final text = _controller.text;
final textSelection = _controller.selection;
final newText = text.replaceRange(
textSelection.start,
textSelection.end,
myText,
);
final myTextLength = myText.length;
_controller.text = newText;
_controller.selection = textSelection.copyWith(
baseOffset: textSelection.start + myTextLength,
extentOffset: textSelection.start + myTextLength,
);
}
Thanks to this Stack Overflow answer for help with this.
There are a few different situations to think about:
Here is the implementation:
void _backspace() {
final text = _controller.text;
final textSelection = _controller.selection;
final selectionLength = textSelection.end - textSelection.start;
// There is a selection.
if (selectionLength > 0) {
final newText = text.replaceRange(
textSelection.start,
textSelection.end,
'',
);
_controller.text = newText;
_controller.selection = textSelection.copyWith(
baseOffset: textSelection.start,
extentOffset: textSelection.start,
);
return;
}
// The cursor is at the beginning.
if (textSelection.start == 0) {
return;
}
// Delete the previous character
final newStart = textSelection.start - 1;
final newEnd = textSelection.start;
final newText = text.replaceRange(
newStart,
newEnd,
'',
);
_controller.text = newText;
_controller.selection = textSelection.copyWith(
baseOffset: newStart,
extentOffset: newStart,
);
}
You can find the full code and more explanation in my article Custom In-App Keyboard in Flutter.
Try this It'll work perfect.
$('body.overflow-hidden').delegate('#skrollr-body','touchmove',function(e){
e.preventDefault();
console.log('Stop skrollrbody');
}).delegate('.mfp-auto-cursor .mfp-content','touchmove',function(e){
e.stopPropagation();
console.log('Scroll scroll');
});
Give a Format String value of C2 for the value's properties as shown in figure below.
Try this
if($("input:radio[name=postage]").is(":checked")){
//Code to append goes here
}
To change the Toolbar's back icon drawable you can use this:
Add the <item name="toolbarStyle">@style/ToolbarStyle</item>
into your Theme.
And here is the ToolbarStyle
itself:
<style name="ToolbarStyle" parent="Widget.AppCompat.Toolbar">
<item name="navigationIcon">@drawable/ic_up_indicator</item>
</style>
I've tried a select statement now with a PreparedStatement
, but it turned out that it was not faster than the Jdbc template. Maybe, as mezmo suggested, it automatically creates prepared statements.
Anyway, the reason for my sql SELECT
s being so slow was another one. In the WHERE
clause I always used the operator LIKE
, when all I wanted to do was finding an exact match. As I've found out LIKE
searches for a pattern and therefore is pretty slow.
I'm using the operator =
now and it's much faster.
Hope it will help u:
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
Problem is, your eclipse is not able to connect the site which actually it is trying to. I have faced similar issue and below given solution worked for me.
Thanks
I faced this issue on Node 10.X version. below is my working code.
const https = require('https');
exports.handler = (event,context,callback) => {
let body='';
let jsonObject = JSON.stringify(event);
// the post options
var optionspost = {
host: 'example.com',
path: '/api/mypath',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'blah blah',
}
};
let reqPost = https.request(optionspost, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
console.log("Result", body.toString());
context.succeed("Sucess")
});
res.on('error', function () {
console.log("Result Error", body.toString());
context.done(null, 'FAILURE');
});
});
reqPost.write(jsonObject);
reqPost.end();
};
I wonder if it could be explained any better than the Wikipedia article.
The basic problem that you are trying to solve with two's complement representation is the problem of storing negative integers.
First, consider an unsigned integer stored in 4 bits. You can have the following
0000 = 0
0001 = 1
0010 = 2
...
1111 = 15
These are unsigned because there is no indication of whether they are negative or positive.
To store negative numbers you can try a number of things. First, you can use sign magnitude notation which assigns the first bit as a sign bit to represent +/- and the remaining bits to represent the magnitude. So using 4 bits again and assuming that 1 means - and 0 means + then you have
0000 = +0
0001 = +1
0010 = +2
...
1000 = -0
1001 = -1
1111 = -7
So, you see the problem there? We have positive and negative 0. The bigger problem is adding and subtracting binary numbers. The circuits to add and subtract using sign magnitude will be very complex.
What is
0010
1001 +
----
?
Another system is excess notation. You can store negative numbers, you get rid of the two zeros problem but addition and subtraction remains difficult.
So along comes two's complement. Now you can store positive and negative integers and perform arithmetic with relative ease. There are a number of methods to convert a number into two's complement. Here's one.
Convert the number to binary (ignore the sign for now) e.g. 5 is 0101 and -5 is 0101
If the number is a positive number then you are done. e.g. 5 is 0101 in binary using two's complement notation.
If the number is negative then
3.1 find the complement (invert 0's and 1's) e.g. -5 is 0101 so finding the complement is 1010
3.2 Add 1 to the complement 1010 + 1 = 1011. Therefore, -5 in two's complement is 1011.
So, what if you wanted to do 2 + (-3) in binary? 2 + (-3) is -1. What would you have to do if you were using sign magnitude to add these numbers? 0010 + 1101 = ?
Using two's complement consider how easy it would be.
2 = 0010
-3 = 1101 +
-------------
-1 = 1111
Converting 1111 to decimal:
The number starts with 1, so it's negative, so we find the complement of 1111, which is 0000.
Add 1 to 0000, and we obtain 0001.
Convert 0001 to decimal, which is 1.
Apply the sign = -1.
Tada!
Try this:
create your table on the target server using your scripts from the Script Table As / Create Script
step
on the target server, you can then issue a T-SQL statement:
INSERT INTO dbo.YourTableNameHere
SELECT *
FROM [SourceServer].[SourceDatabase].dbo.YourTableNameHere
This should work just fine.
ORDER BY article_rating, article_time DESC
will sort by article_time only if there are two articles with the same rating. From all I can see in your example, this is exactly what happens.
? primary sort secondary sort ?
1. 50 | This article rocks | Feb 4, 2009 3.
2. 35 | This article is pretty good | Feb 1, 2009 2.
3. 5 | This Article isn't so hot | Jan 25, 2009 1.
but consider:
? primary sort secondary sort ?
1. 50 | This article rocks | Feb 2, 2009 3.
1. 50 | This article rocks, too | Feb 4, 2009 4.
2. 35 | This article is pretty good | Feb 1, 2009 2.
3. 5 | This Article isn't so hot | Jan 25, 2009 1.
You need to have
#include <string>
in the header file too.The forward declaration on it's own doesn't do enough.
Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:
#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H
/* header goes in here */
#endif
This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.
I tried to use the approach provided by Rod, but taking into consideration BalusC concern about not repeating the same work-around in all the application and came with this class:
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;
public class MyResourceBundle {
// feature variables
private ResourceBundle bundle;
private String fileEncoding;
public MyResourceBundle(Locale locale, String fileEncoding){
this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
this.fileEncoding = fileEncoding;
}
public MyResourceBundle(Locale locale){
this(locale, "UTF-8");
}
public String getString(String key){
String value = bundle.getString(key);
try {
return new String(value.getBytes("ISO-8859-1"), fileEncoding);
} catch (UnsupportedEncodingException e) {
return value;
}
}
}
The way to use this would be very similar than the regular ResourceBundle usage:
private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
String label = labels.getString(key)
Or you can use the alternate constructor which uses UTF-8 by default:
private MyResourceBundle labels = new MyResourceBundle("es");
As it wasn't already suggested here, but is probably one of the easiest solutions:
import subprocess
def play_mp3(path):
subprocess.Popen(['mpg123', '-q', path]).wait()
It depends on any mpg123 compliant player, which you get e.g. for Debian using:
apt-get install mpg123
or
apt-get install mpg321
You can run:
ps -ft pts/6 -t pts/9 -t pts/10
This would produce an output similar to:
UID PID PPID C STIME TTY TIME CMD
Vidya 772 2701 0 15:26 pts/6 00:00:00 bash
Vidya 773 2701 0 16:26 pts/9 00:00:00 bash
Vidya 774 2701 0 17:26 pts/10 00:00:00 bash
Grab the PID
from the result.
Use the PIDs to kill the processes:
kill <PID1> <PID2> <PID3> ...
For the above example:
kill 772 773 774
If the process doesn't gracefully terminate, just as a last option you can forcefully kill by sending a SIGKILL
kill -9 <PID>
Just to round out Reed's answer, you can either get the Button
objects from the Form
or other container and add the handler, or you could create the Button
objects programmatically.
If you get the Button
objects from the Form
or other container, then you can iterate over the Controls
collection of the Form
or other container control, such as Panel
or FlowLayoutPanel
and so on. You can then just add the click handler with
AddHandler ctrl.Click, AddressOf Me.Button_Click
(variables as in the code below),
but I prefer to check the type of the Control
and cast to a Button
so as I'm not adding click handlers for any other controls in the container (such as Labels). Remember that you can add handlers for any event of the Button
at this point using AddHandler
.
Alternatively, you can create the Button
objects programmatically, as in the second block of code below.
Then, of course, you have to write the handler method, as in the third code block below.
Here is an example using Form
as the container, but you're probably better off using a Panel
or some other container control.
Dim btn as Button = Nothing
For Each ctrl As Control in myForm.Controls
If TypeOf ctrl Is Button Then
btn = DirectCast(ctrl, Button)
AddHandler btn.Click, AddressOf Me.Button_Click ' From answer by Reed.
End If
Next
Alternatively creating the Button
s programmatically, this time adding to a Panel
container.
Dim Panel1 As new Panel()
For i As Integer = 1 to 100
btn = New Button()
' Set Button properties or call a method to do so.
Panel1.Controls.Add(btn) ' Add Button to the container.
AddHandler btn.Click, AddressOf Me.Button_Click ' Again from the answer by Reed.
Next
Then your handler will look something like this
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
' Handle your Button clicks here
End Sub
The method len() returns the number of elements in the list.
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)
When we run above program, it produces the following result -
First list length : 3 Second list length : 2
In general, an "object" is an instance of a class, which is an "image"/"fingerprint" of a class created in memory (via New keyword).
The variable of object type refers to this memory location, that is, it essentially contains the address in memory.
So a parameter of object type passes a reference/"link" to an object, not a copy of the whole object.
Here's a reusable Angular directive that will hide and show a Bootstrap modal.
app.directive("modalShow", function () {
return {
restrict: "A",
scope: {
modalVisible: "="
},
link: function (scope, element, attrs) {
//Hide or show the modal
scope.showModal = function (visible) {
if (visible)
{
element.modal("show");
}
else
{
element.modal("hide");
}
}
//Check to see if the modal-visible attribute exists
if (!attrs.modalVisible)
{
//The attribute isn't defined, show the modal by default
scope.showModal(true);
}
else
{
//Watch for changes to the modal-visible attribute
scope.$watch("modalVisible", function (newValue, oldValue) {
scope.showModal(newValue);
});
//Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
element.bind("hide.bs.modal", function () {
scope.modalVisible = false;
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
}
}
};
});
Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition
<div modal-show class="modal fade"> ...bootstrap modal... </div>
Usage Example #2 - this uses an Angular expression in the modal-visible attribute
<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>
Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.
$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)
I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal
Hope this helps.
Hi, This is my example of calculating the difference between two dates
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<br>
<input class='fromdate' type="date" />
<input class='todate' type="date" />
<div class='calculated' /><br>
<div class='minim' />
<input class='todate' type="submit" onclick='showDays()' />
</body>
</html>
This is the function that calculates the difference :
function showDays(){
var start = $('.fromdate').val();
var end = $('.todate').val();
var startDay = new Date(start);
var endDay = new Date(end);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = endDay.getTime() - startDay.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
alert( Math.floor(days));
}
I hope I have helped you
This post summarizes common approaches to element removal from an array as of ECMAScript 2019 (ES10).
.splice()
| In-place: Yes |
| Removes duplicates: Yes(loop), No(indexOf) |
| By value / index: By index |
If you know the value you want to remove from an array you can use the splice method. First, you must identify the index of the target item. You then use the index as the start element and remove just one element.
// With a 'for' loop
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
for( let i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
}
} // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
// With the .indexOf() method
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const i = arr.indexOf(5);
arr.splice(i, 1); // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
.filter()
method| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |
The specific element can be filtered out from the array, by providing a filtering function. Such function is then called for every element in the array.
const value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
Array.prototype
| In-place: Yes/No (Depends on implementation) |
| Removes duplicates: Yes/No (Depends on implementation) |
| By value / index: By index / By value (Depends on implementation) |
The prototype of Array can be extended with additional methods. Such methods will be then available to use on created arrays.
Note: Extending prototypes of objects from the standard library of JavaScript (like Array) is considered by some as an antipattern.
// In-place, removes all, by value implementation
Array.prototype.remove = function(item) {
for (let i = 0; i < this.length; i++) {
if (this[i] === item) {
this.splice(i, 1);
}
}
}
const arr1 = [1,2,3,1];
arr1.remove(1) // arr1 equals [2,3]
// Non-stationary, removes first, by value implementation
Array.prototype.remove = function(item) {
const arr = this.slice();
for (let i = 0; i < this.length; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
return arr;
}
}
return arr;
}
let arr2 = [1,2,3,1];
arr2 = arr2.remove(1) // arr2 equals [2,3,1]
delete
operator| In-place: Yes |
| Removes duplicates: No |
| By value / index: By index |
Using the delete operator does not affect the length property. Nor does it affect the indexes of subsequent elements. The array becomes sparse, which is a fancy way of saying the deleted item is not removed but becomes undefined.
const arr = [1, 2, 3, 4, 5, 6];
delete arr[4]; // Delete element with index 4
console.log( arr ); // [1, 2, 3, 4, undefined, 6]
The delete operator is designed to remove properties from JavaScript objects, which arrays are objects.
Object
utilities (>= ES10)| In-place: No |
| Removes duplicates: Yes |
| By value / index: By value |
ES10 introduced Object.fromEntries
, which can be used to create the desired Array from any Array-like object and filter unwanted elements during the process.
const object = [1,2,3,4];
const valueToRemove = 3;
const arr = Object.values(Object.fromEntries(
Object.entries(object)
.filter(([ key, val ]) => val !== valueToRemove)
));
console.log(arr); // [1,2,4]
length
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
JavaScript Array elements can be removed from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed.
const arr = [1, 2, 3, 4, 5, 6];
arr.length = 5; // Set length to remove element
console.log( arr ); // [1, 2, 3, 4, 5]
2.1.2. Using .pop()
method
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
The pop method removes the last element of the array, returns that element, and updates the length property. The pop method modifies the array on which it is invoked, This means unlike using delete the last element is removed completely and the array length reduced.
const arr = [1, 2, 3, 4, 5, 6];
arr.pop(); // returns 6
console.log( arr ); // [1, 2, 3, 4, 5]
| In-place: Yes |
| Removes duplicates: No |
| By value / index: N/A |
The .shift()
method works much like the pop method except it removes the first element of a JavaScript array instead of the last. When the element is removed the remaining elements are shifted down.
const arr = [1, 2, 3, 4];
arr.shift(); // returns 1
console.log( arr ); // [2, 3, 4]
| In-place: Yes |
| Removes duplicates: N/A |
| By value / index: N/A |
The fastest technique is to set an array variable to an empty array.
let arr = [1];
arr = []; //empty array
Alternatively technique from 2.1.1 can be used by setting length to 0.
Try the Vjet Javascript IDE from ebay (installation)
For an uglier version of unshift
use splice
:
TheArray.splice(0, 0, TheNewObject);
Basically Multi-programming is a concept where you run more than one program simultaneously, suppose you run two programs like chrome(browser) and calculator(system application).
Multi processing is where a user uses more than one processor to accomplish a task.
To know Multi threading we need to know what is a thread. A thread is basically a part of a program running within the program. Best example of thread is the tabs of a browser. If you have 5 tabs which are being opened and used then the program actually creates 5 threads of the program, this concept is called multi-threading.
[enhanced version]
This is going to be much faster and precise than the initial version below and will output the sum of all the file size of current directory:
echo `find . -type f -exec stat -c %s {} \; | tr '\n' '+' | sed 's/+$//g'` | bc
the stat -c %s
command on a file will return its size in bytes. The tr
command here is used to overcome xargs
command limitations (apparently piping to xargs
is splitting results on more lines, breaking the logic of my command). Hence tr
is taking care of replacing line feed with +
(plus) sign. sed
has the only goal to remove the last +
sign from the resulting string to avoid complains from the final bc
(basic calculator) command that, as usual, does the math.
Performances: I tested it on several directories and over ~150.000 files top (the current number of files of my fedora 15 box) having what I believe it is an amazing result:
# time echo `find / -type f -exec stat -c %s {} \; | tr '\n' '+' | sed 's/+$//g'` | bc
12671767700
real 2m19.164s
user 0m2.039s
sys 0m14.850s
Just in case you want to make a comparison with the du -sb /
command, it will output an estimated disk usage in bytes (-b
option)
# du -sb /
12684646920 /
As I was expecting it is a little larger than my command calculation because the du
utility returns allocated space of each file and not the actual consumed space.
[initial version]
You cannot use du
command if you need to know the exact sum size of your folder because (as per man page citation) du
estimates file space usage. Hence it will lead you to a wrong result, an approximation (maybe close to the sum size but most likely greater than the actual size you are looking for).
I think there might be different ways to answer your question but this is mine:
ls -l $(find . -type f | xargs) | cut -d" " -f5 | xargs | sed 's/\ /+/g'| bc
It finds all files under . directory (change . with whatever directory you like), also hidden files are included and (using xargs
) outputs their names in a single line, then produces a detailed list using ls -l
. This (sometimes) huge output is piped towards cut command and only the fifth field (-f5
), which is the file size in bytes is taken and again piped against xargs
which produces again a single line of sizes separated by blanks. Now take place a sed magic which replaces each blank space with a plus (+
) sign and finally bc
(basic calculator) does the math.
It might need additional tuning and you may have ls
command complaining about arguments list too long.
Old post but as it comes up for what I was searching for I thought I'd add some information to this topic. I was going to add a comment but I don't have enough rep.
As others have said:
connection.ConnectionTimeout is used for the initial connection
command.CommandTimeout is used for individual searches, updates, etc.
But:
connection.ConnectionTimeout is also used for committing and rolling back transactions.
Yes, this is an absolutely insane design decision.
So, if you are running into a timeout on commit or rollback you'll need to increase this value through the connection string.
My PrintMax version for prevent bad line breaks on output:
CREATE PROCEDURE [dbo].[PrintMax](@iInput NVARCHAR(MAX))
AS
BEGIN
Declare @i int;
Declare @NEWLINE char(1) = CHAR(13) + CHAR(10);
While LEN(@iInput)>0 BEGIN
Set @i = CHARINDEX(@NEWLINE, @iInput)
if @i>8000 OR @i=0 Set @i=8000
Print SUBSTRING(@iInput, 0, @i)
Set @iInput = SUBSTRING(@iInput, @i+1, LEN(@iInput))
END
END
type="text/javascript"
This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.
W3C did not adopt the
language
attribute, favoring instead atype
attribute which takes a MIME type. Unfortunately, the MIME type was not standardized, so it is sometimes"text/javascript"
or"application/ecmascript"
or something else. Fortunately, all browsers will always choose JavaScript as the default programming language, so it is always best to simply write<script>
. It is smallest, and it works on the most browsers.
For entertainment purposes only, I tried out the following five scripts
<script type="application/ecmascript">alert("1");</script>
<script type="text/javascript">alert("2");</script>
<script type="baloney">alert("3");</script>
<script type="">alert("4");</script>
<script >alert("5");</script>
On Chrome, all but script 3 (type="baloney"
) worked. IE8 did not run script 1 (type="application/ecmascript"
) or script 3. Based on my non-extensive sample of two browsers, it looks like you can safely ignore the type
attribute, but that it you use it you better use a legal (browser dependent) value.
Just do
docker attach container_name
As mentioned in the comments, to detach from the container without stopping it, type Ctrlpthen Ctrlq.
The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.
Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.
However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.
A complete function in DB2 SQL that accounts for the leap year 1900 error:
SELECT
DAYS(INPUT_DATE)
- DAYS(DATE('1899-12-30'))
- CASE
WHEN INPUT_DATE < DATE('1900-03-01')
THEN 1
ELSE 0
END
There is a better solution now: Vertical align anything with just 3 lines of CSS
Direct links to source for some popular programs in coreutils
:
cat
(767 lines)chmod
(570 lines)cp
(2912 lines)cut
(831 lines)date
(570 lines)df
(1718 lines)du
(1112 lines)echo
(272 lines)head
(1070 lines)hostname
(116 lines)kill
(312 lines)ln
(651 lines)ls
(4954 lines)md5sum
(878 lines)mkdir
(306 lines)mv
(512 lines)nice
(220 lines)pwd
(394 lines)rm
(356 lines)rmdir
(252 lines)shred
(1325 lines)tail
(2301 lines)tee
(220 lines)touch
(437 lines)wc
(801 lines)whoami
(91 lines)A somewhat different approach using ggplot2:
dat <- read.table(text = "A B C D E F G
1 480 780 431 295 670 360 190
2 720 350 377 255 340 615 345
3 460 480 179 560 60 735 1260
4 220 240 876 789 820 100 75", header = TRUE)
library(reshape2)
dat$row <- seq_len(nrow(dat))
dat2 <- melt(dat, id.vars = "row")
library(ggplot2)
ggplot(dat2, aes(x = variable, y = value, fill = row)) +
geom_bar(stat = "identity") +
xlab("\nType") +
ylab("Time\n") +
guides(fill = FALSE) +
theme_bw()
this gives:
When you want to include a legend, delete the guides(fill = FALSE)
line.
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
Decorate Components with the JLayer Class:
The JLayer class is a flexible and powerful decorator for Swing components. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project project at java.net. The JLayer class was initially based on the JXLayer project, but its API evolved separately.
Strings in switch Statement:
In the JDK 7 , we can use a String object in the expression of a switch statement. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
Type Inference for Generic Instance:
We can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:
List<String> l = new ArrayList<>();
l.add("A");
l.addAll(new ArrayList<>());
In comparison, the following example compiles:
List<? extends String> list2 = new ArrayList<>();
l.addAll(list2);
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking:
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication. Consider the following code, which contains duplicate code in each of the catch blocks:
catch (IOException e) {
logger.log(e);
throw e;
}
catch (SQLException e) {
logger.log(e);
throw e;
}
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable e has different types. The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch (IOException|SQLException e) {
logger.log(e);
throw e;
}
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).
The java.nio.file package
The java.nio.file
package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7.
If you would like to indent text within a div without changing the size of the div use the CSS text-indent
instead of padding-left
.
.indent {_x000D_
text-indent: 1em;_x000D_
}_x000D_
.border {_x000D_
border-style: solid;_x000D_
}
_x000D_
<div class="border">_x000D_
Non indented_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<div class="border indent">_x000D_
Indented_x000D_
</div>
_x000D_
If you only need the dictionary keys 1
, 2
, and 3
use: your_dict.keys()
.
If you only need the dictionary values -0.3246
, -0.9185
, and -3985
use: your_dict.values()
.
If you want both keys and values use: your_dict.items()
which returns a list of tuples [(key1, value1), (key2, value2), ...]
.
This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer
element in my case didn't show. I added a position: relative
which worked.
Old post but I made an good solution what is tested on serval places.
https://github.com/CreativForm/Load-jQuery-if-it-is-not-already-loaded
CODE:
(function(url, position, callback){
// default values
url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
position = position || 0;
// Check is jQuery exists
if (!window.jQuery) {
// Initialize <head>
var head = document.getElementsByTagName('head')[0];
// Create <script> element
var script = document.createElement("script");
// Append URL
script.src = url;
// Append type
script.type = 'text/javascript';
// Append script to <head>
head.appendChild(script);
// Move script on proper position
head.insertBefore(script,head.childNodes[position]);
script.onload = function(){
if(typeof callback == 'function') {
callback(jQuery);
}
};
} else {
if(typeof callback == 'function') {
callback(jQuery);
}
}
}('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){
console.log($);
}));
At GitHub is better explanation but generaly this function you can add anywhere in your HTML code and you will initialize jquery if is not already loaded.
Pim's answer is very helpful. In my case, I have to use
Expires / Max-Age: "Session"
If it is a dateTime, even it is not expired, it still won't send the cookie to the backend:
Expires / Max-Age: "Thu, 21 May 2020 09:00:34 GMT"
Hope it is helpful for future people who may meet same issue.
I found this question while Googling. Note that if you just want to make use of the URI's content via something like a string, consider using Apache's IOUtils.toString()
method.
For example, a sample line of code could be:
String pageContent = IOUtils.toString("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de", Charset.UTF_8);
Add text-align: center;
to the parent tag of <canvas>
. That's it.
Example:
<div style="text-align: center">
<canvas width="300" height="300">
<!--your canvas code -->
</canvas>
</div>
try this ^^
$(document).ready(function() {
$("form").bind("keypress", function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
Hope this helps
From the man page:
search, -S text|/text/ Perform a substring search of formula names for text. If text is surrounded with slashes, then it is interpreted as a regular expression. If no search term is given, all available formula are displayed.
For your purposes, brew search
will suffice.
The solution tbaxter120 suggested worked for me but I needed something that will be supported both in MySQL & Oracle & MSSQL, and here it is:
WHERE (CONCAT(',' ,CONCAT(RTRIM(MyColumn), ','))) LIKE CONCAT('%,' , CONCAT(@search , ',%'))
You just can put your query as a subquery:
SELECT avg(count)
FROM
(
SELECT COUNT (*) AS Count
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time )
FROM Table B
WHERE (B.Id = T.Id))
GROUP BY T.Grouping
) as counts
Edit: I think this should be the same:
SELECT count(*) / count(distinct T.Grouping)
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time)
FROM Table B
WHERE (B.Id = T.Id))
Add new SSH keys as described in this article on GitHub.
If Git still asks you for username & password, try changing https://github.com/
to [email protected]:
in remote URL:
$ git config remote.origin.url
https://github.com/dir/repo.git
$ git config remote.origin.url "[email protected]:dir/repo.git"
As an extension to what John said, if you want to extract the string representation and store it in a std::string
do this:
#include <sstream>
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace
std::stringstream
is located in the <sstream>
header.
You need to join
the two tables and then filter the result in where
clause:
SELECT country.name as country, country.headofstate
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'
This code:
app.all('*', function (req, res) {
res.sendFile(__dirname+'/index.html') /* <= Where my ng-view is located */
})
tells Express that no matter what the browser requests, your server should return index.html
. So when the browser requests JavaScript files like jquery-x.y.z.main.js
or angular.min.js
, your server is returning the contents of index.html
, which start with <!DOCTYPE html>
, which causes the JavaScript error.
Your code inside the callback should be looking at the request to determine which file to send back, and/or you should be using a different path pattern with app.all
. See the routing guide for details.
This is a CSS trick, not a formal solution. I leave the code with the period black because it helps me position the element. Afterward, color your content (color:white) and (margin-top:-5px or so) to make it as though the period is not there.
div.yourdivname:after {
content: ".";
border-bottom:1px solid grey;
width:60%;
display:block;
margin:0 auto;
}
We can call Controller method using Javascript / Jquery very easily as follows:
Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = null;
try
{
Processing...
Get Result and fill arr.
}
catch { }
return Json(arr , JsonRequestBehavior.AllowGet);
}
Following is the complex type (class)
public class A
{
public string property1 {get ; set ;}
public string property2 {get ; set ;}
}
Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.
function callControllerMethod(value1 , value2) {
var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1 ¶m2=value2'
$.getJSON(strMethodUrl, receieveResponse);
}
function receieveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].property1);
}
}
}
In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.
receieveResponse is the callback function receiving the response or return value of the controllers method.
Here we made use of JSON , since we can't make use of the C# class object
directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:
Json(arr , JsonRequestBehavior.AllowGet);
and returned that Json object.
Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.
For more detaill click here
You need add -> contentType: "application/json; charset=utf-8",
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
I solved this issue this way:
Go to Run menu ====> click on Edit Configurations ====> Micellaneous and finaly uncheck the option Skip installation if APK has not changed
What about using App-V? http://www.microsoft.com/systemcenter/appv/default.mspx
In particular Dynamic Application Virtualization http://www.microsoft.com/systemcenter/appv/dynamic.mspx
It virtualizes at the application level. It is useful when running incompatible software on the same OS instance.
for just translating one char into another throughout a string, tr
is the best tool:
tr '\\' '/'
The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
You can use this configuration for cuda 10.0 (10.1 does not work as of 3/18), this runs for me:
Install version tensorflow gpu:
pip install tensorflow-gpu==1.4.0
it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.
You can do this:
select t2.*
from t1
join t2 on t2.url = 'site.com/path/' + CAST(t1.id AS VARCHAR(10)) + '/more'
where t1.id > 9000
Pay attention to CAST(t1.id AS VARCHAR(10))
.
Maybe someone is looking for a more generic approach, since Java 8 there is the Package java.util.function
that allows to define Supplier Functions. You could have a function that takes a supplier and a default value as follows:
public static <T> T tryGetOrDefault(Supplier<T> supplier, T defaultValue) {
try {
return supplier.get();
} catch (Exception e) {
return defaultValue;
}
}
With this function, you can execute any parsing method or even other methods that could throw an Exception while ensuring that no Exception can ever be thrown:
Integer i = tryGetOrDefault(() -> Integer.parseInt(stringValue), 0);
Long l = tryGetOrDefault(() -> Long.parseLong(stringValue), 0l);
Double d = tryGetOrDefault(() -> Double.parseDouble(stringValue), 0d);
I came across this post in search for the dockerhub repo URL when creating a dockerhub kubernetes secret.. figured id share the URL is used with success, hope that's ok.
Live Current: https://index.docker.io/v2/
Dead Orginal: https://index.docker.io/v1/
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
You forgot to add the global operator. Use this:
var s = "04.07.2012";_x000D_
alert(s.replace(new RegExp("[0-9]","g"), "X"));
_x000D_
There is a cocoapod APScheduledLocationManager that allows to get background location updates every n seconds with desired location accuracy.
let manager = APScheduledLocationManager(delegate: self)
manager.startUpdatingLocation(interval: 170, acceptableLocationAccuracy: 100)
The repository also contains an example app written in Swift 3.
If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.
=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))
or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.
=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")
in earlier versions you need to repeat the VLOOKUP, e.g.
=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))
async
and defer
will download the file during HTML parsing. Both will not interrupt the parser.
The script with async
attribute will be executed once it is downloaded. While the script with defer
attribute will be executed after completing the DOM parsing.
The scripts loaded with async
doesn't guarantee any order. While the scripts loaded with defer
attribute maintains the order in which they appear on the DOM.
Use <script async>
when the script does not rely on anything.
when the script depends use <script defer>
.
Best solution would be add the <script>
at the bottom of the body. There will be no issue with blocking or rendering.
The CompletionService will take your Callables with the .submit() method and you can retrieve the computed futures with the .take() method.
One thing you must not forget is to terminate the ExecutorService by calling the .shutdown() method. Also you can only call this method when you have saved a reference to the executor service so make sure to keep one.
Example code - For a fixed number of work items to be worked on in parallel:
ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
CompletionService<YourCallableImplementor> completionService =
new ExecutorCompletionService<YourCallableImplementor>(service);
ArrayList<Future<YourCallableImplementor>> futures = new ArrayList<Future<YourCallableImplementor>>();
for (String computeMe : elementsToCompute) {
futures.add(completionService.submit(new YourCallableImplementor(computeMe)));
}
//now retrieve the futures after computation (auto wait for it)
int received = 0;
while(received < elementsToCompute.size()) {
Future<YourCallableImplementor> resultFuture = completionService.take();
YourCallableImplementor result = resultFuture.get();
received ++;
}
//important: shutdown your ExecutorService
service.shutdown();
Example code - For a dynamic number of work items to be worked on in parallel:
public void runIt(){
ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
CompletionService<CallableImplementor> completionService = new ExecutorCompletionService<CallableImplementor>(service);
ArrayList<Future<CallableImplementor>> futures = new ArrayList<Future<CallableImplementor>>();
//Initial workload is 8 threads
for (int i = 0; i < 9; i++) {
futures.add(completionService.submit(write.new CallableImplementor()));
}
boolean finished = false;
while (!finished) {
try {
Future<CallableImplementor> resultFuture;
resultFuture = completionService.take();
CallableImplementor result = resultFuture.get();
finished = doSomethingWith(result.getResult());
result.setResult(null);
result = null;
resultFuture = null;
//After work package has been finished create new work package and add it to futures
futures.add(completionService.submit(write.new CallableImplementor()));
} catch (InterruptedException | ExecutionException e) {
//handle interrupted and assert correct thread / work packet count
}
}
//important: shutdown your ExecutorService
service.shutdown();
}
public class CallableImplementor implements Callable{
boolean result;
@Override
public CallableImplementor call() throws Exception {
//business logic goes here
return this;
}
public boolean getResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
}
This comes in late but was quite helpful. I am Just posting for future reference
DataTable dt = new DataTable();
Data.DataView dv = default(Data.DataView);
dv = (Data.DataView)ds.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();
Type 'line numbers' into the Quick Launch textbox (top right VS 2015), and it'll take you right where you need to be (tick Line Numbers checkbox).
Use GET method if you want to retrieve the resources from URL. You could always see the last page if you hit the back button of your browser, and it could be bookmarked, so it is not as secure as POST method.
Use POST method if you want to 'submit' something to the URL. For example you want to create a google account and you may need to fill in all the detailed information, then you hit 'submit' button (POST method is called here), once you submit successfully, and try to hit back button of your browser, you will get error or a new blank form, instead of last page with filled form.
PHP escapes forward slashes by default which is probably why this appears so commonly. I'm not sure why, but possibly because embedding the string "</script>"
inside a <script>
tag is considered unsafe.
This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES
flag but most developers will not use this since the original result is already valid JSON.
Simple sample (without write reflection hard code in the client)
class Customer
{
public string CustomerName { get; set; }
public string Address { get; set; }
// approach here
public string GetPropertyValue(string propertyName)
{
try
{
return this.GetType().GetProperty(propertyName).GetValue(this, null) as string;
}
catch { return null; }
}
}
//use sample
static void Main(string[] args)
{
var customer = new Customer { CustomerName = "Harvey Triana", Address = "Something..." };
Console.WriteLine(customer.GetPropertyValue("CustomerName"));
}
SELECT * FROM table_name WHERE primary_key IN (SELECT MAX(primary_key) FROM table_name GROUP BY column_name )
My guess is that you have to also style the views that are generated from the menu information in your onCreateOptionsMenu(). The styling you applied so far is working, but I doubt that the menu items, when rendered with text use a style that is the same as the title part of the ActionBar.
You may want to look at Menu.getActionView() to get the view for the menu action and then adjust it accordingly.
Besides using Visual Studio's JavaScript debugger, I wrote my own simple panel that I include to a page. It's simply like the Immediate window of Visual Studio. I can change my variables' values, call my functions, and see variables' values. It simply evaluates the code written in the text field.
function getFacebookImageFromURL($url)
{
$headers = get_headers($url, 1);
if (isset($headers['Location']))
{
return $headers['Location'];
}
}
$url = 'https://graph.facebook.com/zuck/picture?type=large';
$imageURL = getFacebookImageFromURL($url);
Why all the other answers use slideUp
is just beyond me. As I'm using the fade
and in
classes to have the alert fade away when closed (or after timeout), I don't want it to "slide up" and conflict with that.
Besides the slideUp
method didn't even work. The alert itself didn't show at all. Here's what worked perfectly for me:
$(document).ready(function() {
// show the alert
setTimeout(function() {
$(".alert").alert('close');
}, 2000);
});
If you want to auto size all columns in a workbook, here is a method that might be useful:
public void autoSizeColumns(Workbook workbook) {
int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = workbook.getSheetAt(i);
if (sheet.getPhysicalNumberOfRows() > 0) {
Row row = sheet.getRow(sheet.getFirstRowNum());
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int columnIndex = cell.getColumnIndex();
sheet.autoSizeColumn(columnIndex);
}
}
}
}
I combined @glenn jackman's answer and @pcarvalho's answer(in comment list, there is something wrong with pcarvalho's answer because the extra style control function of character '`'(backtick)).
My script can accept path as an augument and sort the directory list as ls -l
, also it can handles the problem of "space in file name".
#!/bin/bash
OLD_IFS="$IFS"
IFS=$'\n'
for dir in $(find $1 -maxdepth 1 -type d | sort);
do
files=("$dir"/*)
printf "%5d,%s\n" "${#files[@]}" "$dir"
done
FS="$OLD_IFS"
My first answer in stackoverflow, and I hope it can help someone ^_^
public class FindTextInLine {
String match = "123woods";
String text = "I will come and meet you at the 123woods";
public void findText () {
if (text.contains(match)) {
System.out.println("Keyword matched the string" );
}
}
}
You can try this:
/*iPad landscape oriented styles */
@media only screen and (device-width:768px)and (orientation:landscape){
.yourstyle{
}
}
/*iPad Portrait oriented styles */
@media only screen and (device-width:768px)and (orientation:portrait){
.yourstyle{
}
}
You can use grep to get the byte-offset of the matching part of a string:
echo $str | grep -b -o str
As per your example:
[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat
you can pipe that to awk if you just want the first part
echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'
I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:
@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })
The above format can of course be changed to whatever.
Sometimes you need to grep the process by name - in that case:
ps aux | grep simple-scan
Example output:
simple-scan 1090 0.0 0.1 4248 1432 ? S Jun11 0:00
Nowadays there is a new(ish) API to do this directly. It works on modern browsers and on HTTPS (and localhost) only. Not supported by IE11.
IE11 has its own API.
And the workaround in the accepted answer can be used for unsecure hosts.
function copyToClipboard (text) {
if (navigator.clipboard) { // default: modern asynchronous API
return navigator.clipboard.writeText(text);
} else if (window.clipboardData && window.clipboardData.setData) { // for IE11
window.clipboardData.setData('Text', text);
return Promise.resolve();
} else {
// workaround: create dummy input
const input = h('input', { type: 'text' });
input.value = text;
document.body.append(input);
input.focus();
input.select();
document.execCommand('copy');
input.remove();
return Promise.resolve();
}
}
Note: it uses Hyperscript to create the input element (but should be easy to adapt)
There is no need to make the input invisible, as it is added and removed so fast. Also when hidden (even using some clever method) some browsers will detect it and prevent the copy operation.
Doing this works for me:
moment(new Date("27/04/2016")).format
This may help:
ls -l| grep -v '^d'| awk '{total = total + $5} END {print "Total" , total}'
The above command will sum total all the files leaving the directories size.
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
var sizef = document.getElementById('input-file-id').files[0].size;
if(sizef > 210000){
alert('sorry error');
}else {
//action
}
it works in Linux. perhaps there are system settings which can be changed in Windows to allow it.
jcomeau@aspire:/tmp$ cat test.java; javac test.java; java test
import java.awt.event.*;
import java.awt.Robot;
public class test {
public static void main(String args[]) {
Robot bot = null;
try {
bot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instantiating Robot: " + failed);
}
int mask = InputEvent.BUTTON1_DOWN_MASK;
bot.mouseMove(100, 100);
bot.mousePress(mask);
bot.mouseRelease(mask);
}
}
I'm assuming InputEvent.MOUSE_BUTTON1_DOWN
in your version of Java is the same thing as InputEvent.BUTTON1_DOWN_MASK
in mine; I'm using 1.6.
otherwise, that could be your problem. I can tell it worked because my Chrome browser was open to http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html when I ran the program, and it changed to Debian.org because that was the link in the bookmarks bar at (100, 100).
[added later after cogitating on it today] it might be necessary to trick the listening program by simulating a smoother mouse movement. see the answer here: How to move a mouse smoothly throughout the screen by using java?
sudo apt-get install php5-mcrypt
sudo apt-get install php5-mysql
...etc resolved it for me :)
hope it helps
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
better code that doesn't involve ping:
SET COUNTER=0
:loop
SET /a COUNTER=%COUNTER%+1
XCOPY "Server\*" "c:\minecraft\backups\server_backup_%COUNTER%" /i /s
timeout /t 600 /nobreak >nul
goto loop
600 seconds is 10 minutes, however you can set it whatever time you'd like
There are some basics difference between ICollection and IEnumerable
Simple Program:
using System;
using System.Collections;
using System.Collections.Generic;
namespace StackDemo
{
class Program
{
static void Main(string[] args)
{
List<Person> persons = new List<Person>();
persons.Add(new Person("John",30));
persons.Add(new Person("Jack", 27));
ICollection<Person> personCollection = persons;
IEnumerable<Person> personEnumeration = persons;
// IEnumeration
// IEnumration Contains only GetEnumerator method to get Enumerator and make a looping
foreach (Person p in personEnumeration)
{
Console.WriteLine("Name:{0}, Age:{1}", p.Name, p.Age);
}
// ICollection
// ICollection Add/Remove/Contains/Count/CopyTo
// ICollection is inherited from IEnumerable
personCollection.Add(new Person("Tim", 10));
foreach (Person p in personCollection)
{
Console.WriteLine("Name:{0}, Age:{1}", p.Name, p.Age);
}
Console.ReadLine();
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
}
I experienced this error when have ported Windows application to Linux. In Windows, database table names are case-insensitive, and in Linux they are case-sensitive, probably because of file system difference. So, on Windows table Table1
is the same as table1
, and in REFERENCES
both table1
and Table1
works. On Linux, when application used table1
instead of Table1
when it created database structure I saw error #150; when I made correct character case in Table1
references, it started to work on Linux too. So, if nothing else helps, make you sure that in REFERENCES
you use correct character case in table name when you on Linux.
Use the builtin function zip()
:
In Python 3:
z = list(zip(x,y))
In Python 2:
z = zip(x,y)
I am able to download it using apple's download website today. https://developer.apple.com/download/
I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.
No.
If the user is sophisticated or determined enough to:
then they are probably sophisticated or determined enough to:
So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.
echoing @HYRY, see the new docs in 0.11
http://pandas.pydata.org/pandas-docs/stable/indexing.html
Here we have new operators, .iloc
to explicity support only integer indexing, and .loc
to explicity support only label indexing
e.g. imagine this scenario
In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB'))
In [2]: df
Out[2]:
A B
0 1.068932 -0.794307
2 -0.470056 1.192211
4 -0.284561 0.756029
6 1.037563 -0.267820
8 -0.538478 -0.800654
In [5]: df.iloc[[2]]
Out[5]:
A B
4 -0.284561 0.756029
In [6]: df.loc[[2]]
Out[6]:
A B
2 -0.470056 1.192211
[]
slices the rows (by label location) only
There is a condition that most of these solutions do not address. I revised Patrick Honorez's solution to handle it. I felt I had to share this because I was pulling my hair out when the original function was occasionally clearing more data that I expected.
The situation happens when the table only has one column and the .SpecialCells(xlCellTypeConstants).ClearContents
attempts to clear the contents of the top row. In this situation, only one cell is selected (the top row of the table that only has one column) and the SpecialCells command applies to the entire sheet instead of the selected range. What was happening to me was other cells on the sheet that were outside of my table were also getting cleared.
I did some digging and found this advice from Mathieu Guindon: Range SpecialCells ClearContents clears whole sheet
Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
If the list/table only has one column (in row 1), this revision will check to see if the cell has a formula and if not, it will only clear the contents of that one cell.
Public Sub ClearList(lst As ListObject)
'Clears a listObject while leaving 1 empty row + formula
' https://stackoverflow.com/a/53856079/1898524
'
'With special help from this post to handle a single column table.
' Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
' Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
' https://stackoverflow.com/questions/40537537/range-specialcells-clearcontents-clears-whole-sheet-instead
On Error Resume Next
With lst
'.Range.Worksheet.Activate ' Enable this if you are debugging
If .ShowAutoFilter Then .AutoFilter.ShowAllData
If .DataBodyRange.Rows.Count = 1 Then Exit Sub ' Table is already clear
.DataBodyRange.Offset(1).Rows.Clear
If .DataBodyRange.Columns.Count > 1 Then ' Check to see if SpecialCells is going to evaluate just one cell.
.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
ElseIf Not .Range.HasFormula Then
' Only one cell in range and it does not contain a formula.
.DataBodyRange.Rows(1).ClearContents
End If
.Resize .Range.Rows("1:2")
.HeaderRowRange.Offset(1).Select
' Reset used range on the sheet
Dim X
X = .Range.Worksheet.UsedRange.Rows.Count 'see J-Walkenbach tip 73
End With
End Sub
A final step I included is a tip that is attributed to John Walkenbach, sometimes noted as J-Walkenbach tip 73
Automatically Resetting The Last Cell
In many cases, I believe @allcaps's answer works well.
However, sometimes it is necessary to actually rename an app, e.g. to improve code readability or prevent confusion.
Most of the other answers involve either manual database manipulation or tinkering with existing migrations, which I do not like very much.
As an alternative, I like to create a new app with the desired name, copy everything over, make sure it works, then remove the original app:
Start a new app with the desired name, and copy all code from the original app into that. Make sure you fix the namespaced stuff, in the newly copied code, to match the new app name.
makemigrations
and migrate
Create a data migration that copies the relevant data from the original app's tables into the new app's tables, and migrate
again.
At this point, everything still works, because the original app and its data are still in place.
Now you can refactor all the dependent code, so it only makes use of the new app. See other answers for examples of what to look out for.
Once you are certain that everything works, you can remove the original app.
This has the advantage that every step uses the normal Django migration mechanism, without manual database manipulation, and we can track everything in source control. In addition, we keep the original app and its data in place until we are sure everything works.
If you're using Java, Javascript or PHP, then there's a library that will do these calculations exactly, using some amusingly complicated (but still fast) trigonometry:
At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.
Thats why it always -ve.
URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.
There are several ways to soften the pain:
JSF EL offers a shorthand to ${pageContext.request}
in flavor of #{request}
:
<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>
You can if necessary use <c:set>
tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:
<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>
JSF 2.x offers the <h:link>
which can take a view ID relative to the context root in outcome
and it will append the context path and FacesServlet
mapping automatically:
<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>
HTML offers the <base>
tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>
.
<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>
(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring()
, see also this answer)
This should end up in the generated HTML something like as
<base href="http://example.com/webname/" />
Note that the <base>
tag has a caveat: it makes all jump anchors in the page like <a href="#top">
relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a>
or <h:link value="top" fragment="top" />
.
The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...
ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286
original query...
SELECT StudentId FROM Student WHERE condition = xyz
original result set...
StudentId
1236
7656
8990
new query w/ concat...
SELECT group_concat(concat_ws(',', StudentId) separator '; ')
FROM Student
WHERE condition = xyz
concat string result set...
StudentId
1236; 7656; 8990
note: change the 'separator' to whatever you would like
GLHF!
You cant use href tags within option tags. You will need javascript to do so.
<select name="formal" onchange="javascript:handleSelect(this)">
<option value="home">Home</option>
<option value="contact">Contact</option>
</select>
<script type="text/javascript">
function handleSelect(elm)
{
window.location = elm.value+".php";
}
</script>
Alternatively, if you do not wish to push to a repository:
Export the container to a tarball
docker export <CONTAINER ID> > /home/export.tar
Move your tarball to new machine
Import it back
cat /home/export.tar | docker import - some-name:latest
On Windows, if you're running PuTTY/Pageant, the fingerprint is listed when you load your PuTTY (.ppk) key into Pageant. It is pretty useful in case you forget which one you're using.
Other way which I found useful is:
git checkout <wildcard>
Example:
git checkout *.html
More generally:
git checkout <branch> <filename/wildcard>
This should answer that question, and then some.
The second line, if (obj.GetType() == typeof(ClassA)) {}
, is faster, for those that don't want to read the article.
(Be aware that they don't do the same thing)
mythreads = threading.enumerate()
Enumerate returns a list of all Thread objects still alive. https://docs.python.org/3.6/library/threading.html
Usually I create Fowler's Range implementation for such things.
public interface IRange<T>
{
T Start { get; }
T End { get; }
bool Includes(T value);
bool Includes(IRange<T> range);
}
public class DateRange : IRange<DateTime>
{
public DateRange(DateTime start, DateTime end)
{
Start = start;
End = end;
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
public bool Includes(DateTime value)
{
return (Start <= value) && (value <= End);
}
public bool Includes(IRange<DateTime> range)
{
return (Start <= range.Start) && (range.End <= End);
}
}
Usage is pretty simple:
DateRange range = new DateRange(startDate, endDate);
range.Includes(date)
I suggest to use a CSS class called clickbox and activate it with jQuery:
$(".clickbox").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
Now the only thing you have to do is mark your div as clickable and provide a link:
<div id="logo" class="clickbox"><a href="index.php"></a></div>
Plus a CSS style to change the mouse cursor:
.clickbox {
cursor: pointer;
}
Easy, isn't it?
There is no need to use angular http, you can get with js native functions
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
// on the first then you will return blob from response_x000D_
return await fetch(url).then(r => r.blob())_x000D_
.then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
_x000D_
return new File([blob], fileName+'.'+ blob.type.split('/')[1]) ;_x000D_
});_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
// with file reader you will transform the file in a data url file;_x000D_
var reader = new FileReader();_x000D_
reader.readAsDataURL(file);_x000D_
reader.onloadend = () => {_x000D_
_x000D_
// just putting the data url to img element_x000D_
document.querySelector('#image').src = reader.result ;_x000D_
}_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
If you want more datesource configs e.g.
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1
you could use below code
@Bean
public DataSource dataSource() {
DataSource dataSource = new DataSource(); // org.apache.tomcat.jdbc.pool.DataSource;
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMills);
dataSource.setValidationQuery(validationQuery);
return dataSource;
}
refer: Spring boot jdbc Connection
-ErrorAction Stop
is changing things for you. Try adding this and see what you get:
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
Worked for me. All the similar ones didn't.
Try run the task with high privileges.
put a \ at the end of path in "start in folder" such as c:\temp\
I do not know why , but this works for me sometimes.