I not be able to find squid number in sonar 5.6, with this annotation also works:
@SuppressWarnings({"pmd:AvoidCatchingGenericException", "checkstyle:com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck"})
The FindBugs initial approach involves XML configuration files aka filters. This is really less convenient than the PMD solution but FindBugs works on bytecode, not on the source code, so comments are obviously not an option. Example:
<Match>
<Class name="com.mycompany.Foo" />
<Method name="bar" />
<Bug pattern="DLS_DEAD_STORE_OF_CLASS_LITERAL" />
</Match>
However, to solve this issue, FindBugs later introduced another solution based on annotations (see SuppressFBWarnings
) that you can use at the class or at the method level (more convenient than XML in my opinion). Example (maybe not the best one but, well, it's just an example):
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
value="HE_EQUALS_USE_HASHCODE",
justification="I know what I'm doing")
Note that since FindBugs 3.0.0 SuppressWarnings
has been deprecated in favor of @SuppressFBWarnings
because of the name clash with Java's SuppressWarnings
.
You want to check a couple of things; if this is your own jar file, make sure you have defined a Main-class in the manifest. Since we know you can run it from the command line, the other thing to do is create a windows shortcut, and modify the properties (you'll have to look around, I don't have a Windows machine to look at) so that the command it executes on open is the java -jar command you mentioned.
The other thing: if something isn't confused, it should work anyway; check and make sure you have java associated with the .jar extension.
concat()
function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
When root permissions are required for the destination file, use |sudo tee
instead of >
:
cat << 'EOF' |sudo tee /tmp/yourprotectedfilehere
The variable $FOO will *not* be interpreted.
EOF
cat << "EOF" |sudo tee /tmp/yourprotectedfilehere
The variable $FOO *will* be interpreted.
EOF
file version < 5 : file -i -b /path/to/file
file version >=5 : file --mime-type -b /path/to/file
executePendingTransactions()
, commitNow()
not worked (
Worked in androidx (jetpack).
private final FragmentManager fragmentManager = getSupportFragmentManager();
public void removeFragment(FragmentTag tag) {
Fragment fragmentRemove = fragmentManager.findFragmentByTag(tag.toString());
if (fragmentRemove != null) {
fragmentManager.beginTransaction()
.remove(fragmentRemove)
.commit();
// fix by @Ogbe
fragmentManager.popBackStackImmediate(tag.toString(),
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
enter the below command to verify if zookeeper is running :
echo "ruok" | nc localhost 2181 ; echo
expected response: imok
I had the same problem. This worked better:
Identify which level you want to modify: levels(iris$Species)
"setosa" "versicolor" "virginica"
So, setosa
is the first.
Then, write this:
levels(iris$Species)[1] <-"new name"
For simplicity I am reducing the vector a and b:
Let :
a : [1, 1, 0]
b : [1, 0, 1]
Then cosine similarity (Theta):
(Theta) = (1*1 + 1*0 + 0*1)/sqrt((1^2 + 1^2))* sqrt((1^2 + 1^2)) = 1/2 = 0.5
then inverse of cos 0.5 is 60 degrees.
<?php
if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
$image_path = array();
$count = count($_FILES[$input_name]['name']);
for($key =0; $key <$count; $key++){
$_FILES['file']['name'] = $_FILES[$input_name]['name'][$key];
$_FILES['file']['type'] = $_FILES[$input_name]['type'][$key];
$_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key];
$_FILES['file']['error'] = $_FILES[$input_name]['error'][$key];
$_FILES['file']['size'] = $_FILES[$input_name]['size'][$key];
$config['file_name'] = $_FILES[$input_name]['name'][$key];
$this->upload->initialize($config);
if($this->upload->do_upload('file')) {
$data = $this->upload->data();
$image_path[$key] = $path ."$data[file_name]";
}else{
$error = $this->upload->display_errors();
$this->session->set_flashdata('msg_error',"image upload! ".$error);
}
}
return json_encode($image_path);
}
?>
_x000D_
creating logo
in folders "drawable-...
" create in all of them logo.png
.
The location of the folders: [YOUR APP]\app\src\main\res
In AndroidManifest.xml add line: android:logo="@drawable/logo"
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:logo="@drawable/logo"
...
that's it.
Due to mantain compatibility with ie7, ie8 I suggest using first-child and not last-child to doing this:
table tr td{border-top:1px solid #ffffff;border-left:1px solid #ffffff;}
table tr td:first-child{border-left:0;}
table tr:first-child td{border-top:0;}
You can learn about CSS 2.1 Pseudo-classes at: http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx
A simple way to do that is to use string format, see this page.
>> "{0:b}".format(10)
'1010'
And if you want to have a fixed length of the binary string, you can use this:
>> "{0:{fill}8b}".format(10, fill='0')
'00001010'
If two's complement is required, then the following line can be used:
'{0:{fill}{width}b}'.format((x + 2**n) % 2**n, fill='0', width=n)
where n is the width of the binary string.
awk
awk '{gsub(/two.*/,"")}1' file
Ruby
ruby -ne 'print $_.gsub(/two.*/,"")' file
Git will even determine that it is binary if you have one super-long line in your text file. I broke up a long String, turning it into several source code lines, and suddenly the file went from being 'binary' to a text file that I could see (in SmartGit).
So don't keep typing too far to the right without hitting 'Enter' in your editor - otherwise later on Git will think you have created a binary file.
Use following class which implement fast method described in this article and contains all you need: readPixel
, putPixel
, get width/height
. Class update canvas after calling refresh()
method. Example solve simple case of 2d wave equation
class Screen{
constructor(canvasSelector) {
this.canvas = document.querySelector(canvasSelector);
this.width = this.canvas.width;
this.height = this.canvas.height;
this.ctx = this.canvas.getContext('2d');
this.imageData = this.ctx.getImageData(0, 0, this.width, this.height);
this.buf = new ArrayBuffer(this.imageData.data.length);
this.buf8 = new Uint8ClampedArray(this.buf);
this.data = new Uint32Array(this.buf);
}
// r,g,b,a - red, gren, blue, alpha components in range 0-255
putPixel(x,y,r,g,b,a=255) {
this.data[y * this.width + x] = (a << 24) | (b << 16) | (g << 8) | r;
}
readPixel(x,y) {
let p= this.data[y * this.width + x]
return [p&0xff, p>>8&0xff, p>>16&0xff, p>>>24];
}
refresh() {
this.imageData.data.set(this.buf8);
this.ctx.putImageData(this.imageData, 0, 0);
}
}
// --------
// TEST
// --------
let s=new Screen('#canvas');
function draw() {
for (var y = 1; y < s.height-1; ++y) {
for (var x = 1; x < s.width-1; ++x) {
let a = [[1,0],[-1,0],[0,1],[0,-1]].reduce((a,[xp,yp])=>
a+= s.readPixel(x+xp,y+yp)[0]
,0);
let v=a/2-tmp[x][y];
tmp[x][y]=v<0 ? 0:v;
}
}
for (var y = 1; y < s.height-1; ++y) {
for (var x = 1; x < s.width-1; ++x) {
let v=tmp[x][y];
tmp[x][y]= s.readPixel(x,y)[0];
s.putPixel(x,y, v,v,v);
}
}
s.refresh();
window.requestAnimationFrame(draw)
}
// temporary 2d buffer ()for solving wave equation)
let tmp = [...Array(s.width)].map(x => Array(s.height).fill(0));
function move(e) { s.putPixel(e.x-10, e.y-10, 255,255,255);}
draw();
_x000D_
<canvas id="canvas" height="150" width="512" onmousemove="move(event)"></canvas>
<div>Move mouse on black box</div>
_x000D_
Compromise minimum solution:
| One | Two | Three | Four | Five | Six
| -
| Span <td colspan=3>triple <td colspan=2>double
So you can omit closing </td>
for speed, ?r can leave for consistency.
Result from http://markdown-here.com/livedemo.html :
Works in Jupyter Markdown.
As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.
| One | Two | Three | Four | Five | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple <td colspan=2>double
minimally:
One | Two | Three | Four | Five | Six
-|||||-
Span <td colspan=3>triple <td colspan=2>double
use
pattern.compile("\"");
String s= p.toString()+"yourcontent"+p.toString();
will give result as yourcontent
as is
As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost';
does not work is quite simple : There is no grant called USAGE
.
The actual named grants are in the MySQL Documentation
The grant USAGE
is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user
where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE
. Running DROP USER 'phpmyadmin'@'localhost';
should work just fine. Under the hood, it's really doing this:
DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;
Therefore, the removal of a row from mysql.user
constitutes running REVOKE USAGE
, even though REVOKE USAGE
cannot literally be executed.
You need to create a object from your list like:
List<CartProduct> lst = new List<CartProduct>();
CartProduct obj = lst.Find(x => (x.Name == "product name"));
That object get the looked value searching by their properties: x.name
Then you can use List methods like Contains or Remove
if (lst.Contains(obj))
{
lst.Remove(obj);
}
Most of the time, in enterprise applications the Java heap given is larger than the ideal size of max 12 to 16 GB. I have found it hard to make the NetBeans profiler work directly on these big java apps.
But usually this is not needed. You can use the jmap utility that comes with the jdk to take a "live" heap dump , that is jmap will dump the heap after running GC. Do some operation on the application, wait till the operation is completed, then take another "live" heap dump. Use tools like Eclipse MAT to load the heapdumps, sort on the histogram, see which objects have increased, or which are the highest, This would give a clue.
su proceeuser
/bin/jmap -dump:live,format=b,file=/tmp/2930javaheap.hrpof 2930(pid of process)
There is only one problem with this approach; Huge heap dumps, even with the live option, may be too big to transfer out to development lap, and may need a machine with enough memory/RAM to open.
That is where the class histogram comes into picture. You can dump a live class histogram with the jmap tool. This will give only the class histogram of memory usage.Basically it won't have the information to chain the reference. For example it may put char array at the top. And String class somewhere below. You have to draw the connection yourself.
jdk/jdk1.6.0_38/bin/jmap -histo:live 60030 > /tmp/60030istolive1330.txt
Instead of taking two heap dumps, take two class histograms, like as described above; Then compare the class histograms and see the classes that are increasing. See if you can relate the Java classes to your application classes. This will give a pretty good hint. Here is a pythons script that can help you compare two jmap histogram dumps. histogramparser.py
Finally tools like JConolse and VisualVm are essential to see the memory growth over time, and see if there is a memory leak. Finally sometimes your problem may not be a memory leak , but high memory usage.For this enable GC logging;use a more advanced and new compacting GC like G1GC; and you can use jdk tools like jstat to see the GC behaviour live
jstat -gccause pid <optional time interval>
Other referecences to google for -jhat, jmap, Full GC, Humongous allocation, G1GC
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};
printMatrix(matrix);
public void printMatrix(int[][] m){
try{
int rows = m.length;
int columns = m[0].length;
String str = "|\t";
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
str += m[i][j] + "\t";
}
System.out.println(str + "|");
str = "|\t";
}
}catch(Exception e){System.out.println("Matrix is empty!!");}
}
Output:
| 1 2 3 |
| 4 5 6 |
| 7 8 9 |
| 10 11 12 |
For the particular case of splitting strings into words I've come across another solution for SQL Server 2008.
with testTable AS
(
SELECT 1 AS Id, N'how now brown cow' AS txt UNION ALL
SELECT 2, N'she sells sea shells upon the sea shore' UNION ALL
SELECT 3, N'red lorry yellow lorry' UNION ALL
SELECT 4, N'the quick brown fox jumped over the lazy dog'
)
SELECT display_term, COUNT(*) As Cnt
FROM testTable
CROSS APPLY sys.dm_fts_parser('"' + txt + '"', 1033, 0,0)
GROUP BY display_term
HAVING COUNT(*) > 1
ORDER BY Cnt DESC
Returns
display_term Cnt
------------------------------ -----------
the 3
brown 2
lorry 2
sea 2
I don't believe you can, though I hope that someone will prove me wrong.
I know you can print the query and its toString method will show you the sql without the replacements. That can be handy if you're building complex query strings, but it doesn't give you the full query with values.
To find the last filled column use the following :
lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,60))
plt.subplots_adjust( ... )
The plt.subplots_adjust method:
def subplots_adjust(*args, **kwargs):
"""
call signature::
subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)
Tune the subplot layout via the
:class:`matplotlib.figure.SubplotParams` mechanism. The parameter
meanings (and suggested defaults) are::
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
The actual defaults are controlled by the rc file
"""
fig = gcf()
fig.subplots_adjust(*args, **kwargs)
draw_if_interactive()
or
fig = plt.figure(figsize=(10,60))
fig.subplots_adjust( ... )
The size of the picture matters.
"I've tried messing with hspace, but increasing it only seems to make all of the graphs smaller without resolving the overlap problem."
Thus to make more white space and keep the sub plot size the total image needs to be bigger.
It sounds like you are depending on some feedback to determine what is getting stuck on the receiving end. You should be checking the outbound mail yourself for obvious "spaminess".
Buy any decent spam control system, and send your outbound mail through it. If you send any decent volume of mail, you should be doing this anyhow, because of the risk of sending outbound viruses, especially if you have desktop windows users.
Proofpoint had spam + anti-virus + some reputation services in a single deployment, for example. (I used to work there, so I happen to know this off the top of my head. I'm sure other vendors in this space have similar features.) But you get the idea. If you send your mail through a basic commerical spam control setup, and it doesn't pass, it shouldn't be going out of your network.
Also, there are some companies that can assist you with increasing delivery rates of non-spam, outbound email, like Habeas.
You can do it with javascript/jquery:
<script>
function runScript(e) {
if (e.keyCode == 13) {
$("#myButton").click(); //jquery
document.getElementById("myButton").click(); //javascript
}
}
</script>
<asp:textbox id="txtUsername" runat="server" onkeypress="return runScript(event)" />
<asp:LinkButton id="myButton" text="Login" runat="server" />
This is my experience for this problem maybe it could help you :
I copied all folders and files inside the /data
folder to have a backup from my db
.
When I switched to another Computer's Xampp
and I started copying all folders and files copied before from previous phpmyadmin /data
folder.
So when I was done this problem happened for me .
To solve this issue :
1 - I made a backup from /data
folder of phpmyadmin
by copying only only folders have same name with tables I want to make backup .
2 - Uninstall Xampp.
3 - Reinstall Xampp .
4 - Copy all folders Kept in step 1 inside mysql/data
folder . this folders are only database tables and be careful don't touch another file and folder or replace anything when copying.
You could change your code in this way:
public delegate void CallbackHandler(string str);
public class ServerRequest
{
public void DoRequest(string request, CallbackHandler callback)
{
// do stuff....
callback("asdf");
}
}
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
You can definetely build your code from Vim, that's what the :make
command does.
However, you need to go through the basics first : type vimtutor
in your terminal and follow the instructions to the end.
After you have completed it a few times, open an existing (non-important) text file and try out all the things you learned from vimtutor
: entering/leaving insert mode, undoing changes, quitting/saving, yanking/putting, moving and so on.
For a while you won't be productive at all with Vim and will probably be tempted to go back to your previous IDE/editor. Do that, but keep up with Vim a little bit every day. You'll probably be stopped by very weird and unexpected things but it will happen less and less.
In a few months you'll find yourself hitting o
, v
and i
all the time in every textfield everywhere.
Have fun!
I had the same problem but also listed in the error log was this: CSSMERR_TP_CERT_NOT_VALID_YET
Looking at the certificate in KeyChain showed a similar message. The problem was due to my Mac's system clock being set incorrectly. As soon as I set the correct region/time, the certificate was marked as valid and I could build and run my app on the iPhone
The overall winner between using the np.sum, np.min, and all seems to be np.min in terms of speed for large arrays:
N = 1000000
def func_sum(x):
my_list = np.random.randn(N)
return np.sum(my_list < x )==0
def func_min(x):
my_list = np.random.randn(N)
return np.min(my_list) >= x
def func_all(x):
my_list = np.random.randn(N)
return all(i >= x for i in my_list)
(i need to put the np.array definition inside the function, otherwise the np.min function remembers the value and does not do the computation again when testing for speed with timeit)
The performance of "all" depends very much on when the first element that does not satisfy the criteria is found, the np.sum needs to do a bit of operations, the np.min is the lightest in terms of computations in the general case.
When the criteria is almost immediately met and the all loop exits fast, the all function is winning just slightly over np.min:
>>> %timeit func_sum(10)
10 loops, best of 3: 36.1 ms per loop
>>> %timeit func_min(10)
10 loops, best of 3: 35.1 ms per loop
>>> %timeit func_all(10)
10 loops, best of 3: 35 ms per loop
But when "all" needs to go through all the points, it is definitely much worse, and the np.min wins:
>>> %timeit func_sum(-10)
10 loops, best of 3: 36.2 ms per loop
>>> %timeit func_min(-10)
10 loops, best of 3: 35.2 ms per loop
>>> %timeit func_all(-10)
10 loops, best of 3: 230 ms per loop
But using
np.sum(my_list<x)
can be very useful is one wants to know how many values are below x.
Here is the Basic Difference between Compiler vs Interpreter Language.
Compiler Language
Interpreter Language:
This error occurred for me because i was trying to store the minimum date and time in a column using inline queries directly from C# code.
The date variable was set to 01/01/0001 12:00:00 AM in the code given the fact that DateTime in C# is initialized with this date and time if not set elsewise. And the least possible date allowed in the MS-SQL 2008 datetime datatype is 1753-01-01 12:00:00 AM.
I changed the date from the code and set it to 01/01/1900 and no errors were reported further.
Invoke it from the shell, with an argument like /?
or --help
. Those are the usual help switches.
func isObjectValid(someObject: Any?) -> Any? {
if someObject is String {
if let someObject = someObject as? String {
return someObject
}else {
return ""
}
}else if someObject is Array<Any> {
if let someObject = someObject as? Array<Any> {
return someObject
}else {
return []
}
}else if someObject is Dictionary<AnyHashable, Any> {
if let someObject = someObject as? Dictionary<String, Any> {
return someObject
}else {
return [:]
}
}else if someObject is Data {
if let someObject = someObject as? Data {
return someObject
}else {
return Data()
}
}else if someObject is NSNumber {
if let someObject = someObject as? NSNumber{
return someObject
}else {
return NSNumber.init(booleanLiteral: false)
}
}else if someObject is UIImage {
if let someObject = someObject as? UIImage {
return someObject
}else {
return UIImage()
}
}
else {
return "InValid Object"
}
}
This function checks any kind of object and return's default value of the kind of object, if object is invalid.
The best way to set any feature regarding the colors of any widget is to use QPalette.
And the easiest way to find what you are looking for is to open Qt Designer and set the palette of a QLabel and check the generated code.
The following function searches on multiple patterns, separated by commas. You can also specify an exclusion, eg: "!web.config" will search for all files and exclude "web.config". Patterns can be mixed.
private string[] FindFiles(string directory, string filters, SearchOption searchOption)
{
if (!Directory.Exists(directory)) return new string[] { };
var include = (from filter in filters.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) where !string.IsNullOrEmpty(filter.Trim()) select filter.Trim());
var exclude = (from filter in include where filter.Contains(@"!") select filter);
include = include.Except(exclude);
if (include.Count() == 0) include = new string[] { "*" };
var rxfilters = from filter in exclude select string.Format("^{0}$", filter.Replace("!", "").Replace(".", @"\.").Replace("*", ".*").Replace("?", "."));
Regex regex = new Regex(string.Join("|", rxfilters.ToArray()));
List<Thread> workers = new List<Thread>();
List<string> files = new List<string>();
foreach (string filter in include)
{
Thread worker = new Thread(
new ThreadStart(
delegate
{
string[] allfiles = Directory.GetFiles(directory, filter, searchOption);
if (exclude.Count() > 0)
{
lock (files)
files.AddRange(allfiles.Where(p => !regex.Match(p).Success));
}
else
{
lock (files)
files.AddRange(allfiles);
}
}
));
workers.Add(worker);
worker.Start();
}
foreach (Thread worker in workers)
{
worker.Join();
}
return files.ToArray();
}
Usage:
foreach (string file in FindFiles(@"D:\628.2.11", @"!*.config, !*.js", SearchOption.AllDirectories))
{
Console.WriteLine(file);
}
If the array is statically allocated, use sizeof(array) / sizeof(array[0])
If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0])
(which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.
I think it would make more sense to use "Find" function in Excel instead of For Each loop. It works much much faster and it's designed for such actions. Try this:
Sub FindSomeCells(strSearchQuery As String)
Set SearchRange = Worksheets("Sheet1").Range("A1:A100")
FindWhat = strSearchQuery
Set FoundCells = FindAll(SearchRange:=SearchRange, _
FindWhat:=FindWhat, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByColumns, _
MatchCase:=False, _
BeginsWith:=vbNullString, _
EndsWith:=vbNullString, _
BeginEndCompare:=vbTextCompare)
If FoundCells Is Nothing Then
Debug.Print "Value Not Found"
Else
For Each FoundCell In FoundCells
FoundCell.Interior.Color = XlRgbColor.rgbLightGreen
Next FoundCell
End If
End Sub
That subroutine searches for some string and returns a collections of cells fullfilling your search criteria. Then you can do whatever you want with the cells in that collection. Forgot to add the FindAll
function definition:
Function FindAll(SearchRange As Range, _
FindWhat As Variant, _
Optional LookIn As XlFindLookIn = xlValues, _
Optional LookAt As XlLookAt = xlWhole, _
Optional SearchOrder As XlSearchOrder = xlByRows, _
Optional MatchCase As Boolean = False, _
Optional BeginsWith As String = vbNullString, _
Optional EndsWith As String = vbNullString, _
Optional BeginEndCompare As VbCompareMethod = vbTextCompare) As Range
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FindAll
' This searches the range specified by SearchRange and returns a Range object
' that contains all the cells in which FindWhat was found. The search parameters to
' this function have the same meaning and effect as they do with the
' Range.Find method. If the value was not found, the function return Nothing. If
' BeginsWith is not an empty string, only those cells that begin with BeginWith
' are included in the result. If EndsWith is not an empty string, only those cells
' that end with EndsWith are included in the result. Note that if a cell contains
' a single word that matches either BeginsWith or EndsWith, it is included in the
' result. If BeginsWith or EndsWith is not an empty string, the LookAt parameter
' is automatically changed to xlPart. The tests for BeginsWith and EndsWith may be
' case-sensitive by setting BeginEndCompare to vbBinaryCompare. For case-insensitive
' comparisons, set BeginEndCompare to vbTextCompare. If this parameter is omitted,
' it defaults to vbTextCompare. The comparisons for BeginsWith and EndsWith are
' in an OR relationship. That is, if both BeginsWith and EndsWith are provided,
' a match if found if the text begins with BeginsWith OR the text ends with EndsWith.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim FoundCell As Range
Dim FirstFound As Range
Dim LastCell As Range
Dim ResultRange As Range
Dim XLookAt As XlLookAt
Dim Include As Boolean
Dim CompMode As VbCompareMethod
Dim Area As Range
Dim MaxRow As Long
Dim MaxCol As Long
Dim BeginB As Boolean
Dim EndB As Boolean
CompMode = BeginEndCompare
If BeginsWith <> vbNullString Or EndsWith <> vbNullString Then
XLookAt = xlPart
Else
XLookAt = LookAt
End If
' this loop in Areas is to find the last cell
' of all the areas. That is, the cell whose row
' and column are greater than or equal to any cell
' in any Area.
For Each Area In SearchRange.Areas
With Area
If .Cells(.Cells.Count).Row > MaxRow Then
MaxRow = .Cells(.Cells.Count).Row
End If
If .Cells(.Cells.Count).Column > MaxCol Then
MaxCol = .Cells(.Cells.Count).Column
End If
End With
Next Area
Set LastCell = SearchRange.Worksheet.Cells(MaxRow, MaxCol)
On Error GoTo 0
Set FoundCell = SearchRange.Find(what:=FindWhat, _
after:=LastCell, _
LookIn:=LookIn, _
LookAt:=XLookAt, _
SearchOrder:=SearchOrder, _
MatchCase:=MatchCase)
If Not FoundCell Is Nothing Then
Set FirstFound = FoundCell
Do Until False ' Loop forever. We'll "Exit Do" when necessary.
Include = False
If BeginsWith = vbNullString And EndsWith = vbNullString Then
Include = True
Else
If BeginsWith <> vbNullString Then
If StrComp(Left(FoundCell.Text, Len(BeginsWith)), BeginsWith, BeginEndCompare) = 0 Then
Include = True
End If
End If
If EndsWith <> vbNullString Then
If StrComp(Right(FoundCell.Text, Len(EndsWith)), EndsWith, BeginEndCompare) = 0 Then
Include = True
End If
End If
End If
If Include = True Then
If ResultRange Is Nothing Then
Set ResultRange = FoundCell
Else
Set ResultRange = Application.Union(ResultRange, FoundCell)
End If
End If
Set FoundCell = SearchRange.FindNext(after:=FoundCell)
If (FoundCell Is Nothing) Then
Exit Do
End If
If (FoundCell.Address = FirstFound.Address) Then
Exit Do
End If
Loop
End If
Set FindAll = ResultRange
End Function
There are two ways to do it.
In the method that opens the dialog, pass in the following configuration option disableClose
as the second parameter in MatDialog#open()
and set it to true
:
export class AppComponent {
constructor(private dialog: MatDialog){}
openDialog() {
this.dialog.open(DialogComponent, { disableClose: true });
}
}
Alternatively, do it in the dialog component itself.
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>){
dialogRef.disableClose = true;
}
}
Here's what you're looking for:
And here's a Stackblitz demo
Here's some other use cases and code snippets of how to implement them.
As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:
import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
selector: 'app-third-dialog',
templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {
}
@HostListener('window:keyup.esc') onKeyUp() {
this.dialogRef.close();
}
}
P.S. This is an answer which originated from this answer, where the demo was based on this answer.
To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick
to listen for click events to the backdrop.
Initially, the dialog will have the configuration option disableClose
set as true
. This ensures that the esc
keypress, as well as clicking on the backdrop will not cause the dialog to close.
Afterwards, subscribe to the MatDialogRef#backdropClick
method (which emits when the backdrop gets clicked and returns as a MouseEvent
).
Anyways, enough technical talk. Here's the code:
openDialog() {
let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
// ...
}
Alternatively, this can be done in the dialog component:
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>) {
dialogRef.disableClose = true;
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
}
}
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
For example, if you want convert object fields to map:
Example object:
class Item{
private String code;
private String name;
public Item(String code, String name) {
this.code = code;
this.name = name;
}
//getters and setters
}
And operation convert List To Map:
List<Item> list = new ArrayList<>();
list.add(new Item("code1", "name1"));
list.add(new Item("code2", "name2"));
Map<String,String> map = list.stream()
.collect(Collectors.toMap(Item::getCode, Item::getName));
I'm using the following, though it's hardcoded for gnome-terminal
. It also changes the CWD and buffer for vim to be the same as your current buffer and it's directory.
:silent execute '!gnome-terminal -- zsh -i -c "cd ' shellescape(expand("%:h")) '; vim' shellescape(expand("%:p")) '; zsh -i"' <cr>
The account that sql server is running under does not have access to the location where you have the backup file or are trying to restore the database to. You can use SQL Server Configuration Manager to find which account is used to run the SQL Server instance, and then make sure that account has full control over the .BAK file and the folder where the MDF will be restored to.
There are several related solutions available on the internet, but it all depends on the configuration of the machine and the firewall rules.
For me below solution is worked:
import React, { Component } from 'react';
class Result extends Component {
render() {
if(this.props.resultsfood.status=='found'){
var foodlist = this.props.resultsfood.items.map(name=>{
return (
<div className="row" key={name.id} >
<div className="list-group">
<a href="#" className="list-group-item list-group-item-action disabled">
<span className="badge badge-info"><h6> {name.item}</h6></span>
<span className="badge badge-danger"><h6> Rs.{name.price}/=</h6></span>
</a>
<a href="#" className="list-group-item list-group-item-action disabled">
<div className="alert alert-dismissible alert-secondary">
<strong>{name.description}</strong>
</div>
</a>
<div className="form-group">
<label className="col-form-label col-form-label-sm" htmlFor="inputSmall">Quantitiy</label>
<input className="form-control form-control-sm" placeholder="unit/kg" type="text" ref="qty"/>
<div> <button type="button" className="btn btn-success"
onClick={()=>{this.props.savelist(name.item,name.price);
this.props.pricelist(name.price);
this.props.quntylist(this.refs.qty.value);
}
}>ADD Cart</button>
</div>
<br/>
</div>
</div>
</div>
)
})
}
return (
<ul>
{foodlist}
</ul>
)
}
}
export default Result;
A working example.
DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YourTableName'
EXECUTE ('SELECT * INTO #TEMP FROM ' + @TableName +'; SELECT * FROM #TEMP;')
Second solution with accessible temp table
DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YOUR_TABLE_NAME'
EXECUTE ('CREATE VIEW vTemp AS
SELECT *
FROM ' + @TableName)
SELECT * INTO #TEMP FROM vTemp
--DROP THE VIEW HERE
DROP VIEW vTemp
/*START USING TEMP TABLE
************************/
--EX:
SELECT * FROM #TEMP
--DROP YOUR TEMP TABLE HERE
DROP TABLE #TEMP
SymmetricDS is the answer. It supports multiple subscribers with one direction or bi-directional asynchronous data replication. It uses web and database technologies to replicate tables between relational databases, in near real time if desired.
Comprehensive and robust Java API to suit your needs.
In the form designer add a new timer using the toolbox. In properties set "Enabled" equal to "True".
The set the DataGridView
to equal your new data in the timer
If you need to change the figure size after you have created it, use the methods
fig = plt.figure()
fig.set_figheight(value_height)
fig.set_figwidth(value_width)
where value_height
and value_width
are in inches. For me this is the most practical way.
OK, this post is a little old, but... if you want to do SQL-like query in native JSON (or JS objects) on JS objects, take a look at https://github.com/deitch/searchjs
It is both a jsql language written entirely in JSON, and a reference implementation. You can say, "I want to find all object in an array that have name==="John" && age===25 as:
{name:"John",age:25,_join:"AND"}
The reference implementation searchjs works in the browser as well as as a node npm package
npm install searchjs
It can also do things like complex joins and negation (NOT). It natively ignores case.
It doesn't yet do summation or count, but it is probably easier to do those outside.
but I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???
Don't panic.
Farm constructor will be called in the constructor of PetStore, automatically.
See the base class inheritance calling rules: What are the rules for calling the superclass constructor?
First, make sure you have the environment variable set up. 1. Right click on my computer 2. properties 3. advanced system settings 4. environment variables 5. edit the PATH variable. and add ;"C:\mongoDb\bin\" to the PATH variable.
Path in the quotes may differ depending on your installation directory. Do not forget the last '\' as it was the main problem in my case.
While using Laravel on apache server there is another php.ini
/etc/php/7.2/apache2/php.ini
Modify the memory limit value in this file
memory_limit=1024M
and restart the apache server
sudo service apache2 restart
For Using the_content()
functions (for displaying the main content of the page)
$content = get_the_content();
echo substr($content, 0, 100);
For Using the_excerpt()
functions (for displaying the excerpt-short content of the page)
$excerpt= get_the_excerpt();
echo substr($excerpt, 0, 100);
I use this code to generate a random number:
//
// FactModel.swift
// Collection
//
// Created by Ahmadreza Shamimi on 6/11/16.
// Copyright © 2016 Ahmadreza Shamimi. All rights reserved.
//
import GameKit
struct FactModel {
let fun = ["I love swift","My name is Ahmadreza","I love coding" ,"I love PHP","My name is ALireza","I love Coding too"]
func getRandomNumber() -> String {
let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(fun.count)
return fun[randomNumber]
}
}
Make that variable as transient.Your problem will get solved..
@Column(name="emp_name", nullable=false, length=30)
private transient String empName;
pgrep
can get you all of the child PIDs of a parent process. As mentioned earlier $$
is the current scripts PID. So, if you want a script that cleans up after itself, this should do the trick:
trap 'kill $( pgrep -P $$ | tr "\n" " " )' SIGINT SIGTERM EXIT
Click on the menu Window > Preferences and go to Workspaces like below :
| General
| Startup and Shutdown
| Workspaces
Select the workspace to delete and click on the Remove button.
This problem arose again recently due to a bug in Python itself.
http://bugs.python.org/issue22931
https://code.djangoproject.com/ticket/24280
Among the versions affected were 2.7.8 and 2.7.9.
The cookie was not read correctly if one of the values contained a [
character.
Updating Python (2.7.10) fixes the problem.
Simplest way,
Controller:
[HttpGet("empId={empId}&startDate={startDate}&endDate={endDate}")]
public IEnumerable<Validate> Get(int empId, string startDate, string endDate){}
Postman Request:
{router}/empId=1&startDate=2020-20-20&endDate=2020-20-20
Learning point: Request exact pattern will be accepted by the Controller.
Decode the string to Unicode. Assuming it's UTF-8-encoded:
str.decode("utf-8")
Call the replace
method and be sure to pass it a Unicode string as its first argument:
str.decode("utf-8").replace(u"\u2022", "*")
Encode back to UTF-8, if needed:
str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str
shadows the built-in type str
.)
Maybe you can use pandas crosstab function
test5 = pd.crosstab(index=faultdf['Site Name'], columns=faultdf[''Abuse/NFF''])
test5.plot(kind='bar', stacked=True)
From jquery prospective - it's just adding load
/onload
event to window and document.
Check this out:
It's an HtmlGenericControl so not sure what the recommended way to do this is, so you could also do:
testSpace.Attributes.Add("style", "text-align: center;");
or
testSpace.Attributes.Add("class", "centerIt");
or
testSpace.Attributes["style"] = "text-align: center;";
or
testSpace.Attributes["class"] = "centerIt";
In case someone wants numer of whole days as a double (a
, b
of type DateTime
):
(a.Date - b.Date).TotalDays
Thread.Sleep(50);
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.
This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
Thread.Join
Today I was trying same in db2 and used below, in my case I had spaces at the end of varchar column data
SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(TRIM(EmployeeName))> 4;
DECLARE @FromDate DATETIME
SET @FromDate = 'Jan 10 2016 12:00AM'
DECLARE @ToDate DATETIME
SET @ToDate = 'Jan 10 2017 12:00AM'
DECLARE @Dynamic_Qry nvarchar(Max) =''
SET @Dynamic_Qry='SELECT
(CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN
EMP_DOCUMENT.EXPIRY_DATE ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
)FROM CR.EMP_DOCUMENT as EMP_DOCUMENT WHERE 1=1
AND (
CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN EMP_DOCUMENT.EXPIRY_DATE
ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
) BETWEEN '''+ CONVERT(CHAR(10), @FromDate, 126) +''' AND '''+CONVERT(CHAR(10), @ToDate , 126
)
+'''
'
print @Dynamic_Qry
EXEC(@Dynamic_Qry)
Isn't encoding taking the text TO base64 and decoding taking base64 BACK to text? You seem be mixing them up here. When I decode using this online decoder I get:
BASE64: blahblah
UTF8: nVnV
not the other way around. I can't reproduce it completely in PS though. See sample below:
PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("blahblah"))
nV?nV?
PS > [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("nVnV"))
blZuVg==
EDIT I believe you're using the wrong encoder for your text. The encoded base64 string is encoded from UTF8(or ASCII) string.
PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah
PS > [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
????
PS > [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah
Look at the widgets documentation. Basically it would look like:
q = forms.CharField(label='search',
widget=forms.TextInput(attrs={'placeholder': 'Search'}))
More writing, yes, but the separation allows for better abstraction of more complicated cases.
You can also declare a widgets
attribute containing a <field name> => <widget instance>
mapping directly on the Meta
of your ModelForm
sub-class.
One way with bash (version 4+):
foo=bar
echo "${foo^}"
prints:
Bar
New escape string in PowerShell V3, quoted from New V3 Language Features:
Easier Reuse of Command Lines From Cmd.exe
The web is full of command lines written for Cmd.exe. These commands lines work often enough in PowerShell, but when they include certain characters, for example, a semicolon (;), a dollar sign ($), or curly braces, you have to make some changes, probably adding some quotes. This seemed to be the source of many minor headaches.
To help address this scenario, we added a new way to “escape” the parsing of command lines. If you use a magic parameter --%, we stop our normal parsing of your command line and switch to something much simpler. We don’t match quotes. We don’t stop at semicolon. We don’t expand PowerShell variables. We do expand environment variables if you use Cmd.exe syntax (e.g. %TEMP%). Other than that, the arguments up to the end of the line (or pipe, if you are piping) are passed as is. Here is an example:
PS> echoargs.exe --% %USERNAME%,this=$something{weird}
Arg 0 is <jason,this=$something{weird}>
I wanted to do the same thing as, but I wanted to do it in the one file.
So the logic would be:
I modified the answer by Bakuriu and came up with this:
from os import getpid
from sys import argv, exit
import psutil ## pip install psutil
myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
if process.pid != mypid:
for path in process.cmdline():
if myname in path:
print "process found"
process.terminate()
exit()
## your program starts here...
Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.
I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.
The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:
var len = menuitems.length;
for (var i = 0; i < len; i++){
(function(i) {
$('<li/>',{
'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
'click':function(){
menuitems[i].action();
},
'class':o.itemClass
}).appendTo('.'+o.listClass);
})(i);
}
In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.
My example comment to @qubyte above got chopped, so here's something that's easier to read...
The method @surjikal described above works for branch commits, but it didn't work for a tree commit I was trying include.
The archive mode also works for commits. For example, fetch @ a2fbf83
npm:
npm install https://github.com/github/fetch/archive/a2fbf834773b8dc20eef83bb53d081863d3fc87f.tar.gz
yarn:
yarn add https://github.com/github/fetch/archive/a2fbf834773b8dc20eef83bb53d081863d3fc87f.tar.gz
format:
https://github.com/<owner>/<repo>/archive/<commit-id>.tar.gz
/archive/
mode:
yarn add https://github.com/vuejs/vuex/archive/c3626f779b8ea902789dd1c4417cb7d7ef09b557.tar.gz
for the related vuex commit
<input type='text' minlength=3 /><br />
if browser supports html5,
it will automatical be validate attributes(minlength) in tag
but Safari(iOS) doesn't working
In DBTools for Sybase, it's sp_columns your_table_name
.
Your question shows you have succumbed to some of the common misconceptions surrounding table variables and temporary tables.
I have written quite an extensive answer on the DBA site looking at the differences between the two object types. This also addresses your question about disk vs memory (I didn't see any significant difference in behaviour between the two).
Regarding the question in the title though as to when to use a table variable vs a local temporary table you don't always have a choice. In functions, for example, it is only possible to use a table variable and if you need to write to the table in a child scope then only a #temp
table will do
(table-valued parameters allow readonly access).
Where you do have a choice some suggestions are below (though the most reliable method is to simply test both with your specific workload).
If you need an index that cannot be created on a table variable then you will of course need a #temporary
table. The details of this are version dependant however. For SQL Server 2012 and below the only indexes that could be created on table variables were those implicitly created through a UNIQUE
or PRIMARY KEY
constraint. SQL Server 2014 introduced inline index syntax for a subset of the options available in CREATE INDEX
. This has been extended since to allow filtered index conditions. Indexes with INCLUDE
-d columns or columnstore indexes are still not possible to create on table variables however.
If you will be repeatedly adding and deleting large numbers of rows from the table then use a #temporary
table. That supports TRUNCATE
(which is more efficient than DELETE
for large tables) and additionally subsequent inserts following a TRUNCATE
can have better performance than those following a DELETE
as illustrated here.
#temporary
table. That supports creation of statistics which allows the plan to be dynamically recompiled according to the data (though for cached temporary tables in stored procedures the recompilation behaviour needs to be understood separately).SELECT
statement then consider that using a table variable will block the possibility of this using a parallel plan.#temp
table within a user transaction locks can be held longer than for table variables (potentially until the end of transaction vs end of statement dependent on the type of lock and isolation level) and also it can prevent truncation of the tempdb
transaction log until the user transaction ends. So this might favour the use of table variables.#temporary
tables. Bob Ward points out in his tempdb
presentation that this can cause additional contention on system tables under conditions of high concurrency. Additionally, when dealing with small quantities of data this can make a measurable difference to performance.Effects of rowset sharing
DECLARE @T TABLE(id INT PRIMARY KEY, Flag BIT);
CREATE TABLE #T (id INT PRIMARY KEY, Flag BIT);
INSERT INTO @T
output inserted.* into #T
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), 0
FROM master..spt_values v1, master..spt_values v2
SET STATISTICS TIME ON
/*CPU time = 7016 ms, elapsed time = 7860 ms.*/
UPDATE @T SET Flag=1;
/*CPU time = 6234 ms, elapsed time = 7236 ms.*/
DELETE FROM @T
/* CPU time = 828 ms, elapsed time = 1120 ms.*/
UPDATE #T SET Flag=1;
/*CPU time = 672 ms, elapsed time = 980 ms.*/
DELETE FROM #T
DROP TABLE #T
The find
command will take long time because it scans real files in file system.
The quickest way is using locate
command, which will give result immediately:
locate "John"
If the command is not found, you need to install mlocate
package and run updatedb
command first to prepare the search database for the first time.
More detail here: https://medium.com/@thucnc/the-fastest-way-to-find-files-by-filename-mlocate-locate-commands-55bf40b297ab
For a String constant you have no choice other than escaping via backslash.
Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.
for (let i of Array(100).keys()) {
console.log(i)
}
Close the application, then restart it after changing to a new port:
${port:8181}
You can use any new unused port. Here, I used port 8181.
Source: http://www.nigraphic.com/blog/java-script/how-open-new-window-popup-center-screen
function PopupCenter(pageURL, title,w,h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
return targetWin;
}
In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.
However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.
In that case, you can use
jekyll serve --host 0.0.0.0
This binds your application to the host & next use following to connect to it from some other host
http://host's IP adress/4000
You could try to force the browser to open a "Save As..." dialog by doing something like:
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";
Which should work across most major browsers.
These are typical npm paths if you install a package globally:
Windows XP - %USERPROFILE%\Application Data\npm\node_modules
Newer Windows Versions - %AppData%\npm\node_modules
or - %AppData%\roaming\npm\node_modules
Agree with Ali Parr. The WndTab Line Counter addin is a such tool. http://www.codeproject.com/KB/macros/linecount.aspx
It's also a good idea to search from download site to find some related tool. http://www.cnet.com/1770-5_1-0.html?query=code+counter&tag=srch
I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?
Use a static AutoResetEvent in your spawned threads to call back to the main thread using the Set() method. This guy has a fairly good demo in SO on how to use it.
Unit testing simply verifies that individual units of code (mostly functions) work as expected. Usually you write the test cases yourself, but some can be automatically generated.
The output from a test can be as simple as a console output, to a "green light" in a GUI such as NUnit, or a different language-specific framework.
Performing unit tests is designed to be simple, generally the tests are written in the form of functions that will determine whether a returned value equals the value you were expecting when you wrote the function (or the value you will expect when you eventually write it - this is called Test Driven Development when you write the tests first).
Imagine a very simple function that you would like to test:
int CombineNumbers(int a, int b) {
return a+b;
}
The unit test code would look something like this:
void TestCombineNumbers() {
Assert.IsEqual(CombineNumbers(5, 10), 15); // Assert is an object that is part of your test framework
Assert.IsEqual(CombineNumbers(1000, -100), 900);
}
When you run the tests, you will be informed that these tests have passed. Now that you've built and run the tests, you know that this particular function, or unit, will perform as you expect.
Now imagine another developer comes along and changes the CombineNumbers()
function for performance, or some other reason:
int CombineNumbers(int a, int b) {
return a * b;
}
When the developer runs the tests that you have created for this very simple function, they will see that the first Assert
fails, and they now know that the build is broken.
They should be done as often as possible. When you are performing tests as part of the development process, your code is automatically going to be designed better than if you just wrote the functions and then moved on. Also, concepts such as Dependency Injection are going to evolve naturally into your code.
The most obvious benefit is knowing down the road that when a change is made, no other individual units of code were affected by it if they all pass the tests.
Here's the solution:
<?php
// here's the pattern:
$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*(\/>|>)/';
// a string to parse:
$string = 'Hello, try clicking <a href="#paragraph">here</a>
<br/>and check out.<hr />
<h2>title</h2>
<a name ="paragraph" rel= "I\'m an anchor"></a>
Fine, <span title=\'highlight the "punch"\'>thanks<span>.
<div class = "clear"></div>
<br>';
// let's get the occurrences:
preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER);
// print the result:
print_r($matches[0]);
?>
To test it deeply, I entered in the string auto-closing tags like:
I also entered tags with:
Should you find something which does not work in the proof of concept above, I am available in analyzing the code to improve my skills.
<EDIT> I forgot that the question from the user was to avoid the parsing of self-closing tags. In this case the pattern is simpler, turning into this:
$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*>/';
The user @ridgerunner noticed that the pattern does not allow unquoted attributes or attributes with no value. In this case a fine tuning brings us the following pattern:
$pattern = '/<(\w+)(\s+(\w+)(\s*\=\s*(\'|"|)(.*?)\\5\s*)?)*\s*>/';
</EDIT>
If someone is interested in learning more about the pattern, I provide some line:
Small tip: to better analyze this code it is necessary looking at the source code generated since I did not provide any HTML special characters escaping.
in the below method:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (([array count]*65) > [UIScreen mainScreen].bounds.size.height - 66)
{
Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [array count]*65));
}
else
{
Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [UIScreen mainScreen].bounds.size.height - 66);
}
return [array count];
}
here 65 is the height of the cell and 66 is the height of the navigation bar in UIViewController.
Use this extension and download image faster.
extension UIImageView {
public func imageFromURL(urlString: String) {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
activityIndicator.startAnimating()
if self.image == nil{
self.addSubview(activityIndicator)
}
URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? "No Error")
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
activityIndicator.removeFromSuperview()
self.image = image
})
}).resume()
}
}
This can be done with a simple magic like this:
$(":first-child", element).toggleClass("redClass");
Reference: http://www.snoopcode.com/jquery/jquery-first-child-selector
This worked for me, and produces a list of names:
$Thisfile=(get-childitem -path 10* -include '*.JPG' -recurse).fullname
I found it by using get-member -membertype properties
, an incredibly useful command. most of the options it gives you are appended with a .<thing>
, like fullname
is here. You can stick the same command;
| get-member -membertype properties
at the end of any command to get more information on the things you can do with them and how to access those:
get-childitem -path 10* -include '*.JPG' -recurse | get-member -membertype properties
Complementing the response of @Adrià Cidre
you can do:
status=$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1)
if [[ $status == ok ]] ; then
echo auth ok, do something
elif [[ $status == "Permission denied"* ]] ; then
echo no_auth
else
echo other_error
fi
If you can't get to your php.ini file for some reason, disable errors to stdout (display_errors
) in a .htaccess file in any directory by adding the following line:
php_flag display_errors off
additionally, you can add error logging to a file:
php_flag log_errors on
In the specific case of a Rails action (as opposed to the general case of getting the current method name) you can use params[:action]
Alternatively you might want to look into customising the Rails log format so that the action/method name is included by the format rather than it being in your log message.
If using Python 2.5, you may need to import simplejson
:
try:
import json
except ImportError:
import simplejson as json
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
It's a double-edged sword. It is sometimes very useful, but often dangerous.
When is it good? When you want 10 cases all processed the same way...
switch (c) {
case 1:
case 2:
... Do some of the work ...
/* FALLTHROUGH */
case 17:
... Do something ...
break;
case 5:
case 43:
... Do something else ...
break;
}
The one rule I like is that if you ever do anything fancy where you exclude the break, you need a clear comment /* FALLTHROUGH */ to indicate that was your intention.
<?php
$query = "select username from users";
$res = mysqli_query($connection, $query);
?>
<form>
<select>
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value=" '.$row['id'].' "> '.$row['name'].' </option>';
}
?>
</select>
</form>
Use position: relative on the parent element.
Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.
You can use the following code (For example if one was to want to copy cell data from Sheet2
to Sheet1
).
Sub Copy
Worksheets("Sheet1").Activate
Worksheets("Sheet1").Range(Cells(i, 6), Cells(i, FullPathLastColumn)).Copy_
Destination:=Worksheets("Sheet2").Cells(Path2Row, Path2EndColumn + 1)
End Sub
I noticed there are many answers to this question depending on what you're trying to do, so I'd share mine in case anyone is going for something the same effect:
In my view controller, I have a grouped UITableView
whose tableHeaderView
is composed of a 200-point tall UIScrollView
, and a single attributed UILabel
that contains an ad title, price, location, and time posted. Below it are the contents of the table view.
With the default dimensions of a grouped table view header, the "MORE INFO" header is too far below the "5 days ago" label. I fixed it (already the above image) by overriding the heights for the header and footer of each section.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return section == kMoreInfoSection ? 33 : UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return UITableViewAutomaticDimension;
}
I learned about overriding the heights from @erurainon's comment in the accepted answer, and UITableViewAutomaticDimension
from https://stackoverflow.com/a/14404104/855680. I didn't have to set self.automaticallyAdjustsScrollViewInsets
to NO
in my view controller unlike what the accepted answer suggests.
I also already tried setting the UIEdgeInsets
and giving the table view a negative value for the top, but it didn't work--the entire table view moves up, including the tableHeaderView
.
To make @Raghavendra's answer more specific:
Once you've downloaded 2 zip files,
copy ALL the contents of "win64_11gR2_database_2of2.zip -> Database -> Stage -> Components" folder to "win64_11gR2_database_1of2.zip -> Database -> Stage -> Components" folder.
You'll still get the same warning, however, the installation will run completely without generating any errors.
Have you tried setting JButton.setOpaque(true)?
JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);
You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:
**
operator does exponentiation. a ** b
is a
raised to the b
power. The same **
symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).^
operator does a binary xor. a ^ b
will return a value with only the bits set in a
or in b
but not both. This one is simple!%
operator is mostly to find the modulus of two integers. a % b
returns the remainder after dividing a
by b
. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b
, rather than the same sign as a
. The same operator is also used for the "old" style of string formatting, so a % b
can return a string if a
is a format string and b
is a value (or tuple of values) which can be inserted into a
.//
operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b)
. In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /
). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division
at the top of your files. I strongly recommend it!)You can also try:
{
"dateProp": { $gt: new Date('06/15/2016').getTime() }
}
<asp:GridView ID="GridView1" AutoGenerateEditButton="True"
ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" width="600px">
<Columns>
<asp:BoundField HeaderText="UserId"
DataField="UserId"
SortExpression="UserId" ItemStyle-Width="400px"></asp:BoundField>
</Columns>
</asp:GridView>
On mac OS X Yosemite, after installing it with brew it put it into
/usr/local/opt/openssl/bin/openssl
But kept getting an error "Linking keg-only openssl means you may end up linking against the insecure" when trying to link it
So I just linked it by supplying the full path like so
ln -s /usr/local/opt/openssl/bin/openssl /usr/local/bin/openssl
Now it's showing version OpenSSL 1.0.2o when I do "openssl version -a", I'm assuming it worked
It could be that one or two of your columns may have a factor in them, or what is more likely is that your columns may be formatted as factors. Please would you give str(col1) and str(col2) a try? That should tell you what format those columns are in.
I am unsure if you're trying to add the rows of a column to produce a new column or simply all of the numbers in both columns to get a single number.
Ran into this today and switching to another branch didn't help. It turned out that somehow my worktree information had gotten corrupted and there was a worktree with the same folder path as my working directory with a HEAD
pointing at the branch (git worktree list
). I deleted the .git/worktree/
folder that was referencing it and git branch -d
worked.
On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa
With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '
I was used Total Commander for taking file from Internal storage
Try using an invisible element (or psuedoelement) to force the table-cell to expand.
td:before {
content: '';
display: block;
width: 5em;
}
JSFiddle: https://jsfiddle.net/cibulka/gf45uxr6/1/
As discussed somewhat in the question comments, this is one way you could do it:
<input ... ng-model="$parent.storeDefault" value="{{location.id}}">
The above assumes that each location has a field (e.g., id) that holds a unique value.
Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.
ES6 SOLUTION FOR QUERY STRING ENCODING OF A JAVASCRIPT OBJECT
const params = {
a: 1,
b: 'query stringify',
c: null,
d: undefined,
f: '',
g: { foo: 1, bar: 2 },
h: ['Winterfell', 'Westeros', 'Braavos'],
i: { first: { second: { third: 3 }}}
}
static toQueryString(params = {}, prefix) {
const query = Object.keys(params).map((k) => {
let key = k;
const value = params[key];
if (!value && (value === null || value === undefined || isNaN(value))) {
value = '';
}
switch (params.constructor) {
case Array:
key = `${prefix}[]`;
break;
case Object:
key = (prefix ? `${prefix}[${key}]` : key);
break;
}
if (typeof value === 'object') {
return this.toQueryString(value, key); // for nested objects
}
return `${key}=${encodeURIComponent(value)}`;
});
return query.join('&');
}
toQueryString(params)
"a=1&b=query%20stringify&c=&d=&f=&g[foo]=1&g[bar]=2&h[]=Winterfell&h[]=Westeros&h[]=Braavos&i[first][second][third]=3"
you can use both CSS class or HTML id, for keeping it symmetric I always use CSS class for example
<a class="btn btn-full js--scroll-to-plans" href="#">I’m hungry</a>
|
|
|
<section class="section-plans js--section-plans clearfix">
$(document).ready(function () {
$('.js--scroll-to-plans').click(function () {
$('body,html').animate({
scrollTop: $('.js--section-plans').offset().top
}, 1000);
return false;})
});
A side from the very long complete accepted answer there is an important point to make about IndexOutOfRangeException
compared with many other exception types, and that is:
Often there is complex program state that maybe difficult to have control over at a particular point in code e.g a DB connection goes down so data for an input cannot be retrieved etc... This kind of issue often results in an Exception of some kind that has to bubble up to a higher level because where it occurs has no way of dealing with it at that point.
IndexOutOfRangeException
is generally different in that it in most cases it is pretty trivial to check for at the point where the exception is being raised. Generally this kind of exception get thrown by some code that could very easily deal with the issue at the place it is occurring - just by checking the actual length of the array. You don't want to 'fix' this by handling this exception higher up - but instead by ensuring its not thrown in the first instance - which in most cases is easy to do by checking the array length.
Another way of putting this is that other exceptions can arise due to genuine lack of control over input or program state BUT IndexOutOfRangeException
more often than not is simply just pilot (programmer) error.
None is a special value in Python which usually designates an uninitialized variable. To test whether A does not have this particular value you use:
if A is not None
Falsey values are a special class of objects in Python (e.g. false, []). To test whether A is falsey use:
if not A
Thus, the two expressions are not the same And you'd better not treat them as synonyms.
P.S. None is also falsey, so the first expression implies the second. But the second covers other falsey values besides None. Now... if you can be sure that you can't have other falsey values besides None in A, then you can replace the first expression with the second.
the solution was simple -
toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
Copying by using a for loop:
orig = {"X2": 674.5, "X3": 245.0}
copy = {}
for key in orig:
copy[key] = orig[key]
print(orig) # {'X2': 674.5, 'X3': 245.0}
print(copy) # {'X2': 674.5, 'X3': 245.0}
copy["X2"] = 808
print(orig) # {'X2': 674.5, 'X3': 245.0}
print(copy) # {'X2': 808, 'X3': 245.0}
One of these should work:
import math
math.trunc(1.5)
> 1
math.trunc(-1.5)
> -1
math.floor(1.5)
> 1
math.floor(-1.5)
> -2
From the Java Language Specification, section 15.9.5.1:
An anonymous class cannot have an explicitly declared constructor.
Sorry :(
EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:
public class Test {
public static void main(String[] args) throws Exception {
final int fakeConstructorArg = 10;
Object a = new Object() {
{
System.out.println("arg = " + fakeConstructorArg);
}
};
}
}
It's grotty, but it might just help you. Alternatively, use a proper nested class :)
Your code works just fine. It's most likely the window thats not focused. I use a similar function to close iframe boxes etc.
$(document).ready(function(){
// Set focus
setTimeout('window.focus()',1000);
});
$(document).keypress(function(e) {
// Enable esc
if (e.keyCode == 27) {
parent.document.getElementById('iframediv').style.display='none';
parent.document.getElementById('iframe').src='/views/view.empty.black.html';
}
});
A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.
int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);
@wdavo is correct. The same is also true for functions.
If you override a base function, like Update, then in your subclass you need:
new void Update()
{
//do stufff
}
Without the new at the start of the function decleration you will get the warning flag.
echo 5a | python -c "import sys; print chr(int(sys.stdin.read(),base=16))"
Be sure to have both objects created in controller: @post
and @comment
for the post, eg:
@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)
Then in view:
<%= form_for([@post, @comment]) do |f| %>
Be sure to explicitly define the array in the form_for, not just comma separated like you have above.
In my experience, this example has been the best solution for uploading a resized picture: https://zocada.com/compress-resize-images-javascript-browser/
It uses the HTML5 Canvas feature.
The code is as 'simple' as this:
compress(e) {
const fileName = e.target.files[0].name;
const reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = event => {
const img = new Image();
img.src = event.target.result;
img.onload = () => {
const elem = document.createElement('canvas');
const width = Math.min(800, img.width);
const scaleFactor = width / img.width;
elem.width = width;
elem.height = img.height * scaleFactor;
const ctx = elem.getContext('2d');
// img.width and img.height will contain the original dimensions
ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);
ctx.canvas.toBlob((blob) => {
const file = new File([blob], fileName, {
type: 'image/jpeg',
lastModified: Date.now()
});
}, 'image/jpeg', 1);
},
reader.onerror = error => console.log(error);
};
}
There are two downsides with this solution.
The first one is related with the image rotation, due to ignoring EXIF data. I couldn't tackle this issue, and wasn't so important in my use case, but will be glad to hear any feedback.
The second downside is the lack of support foe IE/Edge (not the Chrome based version though), and I won't put any time on that.
Expression: "Total Count: " + (DT_WSTR, 5)@[User::Cnt]
It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.
wrapper div{
image wrapper div{
div for individual image{ <--- Fixed position
image <--- relative position
}
}
quote wrapper div{
div for individual quote{
quote
}
}
}
you can use bc
as it can also do floats
var=$(echo "1+2"|bc)
Set events after loading DOM Elements.
$(function () {
$(document).on("click","selector",function (e) {
alert("hi");
});
});
You can use format strings as well.
string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros
or some shortcuts if the format works for you
string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();
Either should work.
You can get a really nice, visual output of how your branches differ with this
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative master..branch-X
Start writing, then just press CTRL+SPACE and there you go ...
Follow these simple steps :
1: In the Rmarkdown script run Knit(Ctrl+Shift+K) 2: Then after the html markdown is opened click Open in Browser(top left side) and the html is opened in your web browser 3: Then use Ctrl+P and save as PDF .
if you write Component as React.FC, and using useState(),
just write like this would be helpful:
const [arr, setArr] = useState<any[]>([])
It's 2012, the post-PC era is here, and we still have to struggle with something as basic as this. This ought to be very simple.
Until such time as that dream is fulfilled, here's the best way to do this, cross-browser: use a combination of the input
and onpropertychange
events, like so:
var area = container.querySelector('textarea');
if (area.addEventListener) {
area.addEventListener('input', function() {
// event handling code for sane browsers
}, false);
} else if (area.attachEvent) {
area.attachEvent('onpropertychange', function() {
// IE-specific event handling code
});
}
The input
event takes care of IE9+, FF, Chrome, Opera and Safari, and onpropertychange
takes care of IE8 (it also works with IE6 and 7, but there are some bugs).
The advantage of using input
and onpropertychange
is that they don't fire unnecessarily (like when pressing the Ctrl
or Shift
keys); so if you wish to run a relatively expensive operation when the textarea contents change, this is the way to go.
Now IE, as always, does a half-assed job of supporting this: neither input
nor onpropertychange
fires in IE when characters are deleted from the textarea. So if you need to handle deletion of characters in IE, use keypress
(as opposed to using keyup
/ keydown
, because they fire only once even if the user presses and holds a key down).
Source: http://www.alistapart.com/articles/expanding-text-areas-made-elegant/
EDIT: It seems even the above solution is not perfect, as rightly pointed out in the comments: the presence of the addEventListener
property on the textarea does not imply you're working with a sane browser; similarly the presence of the attachEvent
property does not imply IE. If you want your code to be really air-tight, you should consider changing that. See Tim Down's comment for pointers.
Thread.sleep() could work in most cases, but usually if you're waiting, you are actually waiting for a particular condition or state to occur. Thread.sleep() does not guarantee that whatever you're waiting for has actually happened.
If you are waiting on a rest request for example maybe it usually return in 5 seconds, but if you set your sleep for 5 seconds the day your request comes back in 10 seconds your test is going to fail.
To remedy this JayWay has a great utility called Awatility which is perfect for ensuring that a specific condition occurs before you move on.
It has a nice fluent api as well
await().until(() ->
{
return yourConditionIsMet();
});
HTML 5 video does go fullscreen in the latest nightly build of Safari, though I'm not sure how it is technically accomplished.
To easily apply the comm command to unsorted files, use Bash's process substitution:
$ bash --version
GNU bash, version 3.2.51(1)-release
Copyright (C) 2007 Free Software Foundation, Inc.
$ cat > abc
123
567
132
$ cat > def
132
777
321
So the files abc and def have one line in common, the one with "132". Using comm on unsorted files:
$ comm abc def
123
132
567
132
777
321
$ comm -12 abc def # No output! The common line is not found
$
The last line produced no output, the common line was not discovered.
Now use comm on sorted files, sorting the files with process substitution:
$ comm <( sort abc ) <( sort def )
123
132
321
567
777
$ comm -12 <( sort abc ) <( sort def )
132
Now we got the 132 line!
With minor corrections:
function rearrange()
{
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("foobar").style.height = (windowHeight - document.getElementById("foobar").offsetTop - 6)+ "px";
}
You could import the 'os' module and use it like this :
import os
os.system('#DesiredAction')
I had this problem, and turns out the problem was that I had used
new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("foo")
instead of
new SimpleJdbcCall(jdbcTemplate)
.withFunctionName("foo")
Java is faster than Python. Easily.
Python is favorable for many things; speed isn't necessarily one of them.
the best way for me :
$data=[
'var1'=>'something',
'var2'=>'something',
'var3'=>'something',
];
return View::make('view',$data);
It seems to me you are using the wrong version...
TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!
From what I gather, Matz does not like the construct
begin
<multiple_lines_of_code>
end while <cond>
because, it's semantics is different than
<single_line_of_code> while <cond>
in that the first construct executes the code first before checking the condition, and the second construct tests the condition first before it executes the code (if ever). I take it Matz prefers to keep the second construct because it matches one line construct of if statements.
I never liked the second construct even for if statements. In all other cases, the computer executes code left-to-right (eg. || and &&) top-to-bottom. Humans read code left-to-right top-to-bottom.
I suggest the following constructs instead:
if <cond> then <one_line_code> # matches case-when-then statement
while <cond> then <one_line_code>
<one_line_code> while <cond>
begin <multiple_line_code> end while <cond> # or something similar but left-to-right
I don't know if those suggestions will parse with the rest of the language. But in any case I prefere keeping left-to-right execution as well as language consistency.
Here you go.
SELECT
column1,
column2
FROM
viewWhatever
WHERE
CASE
WHEN @locationType = 'location' AND account_location = @locationID THEN 1
WHEN @locationType = 'area' AND xxx_location_area = @locationID THEN 1
WHEN @locationType = 'division' AND xxx_location_division = @locationID THEN 1
ELSE 0
END = 1
For me it was that my styled-components were defined after my functional component definition. It was only happening in staging and not locally for me. Once I moved my styled-components above my component definition the error went away.
The SAMPLE clause will give you a random sample percentage of all rows in a table.
For example, here we obtain 25% of the rows:
SELECT * FROM emp SAMPLE(25)
The following SQL (using one of the analytical functions) will give you a random sample of a specific number of each occurrence of a particular value (similar to a GROUP BY) in a table.
Here we sample 10 of each:
SELECT * FROM (
SELECT job, sal, ROW_NUMBER()
OVER (
PARTITION BY job ORDER BY job
) SampleCount FROM emp
)
WHERE SampleCount <= 10
I wanted to encrypt and decrypt the string as a readable string.
Here is a very simple quick example in C# Visual Studio 2019 WinForms based on the answer from @Pradip
.
Right click project > properties > settings > Create a username
and password
setting.
Now you can leverage those settings you just created. Here I save the username
and password
but only encrypt the password
in it's respectable value field in the user.config
file.
Example of the encrypted string in the user.config
file.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<secure_password_store.Properties.Settings>
<setting name="username" serializeAs="String">
<value>admin</value>
</setting>
<setting name="password" serializeAs="String">
<value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQpgaPYIUq064U3o6xXkQOQAAAAACAAAAAAAQZgAAAAEAACAAAABlQQ8OcONYBr9qUhH7NeKF8bZB6uCJa5uKhk97NdH93AAAAAAOgAAAAAIAACAAAAC7yQicDYV5DiNp0fHXVEDZ7IhOXOrsRUbcY0ziYYTlKSAAAACVDQ+ICHWooDDaUywJeUOV9sRg5c8q6/vizdq8WtPVbkAAAADciZskoSw3g6N9EpX/8FOv+FeExZFxsm03i8vYdDHUVmJvX33K03rqiYF2qzpYCaldQnRxFH9wH2ZEHeSRPeiG</value>
</setting>
</secure_password_store.Properties.Settings>
</userSettings>
</configuration>
Full Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace secure_password_store
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Exit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Login_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
Properties.Settings.Default.username = textBox1.Text;
Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
Properties.Settings.Default.Save();
}
else if (checkBox1.Checked == false)
{
Properties.Settings.Default.username = "";
Properties.Settings.Default.password = "";
Properties.Settings.Default.Save();
}
MessageBox.Show("{\"data\": \"some data\"}","Login Message Alert",MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void DecryptString_Click(object sender, EventArgs e)
{
SecureString password = DecryptString(Properties.Settings.Default.password);
string readable = ToInsecureString(password);
textBox4.AppendText(readable + Environment.NewLine);
}
private void Form_Load(object sender, EventArgs e)
{
//textBox1.Text = "UserName";
//textBox2.Text = "Password";
if (Properties.Settings.Default.username != string.Empty)
{
textBox1.Text = Properties.Settings.Default.username;
checkBox1.Checked = true;
SecureString password = DecryptString(Properties.Settings.Default.password);
string readable = ToInsecureString(password);
textBox2.Text = readable;
}
groupBox1.Select();
}
static byte[] entropy = Encoding.Unicode.GetBytes("SaLtY bOy 6970 ePiC");
public static string EncryptString(SecureString input)
{
byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),entropy,DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
public static SecureString DecryptString(string encryptedData)
{
try
{
byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData),entropy,DataProtectionScope.CurrentUser);
return ToSecureString(Encoding.Unicode.GetString(decryptedData));
}
catch
{
return new SecureString();
}
}
public static SecureString ToSecureString(string input)
{
SecureString secure = new SecureString();
foreach (char c in input)
{
secure.AppendChar(c);
}
secure.MakeReadOnly();
return secure;
}
public static string ToInsecureString(SecureString input)
{
string returnValue = string.Empty;
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
try
{
returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
}
return returnValue;
}
private void EncryptString_Click(object sender, EventArgs e)
{
Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
textBox3.AppendText(Properties.Settings.Default.password.ToString() + Environment.NewLine);
}
}
}
The best thing about C# is that it is very catchy. Easy to pick up, and you'll also have fun doing it.
But .Net framework is a very big library full of wonderful things to discover, and yet again due to the nature of .Net you'll also have fun learning it. It's a coherent, object oriented, well documented library, and C# makes it so simple to work with it that you can simply discover your way through it while coding.
The vast majority of articles, books or resources about .Net and C# simply concentrate on explaining functionality and the framework and far less about how to avoid quirks, workarounds or exceptional cases, like it happens with other languages I don't want to name (*cough C++*) so in the end the experience of learning C# and .Net is very enjoyable from start to finish, and the things you can accomplish using .Net also makes it very rewarding.
You picked a good language to start with, in my opinion, and finally to answer your question, it will take you about:
But then again, beating the numbers and breaking the limits lies inside human nature. Can you do it faster than this? ;-)
$('input:radio[name="postage"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'Yes') {
// append goes here
}
});
Or, the above - again - using a little less superfluous jQuery:
$('input:radio[name="postage"]').change(
function(){
if (this.checked && this.value == 'Yes') {
// note that, as per comments, the 'changed'
// <input> will *always* be checked, as the change
// event only fires on checking an <input>, not
// on un-checking it.
// append goes here
}
});
Revised (improved-some) jQuery:
// defines a div element with the text "You're appendin'!"
// assigns that div to the variable 'appended'
var appended = $('<div />').text("You're appendin'!");
// assigns the 'id' of "appended" to the 'appended' element
appended.id = 'appended';
// 1. selects '<input type="radio" />' elements with the 'name' attribute of 'postage'
// 2. assigns the onChange/onchange event handler
$('input:radio[name="postage"]').change(
function(){
// checks that the clicked radio button is the one of value 'Yes'
// the value of the element is the one that's checked (as noted by @shef in comments)
if ($(this).val() == 'Yes') {
// appends the 'appended' element to the 'body' tag
$(appended).appendTo('body');
}
else {
// if it's the 'No' button removes the 'appended' element.
$(appended).remove();
}
});
var appended = $('<div />').text("You're appendin'!");_x000D_
appended.id = 'appended';_x000D_
$('input:radio[name="postage"]').change(function() {_x000D_
if ($(this).val() == 'Yes') {_x000D_
$(appended).appendTo('body');_x000D_
} else {_x000D_
$(appended).remove();_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
<input type="radio" id="postageyes" name="postage" value="Yes" />Yes_x000D_
<input type="radio" id="postageno" name="postage" value="No" />No
_x000D_
And, further, a mild update (since I was editing to include Snippets as well as the JS Fiddle links), in order to wrap the <input />
elements with <label>
s - allow for clicking the text to update the relevant <input />
- and changing the means of creating the content to append:
var appended = $('<div />', {_x000D_
'id': 'appended',_x000D_
'text': 'Appended content'_x000D_
});_x000D_
$('input:radio[name="postage"]').change(function() {_x000D_
if ($(this).val() == 'Yes') {_x000D_
$(appended).appendTo('body');_x000D_
} else {_x000D_
$(appended).remove();_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>_x000D_
<input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label>_x000D_
<label>_x000D_
<input type="radio" id="postageno" name="postage" value="No" />No</label>
_x000D_
Also, if you only need to show content depending on which element is checked by the user, a slight update that will toggle visibility using an explicit show/hide:
// caching a reference to the dependant/conditional content:_x000D_
var conditionalContent = $('#conditional'),_x000D_
// caching a reference to the group of inputs, since we're using that_x000D_
// same group twice:_x000D_
group = $('input[type=radio][name=postage]');_x000D_
_x000D_
// binding the change event-handler:_x000D_
group.change(function() {_x000D_
// toggling the visibility of the conditionalContent, which will_x000D_
// be shown if the assessment returns true and hidden otherwise:_x000D_
conditionalContent.toggle(group.filter(':checked').val() === 'Yes');_x000D_
// triggering the change event on the group, to appropriately show/hide_x000D_
// the conditionalContent on page-load/DOM-ready:_x000D_
}).change();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>_x000D_
<input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label>_x000D_
<label>_x000D_
<input type="radio" id="postageno" name="postage" value="No" />No</label>_x000D_
<div id="conditional">_x000D_
<p>This should only show when the 'Yes' radio <input> element is checked.</p>_x000D_
</div>
_x000D_
And, finally, using just CSS:
/* setting the default of the conditionally-displayed content_x000D_
to hidden: */_x000D_
#conditional {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
/* if the #postageyes element is checked then the general sibling of_x000D_
that element, with the id of 'conditional', will be shown: */_x000D_
#postageyes:checked ~ #conditional {_x000D_
display: block;_x000D_
}
_x000D_
<!-- note that the <input> elements are now not wrapped in the <label> elements,_x000D_
in order that the #conditional element is a (subsequent) sibling of the radio_x000D_
<input> elements: -->_x000D_
<input type="radio" id="postageyes" name="postage" value="Yes" />_x000D_
<label for="postageyes">Yes</label>_x000D_
<input type="radio" id="postageno" name="postage" value="No" />_x000D_
<label for="postageno">No</label>_x000D_
<div id="conditional">_x000D_
<p>This should only show when the 'Yes' radio <input> element is checked.</p>_x000D_
</div>
_x000D_
References:
:checked
selector.~
) combinator.R only automatically prints the output of unassigned expressions, so just assign the result of the apply
to a variable, and it won't get printed.
MyModel.objects.get(pk=1).delete()
this will raise exception if the object with specified primary key doesn't exist because at first it tries to retrieve the specified object.
MyModel.objects.filter(pk=1).delete()
this wont raise exception if the object with specified primary key doesn't exist and it directly produces the query
DELETE FROM my_models where id=1
Object AccountObject = _dbContext.Accounts
.Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
.Where(x => x.usr.EmailAddress == key1)
.Where(x => x.usr.Hash == key2)
.Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
.SingleOrDefault();
sudo chown -R $(whoami) /usr/local
would do just fine as mentioned in the brew site troubleshooting
As a side-note...this can also happen when there is a problem with (internal) data-mapping from SQL Objects.
For instance...
I created a SQL Scalar Function
that accidentally returned a VARCHAR
...and then...used it to generate a column in a VIEW
. The VIEW
was correctly mapped in the DbContext
...so Linq was calling it just fine. However, the Entity expected DateTime? and the VIEW
was returning String.
Which ODDLY throws...
"There is already an open DataReader associated with this Command which must be closed first"
It was hard to figure out...but after I corrected the return parameters...all was well
Here is a fast vectorized version of @Dimitri's solution if you have many values
to search for (values
can be multi-dimensional array):
#`values` should be sorted
def get_closest(array, values):
#make sure array is a numpy array
array = np.array(array)
# get insert positions
idxs = np.searchsorted(array, values, side="left")
# find indexes where previous index is closer
prev_idx_is_less = ((idxs == len(array))|(np.fabs(values - array[np.maximum(idxs-1, 0)]) < np.fabs(values - array[np.minimum(idxs, len(array)-1)])))
idxs[prev_idx_is_less] -= 1
return array[idxs]
Benchmarks
> 100 times faster than using a for
loop with @Demitri's solution`
>>> %timeit ar=get_closest(np.linspace(1, 1000, 100), np.random.randint(0, 1050, (1000, 1000)))
139 ms ± 4.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> %timeit ar=[find_nearest(np.linspace(1, 1000, 100), value) for value in np.random.randint(0, 1050, 1000*1000)]
took 21.4 seconds
// Convert millis to seconds. This can be simplified a bit,
// but I left it in this form for clarity.
long m = System.currentTimeMillis(); // that's our input
int s = Math.max(
.18 * (Math.toRadians(m)/Math.PI),
Math.pow( Math.E, Math.log(m)-Math.log(1000) )
);
System.out.println( "seconds: "+s );
Here is how I do. Much easier than alot of the answers here IMO:
Create this SortDirection class
// ==================================================
// SortByDirection
// ==================================================
public SortDirection SortByDirection
{
get
{
if (ViewState["SortByDirection"] == null)
{
ViewState["SortByDirection"] = SortDirection.Ascending;
}
return (SortDirection)Enum.Parse(typeof(SortDirection), ViewState["SortByDirection"].ToString());
}
set { ViewState["SortByDirection"] = value; }
}
And then use it in your sort function like this:
// Created Date
if (sortBy == "CreatedDate")
{
if (SortByDirection == SortDirection.Ascending)
{
data = data.OrderBy(x => x.CreatedDate).ToList();
SortByDirection = SortDirection.Descending;
}
else {
data = data.OrderByDescending(x => x.CreatedDate).ToList();
SortByDirection = SortDirection.Ascending;
}
}
The order in which ng-click
and ng-model
will be executed is ambiguous (since neither explicitly set their priority
). The most stable solution to this would be to avoid using them on the same element.
Also, you probably do not want the behavior that the examples show; you want the checkbox
to respond to clicks on the complete label text, not only the checkbox. Hence, the cleanest solution would be to wrap the input
(with ng-model
) inside a label
(with ng-click
):
<label ng-click="onCompleteTodo(todo)">
<input type='checkbox' ng-model="todo.done">
{{todo.text}}
</label>
Working example: http://jsfiddle.net/b3NLH/1/
How do I delete a file or folder in Python?
For Python 3, to remove the file and directory individually, use the unlink
and rmdir
Path
object methods respectively:
from pathlib import Path
dir_path = Path.home() / 'directory'
file_path = dir_path / 'file'
file_path.unlink() # remove file
dir_path.rmdir() # remove directory
Note that you can also use relative paths with Path
objects, and you can check your current working directory with Path.cwd
.
For removing individual files and directories in Python 2, see the section so labeled below.
To remove a directory with contents, use shutil.rmtree
, and note that this is available in Python 2 and 3:
from shutil import rmtree
rmtree(dir_path)
New in Python 3.4 is the Path
object.
Let's use one to create a directory and file to demonstrate usage. Note that we use the /
to join the parts of the path, this works around issues between operating systems and issues from using backslashes on Windows (where you'd need to either double up your backslashes like \\
or use raw strings, like r"foo\bar"
):
from pathlib import Path
# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()
file_path = directory_path / 'file'
file_path.touch()
and now:
>>> file_path.is_file()
True
Now let's delete them. First the file:
>>> file_path.unlink() # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
We can use globbing to remove multiple files - first let's create a few files for this:
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
Then just iterate over the glob pattern:
>>> for each_file_path in directory_path.glob('*.my'):
... print(f'removing {each_file_path}')
... each_file_path.unlink()
...
removing ~/directory/foo.my
removing ~/directory/bar.my
Now, demonstrating removing the directory:
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
What if we want to remove a directory and everything in it?
For this use-case, use shutil.rmtree
Let's recreate our directory and file:
file_path.parent.mkdir()
file_path.touch()
and note that rmdir
fails unless it's empty, which is why rmtree is so convenient:
>>> directory_path.rmdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
self._accessor.rmdir(self)
File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/username/directory'
Now, import rmtree and pass the directory to the funtion:
from shutil import rmtree
rmtree(directory_path) # remove everything
and we can see the whole thing has been removed:
>>> directory_path.exists()
False
If you're on Python 2, there's a backport of the pathlib module called pathlib2, which can be installed with pip:
$ pip install pathlib2
And then you can alias the library to pathlib
import pathlib2 as pathlib
Or just directly import the Path
object (as demonstrated here):
from pathlib2 import Path
If that's too much, you can remove files with os.remove
or os.unlink
from os import unlink, remove
from os.path import join, expanduser
remove(join(expanduser('~'), 'directory/file'))
or
unlink(join(expanduser('~'), 'directory/file'))
and you can remove directories with os.rmdir
:
from os import rmdir
rmdir(join(expanduser('~'), 'directory'))
Note that there is also a os.removedirs
- it only removes empty directories recursively, but it may suit your use-case.
I have to add to Collin Andersons answer that this method also takes into account if you have two interfaces and they're both showing as up.
ip route get 1 | awk '{print $NF;exit}'
I have been working on an application with Raspberry Pi's and needed the IP address that was actually being used not just whether it was up or not. Most of the other answers will return both IP address which isn't necessarily helpful - for my scenario anyway.
Pete Goodliffe has a series on the unit testing of threaded code.
It's hard. I take the easier way out and try to keep the threading code abstracted from the actual test. Pete does mention that the way I do it is wrong but I've either got the separation right or I've just been lucky.
IIRC they suggest using the preg_
functions instead (in this case, preg_replace
).
As I parse it, those words are wrong. It should read "If the function modifies that value, the modifications appear also within the scope of the calling function when passing by reference, but not when passing by value."
If you don't mind using jQuery you can use the code bellow:
<script>
$(document).ready(function(){
$("#department").val("${requestScope.selectedDepartment}").attr('selected', 'selected');
});
</script>
<select id="department" name="department">
<c:forEach var="item" items="${dept}">
<option value="${item.key}">${item.value}</option>
</c:forEach>
</select>
In the your Servlet add the following:
request.setAttribute("selectedDepartment", YOUR_SELECTED_DEPARTMENT );
I know this is a wicked old post with a whole lot of answers but a lot of people think that they NEED to either break things apart and put them back together or they insist that there's no way to implicitly do the conversion the OP original asked for.
To review and to hopefully provide an easy answer to others with the same question, the OP asked how to convert '10/15/2008 10:06:32 PM' to a DATETIME. Now, SQL Server does have some language dependencies for temporal conversions but if the language is english or something similar, this becomes a simple problem... just do the conversion and don't worry about the format. For example (and you can use CONVERT or CAST)...
SELECT UsingCONVERT = CONVERT(DATETIME,'10/15/2008 10:06:32 PM')
,UsingCAST = CAST('10/15/2008 10:06:32 PM' AS DATETIME)
;
... and that produces the follow answers, both of which are correct.
Like they say on the TV commercials, "But wait! Don't order yet! For no extra cost, it can do MUCH more!"
Let's see the real power of temporal conversions with the DATETIME and partially examine the mistake known as DATETIME2. Check out the whacky formats that DATETIME can handle auto-magically and that DATETIME2 cannot. Run the following code and see...
--===== Set the language for this example.
SET LANGUAGE ENGLISH --Same a US-English
;
--===== Use a table constructor as if it were a table for this example.
SELECT *
,DateTimeCONVERT = TRY_CONVERT(DATETIME,StringDT)
,DateTimeCAST = TRY_CAST(StringDT AS DATETIME)
,DateTime2CONVERT = TRY_CONVERT(DATETIME2,StringDT)
,DateTime2CAST = TRY_CAST(StringDT AS DATETIME2)
FROM (
VALUES
('Same Format As In The OP' ,'12/16/2001 01:51:01 PM')
,('Almost Normal' ,'16 December, 2001 1:51:01 PM')
,('More Normal' ,'December 16, 2001 01:51:01 PM')
,('Time Up Front + Spaces' ,' 13:51:01 16 December 2001')
,('Totally Whacky Format #01' ,' 16 13:51:01 December 2001')
,('Totally Whacky Format #02' ,' 16 December 13:51:01 2001 ')
,('Totally Whacky Format #03' ,' 16 December 01:51:01 PM 2001 ')
,('Totally Whacky Format #04' ,' 2001 16 December 01:51:01 PM ')
,('Totally Whacky Format #05' ,' 2001 December 01:51:01 PM 16 ')
,('Totally Whacky Format #06' ,' 2001 16 December 01:51:01 PM ')
,('Totally Whacky Format #07' ,' 2001 16 December 13:51:01 PM ')
,('Totally Whacky Format #08' ,' 2001 16 13:51:01 PM December ')
,('Totally Whacky Format #09' ,' 13:51:01 PM 2001.12/16 ')
,('Totally Whacky Format #10' ,' 13:51:01 PM 2001.December/16 ')
,('Totally Whacky Format #11' ,' 13:51:01 PM 2001.Dec/16 ')
,('Totally Whacky Format #12' ,' 13:51:01 PM 2001.Dec.16 ')
,('Totally Whacky Format #13' ,' 13:51:01 PM 2001/Dec.16')
,('Totally Whacky Format #14' ,' 13:51:01 PM 2001 . 12/16 ')
,('Totally Whacky Format #15' ,' 13:51:01 PM 2001 . December / 16 ')
,('Totally Whacky Format #16' ,' 13:51:01 PM 2001 . Dec / 16 ')
,('Totally Whacky Format #17' ,' 13:51:01 PM 2001 . Dec . 16 ')
,('Totally Whacky Format #18' ,' 13:51:01 PM 2001 / Dec . 16')
,('Totally Whacky Format #19' ,' 13:51:01 PM 2001 . Dec - 16 ')
,('Totally Whacky Format #20' ,' 13:51:01 PM 2001 - Dec - 16 ')
,('Totally Whacky Format #21' ,' 13:51:01 PM 2001 - Dec . 16')
,('Totally Whacky Format #22' ,' 13:51:01 PM 2001 - Dec / 16 ')
,('Totally Whacky Format #23' ,' 13:51:01 PM 2001 / Dec - 16')
,('Just the year' ,' 2001 ')
,('YYYYMM' ,' 200112 ')
,('YYYY MMM' ,'2001 Dec')
,('YYYY-MMM' ,'2001-Dec')
,('YYYY . MMM' ,'2001 . Dec')
,('YYYY / MMM' ,'2001 / Dec')
,('YYYY - MMM' ,'2001 / Dec')
,('Forgot The Spaces #1' ,'2001December26')
,('Forgot The Spaces #2' ,'2001Dec26')
,('Forgot The Spaces #3' ,'26December2001')
,('Forgot The Spaces #4' ,'26Dec2001')
,('Forgot The Spaces #5' ,'26Dec2001 13:51:01')
,('Forgot The Spaces #6' ,'26Dec2001 13:51:01PM')
,('Oddly, this doesn''t work' ,'2001-12')
,('Oddly, this doesn''t work' ,'12-2001')
) v (Description,StringDT)
;
So, yeah... SQL Server DOES actually have a pretty flexible method of handling all sorts of weird-o temporal formats and no special handling is required. We didn't even need to remove the "PM"s that were added to the 24 hour times. It's "PFM" (Pure Freakin' Magic).
Things will vary a bit depending on the the LANGUAGE is that you've selected for your server but a whole lot of it will be handled either way.
And these "auto-magic" conversions aren't something new. They go a real long way back.
JMeter would be one such tool. Can be a bit hard to learn and configure, but it's usually worth it.
Sometimes df.name
doesn't work.
you might get an error message:
'DataFrame' object has no attribute 'name'
try the below function:
def get_df_name(df):
name =[x for x in globals() if globals()[x] is df][0]
return name
Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.
In the case of local variables you can not use any kind of accessor (public, protected or private).
You should also know what the static keyword means. In method checkYourself
, you use the Integer array locations
.
The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.
public class Test { //Capitalized name for classes are used in Java
private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later.
public Test(int[] locations) {
this.locations = locations;//To access to class member, when method argument has the same name use `this` key word.
}
public boolean checkYourSelf(int value) { //This method is accessed only from a object.
for(int location : locations) {
if(location == value) {
return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
}
}
return false; //Method should be simple and perform one task. So you can get more flexibility.
}
public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it.
public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.
String result;
if(test.checkYourSelf(2)) {//We moved outside the string
result = "Hurray";
} else {
result = "Try again"
}
System.out.println(result); //We have only one place where write is done. Easy to change in future.
}
}
Something like this:
DataTable dt = new DataTable();
// For each row, print the values of each column.
foreach(DataRow row in dt .Rows)
{
foreach(DataColumn column in dt .Columns)
{
Console.WriteLine(row[column]);
}
}
http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx
There are also the rows
and cells
members;
var t = document.getElementById("tbl");
for (var r = 0; r < t.rows.length; r++) {
for (var c = 0; c < t.rows[r].cells.length; c++) {
alert(t.rows[r].cells[c].innerHTML)
}
}
That's a lot of questions.
Why EOF
is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"
any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF
is 0
when it's FALSE, meaning getchar()
returned EOF
.
in order to emulate EOF
when reading from stdin
press Ctrl+D
You should remove them from the <select>
using JavaScript. That is the only guaranteed way to make them go away.
Implicit wait --
Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. So in this case, you are telling WebDriver that it should wait 10 seconds in cases of specified element not available on the UI (DOM).
Explicit wait--
Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling WebDriver at the max it is to wait for X units of time before it gives up.
[checked 27 Nov 2020 and confirmed to be still accurate with Xcode 12.1]
The most convenient way these days: Xcode provides a code snippet to do this where you just have to enter the delay value and the code you wish to run after the delay.
+
button at the top right of Xcode.after
Let's say you have installed the package 'django'. import it and type in dir(django). It will show you, all the functions and attributes with that module. Type in the python interpreter -
>>> import django
>>> dir(django)
['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']
>>> print django.__path__
['/Library/Python/2.6/site-packages/django']
You can do the same thing if you have installed mercurial.
This is for Snow Leopard. But I think it should work in general as well.
The default date format depends on the language setting for the database server. You can also change it per session, like:
set language french
select cast(getdate() as varchar(50))
-->
févr 8 2013 9:45AM
Try /*string with {}*/ string.trim().equalsIgnoreCase("{}"))
, maybe there is some extra spaces or something
try this code in here...this is done using javascript onKeyUp() function...
<script>
function toCount(entrance,exit,text,characters) {
var entranceObj=document.getElementById(entrance);
var exitObj=document.getElementById(exit);
var length=characters - entranceObj.value.length;
if(length <= 0) {
length=0;
text='<span class="disable"> '+text+' <\/span>';
entranceObj.value=entranceObj.value.substr(0,characters);
}
exitObj.innerHTML = text.replace("{CHAR}",length);
}
</script>
If you are worrying about Case sensitive change the case and compare the string.
if (stringvalue.toLocaleLowerCase().indexOf("mytexttocompare")!=-1)
{
alert("found");
}
You need to link with the math library:
gcc -o sphere sphere.c -lm
The error you are seeing: error: ld returned 1 exit status
is from the linker ld
(part of gcc that combines the object files) because it is unable to find where the function pow
is defined.
Including math.h
brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a
. You need to link your program with this library so that the calls to functions like pow() are resolved.
plot.new() error occurs when only part of the function is ran.
Please find the attachment for an example to correct error With error....When abline is ran without plot() above Error-free ...When both plot and abline ran together
This is a common function of Adorners in WPF. Adorners typically appear above all other controls, but the other answers that mention z-order may fit your case better.
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
s = s.Date.AddHours(x).AddMinutes(y).AddSeconds(z);
In this way you preserve your date, while inserting a new hours, minutes and seconds part to your liking.
var cubes = [["string", "string"], ["string", "string"]];
for(var i = 0; i < cubes.length; i++) {
for(var j = 0; j < cubes[i].length; j++) {
console.log(cubes[i][j]);
}
}
Here are the docs about the "new" format syntax. An example would be:
"({:d} goals, ${:d})".format(self.goals, self.penalties)
If both goals
and penalties
are integers (i.e. their default format is ok), it could be shortened to:
"({} goals, ${})".format(self.goals, self.penalties)
And since the parameters are fields of self
, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):
"({0.goals} goals, ${0.penalties})".format(self)
Explaining:
{}
means just the next positional argument, with default format;{0}
means the argument with index 0
, with default format;{:d}
is the next positional argument, with decimal integer format;{0:d}
is the argument with index 0
, with decimal integer format.There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:
"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)
"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)
"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'
"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'
"games: {:>3}".format(player1.games) # 'games: 123'
"games: {:>3}".format(player2.games) # 'games: 4'
"games: {:0>3}".format(player2.games) # 'games: 004'
Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).