select status, timeplaced
from orders
where TIMEPLACED>'2017-06-12 00:00:00'
I'm the author of a package that's been around for about 10 years, and it has a function that addresses this question directly. Basically, if you are on a non-Windows system, it uses Popen
to access find
. However, if you are on Windows, it replicates find
with an efficient filesystem walker.
The code itself does not use a try
block… except in determining the operating system and thus steering you to the "Unix"-style find
or the hand-buillt find
. Timing tests showed that the try
was faster in determining the OS, so I did use one there (but nowhere else).
>>> import pox
>>> pox.find('*python*', type='file', root=pox.homedir(), recurse=False)
['/Users/mmckerns/.python']
And the doc…
>>> print pox.find.__doc__
find(patterns[,root,recurse,type]); Get path to a file or directory
patterns: name or partial name string of items to search for
root: path string of top-level directory to search
recurse: if True, recurse down from root directory
type: item filter; one of {None, file, dir, link, socket, block, char}
verbose: if True, be a little verbose about the search
On some OS, recursion can be specified by recursion depth (an integer).
patterns can be specified with basic pattern matching. Additionally,
multiple patterns can be specified by splitting patterns with a ';'
For example:
>>> find('pox*', root='..')
['/Users/foo/pox/pox', '/Users/foo/pox/scripts/pox_launcher.py']
>>> find('*shutils*;*init*')
['/Users/foo/pox/pox/shutils.py', '/Users/foo/pox/pox/__init__.py']
>>>
The implementation, if you care to look, is here: https://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190
I actually just found this today for something I'm working on. This will return file paths for all files in a folder and its subfolders.
Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Users\Marek\Desktop\Makro\", "*.*", True
Dim vFile As Variant
For Each vFile In colFiles
'file operation here or store file name/path in a string array for use later in the script
filepath(n) = vFile
filename = fso.GetFileName(vFile) 'If you want the filename without full path
n=n+1
Next vFile
'These two functions are required
Public Function RecursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Function
Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If Right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function
This is adapted from a post by Ammara Digital Image Solutions.(http://www.ammara.com/access_image_faq/recursive_folder_search.html).
just return true inside your if statement
var myArr = [1,2,3,4];
myArr.forEach(function(elem){
if (elem === 3) {
return true;
// Go to "next" iteration. Or "continue" to next iteration...
}
console.log(elem);
});
Use style="display:none"
in your dropdown list tag and in jquery use the following to display and hide.
$("#yourdropdownid").css('display', 'inline');
OR
$("#yourdropdownid").css('display', 'none');
Try this:
df.my_channel = df.my_channel.where(df.my_channel <= 20000, other= 0)
or
df.my_channel = df.my_channel.mask(df.my_channel > 20000, other= 0)
SELECT P.*
FROM primary_table P
LEFT JOIN secondary_table S on P.id = S.p_id
WHERE S.p_id IS NULL
There are really two big benefits to guard
. One is avoiding the pyramid of doom, as others have mentioned – lots of annoying if let
statements nested inside each other moving further and further to the right.
The other benefit is often the logic you want to implement is more "if not let
” than "if let { } else
".
Here’s an example: suppose you want to implement accumulate
– a cross between map
and reduce
where it gives you back an array of running reduces. Here it is with guard
:
extension Sliceable where SubSlice.Generator.Element == Generator.Element {
func accumulate(combine: (Generator.Element,Generator.Element)->Generator.Element) -> [Generator.Element] {
// if there are no elements, I just want to bail out and
// return an empty array
guard var running = self.first else { return [] }
// running will now be an unwrapped non-optional
var result = [running]
// dropFirst is safe because the collection
// must have at least one element at this point
for x in dropFirst(self) {
running = combine(running, x)
result.append(running)
}
return result
}
}
let a = [1,2,3].accumulate(+) // [1,3,6]
let b = [Int]().accumulate(+) // []
How would you write it without guard, but still using first
that returns an optional? Something like this:
extension Sliceable where SubSlice.Generator.Element == Generator.Element {
func accumulate(combine: (Generator.Element,Generator.Element)->Generator.Element) -> [Generator.Element] {
if var running = self.first {
var result = [running]
for x in dropFirst(self) {
running = combine(running, x)
result.append(running)
}
return result
}
else {
return []
}
}
}
The extra nesting is annoying, but also, it’s not as logical to have the if
and the else
so far apart. It’s much more readable to have the early exit for the empty case, and then continue with the rest of the function as if that wasn’t a possibility.
No need to reinvent the wheel! Use Currency Mask, unlike TextMaskModule, this one works with number input type and it's super easy to configure. I found when I made my own directive, I had to keep converting between number and string to do calculations. Save yourself the time. Here's the link:
Nowadays your compiler should do all the work for you. At least of what I know gcc is very efficient in optimizing calls to memset
away (better check the assembler, though).
Then also, avoid memset
if you don't have to:
... = { 0
}
) for stack memoryAnd for really large chunks use mmap
if you have it. This just gets zero initialized memory from the system "for free".
In Intent, you can directly put Uri. You don't need to convert the Uri to string and convert back again to Uri.
Look at this simple approach.
// put uri to intent
intent.setData(imageUri);
And to get Uri back from intent:
// Get Uri from Intent
Uri imageUri=getIntent().getData();
You can't manipulate :after
, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after
specified.
CSS:
.pageMenu .active.changed:after {
/* this selector is more specific, so it takes precedence over the other :after */
border-top-width: 22px;
border-left-width: 22px;
border-right-width: 22px;
}
JS:
$('.pageMenu .active').toggleClass('changed');
UPDATE: while it's impossible to directly modify the :after
content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.
Flexible solution:
function size($size, array $options=null) {
$o = [
'binary' => false,
'decimalPlaces' => 2,
'decimalSeparator' => '.',
'thausandsSeparator' => '',
'maxThreshold' => false, // or thresholds key
'suffix' => [
'thresholds' => ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
'decimal' => ' {threshold}B',
'binary' => ' {threshold}iB',
'bytes' => ' B'
]
];
if ($options !== null)
$o = array_replace_recursive($o, $options);
$base = $o['binary'] ? 1024 : 1000;
$exp = $size ? floor(log($size) / log($base)) : 0;
if (($o['maxThreshold'] !== false) &&
($o['maxThreshold'] < $exp)
)
$exp = $o['maxThreshold'];
return !$exp
? (round($size) . $o['suffix']['bytes'])
: (
number_format(
$size / pow($base, $exp),
$o['decimalPlaces'],
$o['decimalSeparator'],
$o['thausandsSeparator']
) .
str_replace(
'{threshold}',
$o['suffix']['thresholds'][$exp],
$o['suffix'][$o['binary'] ? 'binary' : 'decimal']
)
);
}
var_dump(size(disk_free_space('/')));
// string(8) "14.63 GB"
var_dump(size(disk_free_space('/'), ['binary' => true]));
// string(9) "13.63 GiB"
var_dump(size(disk_free_space('/'), ['maxThreshold' => 2]));
// string(11) "14631.90 MB"
var_dump(size(disk_free_space('/'), ['binary' => true, 'maxThreshold' => 2]));
// string(12) "13954.07 MiB"
NSString * pathv = [[NSBundle mainBundle] pathForResource:@"vfile" ofType:@"mov"];
playerv = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:pathv]];
[self presentMoviePlayerViewControllerAnimated:playerv];
Googling gives me this:
Command A & Command B
Execute Command A, then execute Command B (no evaluation of anything)
Command A | Command B
Execute Command A, and redirect all its output into the input of Command B
Command A && Command B
Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B
Command A || Command B
Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B
This was the order I got everything working. The second point is the most important one. Scipy needs Numpy+MKL
, not just vanilla Numpy
.
pip install "file path"
(download Numpy+MKL wheel from here http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy)pip install scipy
I use git gc after I do a big checkout, and have a lot of new object. it can save space. E.g. if you checkout a big SVN project using git-svn, and do a git gc, you typically save a lot of space
Is not necessary to pass the data as JSON string, you can pass the object directly, without defining contentType
or dataType
, like this:
$.ajax({
type: "POST",
url: "TelephoneNumbers.aspx/DeleteNumber",
data: data0,
success: function(data)
{
alert('Done');
}
});
In your onCreate()
method:
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.main_activity_background_color));
Also you need to add to values folder a new XML file called color.xml
and Assign there a new color property:
color.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="main_activity_background_color">#000000</color>
</resources>
Note that you can name the color.xml
any name you want but you refer to it by code as R.color.yourId
.
EDIT
Because getResources().getColor()
is deprecated, use getWindow().getDecorView().setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.main_activity_background_color));
instead.
This isn't so difficult.
Just check your gtk+ toolkit utilities version from terminal:
gtk-launch --version
The problem is with the method:
private void Flow()
{
X = x;
Y = y;
}
Your class is named Flow
so this method can't also be named Flow
. You will have to change the name of the Flow
method to something else to make this code compile.
Or did you mean to create a private constructor to initialize your class? If that's the case, you will have to remove the void
keyword to let the compiler know that your declaring a constructor.
bool contains = pricePublicList.Any(p => p.Size == 200);
AD Powershell module should be listed under installed Features. See image:
.
If you're dealing with a single element preferably you should use the id
selector as stated on GenericTypeTea answer and get the name like $("#id").attr("name");
.
But if you want, as I did when I found this question, a list with all the input names of a specific class (in my example a list with the names of all unchecked checkboxes with .selectable-checkbox
class) you could do something like:
var listOfUnchecked = $('.selectable-checkbox:unchecked').toArray().map(x=>x.name);
or
var listOfUnchecked = [];
$('.selectable-checkbox:unchecked').each(function () {
listOfUnchecked.push($(this).attr('name'));
});
text1.setTextColor(Color.parseColor("#000000"));
This line of code might not work in IE 8 because of native support problems.
$(".hidden").attr("placeholder", "Type here to search");
You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.
$('input, textarea').placeholder();
If you're using an UNIX-like environment, just use &
as the separator:
"dev": "npm run start-watch & npm run wp-server"
Otherwise if you're interested on a cross-platform solution, you could use npm-run-all module:
"dev": "npm-run-all --parallel start-watch wp-server"
Image size is not depend on div height and width,
use img element in css
Here is css code that help you
div img{
width: 100px;
height:100px;
}
if you want to set size by div
use this
div {
width:100px;
height:100px;
overflow:hidden;
}
by this code your image show in original size but show first 100x100px overflow will hide
As pointed out by @Nenad Bulatovic one has to be careful while adding libraries(19th step). one should not add any trailing spaces while adding each library line by line. otherwise mingw goes haywire.
Set variable "a" to some value like this,
a=0;
Declaring and initialzing are both different.
Good Luck
Given
<div id="This-is-the-real-id"></div>
then
function setText(id,newvalue) {
var s= document.getElementById(id);
s.innerHTML = newvalue;
}
window.onload=function() { // or window.addEventListener("load",function() {
setText("This-is-the-real-id","Hello there");
}
will do what you want
Given
<input id="This-is-the-real-id" type="text" value="">
then
function setValue(id,newvalue) {
var s= document.getElementById(id);
s.value = newvalue;
}
window.onload=function() {
setValue("This-is-the-real-id","Hello there");
}
will do what you want
function setContent(id, newvalue) {_x000D_
var s = document.getElementById(id);_x000D_
if (s.tagName.toUpperCase()==="INPUT") s.value = newvalue;_x000D_
else s.innerHTML = newvalue;_x000D_
_x000D_
}_x000D_
window.addEventListener("load", function() {_x000D_
setContent("This-is-the-real-id-div", "Hello there");_x000D_
setContent("This-is-the-real-id-input", "Hello there");_x000D_
})
_x000D_
<div id="This-is-the-real-id-div"></div>_x000D_
<input id="This-is-the-real-id-input" type="text" value="">
_x000D_
The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).
You can return it as an int by casting it as follows:
string sql = @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() AS INT)";
int id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();
You can use the .hide()
function bound to a click
handler:
$('#Comanda').click(function() {
$(this).hide();
});
cd somedir
npm install .
or
npm install path/to/somedir
somedir
must contain the package.json
inside it.
It knows about git too:
npm install git://github.com/visionmedia/express.git
Just set the Environment variable to JAVA_HOME of
C:\Program Files\Java\jdk1.7.0_51)
with out bin for 64 bit version and same for 32 bit version with Program Files(x86).
NO \BIN
after the path it will work properly.
Try this example:
exec DBMS_LOCK.sleep(5);
This is the whole script:
SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Start Date / Time" FROM DUAL;
exec DBMS_LOCK.sleep(5);
SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "End Date / Time" FROM DUAL;
what language is this? If you're using a language that passes everything by reference like Java (except for native types), typically you can call .clone()
method. The .clone() method is typically implemented by copying/cloning all relevant instance fields into the new object.
Could be easier and safer this alternative if you have multiple plots:
import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np
cdict = {
'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
'green': ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
'blue' : ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}
cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)
data = 2*( np.sin(X) + np.sin(3*Y) )
data1 = np.clip(data,0,6)
data2 = np.clip(data,-6,0)
vmin = np.min(np.array([data,data1,data2]))
vmax = np.max(np.array([data,data1,data2]))
fig = plt.figure()
ax = fig.add_subplot(131)
mesh = ax.pcolormesh(data, cmap = cm)
mesh.set_clim(vmin,vmax)
ax1 = fig.add_subplot(132)
mesh1 = ax1.pcolormesh(data1, cmap = cm)
mesh1.set_clim(vmin,vmax)
ax2 = fig.add_subplot(133)
mesh2 = ax2.pcolormesh(data2, cmap = cm)
mesh2.set_clim(vmin,vmax)
# Visualizing colorbar part -start
fig.colorbar(mesh,ax=ax)
fig.colorbar(mesh1,ax=ax1)
fig.colorbar(mesh2,ax=ax2)
fig.tight_layout()
# Visualizing colorbar part -end
plt.show()
The best alternative is then to use a single color bar for the entire plot. There are different ways to do that, this tutorial is very useful for understanding the best option. I prefer this solution that you can simply copy and paste instead of the previous visualizing colorbar part of the code.
fig.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.8,
wspace=0.4, hspace=0.1)
cb_ax = fig.add_axes([0.83, 0.1, 0.02, 0.8])
cbar = fig.colorbar(mesh, cax=cb_ax)
I would suggest using pcolormesh
instead of pcolor
because it is faster (more infos here ).
I have tried this
C:\Users\radhason\AppData\Local\NetBeans\Cache
Press Ok button , then cache folder will be shown and delete this cache folder of netbeans.
I just had to do this and this was my manual solution:
If you don't know what the PRIMARY field is, look back at your phpmyadmin page, click on the 'Structure' tab and at the bottom of the page under 'Indexes' it will show you which 'Field' has a 'Keyname' value 'PRIMARY'.
Kind of a long way around, but if you don't want to deal with markup and just need to duplicate a single row there you go.
/bookstore/book[@location='US'][1]
works only with simple structure.
Add a bit more structure and things break.
With-
<bookstore>
<category>
<book location="US">A1</book>
<book location="FIN">A2</book>
</category>
<category>
<book location="FIN">B1</book>
<book location="US">B2</book>
</category>
</bookstore>
/bookstore/category/book[@location='US'][1]
yields
<book location="US">A1</book>
<book location="US">B2</book>
not "the first node that matches a more complicated condition". /bookstore/category/book[@location='US'][2]
returns nothing.
With parentheses you can get the result the original question was for:
(/bookstore/category/book[@location='US'])[1]
gives
<book location="US">A1</book>
and (/bookstore/category/book[@location='US'])[2]
works as expected.
I found this to work nicely
function drawCurve(points, tension) {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
var t = (tension != null) ? tension : 1;
for (var i = 0; i < points.length - 1; i++) {
var p0 = (i > 0) ? points[i - 1] : points[0];
var p1 = points[i];
var p2 = points[i + 1];
var p3 = (i != points.length - 2) ? points[i + 2] : p2;
var cp1x = p1.x + (p2.x - p0.x) / 6 * t;
var cp1y = p1.y + (p2.y - p0.y) / 6 * t;
var cp2x = p2.x - (p3.x - p1.x) / 6 * t;
var cp2y = p2.y - (p3.y - p1.y) / 6 * t;
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, p2.x, p2.y);
}
ctx.stroke();
}
What is the difference between them?
Image: the generic Linux kernel binary image file.
zImage: a compressed version of the Linux kernel image that is self-extracting.
uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.
Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:
Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.
(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)
Which type of kernel image do I have to use?
You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.
ADDENDUM
I know that u-boot needs a kernel in uImage format.
That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.
There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check this link.
In your case the code is
$("#title1").animatedScroll({easing: "easeOutExpo"});
Actually, it seems sufficient to merely attach a stock WebChromeClient to the client view, ala
mWebView.setWebChromeClient(new WebChromeClient());
and you need to have hardware acceleration turned on!
At least, if you don't need to play a full-screen video, there's no need to pull the VideoView out of the WebView and push it into the Activity's view. It will play in the video element's allotted rect.
Any ideas how to intercept the expand video button?
I got this type question on Django, and My issue is forget to add static
to the <script>
tag.
Such as in my template:
<script type="text/javascript" src="css/layer.js"></script>
I should add the static
to it like this:
<script type="text/javascript" src="{% static 'css/layer.js' %}" ></script>
Solution by Mosh Hamedani
Creating a StopWatch function constructor.
if you want to access the duration local variable you need to define a property using Object.defineProperty. It's useful when you want to create a read-only property.
the value of the key property.
We want to create a Read-only property so we pass an object as a value. The object contain a get method that return the duration local variable. in this way we cannot change the property only get it.
The trick is to use Date() object to calculate the time.
Reference the code below
function StopWatch() {
let startTime,
endTime,
isRunning,
duration = 0;
this.start = function () {
if (isRunning) throw new Error("StopWatch has already been started.");
isRunning = true;
startTime = new Date();
};
this.stop = function () {
if (!isRunning) throw new Error("StopWatch has already been stop.");
isRunning = false;
endTime = new Date();
const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
duration += seconds;
};
this.reset = function () {
duration = 0;
startTime = null;
endTime = null;
isRunning = false;
};
Object.defineProperty(this, "duration", {
get: function () {
return duration;
},
});
}
const sw = new StopWatch();
If the sites are on separate domains, the calling page can't access the height of the iframe due to cross-browser domain restrictions. If you have access to both sites, you may be able to use the [document domain hack].1 Then anroesti's links should help.
The negative margin trick:
http://pastehtml.com/view/1dujbt3.html
Not elegant, I suppose, but it works in some cases.
I had a terrible time getting global modules to work. Eventually, I explicitly added C:\Users\yourusername\AppData\Roaming\npm
to the PATH variable under System Variables. I also needed to have this variable come before the nodejs path variable in the list.
I am running Windows 10.
Let me add another solution:
>> N = 5;
>> f = cellstr(num2str((1:N)', 'f%d'))
f =
'f1'
'f2'
'f3'
'f4'
'f5'
If N
is more than two digits long (>= 10
), you will start getting extra spaces. Add a call to strtrim(f)
to get rid of them.
As a bonus, there is an undocumented built-in function sprintfc
which nicely returns a cell arrays of strings:
>> N = 10;
>> f = sprintfc('f%d', 1:N)
f =
'f1' 'f2' 'f3' 'f4' 'f5' 'f6' 'f7' 'f8' 'f9' 'f10'
You can also include this task within another macro, without opening a new one:
I don't put Sub and end Sub, because the macro contains much longer code, as per picture below
With Sheets("1_PL").Range("EF1631:JJ1897")
With .Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
[![enter image description here][1]][1]End With
in React v16.8+
function component, you can use useState()
to create a function state that lets you update the parent state, then pass it on to child as a props attribute, then inside the child component you can trigger the parent state function, the following is a working snippet:
const { useState , useEffect } = React;_x000D_
_x000D_
function Timer({ setParentCounter }) {_x000D_
const [counter, setCounter] = React.useState(0);_x000D_
_x000D_
useEffect(() => {_x000D_
let countersystem;_x000D_
countersystem = setTimeout(() => setCounter(counter + 1), 1000);_x000D_
_x000D_
return () => {_x000D_
clearTimeout(countersystem);_x000D_
};_x000D_
}, [counter]);_x000D_
_x000D_
return (_x000D_
<div className="App">_x000D_
<button_x000D_
onClick={() => {_x000D_
setParentCounter(counter);_x000D_
}}_x000D_
>_x000D_
Set parent counter value_x000D_
</button>_x000D_
<hr />_x000D_
<div>Child Counter: {counter}</div>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
_x000D_
function App() {_x000D_
const [parentCounter, setParentCounter] = useState(0);_x000D_
_x000D_
return (_x000D_
<div className="App">_x000D_
Parent Counter: {parentCounter}_x000D_
<hr />_x000D_
<Timer setParentCounter={setParentCounter} />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById('react-root'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>_x000D_
<div id="react-root"></div>
_x000D_
I was been getting that error in mobile safari when using ASP.NET MVC to return a FileResult with the overload that returns a file with a different file name than the original. So,
return File(returnFilePath, contentType, fileName);
would give the error in mobile safari, where as
return File(returnFilePath, contentType);
would not.
I don't even remember why I thought what I was doing was a good idea. Trying to be clever I guess.
Open this Link and select follow the instructions google servers blocks any attempts from unknown servers so once you click on captcha check every thing will be fine
After Change your Function or Code Follow these two steps.
First Enable CORS Then Deploy API every time.
I got this error using PHP7 / Apache 2.4 on a windows platform. curl_init
worked from CLI but not with Apache 2.4. I resolved it by adding LoadFile
directives for libeay32.dll and ssleay32.dll:
LoadFile "C:/path/to/Php7/libeay32.dll"
LoadFile "C:/path/to/Php7/ssleay32.dll"
LoadFile "C:/path/to/Php7/php7ts.dll"
LoadModule php7_module "C:/path/to/Php7/php7apache2_4.dll"
This works also:
for i in range(19):
plt.subplot(5,4,i+1)
It plots 19 total graphs on one page. The format is 5 down and 4 across..
Both const
and constexpr
can be applied to variables and functions. Even though they are similar to each other, in fact they are very different concepts.
Both const
and constexpr
mean that their values can't be changed after their initialization. So for example:
const int x1=10;
constexpr int x2=10;
x1=20; // ERROR. Variable 'x1' can't be changed.
x2=20; // ERROR. Variable 'x2' can't be changed.
The principal difference between const
and constexpr
is the time when their initialization values are known (evaluated). While the values of const
variables can be evaluated at both compile time and runtime, constexpr
are always evaluated at compile time. For example:
int temp=rand(); // temp is generated by the the random generator at runtime.
const int x1=10; // OK - known at compile time.
const int x2=temp; // OK - known only at runtime.
constexpr int x3=10; // OK - known at compile time.
constexpr int x4=temp; // ERROR. Compiler can't figure out the value of 'temp' variable at compile time so `constexpr` can't be applied here.
The key advantage to know if the value is known at compile time or runtime is the fact that compile time constants can be used whenever compile time constants are needed. For instance, C++ doesn't allow you to specify C-arrays with the variable lengths.
int temp=rand(); // temp is generated by the the random generator at runtime.
int array1[10]; // OK.
int array2[temp]; // ERROR.
So it means that:
const int size1=10; // OK - value known at compile time.
const int size2=temp; // OK - value known only at runtime.
constexpr int size3=10; // OK - value known at compile time.
int array3[size1]; // OK - size is known at compile time.
int array4[size2]; // ERROR - size is known only at runtime time.
int array5[size3]; // OK - size is known at compile time.
So const
variables can define both compile time constants like size1
that can be used to specify array sizes and runtime constants like size2
that are known only at runtime and can't be used to define array sizes. On the other hand constexpr
always define compile time constants that can specify array sizes.
Both const
and constexpr
can be applied to functions too. A const
function must be a member function (method, operator) where application of const
keyword means that the method can't change the values of their member (non-static) fields. For example.
class test
{
int x;
void function1()
{
x=100; // OK.
}
void function2() const
{
x=100; // ERROR. The const methods can't change the values of object fields.
}
};
A constexpr
is a different concept. It marks a function (member or non-member) as the function that can be evaluated at compile time if compile time constants are passed as their arguments. For example you can write this.
constexpr int func_constexpr(int X, int Y)
{
return(X*Y);
}
int func(int X, int Y)
{
return(X*Y);
}
int array1[func_constexpr(10,20)]; // OK - func_constexpr() can be evaluated at compile time.
int array2[func(10,20)]; // ERROR - func() is not a constexpr function.
int array3[func_constexpr(10,rand())]; // ERROR - even though func_constexpr() is the 'constexpr' function, the expression 'constexpr(10,rand())' can't be evaluated at compile time.
By the way the constexpr
functions are the regular C++ functions that can be called even if non-constant arguments are passed. But in that case you are getting the non-constexpr values.
int value1=func_constexpr(10,rand()); // OK. value1 is non-constexpr value that is evaluated in runtime.
constexpr int value2=func_constexpr(10,rand()); // ERROR. value2 is constexpr and the expression func_constexpr(10,rand()) can't be evaluated at compile time.
The constexpr
can be also applied to the member functions (methods), operators and even constructors. For instance.
class test2
{
static constexpr int function(int value)
{
return(value+1);
}
void f()
{
int x[function(10)];
}
};
A more 'crazy' sample.
class test3
{
public:
int value;
// constexpr const method - can't chanage the values of object fields and can be evaluated at compile time.
constexpr int getvalue() const
{
return(value);
}
constexpr test3(int Value)
: value(Value)
{
}
};
constexpr test3 x(100); // OK. Constructor is constexpr.
int array[x.getvalue()]; // OK. x.getvalue() is constexpr and can be evaluated at compile time.
Please try this,
SELECT
c.Id,
c.name,
(SELECT pi.price FROM purchase pi WHERE pi.Id = MAX(p.Id)) AS [LastPurchasePrice]
FROM customer c INNER JOIN purchase p
ON c.Id = p.customerId
GROUP BY c.Id,c.name;
Bradorego's solution is what worked for me, but here is a more expanded answer.
A small consideration is that you need to encode the body using %20
instead of +
. For PHP, this means using rawurlencode($body)
instead of urlencode($body)
. Otherwise you'll see plus signs in the message on old versions of iOS, instead of spaces.
Here is a jQuery function which will refit your SMS links for iOS devices. Android/other devices should work normally and won't execute the code.
HTML:
<a href="sms:+15551231234?body=Hello%20World">SMS "Hello World" to 555-123-1234</a>
jQuery:
(function() {
if ( !navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ) return;
jQuery('a[href^="sms:"]').attr('href', function() {
// Convert: sms:+000?body=example
// To iOS: sms:+000;body=example (semicolon, not question mark)
return jQuery(this).attr('href').replace(/sms:(\+?([0-9]*))?\?/, 'sms:$1;');
});
})();
Consider using a class like a.sms-link
instead of a[href^="sms:"]
if possible.
I wrestled with this problem and implemented the URL concatenation solution contributed by @Kushan in the accepted answer above. It worked in my local MySql instance. But when I deployed my Play/Scala app to Heroku it no longer would work. Heroku also concatenates several args to the DB URL that they provide users, and this solution, because of Heroku's use concatenation of "?" before their own set of args, will not work. However I found a different solution which seems to work equally well.
SET sql_mode = 'NO_ZERO_DATE';
I put this in my table descriptions and it solved the problem of '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp
In my case I have 3 params, one of them is string (mensaje):
exec("C:\wamp\bin\php\php5.5.12\php.exe C:/test/N/trunk/api/v1/Process.php $idTest2 $idTest3 \"$mensaje\" >> c:/log.log &");
In my Process.php I have this code:
if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3]))
{
die("Error.");
}
$idCurso = $argv[1];
$idDestino = $argv[2];
$mensaje = $argv[3];
When you create a new File
, you are supposed to provide the file name, not only the directory you want to put your file in.
Try with something like
File file = new File("D:/Data/" + item.getFileName());
Check that the port that SQL Server is using is not being blocked by either your firewall or the VPN.
File[] files = null;
File file = new File("/storage");// /storage/emulated
if (file.exists()) {
files = file.listFiles();
}
if (null != files)
for (int j = 0; j < files.length; j++) {
Log.e(TAG, "" + files[j]);
Log.e(TAG, "//--//--// " + files[j].exists());
if (files[j].toString().replaceAll("_", "")
.toLowerCase().contains("extsdcard")) {
external_path = files[j].toString();
break;
} else if (files[j].toString().replaceAll("_", "")
.toLowerCase()
.contains("sdcard".concat(Integer.toString(j)))) {
// external_path = files[j].toString();
}
Log.e(TAG, "--///--///-- " + external_path);
}
I had the same error, but in my case it was caused by the DEBUG mode in Intellij IDE. The debug slowed down the library and then server ended communication at handshake phase. The standard "RUN" worked perfectly.
This can be done without specifying the columns in the INSERT INTO
part if you are supplying values for all columns in the SELECT
part.
Let's say table1 has two columns. This query should work:
INSERT INTO table1
SELECT col1, col2
FROM table2
This WOULD NOT work (value for col2
is not specified):
INSERT INTO table1
SELECT col1
FROM table2
I'm using MS SQL Server. I don't know how other RDMS work.
There is no explicitly defined limit. The amount of available address space forms a practical limit.
(Taken from this site). See the docs on Numeric Types where you'll see that Long integers have unlimited precision
. In Python 2, Integers will automatically switch to longs when they grow beyond their limit:
>>> import sys
>>> type(sys.maxsize)
<type 'int'>
>>> type(sys.maxsize+1)
<type 'long'>
for integers we have
The maximum value of an int can be found in Python 2.x with sys.maxint
. It was removed in Python 3, but sys.maxsize
can often be used instead. From the changelog:
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
and, for anyone interested in the difference (Python 2.x):
sys.maxint The largest positive integer supported by Python’s regular integer type. This is at least 2**31-1. The largest negative integer is -maxint-1 — the asymmetry results from the use of 2’s complement binary arithmetic.
sys.maxsize The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.
and for completeness, here's the Python 3 version:
sys.maxsize An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2^31 - 1 on a 32-bit platform and 2^63 - 1 on a 64-bit platform.
There's float("inf")
and float("-inf")
. These can be compared to other numeric types:
>>> import sys
>>> float("inf") > sys.maxsize
True
That's because you created a Web Site instead of a Web Application. The cs/vb
files can only be seen in a Web Application, but in a website you can't have a separate cs/vb
file.
Edit: In the website you can add a cs file behavior like..
<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>
~/Global.asax.cs:
namespace ApplicationName
{
public partial class MyApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
}
}
}
You might consider adding an additional radio button to each group labeled 'none' or the like. This can create a consistent user experience without complicating the development process.
A suggestion for you - you can use parameter expansion to remove the part of the name from the last underscore onwards, and similarly at the start:
f=001_abc_0za.jpg
work=${f%_*}
name=${work#*_}
Then name
will have the value abc
.
See Apple developer docs, search forward for 'Parameter Expansion'.
This GitPro page does summarize the consequence of a git submodule update nicely
When you run
git submodule update
, it checks out the specific version of the project, but not within a branch. This is called having a detached head — it means the HEAD file points directly to a commit, not to a symbolic reference.
The issue is that you generally don’t want to work in a detached head environment, because it’s easy to lose changes.
If you do an initial submodule update, commit in that submodule directory without creating a branch to work in, and then run git submodule update again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve.
Note March 2013:
As mentioned in "git submodule tracking latest", a submodule now (git1.8.2) can track a branch.
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
# or (with rebase)
git submodule update --rebase --remote
See "git submodule update --remote
vs git pull
".
MindTooth's answer illustrate a manual update (without local configuration):
git submodule -q foreach git pull -q origin master
In both cases, that will change the submodules references (the gitlink, a special entry in the parent repo index), and you will need to add, commit and push said references from the main repo.
Next time you will clone that parent repo, it will populate the submodules to reflect those new SHA1 references.
The rest of this answer details the classic submodule feature (reference to a fixed commit, which is the all point behind the notion of a submodule).
To avoid this issue, create a branch when you work in a submodule directory with git checkout -b work or something equivalent. When you do the submodule update a second time, it will still revert your work, but at least you have a pointer to get back to.
Switching branches with submodules in them can also be tricky. If you create a new branch, add a submodule there, and then switch back to a branch without that submodule, you still have the submodule directory as an untracked directory:
So, to answer your questions:
can I create branches/modifications and use push/pull just like I would in regular repos, or are there things to be cautious about?
You can create a branch and push modifications.
WARNING (from Git Submodule Tutorial): Always publish (push) the submodule change before publishing (push) the change to the superproject that references it. If you forget to publish the submodule change, others won't be able to clone the repository.
how would I advance the submodule referenced commit from say (tagged) 1.0 to 1.1 (even though the head of the original repo is already at 2.0)
The page "Understanding Submodules" can help
Git submodules are implemented using two moving parts:
- the
.gitmodules
file and- a special kind of tree object.
These together triangulate a specific revision of a specific repository which is checked out into a specific location in your project.
From the git submodule page
you cannot modify the contents of the submodule from within the main project
100% correct: you cannot modify a submodule, only refer to one of its commits.
This is why, when you do modify a submodule from within the main project, you:
A submodule enables you to have a component-based approach development, where the main project only refers to specific commits of other components (here "other Git repositories declared as sub-modules").
A submodule is a marker (commit) to another Git repository which is not bound by the main project development cycle: it (the "other" Git repo) can evolves independently.
It is up to the main project to pick from that other repo whatever commit it needs.
However, should you want to, out of convenience, modify one of those submodules directly from your main project, Git allows you to do that, provided you first publish those submodule modifications to its original Git repo, and then commit your main project refering to a new version of said submodule.
But the main idea remains: referencing specific components which:
The list of specific commits you are refering to in your main project defines your configuration (this is what Configuration Management is all about, englobing mere Version Control System)
If a component could really be developed at the same time as your main project (because any modification on the main project would involve modifying the sub-directory, and vice-versa), then it would be a "submodule" no more, but a subtree merge (also presented in the question Transferring legacy code base from cvs to distributed repository), linking the history of the two Git repo together.
Does that help understanding the true nature of Git Submodules?
Short, portable and declared in stdio.h
stdin = freopen(NULL,"r",stdin);
Doesn't get hung in an infinite loop when there is nothing on stdin to flush like the following well know line:
while ((c = getchar()) != '\n' && c != EOF) { }
A little expensive so don't use it in a program that needs to repeatedly clear the buffer.
Stole from a coworker :)
Another possibility would be to have a little NSNumber
subclass singleton.
For objects you can nest the queries:
DB::table('orders')->find(DB::table('orders')->max('id'));
So the inside query looks up the max id in the table and then passes that to the find, which gets you back the object.
The solutions above are superior, especially if using Java, and encountering more numbers with more than 10 digits such as the international code prefix or additional extension numbers. This solution is basic (I'm a beginner in the regex world) and designed with US Phone numbers in mind and is only useful for strings with just 10 numbers with perhaps some formatting characters, or perhaps no formatting characters at all (just 10 numbers). As such I would recomend this solution only for semi-automatic applications. I Personally prefer to store numbers as just 10 numbers without formatting characters, but also want to be able to convert or clean phone numbers to the standard format normal people and apps/phones will recognize instantly at will.
I came across this post looking for something I could use with a text cleaner app that has PCRE Regex capabilities (but no java functions). I will post this here for people who could use a simple pure Regex solution that could work in a variety of text editors, cleaners, expanders, or even some clipboard managers. I personally use Sublime and TextSoap. This solution was made for Text Soap as it lives in the menu bar and provides a drop-down menu where you can trigger text manipulation actions on what is selected by the cursor or what's in the clipboard.
My approach is essentially two substitution/search and replace regexes. Each substitution search and replace involves two regexes, one for search and one for replace.
Substitution/ Search & Replace #1
First Substitution/ Search Regex: \D
First Substitution/ Replace Regex: "" (nothing, not even a space)
Substitution/ Search & Replace #2
$1
, a capture group for the second set of three numbers $2
, and the last capture group for the last set of four numbers $3
. The regex for the substitute portion of the operation inserts US phone number formatting in between the captured group of digits.Second Substitution/ Search Regex: (\d{3})(\d{3})(\d{4})
Second Substitution/ Replace Regex: \($1\) $2\-$3
The backslash \
escapes the special characters (
, )
,
(<-whitespace), and -
since we are inserting them between our captured numbers in capture groups $1
, $2
, & $3
for US phone number formatting purposes.
In TextSoap I created a custom cleaner that includes the two substitution operation actions, so in practice it feels identical to executing a script. I'm sure this solution could be improved but I expect complexity to go up quite a bit. An improved version of this solution is welcomed as a learning experience if anyone wants to add to this.
Run yarn cache clean
.
Run yarn help cache
in your bash, and you will see:
Usage: yarn cache [ls|clean] [flags]
Options: -h, --help output usage information -V, --version output the version number --offline
--prefer-offline
--strict-semver
--json
--global-folder [path]
--modules-folder [path] rather than installing modules into the node_modules folder relative to the cwd, output them here
--packages-root [path] rather than storing modules into a global packages root, store them here
--mutex [type][:specifier] use a mutex to ensure only one yarn instance is executingVisit http://yarnpkg.com/en/docs/cli/cache for documentation about this command.
The simple solution: Add the following to the very top of the php file you are requesting the data from.
header("Access-Control-Allow-Origin: *");
Check openssl tool which is a collection of Openssl from the LibreSSL project and Cygwin libraries (2.5 MB). NB! We're the packager.
One liner to create a self signed certificate:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt
I installed 2 and 3 and had the same problem finding 3. Fortunately, typing path at the windows path let me find where I had installed it. The path was an option when I installed Python which I just forgot. If you didn't select setting the path when you installed Python 3 that probably won't work - unless you manually updated the path when you installed it. In my case it was at c:\Program Files\Python37\python.exe
Try this
'''
This is a multiline
comment. I can type here whatever I want.
'''
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
This:
SELECT col1 as a,
CASE WHEN a = 'test' THEN 'yes' END as value
FROM table;
...will not work. This will:
SELECT CASE WHEN a = 'test' THEN 'yes' END as value
FROM (SELECT col1 AS a
FROM TABLE)
Why you wouldn't use:
SELECT t.col1 as a,
CASE WHEN t.col1 = 'test' THEN 'yes' END as value
FROM TABLE t;
...I don't know.
Seems to me you could've saved some memory by declaring your activity with "implements Handler.Callback"
You can do pretty much the same as in JavaScript. Try this:
Console.WriteLine(mon + "." + da + "." + yer);
Or you can use WriteLine
as if it were a string.Format
statement by doing:
Console.WriteLine("{0}.{1}.{2}", mon, da, yer);
which is equivalent to:
string.Format("{0}.{1}.{2}", mon, da, yer);
The number of parameters can be infinite, just make sure you correctly index those numbers (starting at 0).
As mentioned before, there is a tool SQLite Database Browser, which does this. Lyckily, this tool keeps a log of all operations performed by the user or the application. Doing this once and looking at the application log, you will see the code involved. Copy the query and paste as required. Worked for me. Hope this helps
I got the following error:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
I fixed this by changing my hibernate properties file
hibernate.current_session_context_class=thread
My code and configuration file as follows
session = getHibernateTemplate().getSessionFactory().getCurrentSession();
session.beginTransaction();
session.createQuery(Qry).executeUpdate();
session.getTransaction().commit();
on properties file
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.query_factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory
hibernate.current_session_context_class=thread
on cofiguration file
<properties>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.query.factory_class">${hibernate.query_factory_class}</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
</props>
</property>
</properties>
Thanks,
Ashok
This what helped me:
List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);
Taken from Java 8 Finding Specific Element in List with Lambda
class Program
{
static void Main(string[] args)
{
var @decimal = 42;
var binaryVal = ToBinary(@decimal, 2);
var binary = "101010";
var decimalVal = ToDecimal(binary, 2);
Console.WriteLine("Binary value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
@decimal = 6;
binaryVal = ToBinary(@decimal, 3);
binary = "20";
decimalVal = ToDecimal(binary, 3);
Console.WriteLine("Base3 value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
@decimal = 47;
binaryVal = ToBinary(@decimal, 4);
binary = "233";
decimalVal = ToDecimal(binary, 4);
Console.WriteLine("Base4 value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
@decimal = 99;
binaryVal = ToBinary(@decimal, 5);
binary = "344";
decimalVal = ToDecimal(binary, 5);
Console.WriteLine("Base5 value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
Console.WriteLine();
@decimal = 16;
binaryVal = ToBinary(@decimal, 11);
binary = "b";
decimalVal = ToDecimal(binary, 11);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("Uh oh.. this aint right :( ... but let's cheat :P");
Console.WriteLine();
@decimal = 11;
binaryVal = Convert.ToString(@decimal, 16);
binary = "b";
decimalVal = Convert.ToInt32(binary, 16);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.ReadLine();
}
static string ToBinary(decimal number, int @base)
{
var round = 0;
var reverseBinary = string.Empty;
while (number > 0)
{
var remainder = number % @base;
reverseBinary += remainder;
round = (int)(number / @base);
number = round;
}
var binaryArray = reverseBinary.ToCharArray();
Array.Reverse(binaryArray);
var binary = new string(binaryArray);
return binary;
}
static double ToDecimal(string binary, int @base)
{
var val = 0d;
if (!binary.All(char.IsNumber))
return 0d;
for (int i = 0; i < binary.Length; i++)
{
var @char = Convert.ToDouble(binary[i].ToString());
var pow = (binary.Length - 1) - i;
val += Math.Pow(@base, pow) * @char;
}
return val;
}
}
Learning sources:
I was facing the similar issue while toggling the disabled state of button! After firing the removeProp('disabled')
the button refused to get "disabled" again! I found an interesting solution : use prop("disabled",true)
to disable the button and prop("disabled",false)
to re-enable it!
Now I was able to toggle the "disabled" state of my button as many times I needed! Try it out.
To make this simple, you have two options to reapply your stash:
git stash pop
- Restore back to the saved state, but it deletes the stash from the temporary storage.git stash apply
- Restore back to the saved state and leaves the stash list for possible later reuse.You can read in more detail about git stashes in this article.
this code will work with OI File Manager :
File root = new File(Environment.getExternalStorageDirectory().getPath()
+ "/myFolder/");
Uri uri = Uri.fromFile(root);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(uri);
startActivityForResult(intent, 1);
you can get OI File manager here : http://www.openintents.org/en/filemanager
I just had the same problem. In my case PHP code generated few times the same jQuery code and that was the multiple trigger.
<a href="#popraw" class="report" rel="884(PHP MULTIPLE GENERATER NUMBERS)">Popraw / Zglos</a>
(PHP MULTIPLE GENERATER NUMBERS generated also the same code multiple times)
<script type="text/javascript">
$('.report').click(function(){...});
</script>
My solution was to separate script in another php file and load that file ONE TIME.
There is now a to_sql
method, which is the preferred way to do this, rather than write_frame
:
df.to_sql(con=con, name='table_name_for_df', if_exists='replace', flavor='mysql')
Also note: the syntax may change in pandas 0.14...
You can set up the connection with MySQLdb:
from pandas.io import sql
import MySQLdb
con = MySQLdb.connect() # may need to add some other options to connect
Setting the flavor
of write_frame
to 'mysql'
means you can write to mysql:
sql.write_frame(df, con=con, name='table_name_for_df',
if_exists='replace', flavor='mysql')
The argument if_exists
tells pandas how to deal if the table already exists:
if_exists: {'fail', 'replace', 'append'}
, default'fail'
fail
: If table exists, do nothing.
replace
: If table exists, drop it, recreate it, and insert data.
append
: If table exists, insert data. Create if does not exist.
Although the write_frame
docs currently suggest it only works on sqlite, mysql appears to be supported and in fact there is quite a bit of mysql testing in the codebase.
Pass an argument to round containing the number of decimal places to round to
>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347
The main problem for me is that I don't know what encoding the source of any string is going to be - it could be from a text box (using is only useful if the user is actually submitted the form), or it could be from an uploaded text file, so I really have no control over the input.
I don't think it's a problem. An application knows the source of the input. If it's from a form, use UTF-8 encoding in your case. That works. Just verify the data provided is correctly encoded (validation). Keep in mind that not all databases support UTF-8 in it's full range.
If it's a file you won't save it UTF-8 encoded into the database but in binary form. When you output the file again, use binary output as well, then this is totally transparent.
Your idea is nice that a user can tell the encoding, be he/she can tell anyway after downloading the file, as it's binary.
So I must admit I don't see a specific issue you raise with your question. But maybe you can add some more details what your problem is.
Have you tried the SVG text element?
.append("text").text(function(d, i) { return d[whichevernode];})
rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>
) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>
)
Append the text element as a sibling and work on positioning.
UPDATE
Using g grouping, how about something like this? fiddle
You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)
There can be 2 issues :=
1. Your are trying the command in machine that does not support apt-get command
because apt-get is suitable for Linux based Ubuntu machines; for MAC, try
apt-get equivalent such as Brew
2. The other issue can be that your installation was not completed properly So
Re-install Ubuntu from a Live CD or USB.
The long version would be a waste of your time: your system will never
be clean, but if you insist you could try:
==> Copying everything (missing) except for the /home folder from the Live
CD/USB to your HDD.
OR
==> Do a re-install/repair over the broken system again with the Live
CD / USB stick.
OR
==> Download the deb file for apt-get and install as explained on above posts.
I would definitely go for a fresh new install as there are so many things to
do and so little time.
I recently encountered this issue while mocking a function in a Kotlin data class. For some unknown reason one of my test runs ended up in a frozen state. When I ran the tests again some of my tests that had previously passed started to fail with the WrongTypeOfReturnValue
exception.
I ensured I was using org.mockito:mockito-inline
to avoid the issues with final classes (mentioned by Arvidaa), but the problem remained. What solved it for me was to kill the process and restart Android Studio. This terminated my frozen test run and the following test runs passed without issues.
For me only this one worked
git checkout -p filename
The problem is that the package that used to connect PHP to MySQL is deprecated (php5-mysql). If you install the new package,
sudo apt-get install php-mysql
this will automatically update Apache and PHP 7.
document.getElementById('drpSelectSourceLibrary').value = 'Seven';
var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');
if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
futureMonth = futureMonth.add(1, 'd');
}
console.log(currentDate);
console.log(futureMonth);
EDIT
moment.addRealMonth = function addRealMonth(d) {
var fm = moment(d).add(1, 'M');
var fmEnd = moment(fm).endOf('month');
return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;
}
var nextMonth = moment.addRealMonth(moment());
In my understanding, calling Dispose()
is necessary only when it's locking resources you need later (like a particular connection). It's always recommended to free resources you're no longer using, even if you don't need them again, simply because you shouldn't generally be holding onto resources you're not using (pun intended).
The Microsoft example is not incorrect, necessarily. All resources used will be released when the application exits. And in the case of that example, that happens almost immediately after the HttpClient
is done being used. In like cases, explicitly calling Dispose()
is somewhat superfluous.
But, in general, when a class implements IDisposable
, the understanding is that you should Dispose()
of its instances as soon as you're fully ready and able. I'd posit this is particularly true in cases like HttpClient
wherein it's not explicitly documented as to whether resources or connections are being held onto/open. In the case wherein the connection will be reused again [soon], you'll want to forgo Dipose()
ing of it -- you're not "fully ready" in that case.
See also: IDisposable.Dispose Method and When to call Dispose
Unfortunately the standard DNS A-record (domain name to IP address) used by web-browsers to locate web-servers does not include a port number. Web-browsers use the URL protocol prefix (http://) to determine the port number (http = 80, https = 443, ftp = 21, etc.) unless the port number is specifically typed in the URL (for example "http://www.simpledns.com:5000" = port 5000).
Can I specify a TCP/IP port number for my web-server in DNS? (Other than the standard port 80)
Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.
Try the following code:
var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()
You could also simply link both cells, and have an =Cell formula in each column like, =Sheet2!A2
in Sheet 1 A2 and =Sheet2!B2
in Sheet 1 B2, and drag it down, and then sort those two columns the way you want.
This would be better if your unique items change also, then all you would do is sort and be done.
If there will be no content after the row (whole screen height is taken), the trick with using position: fixed; height: 100%
for .col:before
element may work well:
header {_x000D_
background: green;_x000D_
height: 50px;_x000D_
}_x000D_
.col-xs-3 {_x000D_
background: pink;_x000D_
}_x000D_
.col-xs-3:before {_x000D_
background: pink;_x000D_
content: ' ';_x000D_
height: 100%;_x000D_
margin-left: -15px; /* compensates column's padding */_x000D_
position: fixed;_x000D_
width: inherit; /* bootstrap column's width */_x000D_
z-index: -1; /* puts behind content */_x000D_
}_x000D_
.col-xs-9 {_x000D_
background: yellow;_x000D_
}_x000D_
.col-xs-9:before {_x000D_
background: yellow;_x000D_
content: ' ';_x000D_
height: 100%;_x000D_
margin-left: -15px; /* compensates column's padding */_x000D_
position: fixed;_x000D_
width: inherit; /* bootstrap column's width */_x000D_
z-index: -1; /* puts behind content */_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<header>Header</header>_x000D_
<div class="container-fluid">_x000D_
<div class="row">_x000D_
<div class="col-xs-3">Navigation</div>_x000D_
<div class="col-xs-9">Content</div>_x000D_
</div>_x000D_
</div>
_x000D_
<div id="my_id" class="my_class"></div>
if that is the first div then address it like so:
document.write("div CSS class: " + document.getElementsByTagName('div')[0].className);
alternatively do this:
document.write("alternative way: " + document.getElementById('my_id').className);
It yields the following results:
div CSS class: my_class
alternative way: my_class
For those new to angularjs. The index can be gotten by using $index.
For example:
<div ng-repeat="n in [] | range:10">
do something number {{$index}}
</div>
Which will, when you're using Gloopy's handy filter, print:
do something number 0
do something number 1
do something number 2
do something number 3
do something number 4
do something number 5
do something number 6
do something number 7
do something number 8
do something number 9
I am late here, but this might help someone looking for the answer. Typically servletRequest.getRemoteAddr()
works.
In many cases your application users might be accessing your web server via a proxy server or maybe your application is behind a load balancer.
So you should access the X-Forwarded-For http header in such a case to get the user's IP address.
e.g. String ipAddress = request.getHeader("X-FORWARDED-FOR");
Hope this helps.
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
response = client.execute(httppost, localContext);
doesn't work in 4.5 version without
cookie.setDomain(".domain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
To start the process with parameters, you can use following code:
string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);
To kill/exit the program again, you can use following code:
proc.CloseMainWindow();
proc.Close();
An enhanced for
loop is just limiting the number of parameters inside the parenthesis.
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
Can be written as:
for (int myValue : myArray) {
System.out.println(myValue);
}
Running on Ubuntu 18.04, with VS code 1.51.0
My deleted files from VS Code are located at:
~/.local/share/Trash/files
To search for your deleted files:
find ~/.local/share/Trash/files -name your_file_name
Hope my case helped!
We can also use cSplit_e
from splitstackshape
. Using @zx8754's data
df1 <- data.frame(id = 1:4, year = 1991:1994)
splitstackshape::cSplit_e(df1, "year", fill = 0)
# id year year_1 year_2 year_3 year_4
#1 1 1991 1 0 0 0
#2 2 1992 0 1 0 0
#3 3 1993 0 0 1 0
#4 4 1994 0 0 0 1
To make it work for data other than numeric we need to specify type
as "character"
explicitly
df1 <- data.frame(id = 1:4, let = LETTERS[1:4])
splitstackshape::cSplit_e(df1, "let", fill = 0, type = "character")
# id let let_A let_B let_C let_D
#1 1 A 1 0 0 0
#2 2 B 0 1 0 0
#3 3 C 0 0 1 0
#4 4 D 0 0 0 1
You can use "svn export" for creating a copy of that folder without svn data, or you can add that folder to ignore list
When doing a getObject()
from the S3 API, per the docs the contents of your file are located in the Body
property, which you can see from your sample output. You should have code that looks something like the following
const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary
var getParams = {
Bucket: 'abc', // your bucket name,
Key: 'abc.txt' // path to the object you're looking for
}
s3.getObject(getParams, function(err, data) {
// Handle any error and exit
if (err)
return err;
// No error happened
// Convert Body from a Buffer to a String
let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});
You may not need to create a new buffer from the data.Body
object but if you need you can use the sample above to achieve that.
CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.
Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.
Try something like this:
var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
method: 'JSONP',
url: url
}).
success(function(status) {
//your code when success
}).
error(function(status) {
//your code when fails
});
Regarding David Elizondo's answer, this can give false positives. It also does not give zeroes where the values don't match.
DECLARE @t1 TABLE (
ColID int IDENTITY,
Col2 int
)
DECLARE @t2 TABLE (
ColID int IDENTITY,
Col2 int
)
INSERT INTO @t1 (Col2) VALUES (123)
INSERT INTO @t1 (Col2) VALUES (234)
INSERT INTO @t1 (Col2) VALUES (456)
INSERT INTO @t1 (Col2) VALUES (1)
INSERT INTO @t2 (Col2) VALUES (123)
INSERT INTO @t2 (Col2) VALUES (345)
INSERT INTO @t2 (Col2) VALUES (456)
INSERT INTO @t2 (Col2) VALUES (2)
SELECT
t1.Col2 AS t1Col2,
t2.Col2 AS t2Col2,
ISNULL(NULLIF(t1.Col2, t2.Col2), 1) AS MyDesiredResult
FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID
t1Col2 t2Col2 MyDesiredResult
----------- ----------- ---------------
123 123 1
234 345 234 <- Not a zero
456 456 1
1 2 1 <- Not a match
There is nothing wrong with your code. It's the NBC.com doing tricks on you. When NBC.com decides that your browser is not capable of displaying PDF, it simply sends back a webpage regardless what you are requesting, even if it doesn't exist.
You need to trick it back by telling it your browser is capable, something like,
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13");
You can refer to this blog for printing formatted coloured text on console
https://javaforqa.wordpress.com/java-print-coloured-table-on-console/
public class ColourConsoleDemo {
/**
*
* @param args
*
* "\033[0m BLACK" will colour the whole line
*
* "\033[37m WHITE\033[0m" will colour only WHITE.
* For colour while Opening --> "\033[37m" and closing --> "\033[0m"
*
*
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("\033[0m BLACK");
System.out.println("\033[31m RED");
System.out.println("\033[32m GREEN");
System.out.println("\033[33m YELLOW");
System.out.println("\033[34m BLUE");
System.out.println("\033[35m MAGENTA");
System.out.println("\033[36m CYAN");
System.out.println("\033[37m WHITE\033[0m");
//printing the results
String leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.format("|---------Test Cases with Steps Summary -------------|%n");
System.out.format("+----------------------+---------+---------+---------+%n");
System.out.format("| Test Cases |Passed |Failed |Skipped |%n");
System.out.format("+----------------------+---------+---------+---------+%n");
String formattedMessage = "TEST_01".trim();
leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.print("\033[31m"); // Open print red
System.out.printf(leftAlignFormat, formattedMessage, 2, 1, 0);
System.out.print("\033[0m"); // Close print red
System.out.format("+----------------------+---------+---------+---------+%n");
}
Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For
and take a lambda expression cannot work with weakly typed structures such as ViewData
.
Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.
For example in your case I would define a view model:
public class MyViewModel
{
[HiddenInput(DisplayValue = false)]
public string CRN { get; set; }
}
have my controller action populate this view model:
public ActionResult Index()
{
var model = new MyViewModel
{
CRN = "foo bar"
};
return View(model);
}
and then have my strongly typed view simply use an EditorFor
helper:
@model MyViewModel
@Html.EditorFor(x => x.CRN)
which would generate me:
<input id="CRN" name="CRN" type="hidden" value="foo bar" />
in the resulting HTML.
You can use ES6 spread on previous values in the object to avoid overwrite
this.setState({
abc: {
...this.state.abc,
xyz: 'new value'
}
});
protected void switchTabsUsingPartOfUrl(String platform) {
String currentHandle = null;
try {
final Set<String> handles = driver.getWindowHandles();
if (handles.size() > 1) {
currentHandle = driver.getWindowHandle();
}
if (currentHandle != null) {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform) && !currentHandle.equals(handle)) {
break;
}
}
} else {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform)) {
break;
}
}
}
} catch (Exception e) {
System.out.println("Switching tabs failed");
}
}
Call this method and pass parameter a substring of url of the tab you want to switch to
Starting with SQL Server 2012, you could use TRY_PARSE or TRY_CONVERT.
SELECT TRY_PARSE(MyVarcharCol as int)
SELECT TRY_CONVERT(int, MyVarcharCol)
There are 3 location providers in Android.
They are:
gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.
network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.
passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).
The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).
Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris
Code Reference : https://stackoverflow.com/a/3145655/28557
-----------------------Update-----------------------
Now Android have Fused location provider
The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage
Fused location provider provide three ways to fetch location
References :
Official site : http://developer.android.com/google/play-services/location.html
Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example
http://blog.lemberg.co.uk/fused-location-provider
--------------------------------------------------------
I had same problem and this accepted solution didn't helped me, if someone has same problem you can use my code snippet:
// example of filtering and sharing multiple images with texts
// remove facebook from sharing intents
private void shareFilter(){
String share = getShareTexts();
ArrayList<Uri> uris = getImageUris();
List<Intent> targets = new ArrayList<>();
Intent template = new Intent(Intent.ACTION_SEND_MULTIPLE);
template.setType("image/*");
List<ResolveInfo> candidates = getActivity().getPackageManager().
queryIntentActivities(template, 0);
// remove facebook which has a broken share intent
for (ResolveInfo candidate : candidates) {
String packageName = candidate.activityInfo.packageName;
if (!packageName.equals("com.facebook.katana")) {
Intent target = new Intent(Intent.ACTION_SEND_MULTIPLE);
target.setType("image/*");
target.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
target.putExtra(Intent.EXTRA_TEXT, share);
target.setPackage(packageName);
targets.add(target);
}
}
Intent chooser = Intent.createChooser(targets.remove(0), "Share Via");
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targets.toArray(new Parcelable[targets.size()]));
startActivity(chooser);
}
The best approach depends on the expected key distribution and number of collisions. If relatively few collisions are expected, it really doesn't matter which method is used. If lots of collisions are expected, then which to use depends on the cost of rehashing or probing vs. manipulating the extensible bucket data structure.
But here is source code example of An Hashmap Implementation in C
You might also take a look at the Memoize decorator. You could probably get it to do what you want without too much modification.
In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.
Window ? Preferences ? General ? Editors ? Text Editors ? Show line numbers.
Edit: I wrote this long ago but as @ArtOfWarfar and @voidstate mentioned you can now simply:
Right click the gutter and select "Show Line Numbers":
The file module doesn't copy files on the remote system. The src parameter is only used by the file module when creating a symlink to a file.
If you want to move/rename a file entirely on a remote system then your best bet is to use the command module to just invoke the appropriate command:
- name: Move foo to bar
command: mv /path/to/foo /path/to/bar
If you want to get fancy then you could first use the stat module to check that foo actually exists:
- name: stat foo
stat: path=/path/to/foo
register: foo_stat
- name: Move foo to bar
command: mv /path/to/foo /path/to/bar
when: foo_stat.stat.exists
Like other people have said, generally Python strings are supposed to be immutable.
However, if you are using CPython, the implementation at python.org, it is possible to use ctypes to modify the string structure in memory.
Here is an example where I use the technique to clear a string.
Mark data as sensitive in python
I mention this for the sake of completeness, and this should be your last resort as it is hackish.
Read /usr/src/linux/Documentation/sysctl/kernel.txt.
[/proc/sys/kernel/]core_pattern is used to specify a core dumpfile pattern name.
- If the first character of the pattern is a '|', the kernel will treat the rest of the pattern as a command to run. The core dump will be written to the standard input of that program instead of to a file.
Instead of writing the core dump to disk, your system is configured to send it to the abrt
program instead. Automated Bug Reporting Tool is possibly not as documented as it should be...
In any case, the quick answer is that you should be able to find your core file in /var/cache/abrt
, where abrt
stores it after being invoked. Similarly, other systems using Apport may squirrel away cores in /var/crash
, and so on.
I have this piece of code that does the job very well for me.
var prevVal = '';
$(".numericValue").on("input", function (evt) {
var self = $(this);
if (self.val().match(/^-?\d*(\.(?=\d*)\d*)?$/) !== null) {
prevVal = self.val()
} else {
self.val(prevVal);
}
if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57) && (evt.which != 45 && self.val().indexOf("-") == 0)) {
evt.preventDefault();
}
});
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
Generate numbers between 0 and 65535 then just subtract 32768
Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]
Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.
So, to summarize:
Transfer on established connection:
First connection establishment:
Subsequent connection establishments:
I was uninstalled compass 1.0.1 and install compass 0.12.7, this fix problem for me
$ sudo gem uninstall compass
$ sudo gem install compass -v 0.12.7
Do not invoke the method when assigning the new onclick
handler.
Simply remove the parenthesis:
document.getElementById("a").onclick = Foo;
UPDATE (due to new information):
document.getElementById("a").onclick = function () { Foo(param); };
Here is an example that I used:
def volume(self):
return round(pi * self.radius ** 2 * self.height, 2)
def surface_area(self):
return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2)
For me it was fixed by just removing the static
property in the DialogHelper.class methods (resposble for creating & hiding the dialog), as I have properties related to Window
in those methods
Here is another version if you have to reference a specific docker file:
version: "3"
services:
nginx:
container_name: nginx
build:
context: ../..
dockerfile: ./docker/nginx/Dockerfile
image: my_nginx:latest
Then you just run
docker-compose build
Use q
flag for quiet mode, and tell wget
to output to stdout with O-
(uppercase o) and redirect to /dev/null
to discard the output:
wget -qO- $url &> /dev/null
>
redirects application output (to a file). if >
is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >
. If you don't specify ampersand, then only normal output is redirected.
./app &> file # redirect error and standard output to file
./app > file # redirect standard output to file
./app 2> file # redirect error output to file
if file is /dev/null
then all is discarded.
This works as well, and simpler:
wget -O/dev/null -q $url
I had the same problem. So here is what i did
And it worked.
There are two ways to go about doing this.
Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.
handleClick: function() { alert(this.refs.myInput.value); },
Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.
Restarting Visual Studio with administrator privilege solved the issue for me.
There are a few reasons for the main thread (or any other thread) to join other threads
A thread may have created or holding (locking) some resources. The join-calling thread may be able to clear the resources on its behalf
join() is a natural blocking call for the join-calling thread to continue after the called thread has terminated.
If a python program does not join other threads, the python interpreter will still join non-daemon threads on its behalf.
Use this Library for the ease of a simple solution. Add to the manifest whatever you need and then query by string.
System.out.println("JAR was created by " + Manifests.read("Created-By"));
Try using RUN /bin/sh
instead of bash.
node-memwatch : detect and find memory leaks in Node.JS code. Check this tutorial Tracking Down Memory Leaks in Node.js
The reason that this is happening is because the stack panel measures every child element with positive infinity as the constraint for the axis that it is stacking elements along. The child controls have to return how big they want to be (positive infinity is not a valid return from the MeasureOverride in either axis) so they return the smallest size where everything will fit. They have no way of knowing how much space they really have to fill.
If your view doesn’t need to have a scrolling feature and the answer above doesn't suit your needs, I would suggest implement your own panel. You can probably derive straight from StackPanel and then all you will need to do is change the ArrangeOverride method so that it divides the remaining space up between its child elements (giving them each the same amount of extra space). Elements should render fine if they are given more space than they wanted, but if you give them less you will start to see glitches.
If you want to be able to scroll the whole thing then I am afraid things will be quite a bit more difficult, because the ScrollViewer gives you an infinite amount of space to work with which will put you in the same position as the child elements were originally. In this situation you might want to create a new property on your new panel which lets you specify the viewport size, you should be able to bind this to the ScrollViewer’s size. Ideally you would implement IScrollInfo, but that starts to get complicated if you are going to implement all of it properly.
This is probably the best way, since it’s reliable and works on old browsers:
function indexOfMax(arr) {
if (arr.length === 0) {
return -1;
}
var max = arr[0];
var maxIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
return maxIndex;
}
There’s also this one-liner:
let i = arr.indexOf(Math.max(...arr));
It performs twice as many comparisons as necessary and will throw a RangeError
on large arrays, though. I’d stick to the function.
select *
from blah
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'
Depending on the country setting for the login, the month/day may need to be swapped around.
We can all see that the code you provided won't work at run time. That's because we know that the expression new A()
can never be an object of type B
.
But that's not how the compiler sees it. By the time the compiler is checking whether the cast is allowed, it just sees this:
variable_of_type_B = (B)expression_of_type_A;
And as others have demonstrated, that sort of cast is perfectly legal. The expression on the right could very well evaluate to an object of type B
. The compiler sees that A
and B
have a subtype relation, so with the "expression" view of the code, the cast might work.
The compiler does not consider the special case when it knows exactly what object type expression_of_type_A
will really have. It just sees the static type as A
and considers the dynamic type could be A
or any descendant of A
, including B
.
I wouldn't recommend debugger;
if you just want to kill and stop the javascript code, since debugger;
will just temporally freeze your javascript code and not stop it permanently.
If you want to properly kill and stop javascript code at your command use the following:
throw new Error("This error message appears because I placed it");
I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
_x000D_
#yourElement {
margin-left: 10px;
}
_x000D_
<div id="yourElement"></div>
_x000D_
//set
comboBox1.DisplayMember = "Value";
//to add
comboBox1.Items.Add(new KeyValuePair("2", "This text is displayed"));
//to access the 'tag' property
string tag = ((KeyValuePair< string, string >)comboBox1.SelectedItem).Key;
MessageBox.Show(tag);
I found a workaround for recursive copying from remote to remote :
- name: List files in /usr/share/easy-rsa
find:
path: /usr/share/easy-rsa
recurse: yes
file_type: any
register: find_result
- name: Create the directories
file:
path: "{{ item.path | regex_replace('/usr/share/easy-rsa','/etc/easy-rsa') }}"
state: directory
mode: "{{ item.mode }}"
with_items:
- "{{ find_result.files }}"
when:
- item.isdir
- name: Copy the files
copy:
src: "{{ item.path }}"
dest: "{{ item.path | regex_replace('/usr/share/easy-rsa','/etc/easy-rsa') }}"
remote_src: yes
mode: "{{ item.mode }}"
with_items:
- "{{ find_result.files }}"
when:
- item.isdir == False
(edited Dec 2018: Android Studio 3.2.1 on Mac too)
For Android Studio 3.1.3 on a Mac, it was under
Android Studio -> Preferences -> Build, Execution, Deployment -> Compiler
and then, to view the stack trace, press this button
To allow receiving & sending cookies by a CORS request successfully, do the following.
Back-end (server):
Set the HTTP header Access-Control-Allow-Credentials
value to true
.
Also, make sure the HTTP headers Access-Control-Allow-Origin
and Access-Control-Allow-Headers
are set and not with a wildcard *
.
Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None
and Secure
. See MDN documentation
For more info on setting CORS in express js read the docs here
Front-end (client): Set the XMLHttpRequest.withCredentials
flag to true
, this can be achieved in different ways depending on the request-response library used:
jQuery 1.5.1 xhrFields: {withCredentials: true}
ES6 fetch() credentials: 'include'
axios: withCredentials: true
Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.
If you for whatever reason don't avoid it. The solution is above.
It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost
(without port) is not a problem. Many thanks to Erwin for this tip!
The Prototype creates new object by cloning existing object. So really when we think about prototype we can really think cloning or making a copy of something instead of making it up.
You can also write a custom query using @Query
@Query(value = "from EntityClassTable t where yourDate BETWEEN :startDate AND :endDate")
public List<EntityClassTable> getAllBetweenDates(@Param("startDate")Date startDate,@Param("endDate")Date endDate);
This solution runs in O(N) complexity and all the corner cases are covered.
public int solution(int[] A) {
Arrays.sort(A);
//find the first positive integer
int i = 0, len = A.length;
while (i < len && A[i++] < 1) ;
--i;
//Check if minimum value 1 is present
if (A[i] != 1)
return 1;
//Find the missing element
int j = 1;
while (i < len - 1) {
if (j == A[i + 1]) i++;
else if (++j != A[i + 1])
return j;
}
// If we have reached the end of array, then increment out value
if (j == A[len - 1])
j++;
return j;
}
You will need to get the textbox via javascript when moving the mouse over it and change its type
to text
. And when moving it out, you will want to change it back to password
. No chance of doing this in pure CSS.
HTML:
<input type="password" name="password" id="myPassword" size="30" />
<img src="theicon" onmouseover="mouseoverPass();" onmouseout="mouseoutPass();" />
JS:
function mouseoverPass(obj) {
var obj = document.getElementById('myPassword');
obj.type = "text";
}
function mouseoutPass(obj) {
var obj = document.getElementById('myPassword');
obj.type = "password";
}
A lot of the answers here go the "use a framework" route. There's zero wrong with that. However I don't think it really answers your question, because frameworks may or may not use JSPs, nor are they designed in any way with removing java use in JSPs as a primary goal.
The only good answer to your question "how do I avoid using Java in a JSP" is: you can't.
That's what JSPs are for - using Java to render HTML with dynamic data/logic.
The follow up question might be, how much java should I use in my JSPs.
Before we answer that question, you should also ponder, "do I need to use JSPs to build web content using Java?" The answer to that last one is, no. There are many alternatives to JSPs for developing web facing applications using Java. Struts for example does not force you to use JSPs - don't get me wrong, you can use them and many implementations do, but you don't absolutely have to. Struts doesn't even force you to use any HTML. A JSP doesn't either, but let's be honest, a JSP producing no HTML is kinda weird. Servlets, famously, allow you to serve any kind of content you like over HTTP dynamically. They are the primary tech behind pretty much everything java web - JSPs are just HTML templates for servlets, really.
So the answer to how much java you should put in a JSP is, "as little as possible". I of course have java in my JSPs, but it consists exclusively of tag library definitions, session and client variables, and beans encapsulating server side objects. The <%%> tags in my HTML are almost exclusively property calls or variable expressions. Rare exceptions include ultra-specific calculations pertaining to a single page and unlikely to ever be reused; bugfixes stemming from page-specific issues only applying to one page; last minute concatenations and arithmetic stemming from unusual requirements limited in scope to a single page; and other similar cases. In a code set of 1.5 million lines, 3000 JSPs and 5000 classes, there are maybe 100 instances of such unique snippets. It would have been quite possible to make these changes in classes or tag library definitions, but it would have been inordinately complex due to the specificity of each case, taken longer to write and debug, and taken more time as a result to get to my users. It's a judgement call. But make no mistake, you cannot write JSPs of any meaning with "no java" nor would you want to. The capability is there for a reason.
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
You can use TreeSet
that automatically order list values:
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
System.out.println("Tree Set Example!\n");
TreeSet <String>tree = new TreeSet<String>();
tree.add("aaa");
tree.add("acbbb");
tree.add("aab");
tree.add("c");
tree.add("a");
Iterator iterator;
iterator = tree.iterator();
System.out.print("Tree set data: ");
//Displaying the Tree set data
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
}
}
I lastly add 'a' but last element must be 'c'.
Yet another answer, in case the byte array is defined as char[]
, uppercase and separated by spaces.
void debugArray(const unsigned char* data, size_t len) {
std::ios_base::fmtflags f( std::cout.flags() );
for (size_t i = 0; i < len; ++i)
std::cout << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << (((int)data[i]) & 0xFF) << " ";
std::cout << std::endl;
std::cout.flags( f );
}
Example:
unsigned char test[]={0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
debugArray(test, sizeof(test));
Output:
01 02 03 04 05 06
Gradle looks for gradle.properties
files in these places:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
)Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).
Reference: https://gradle.org/docs/current/userguide/build_environment.html
This is what I did to integrate Identity with an existing database.
Create a sample MVC project with MVC template. This has all the code needed for Identity implementation - Startup.Auth.cs, IdentityConfig.cs, Account Controller code, Manage Controller, Models and related views.
Install the necessary nuget packages for Identity and OWIN. You will get an idea by seeing the references in the sample Project and the answer by @Sam
Copy all these code to your existing project. Please note don't forget to add the "DefaultConnection" connection string for Identity to map to your database. Please check the ApplicationDBContext class in IdentityModel.cs where you will find the reference to "DefaultConnection" connection string.
This is the SQL script I ran on my existing database to create necessary tables:
USE ["YourDatabse"]
GO
/****** Object: Table [dbo].[AspNetRoles] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetRoles](
[Id] [nvarchar](128) NOT NULL,
[Name] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserClaims] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserClaims](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserLogins] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserLogins](
[LoginProvider] [nvarchar](128) NOT NULL,
[ProviderKey] [nvarchar](128) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED
(
[LoginProvider] ASC,
[ProviderKey] ASC,
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUserRoles] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUserRoles](
[UserId] [nvarchar](128) NOT NULL,
[RoleId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[AspNetUsers] Script Date: 16-Aug-15 6:52:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AspNetUsers](
[Id] [nvarchar](128) NOT NULL,
[Email] [nvarchar](256) NULL,
[EmailConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](max) NULL,
[SecurityStamp] [nvarchar](max) NULL,
[PhoneNumber] [nvarchar](max) NULL,
[PhoneNumberConfirmed] [bit] NOT NULL,
[TwoFactorEnabled] [bit] NOT NULL,
[LockoutEndDateUtc] [datetime] NULL,
[LockoutEnabled] [bit] NOT NULL,
[AccessFailedCount] [int] NOT NULL,
[UserName] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[AspNetUserClaims] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[AspNetUserLogins] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
GO
ALTER TABLE [dbo].[AspNetUserRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[AspNetRoles] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
GO
ALTER TABLE [dbo].[AspNetUserRoles] WITH CHECK ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
GO
Check and solve any remaining errors and you are done. Identity will handle the rest :)
If you want to hide search for a specific drop down use the id attribute for that.
$('#select_id').select2({ minimumResultsForSearch: -1 });
The awk is ok. I'm guessing the file is from a windows system and has a CR (^m ascii 0x0d) on the end of the line.
This will cause the cursor to go to the start of the line after $2.
Use dos2unix or vi with :se ff=unix
to get rid of the CRs.
UPDATE Employee SET Empid=emp3.empid
FROM EMP_Employee AS emp3
WHERE Employee.Empid=emp3.empid
Try... for YUI
Dom.get("gadget_url").set("value","");
with normal Javascript
document.getElementById('gadget_url').value = '';
with JQuery
$("#gadget_url").val("");
With IntelliJ IDEA
you can create a Jar Application
runtime configuration, select the JAR
, the sources, the JRE
to run the Jar
with and start debugging. Here is the documentation.
Attaching a Simple Snippet for renaming your current branch (local and on origin):
git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>
Explanation from git docs:
git branch -m or -M option, will be renamed to . If had a corresponding reflog, it is renamed to match , and a reflog entry is created to remember the branch renaming. If exists, -M must be used to force the rename to happen.
The special refspec : (or +: to allow non-fast-forward updates) directs Git to push "matching" branches: for every branch that exists on the local side, the remote side is updated if a branch of the same name already exists on the remote side.
--set-upstream Set up 's tracking information so is considered 's upstream branch. If no is specified, then it defaults to the current branch.
To get a Buffered Image with ImageIO.read is a very heavy method, as it's creating a complete uncompressed copy of the image in memory. For png's you may also use pngj and the code:
if (png)
PngReader pngr = new PngReader(file);
width = pngr.imgInfo.cols;
height = pngr.imgInfo.rows;
pngr.close();
}
In german VS-Environments(here 2015): Optionen/Umgebung/Tastatur. (english: options/environment/keyboard). Show Commands With "GeheZuKlammer" (english: "GoToBracket"). Set your own Shortcut.
Add a line getchar();
or system("pause");
before your return 0;
in main function.
It will work for you.
Resumee of Richard Fearn's answer , to make each second line gray:
jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
return c;
}
});
Just create a small delete function which can help you to achieve this task, I have tested this code and it runs perfectly well.
This function deletes files older than 90 days as well as a file with extension .zip to be deleted from a folder.
Private Sub DeleteZip()
Dim eachFileInMydirectory As New DirectoryInfo("D:\Test\")
Dim fileName As IO.FileInfo
Try
For Each fileName In eachFileInMydirectory.GetFiles
If fileName.Extension.Equals("*.zip") AndAlso (Now - fileName.CreationTime).Days > 90 Then
fileName.Delete()
End If
Next
Catch ex As Exception
WriteToLogFile("No Files older than 90 days exists be deleted " & ex.Message)
End Try
End Sub
None of the other answers here worked for me, but this did.
var topSafeAreaHeight: CGFloat = 0
var bottomSafeAreaHeight: CGFloat = 0
if #available(iOS 11.0, *) {
let window = UIApplication.shared.windows[0]
let safeFrame = window.safeAreaLayoutGuide.layoutFrame
topSafeAreaHeight = safeFrame.minY
bottomSafeAreaHeight = window.frame.maxY - safeFrame.maxY
}
Late reaction, but I've struggled with this for a while so maybe I can save somebody some time by showing my solution.
My problem showed a bit different, but the cause might be the same.
In my situation, TortoiseSVN kept on trying to connect via a proxy server. I could access SVN via chrome, firefox and IE fine.
Turns out that there is a configuration file that has a different configuration than the GUI in TortoiseSVN shows.
Mine was located here:
C:\Documents and Settings\[username]\Application Data\Subversion\
, but you can also open the file via the TortoiseSVN gui.
In my file, http-proxy-exceptions was empty
. After I specified it, everything worked fine.
[global]
http-proxy-exceptions = 10.1.1.11
http-proxy-host = 197.132.0.223
http-proxy-port = 8080
http-proxy-username = defaultusername
http-proxy-password = defaultpassword
http-compression = no
I've mostly just seen the builtin ValueError
used in this situation.
org.apache.commons.lang3.StringEscapeUtils
from commons-lang3 is marked deprecated now. You can use org.apache.commons.text.StringEscapeUtils#unescapeJava(String)
instead. It requires an additional Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.4</version>
</dependency>
and seems to handle some more special cases, it e.g. unescapes:
\\b
, \\n
, \\t
, \\f
, \\r
An alternative to CrackerJacks suggestion, if you want the HashMap to maintain order you could consider using a LinkedHashMap instead. As far as im aware it's functionality is identical to a HashMap but it is FIFO so it maintains the order in which items were added.
In project Reactor (io.projectreactor:reactor-core) there is advanced support for n-Tuples:
Tuple2<String, Integer> t = Tuples.of("string", 1)
There you can get t.getT1(), t.getT2(), ...
Especially with Stream or Flux you can even map the tuple elements:
Stream<Tuple2<String, Integer>> s;
s.map(t -> t.mapT2(i -> i + 2));
If an axes (generated by code below the code shown in the question) is sharing the range with the first axes, make sure that you set the range after the last plot of that axes.
Today. I have same problem... my solution:
1) check inode: df -i
I saw:
root@vm22433:/etc/mysql# df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
udev 124696 304 124392 1% /dev
tmpfs 127514 452 127062 1% /run
/dev/vda1 1969920 1969920 0 100% /
tmpfs 127514 1 127513 1% /dev/shm
tmpfs 127514 3 127511 1% /run/lock
tmpfs 127514 15 127499 1% /sys/fs/cgroup
tmpfs 127514 12 127502 1% /run/user/1002
2) I began to look what folders use the maximum number of inods:
for i in /*; do echo $i; find $i |wc -l; done
soon I found in /home/tomnolane/tmp folder, which contained a huge number of files.
3) I removed /home/tomnolane/tmp folder PROFIT.
4) checked:
Filesystem Inodes IUsed IFree IUse% Mounted on
udev 124696 304 124392 1% /dev
tmpfs 127514 454 127060 1% /run
/dev/vda1 1969920 450857 1519063 23% /
tmpfs 127514 1 127513 1% /dev/shm
tmpfs 127514 3 127511 1% /run/lock
tmpfs 127514 15 127499 1% /sys/fs/cgroup
tmpfs 127514 12 127502 1% /run/user/1002
it's ok.
5) restart mysql service
- it's ok!!!!
Try using RenderAction("myPartial","Account");
html { overflow-y: scroll; }
This css
rule causes a vertical scrollbar to always appear.
Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/