Return back to MainActivity from another activity
Use this code on button click in activity and When return back to another activity just finish previous activity by setting flag in intent then put only one Activity in the Stack and destroy the previous one.
Intent i=new Intent("this","YourClassName.Class");
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
Unbound classpath container in Eclipse
Indeed this problem is to be fixed under Preferences -> Java -> Installed JREs.
If the desired JRE is apparent in the list - just select it, and that's it.
Otherwise it has to be installed on your computer first so you could
add it with "Add" -> Standard VM -> Directory, in the pop-up browser window choose its path - something like "program files\Java\Jre#" -> "ok". And now you can select it from the list.
Cache an HTTP 'Get' service response in AngularJS?
In Angular 8 we can do like this:
import { Injectable } from '@angular/core';
import { YourModel} from '../models/<yourModel>.model';
import { UserService } from './user.service';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GlobalDataService {
private me: <YourModel>;
private meObservable: Observable<User>;
constructor(private yourModalService: <yourModalService>, private http: HttpClient) {
}
ngOnInit() {
}
getYourModel(): Observable<YourModel> {
if (this.me) {
return of(this.me);
} else if (this.meObservable) {
return this.meObservable;
}
else {
this.meObservable = this.yourModalService.getCall<yourModel>() // Your http call
.pipe(
map(data => {
this.me = data;
return data;
})
);
return this.meObservable;
}
}
}
You can call it like this:
this.globalDataService.getYourModel().subscribe(yourModel => {
});
The above code will cache the result of remote API at first call so that it can be used on further requests to that method.
Open Cygwin at a specific folder
I used the following lines of code to start zsh in the current directory in Win7.
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\Background\shell\cygwin_bash]
@="Open Cygwin Here"
"NoWorkingDirectory"=""
[HKEY_CLASSES_ROOT\Directory\Background\shell\cygwin_bash\command]
@="\"C:\\Programmieren\\cygwin64\\bin\\mintty.exe\" -i /Cygwin-Terminal.ico /bin/zsh --login -c 'cd \"%V\";zsh'"
note that i used %V instead of %L or %1 (since both didn't work for me)
Sieve of Eratosthenes - Finding Primes Python
not sure if my code is efficeient, anyone care to comment?
from math import isqrt
def isPrime(n):
if n >= 2: # cheating the 2, is 2 even prime?
for i in range(3, int(n / 2 + 1),2): # dont waste time with even numbers
if n % i == 0:
return False
return True
def primesTo(n):
x = [2] if n >= 2 else [] # cheat the only even prime
if n >= 2:
for i in range(3, n + 1,2): # dont waste time with even numbers
if isPrime(i):
x.append(i)
return x
def primes2(n): # trying to do this using set methods and the "Sieve of Eratosthenes"
base = {2} # again cheating the 2
base.update(set(range(3, n + 1, 2))) # build the base of odd numbers
for i in range(3, isqrt(n) + 1, 2): # apply the sieve
base.difference_update(set(range(2 * i, n + 1 , i)))
return list(base)
print(primesTo(10000)) # 2 different methods for comparison
print(primes2(10000))
How do I select a random value from an enumeration?
Here is a generic function for it.
Keep the RNG creation outside the high frequency code.
public static Random RNG = new Random();
public static T RandomEnum<T>()
{
Type type = typeof(T);
Array values = Enum.GetValues(type);
lock(RNG)
{
object value= values.GetValue(RNG.Next(values.Length));
return (T)Convert.ChangeType(value, type);
}
}
Usage example:
System.Windows.Forms.Keys randomKey = RandomEnum<System.Windows.Forms.Keys>();
What's the difference between equal?, eql?, ===, and ==?
I love jtbandes answer, but since it is pretty long, I will add my own compact answer:
==
, ===
, eql?
, equal?
are 4 comparators, ie. 4 ways to compare 2 objects, in Ruby.
As, in Ruby, all comparators (and most operators) are actually method-calls, you can change, overwrite, and define the semantics of these comparing methods yourself. However, it is important to understand, when Ruby's internal language constructs use which comparator:
==
(value comparison)
Ruby uses :== everywhere to compare the values of 2 objects, eg. Hash-values:
{a: 'z'} == {a: 'Z'} # => false
{a: 1} == {a: 1.0} # => true
===
(case comparison)
Ruby uses :=== in case/when constructs. The following code snippets are logically identical:
case foo
when bar; p 'do something'
end
if bar === foo
p 'do something'
end
eql?
(Hash-key comparison)
Ruby uses :eql? (in combination with the method hash) to compare Hash-keys. In most classes :eql? is identical with :==.
Knowledge about :eql? is only important, when you want to create your own special classes:
class Equ
attr_accessor :val
alias_method :initialize, :val=
def hash() self.val % 2 end
def eql?(other) self.hash == other.hash end
end
h = {Equ.new(3) => 3, Equ.new(8) => 8, Equ.new(15) => 15} #3 entries, but 2 are :eql?
h.size # => 2
h[Equ.new(27)] # => 15
Note: The commonly used Ruby-class Set also relies on Hash-key-comparison.
equal?
(object identity comparison)
Ruby uses :equal? to check if two objects are identical. This method (of class BasicObject) is not supposed to be overwritten.
obj = obj2 = 'a'
obj.equal? obj2 # => true
obj.equal? obj.dup # => false
Is there any way to specify a suggested filename when using data: URI?
Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.
var exportFileName = "export-" + filename;
$('<a></a>', {
"download": exportFileName,
"href": "data:," + JSON.stringify(exportData, null,5),
"id": "exportDataID"
}).appendTo("body")[0].click().remove();
How does one extract each folder name from a path?
There are a few ways that a file path can be represented. You should use the System.IO.Path
class to get the separators for the OS, since it can vary between UNIX and Windows. Also, most (or all if I'm not mistaken) .NET libraries accept either a '\' or a '/' as a path separator, regardless of OS. For this reason, I'd use the Path class to split your paths. Try something like the following:
string originalPath = "\\server\\folderName1\\another\ name\\something\\another folder\\";
string[] filesArray = originalPath.Split(Path.AltDirectorySeparatorChar,
Path.DirectorySeparatorChar);
This should work regardless of the number of folders or the names.
Loop through files in a folder using VBA?
Try this one. (LINK)
Private Sub CommandButton3_Click()
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim xWs As Worksheet
Dim xWb As Workbook
Dim FolderName As String
Application.ScreenUpdating = False
Set xWb = Application.ThisWorkbook
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = xWb.Path & "\" & xWb.Name & " " & DateString
MkDir FolderName
For Each xWs In xWb.Worksheets
xWs.Copy
If Val(Application.Version) < 12 Then
FileExtStr = ".xls": FileFormatNum = -4143
Else
Select Case xWb.FileFormat
Case 51:
FileExtStr = ".xlsx": FileFormatNum = 51
Case 52:
If Application.ActiveWorkbook.HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 52
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
Case 56:
FileExtStr = ".xls": FileFormatNum = 56
Case Else:
FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
xFile = FolderName & "\" & Application.ActiveWorkbook.Sheets(1).Name & FileExtStr
Application.ActiveWorkbook.SaveAs xFile, FileFormat:=FileFormatNum
Application.ActiveWorkbook.Close False
Next
MsgBox "You can find the files in " & FolderName
Application.ScreenUpdating = True
End Sub
Less aggressive compilation with CSS3 calc
There is several escaping options with same result:
body { width: ~"calc(100% - 250px - 1.5em)"; }
body { width: calc(~"100% - 250px - 1.5em"); }
body { width: calc(100% ~"-" 250px ~"-" 1.5em); }
mysql update column with value from another table
you need to join the two tables:
for instance you want to copy the value of name
from tableA into tableB
where they have the same ID
UPDATE tableB t1
INNER JOIN tableA t2
ON t1.id = t2.id
SET t1.name = t2.name
WHERE t2.name = 'Joe'
UPDATE 1
UPDATE tableB t1
INNER JOIN tableA t2
ON t1.id = t2.id
SET t1.name = t2.name
UPDATE 2
UPDATE tableB t1
INNER JOIN tableA t2
ON t1.name = t2.name
SET t1.value = t2.value
Java Regex Replace with Capturing Group
How about:
if (regexMatcher.find()) {
resultString = regexMatcher.replaceAll(
String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}
To get the first match, use #find()
. After that, you can use #group(1)
to refer to this first match, and replace all matches by the first maches value multiplied by 3.
And in case you want to replace each match with that match's value multiplied by 3:
Pattern p = Pattern.compile("(\\d{1,2})");
Matcher m = p.matcher("12 54 1 65");
StringBuffer s = new StringBuffer();
while (m.find())
m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
System.out.println(s.toString());
You may want to look through Matcher
's documentation, where this and a lot more stuff is covered in detail.
How do I debug jquery AJAX calls?
Firebug as Firefox (FF) extension is currently (as per 01/2017) the only way to debug direct javascript responses from AJAX calls. Unfortunately, it's development is discontinued. And since Firefox 50, the Firebug also cannot be installed anymore due to compatability issues :-( They kind of emulated FF developer tools UI to recall Firebug UI in some way.
Unfortunatelly, FF native developer tools are not able to debug javascript returned directly by AJAX calls. Same applies to Chrome devel. tools.
I must have disabled upgrades of FF due to this issue, since I badly need to debug JS from XHR calls on current project. So not good news here - let's hope the feature to debug direct JS responses will be incorporated into FF/Chrome developer tools soon.
jquery, find next element by class
You cannot use next() in this scenario, if you look at the documentation it says:
Next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling that matches the selector.
so if the second DIV was in the same TD then you could code:
// Won't work in your case
$(obj).next().filter('.class');
But since it's not, I don't see a point to use next(). You can instead code:
$(obj).parents('table').find('.class')
Print a file, skipping the first X lines, in Bash
Use the sed delete
command with a range address. For example:
sed 1,100d file.txt # Print file.txt omitting lines 1-100.
Alternatively, if you want to only print a known range, use the print command with the -n
flag:
sed -n 201,300p file.txt # Print lines 201-300 from file.txt
This solution should work reliably on all Unix systems, regardless of the presence of GNU utilities.
HTML colspan in CSS
I came here because currently the WordPress table block doesn't support the colspan parameter and i thought i will replace it using CSS. This was my solution, assuming that the columns are the same width:
_x000D_
_x000D_
table {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
table td {_x000D_
width: 50%;_x000D_
background: #dbdbdb;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
table tr:nth-child(2n+1) {_x000D_
position:relative;_x000D_
display:block;_x000D_
height:20px;_x000D_
background:green;_x000D_
}_x000D_
_x000D_
table tr:nth-child(2n+1) td {_x000D_
position:absolute;_x000D_
left:0;_x000D_
right:-100%;_x000D_
width: auto;_x000D_
top:0;_x000D_
bottom:0;_x000D_
background:red;_x000D_
text-align:center;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>row</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cell</td>_x000D_
<td>cell</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cell</td>_x000D_
<td>cell</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
How do I create test and train samples from one dataframe with pandas?
There are many valid answers. Adding one more to the bunch.
from sklearn.cross_validation import train_test_split
#gets a random 80% of the entire set
X_train = X.sample(frac=0.8, random_state=1)
#gets the left out portion of the dataset
X_test = X.loc[~df_model.index.isin(X_train.index)]
Reading in from System.in - Java
You can use System.in
to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.
class MyProg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Printing the file passed in:");
while(sc.hasNextLine()) System.out.println(sc.nextLine());
}
}
Staging Deleted files
Use git rm foo
to stage the file for deletion. (This will also delete the file from the file system, if it hadn't been previously deleted. It can, of course, be restored from git, since it was previously checked in.)
To stage the file for deletion without deleting it from the file system, use git rm --cached foo
How can I remove leading and trailing quotes in SQL Server?
You can simply use the "Replace" function in SQL Server.
like this ::
select REPLACE('this is a test message','"','')
note: second parameter here is "double quotes" inside two single quotes and third parameter is simply a combination of two single quotes. The idea here is to replace the double quotes with a blank.
Very simple and easy to execute !
Strings as Primary Keys in SQL Database
Yes, but unless you expect to have millions of rows, not using a string-based key because it's slower is usually "premature optimization." After all, strings are stored as big numbers while numeric keys are usually stored as smaller numbers.
One thing to watch out for, though, is if you have clustered indices on a any key and are doing large numbers of inserts that are non-sequential in the index. Every line written will cause the index to re-write. if you're doing batch inserts, this can really slow the process down.
How to define the basic HTTP authentication using cURL correctly?
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication.
Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which
makes it impossible to use a colon in the user name with this option.
The password can, still.
When using Kerberos V5 with a Windows based server you should include
the Windows domain name in the user name, in order for the server to
succesfully obtain a Kerberos Ticket. If you don't then the initial
authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user
name, without the domain, if there is a single domain and forest in
your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN
(User Principal Name) formats. For example, EXAMPLE\user and
[email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5,
Negotiate, NTLM or Digest authentication then you can tell curl to
select the user name and password from your environment by specifying
a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
How to get back Lost phpMyAdmin Password, XAMPP
The question may be getting old, but I've struggled with the same issue just now.
After deleting passwords with resetroot.bat
, as instructed by Nedshed, you can choose another password by going to http://localhost/security/index.php
Python Accessing Nested JSON Data
In your code j is Already json data and j['places'] is list not dict.
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print j['state']
for each in j['places']:
print each['latitude']
Razor view engine - How can I add Partial Views
You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates
subfolder):
@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)
Or if this is not the case simply:
@Html.Partial("nameOfPartial", Model)
use std::fill to populate vector with increasing numbers
brainsandwich and underscore_d gave very good ideas. Since to fill is to change content, for_each(), the simplest among the STL algorithms, should also fill the bill:
std::vector<int> v(10);
std::for_each(v.begin(), v.end(), [i=0] (int& x) mutable {x = i++;});
The generalized capture [i=o]
imparts the lambda expression with an invariant and initializes it to a known state (in this case 0). the keyword mutable
allows this state to be updated each time lambda is called.
It takes only a slight modification to get a sequence of squares:
std::vector<int> v(10);
std::for_each(v.begin(), v.end(), [i=0] (int& x) mutable {x = i*i; i++;});
To generate R-like seq is no more difficult, but note that in R, the numeric mode is actually double, so there really isn't a need to parametrize the type. Just use double.
Cleaning `Inf` values from an R dataframe
Use sapply
and is.na<-
> dat <- data.frame(a=c(1, Inf), b=c(Inf, 3), d=c("a","b"))
> is.na(dat) <- sapply(dat, is.infinite)
> dat
a b d
1 1 NA a
2 NA 3 b
Or you can use (giving credit to @mnel, whose edit this is),
> is.na(dat) <- do.call(cbind,lapply(dat, is.infinite))
which is significantly faster.
How do you make strings "XML safe"?
If at all possible, its always a good idea to create your XML using the XML classes rather than string manipulation - one of the benefits being that the classes will automatically escape characters as needed.
Find files with size in Unix
find . -size +10000k -exec ls -sd {} +
If your version of find
won't accept the +
notation (which acts rather like xargs
does), then you might use (GNU find
and xargs
, so find
probably supports +
anyway):
find . -size +10000k -print0 | xargs -0 ls -sd
or you might replace the +
with \;
(and live with the relative inefficiency of this), or you might live with problems caused by spaces in names and use the portable:
find . -size +10000k -print | xargs ls -sd
The -d
on the ls
commands ensures that if a directory is ever found (unlikely, but...), then the directory information will be printed, not the files in the directory. And, if you're looking for files more than 1 MB (as a now-deleted comment suggested), you need to adjust the +10000k
to 1000k
or maybe +1024k
, or +2048
(for 512-byte blocks, the default unit for -size
). This will list the size and then the file name. You could avoid the need for -d
by adding -type f
to the find
command, of course.
Python: Number of rows affected by cursor.execute("SELECT ...)
Try using fetchone
:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
result=cursor.fetchone()
result
will hold a tuple with one element, the value of COUNT(*)
.
So to find the number of rows:
number_of_rows=result[0]
Or, if you'd rather do it in one fell swoop:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
(number_of_rows,)=cursor.fetchone()
PS. It's also good practice to use parametrized arguments whenever possible, because it can automatically quote arguments for you when needed, and protect against sql injection.
The correct syntax for parametrized arguments depends on your python/database adapter (e.g. mysqldb, psycopg2 or sqlite3). It would look something like
cursor.execute("SELECT COUNT(*) from result where server_state= %s AND name LIKE %s",[2,digest+"_"+charset+"_%"])
(number_of_rows,)=cursor.fetchone()
Plot multiple lines (data series) each with unique color in R
If your data is in wide format matplot
is made for this and often forgotten about:
dat <- matrix(runif(40,1,20),ncol=4) # make data
matplot(dat, type = c("b"),pch=1,col = 1:4) #plot
legend("topleft", legend = 1:4, col=1:4, pch=1) # optional legend
There is also the added bonus for those unfamiliar with things like ggplot
that most of the plotting paramters such as pch
etc. are the same using matplot()
as plot()
.
Passing references to pointers in C++
EDIT: I experimented some, and discovered thing are a bit subtler than I thought. Here's what I now think is an accurate answer.
&s
is not an lvalue so you cannot create a reference to it unless the type of the reference is reference to const
. So for example, you cannot do
string * &r = &s;
but you can do
string * const &r = &s;
If you put a similar declaration in the function header, it will work.
void myfunc(string * const &a) { ... }
There is another issue, namely, temporaries. The rule is that you can get a reference to a temporary only if it is const
. So in this case one might argue that &s is a temporary, and so must be declared const
in the function prototype. From a practical point of view it makes no difference in this case. (It's either an rvalue or a temporary. Either way, the same rule applies.) However, strictly speaking, I think it is not a temporary but an rvalue. I wonder if there is a way to distinguish between the two. (Perhaps it is simply defined that all temporaries are rvalues, and all non-lvalues are temporaries. I'm not an expert on the standard.)
That being said, your problem is probably at a higher level. Why do you want a reference to the address of s
? If you want a reference to a pointer to s
, you need to define a pointer as in
string *p = &s;
myfunc(p);
If you want a reference to s
or a pointer to s
, do the straightforward thing.
400 BAD request HTTP error code meaning?
Using 400
status codes for any other purpose than indicating that the request is malformed is just plain wrong.
If the request payload contains a byte-sequence that could not be parsed as application/json
(if the server expects that dataformat), the appropriate status code is 415
:
The server is refusing to service the request because the entity of
the request is in a format not supported by the requested resource for
the requested method.
If the request payload is syntactically correct but semantically incorrect, the non-standard 422
response code may be used, or the standard 403
status code:
The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated.
The correct way to read a data file into an array
Just reading the file into an array, one line per element, is trivial:
open my $handle, '<', $path_to_file;
chomp(my @lines = <$handle>);
close $handle;
Now the lines of the file are in the array @lines
.
If you want to make sure there is error handling for open
and close
, do something like this (in the snipped below, we open the file in UTF-8 mode, too):
my $handle;
unless (open $handle, "<:encoding(utf8)", $path_to_file) {
print STDERR "Could not open file '$path_to_file': $!\n";
# we return 'undefined', we could also 'die' or 'croak'
return undef
}
chomp(my @lines = <$handle>);
unless (close $handle) {
# what does it mean if close yields an error and you are just reading?
print STDERR "Don't care error while closing '$path_to_file': $!\n";
}
In Perl, how to remove ^M from a file?
This is what solved my problem. ^M is a carriage return, and it can be easily avoided in a Perl script.
while(<INPUTFILE>)
{
chomp;
chop($_) if ($_ =~ m/\r$/);
}
How to find a whole word in a String in java
The example below is based on your comments. It uses a List of keywords, which will be searched in a given String using word boundaries. It uses StringUtils from Apache Commons Lang to build the regular expression and print the matched groups.
String text = "I will come and meet you at the woods 123woods and all the woods";
List<String> tokens = new ArrayList<String>();
tokens.add("123woods");
tokens.add("woods");
String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
If you are looking for more performance, you could have a look at StringSearch: high-performance pattern matching algorithms in Java.
Curl GET request with json parameter
If you want to send your data inside the body, then you have to make a POST
or PUT
instead of GET
.
For me, it looks like you're trying to send the query with uri parameters, which is not related to GET
, you can also put these parameters on POST
, PUT
and so on.
The query is an optional part, separated by a question mark ("?"), that contains additional identification information that is not hierarchical in nature. The query string syntax is not generically defined, but it is commonly organized as a sequence of = pairs, with the pairs separated by a semicolon or an ampersand.
For example:
curl http://server:5050/a/c/getName?param0=foo¶m1=bar
How to get date in BAT file
You get and format like this
for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
set dow=%%i
set month=%%j
set day=%%k
set year=%%l
)
set datestr=%month%_%day%_%year%
echo datestr is %datestr%
Note: Above only works on US locale. It assumes the output of echo %date%
looks like this: Thu 02/13/21
. If you have different Windows locale settings, you will need to modify the script based on your configuration.
How to append output to the end of a text file
Using tee with option -a (--append) allows you to append to multiple files at once and also to use sudo (very useful when appending to protected files). Besides that, it is interesting if you need to use other shells besides bash, as not all shells support the > and >> operators
echo "hello world" | sudo tee -a output.txt
This thread has good answers about tee
MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result
I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:
SELECT * FROM match WHERE id NOT IN
( SELECT id FROM email WHERE id IS NOT NULL) ;
SELECT
m.*
FROM
match m
LEFT OUTER JOIN email e ON
m.id = e.id
AND e.id IS NOT NULL
WHERE
e.id IS NULL
The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.
What is the difference between POST and GET?
Whilst not a description of the differences, below are a couple of things to think about when choosing the correct method.
- GET requests can get cached by the browser which can be a problem (or benefit) when using ajax.
- GET requests expose parameters to users (POST does as well but they are less visible).
- POST can pass much more information to the server and can be of almost any length.
Space between Column's children in Flutter
Just use padding to wrap it like this:
Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(8.0),
child: Text('Hello World!'),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text('Hello World2!'),
)
]);
You can also use Container(padding...) or SizeBox(height: x.x). The last one is the most common but it will depents of how you want to manage the space of your widgets, I like to use padding if the space is part of the widget indeed and use sizebox for lists for example.
Android ImageView's onClickListener does not work
can you Try this and tell me what happens ?? :
JAVA :
ImageView imgFavorite = (ImageView) findViewById(R.id.favorite_icon);
imgFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(YourActivityName.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
}
});
or you should add this :
imgFavorite.setClickable(true);
KOTLIN :
imgFavorite.setOnClickListener { view ->
Toast.makeText(this@YourActivityName, R.string.toast_favorite_list_would_appear, Toast.LENGTH_LONG).show()
}
// either you make your imageView clickable programmatically
imgFavorite.clickable = true
// or via xml on your layout file
<ImageView .... android:clickable="true" />
CSS border less than 1px
A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).
Here is a test to prove this point:
_x000D_
_x000D_
div { border-color: blue; border-style: solid; margin: 2px; }
div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
_x000D_
_x000D_
Output
Which gives the illusion that the last DIV
has a smaller border width, because the blue border blends more with the white background.
Edit: Alternate solution
Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.
_x000D_
_x000D_
.container {
border-style: solid;
border-width: 1px;
margin-bottom: 10px;
}
.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
_x000D_
_x000D_
How do I write a "tab" in Python?
Assume I have a variable named file
that contains a file.
Then I could use file.write("hello\talex")
.
file.write("hello
means I'm starting to write to this file.
\t
means a tab
alex")
is the rest I'm writing
BSTR to std::string (std::wstring) and vice versa
You could also do this
#include <comdef.h>
BSTR bs = SysAllocString("Hello");
std::wstring myString = _bstr_t(bs, false); // will take over ownership, so no need to free
or std::string if you prefer
EDIT: if your original string contains multiple embedded \0 this approach will not work.
How to put a UserControl into Visual Studio toolBox
I had many users controls but one refused to show in the Toolbox, even though I rebuilt the solution and it was checked in the Choose Items... dialog.
Solution:
- From Solution Explorer I Right-Clicked the offending user control file and selected Exclude From Project
- Rebuild the solution
- Right-Click the user control and select Include in Project (assuming you have the Show All Files enabled in the Solution Explorer)
Note this also requires you have the AutoToolboxPopulate option enabled. As @DaveF answer suggests.
Alternate Solution: I'm not sure if this works, and I couldn't try it since I already resolved my issue, but if you unchecked the user control from the Choose Items... dialog, hit OK, then opened it back up and checked the user control. That might also work.
Can we cast a generic object to a custom object type in javascript?
The answer of @PeterOlson may be worked back in the day but it looks like Object.create
is changed.
I would go for the copy-constructor way like @user166390 said in the comments.
The reason I necromanced this post is because I needed such implementation.
Nowadays we can use Object.assign
(credits to @SayanPal solution) & ES6 syntax:
class Person {
constructor(obj) {
obj && Object.assign(this, obj);
}
getFullName() {
return `${this.lastName} ${this.firstName}`;
}
}
Usage:
const newPerson = new Person(person1)
newPerson.getFullName() // -> Freeman Gordon
ES5 answer below
function Person(obj) {
for(var prop in obj){
// for safety you can use the hasOwnProperty function
this[prop] = obj[prop];
}
}
Usage:
var newPerson = new Person(person1);
console.log(newPerson.getFullName()); // -> Freeman Gordon
Using a shorter version, 1.5 liner:
function Person(){
if(arguments[0]) for(var prop in arguments[0]) this[prop] = arguments[0][prop];
}
Fitting polynomial model to data in R
The easiest way to find the best fit in R is to code the model as:
lm.1 <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + ...)
After using step down AIC regression
lm.s <- step(lm.1)
How to assert greater than using JUnit Assert?
Just how you've done it. assertTrue(boolean)
also has an overload assertTrue(String, boolean)
where the String
is the message in case of failure; you can use that if you want to print that such-and-such wasn't greater than so-and-so.
You could also add hamcrest-all
as a dependency to use matchers. See https://code.google.com/p/hamcrest/wiki/Tutorial:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
assertThat("timestamp",
Long.parseLong(previousTokenValues[1]),
greaterThan(Long.parseLong(currentTokenValues[1])));
That gives an error like:
java.lang.AssertionError: timestamp
Expected: a value greater than <456L>
but: <123L> was less than <456L>
Using multiple parameters in URL in express
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
If that doesn't work, try using console.log(req.params) to see what it is giving you.
How to merge specific files from Git branches
None of the other current answers will actually "merge" the files, as if you were using the merge command. (At best they'll require you to manually pick diffs.) If you actually want to take advantage of merging using the information from a common ancestor, you can follow a procedure based on one found in the "Advanced Merging" section of the git Reference Manual.
For this protocol, I'm assuming you're wanting to merge the file 'path/to/file.txt' from origin/master into HEAD - modify as appropriate. (You don't have to be in the top directory of your repository, but it helps.)
# Find the merge base SHA1 (the common ancestor) for the two commits:
git merge-base HEAD origin/master
# Get the contents of the files at each stage
git show <merge-base SHA1>:path/to/file.txt > ./file.common.txt
git show HEAD:path/to/file.txt > ./file.ours.txt
git show origin/master:path/to/file.txt > ./file.theirs.txt
# You can pre-edit any of the files (e.g. run a formatter on it), if you want.
# Merge the files
git merge-file -p ./file.ours.txt ./file.common.txt ./file.theirs.txt > ./file.merged.txt
# Resolve merge conflicts in ./file.merged.txt
# Copy the merged version to the destination
# Clean up the intermediate files
git merge-file should use all of your default merge settings for formatting and the like.
Also note that if your "ours" is the working copy version and you don't want to be overly cautious, you can operate directly on the file:
git merge-base HEAD origin/master
git show <merge-base SHA1>:path/to/file.txt > ./file.common.txt
git show origin/master:path/to/file.txt > ./file.theirs.txt
git merge-file path/to/file.txt ./file.common.txt ./file.theirs.txt
How to get the new value of an HTML input after a keypress has modified it?
<html>
<head>
<script>
function callme(field) {
alert("field:" + field.value);
}
</script>
</head>
<body>
<form name="f1">
<input type="text" onkeyup="callme(this);" name="text1">
</form>
</body>
</html>
It looks like you can use the onkeyup to get the new value of the HTML input control. Hope it helps.
How to get an object's methods?
Get the Method Names:
var getMethodNames = function (obj) {
return (Object.getOwnPropertyNames(obj).filter(function (key) {
return obj[key] && (typeof obj[key] === "function");
}));
};
Or, Get the Methods:
var getMethods = function (obj) {
return (Object.getOwnPropertyNames(obj).filter(function (key) {
return obj[key] && (typeof obj[key] === "function");
})).map(function (key) {
return obj[key];
});
};
postgresql sequence nextval in schema
SELECT last_value, increment_by from "other_schema".id_seq;
for adding a seq to a column where the schema is not public try this.
nextval('"other_schema".id_seq'::regclass)
Handling of non breaking space: <p> </p> vs. <p> </p>
How about a workaround?
In my case I took the value of the textarea in a jQuery variable, and changed all "<p> "
to <p class="clear">
and clear class to have certain height and margin, as the following example:
jQuery
tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p> /g, '<p class="clear">');
the val is then saved to the database with the new val.
CSS
p.clear{height: 2px; margin-bottom: 3px;}
You can adjust the height & margin as you wish.
And since 'p' is a display: block element. it should give you the expected output.
Hope that helps!
How do I get into a non-password protected Java keystore or change the password?
which means that cacerts keystore isn't password protected
That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:
In order to verify its integrity, you must provide your keystore password.
Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.
URL rewriting with PHP
this is an .htaccess file that forward almost all to index.php
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php
then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever
How to trim a string in SQL Server before 2017?
I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.
ALTER TABLE Customer ADD
CONSTRAINT customer_names__whitespace
CHECK (
Names NOT LIKE ' %'
AND Names NOT LIKE '% '
AND Names NOT LIKE '% %'
);
Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.
It may also be a good time to split those Names into family_name
, first_name
, etc :)
Run Bash Command from PHP
Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.
Undefined reference to sqrt (or other mathematical functions)
I suppose you have imported math.h with #include <math.h>
So the only other reason I can see is a missing linking information. You must link your code with the -lm
option.
If you're simply trying to compile one file with gcc, just add -lm
to your command line, otherwise, give some informations about your building process.
Is it better to use std::memcpy() or std::copy() in terms to performance?
Just a minor addition: The speed difference between memcpy()
and std::copy()
can vary quite a bit depending on if optimizations are enabled or disabled. With g++ 6.2.0 and without optimizations memcpy()
clearly wins:
Benchmark Time CPU Iterations
---------------------------------------------------
bm_memcpy 17 ns 17 ns 40867738
bm_stdcopy 62 ns 62 ns 11176219
bm_stdcopy_n 72 ns 72 ns 9481749
When optimizations are enabled (-O3
), everything looks pretty much the same again:
Benchmark Time CPU Iterations
---------------------------------------------------
bm_memcpy 3 ns 3 ns 274527617
bm_stdcopy 3 ns 3 ns 272663990
bm_stdcopy_n 3 ns 3 ns 274732792
The bigger the array the less noticeable the effect gets, but even at N=1000
memcpy()
is about twice as fast when optimizations aren't enabled.
Source code (requires Google Benchmark):
#include <string.h>
#include <algorithm>
#include <vector>
#include <benchmark/benchmark.h>
constexpr int N = 10;
void bm_memcpy(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
memcpy(r.data(), a.data(), N * sizeof(int));
}
}
void bm_stdcopy(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
std::copy(a.begin(), a.end(), r.begin());
}
}
void bm_stdcopy_n(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
std::copy_n(a.begin(), N, r.begin());
}
}
BENCHMARK(bm_memcpy);
BENCHMARK(bm_stdcopy);
BENCHMARK(bm_stdcopy_n);
BENCHMARK_MAIN()
/* EOF */
maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar
Summary : Use an external script (batch file) that a) stops the server and b) Unlocks the .jar file before running maven-clean.
Steps:
Bind the maven-antrun-plugin:run goal to the pre-clean phase of mvn clean. See how to do this here
See how to use the antrun plugin to run an external batch file in Windows here : sblundy's answer to "Starting external process". Let's call this file unlock_handles.bat
Use the Sysinternals handle utility download link in the pre_clean.bat to a) stop the Tomcat server and b) unlock the .jar file. handle -c
and handle -p
would be useful here.
Whew! That's a bit of work, but it will reliably automate the process for you so that you do need to do it manually yourself each time!
OK, here's a rough, proof-of-concept version of unlock_handles.bat for you to try out:
REM "Use handle.exe to figure out the process id and handle ids, parse the output, then close the handle (again using handle.exe)"
cd "C:\Users\Nikolay_Tkachev\workspace\HHSystem\UI\target"
"c:/Program Files/Process Explorer/handle.exe" -p java.exe "C:\Users\Nikolay_Tkachev\workspace\HHSystem\UI\target" > handles.txt
@echo "O====== Going to unlock all the below file handles! =======O"
FOR /F "tokens=1-26 delims=: " %a in (handles.txt) DO @echo %h
FOR /F "tokens=1-26 delims=: " %a in (handles.txt) DO handle -p %c -c %f -y
Of course, you have to change the path to Sysinternals' handle.exe before giving this a try.
How to handle notification when app in background in Firebase
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
}
is not called every time it is called only when app is in forground
there is one override method this method is called every time , no matter what app is in foreground or in background or killed but this method is available with this firebase api version
this is the version u have to import from gradle
compile 'com.google.firebase:firebase-messaging:10.2.1'
this is the method
@Override
public void handleIntent(Intent intent) {
super.handleIntent(intent);
// you can get ur data here
//intent.getExtras().get("your_data_key")
}
with previous firebase api this method was not there so in that case
fire base handle itself when app is in background .... now u have this method
what ever u want to do ... u can do it here in this method .....
if you are using previous version than default activity will start
in that case u can get data same way
if(getIntent().getExtras() != null && getIntent().getExtras().get("your_data_key") != null) {
String strNotificaiton = getIntent().getExtras().get("your_data_key").toString();
// do what ever u want ....
}
generally this is the structure from server we get in notification
{
"notification": {
"body": "Cool offers. Get them before expiring!",
"title": "Flat 80% discount",
"icon": "appicon",
"click_action": "activity name" //optional if required.....
},
"data": {
"product_id": 11,
"product_details": "details.....",
"other_info": "......."
}
}
it's up to u how u want to give that data key or u want give notification anything u can give .......
what ever u will give here with same key u will get that data .........
there are few cases if u r not sending click action in that case when u will click on notification default activity will open , but if u want to open your specific activity when app is in background u can call your activity from this on handleIntent method because this is called every time
How to prevent a file from direct URL Access?
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
RewriteCond %{REQUEST_URI} !^http://(www\.)?localhost/(.*)\.(gif|jpg|png|jpeg|mp4)$ [NC]
RewriteRule . - [F]
Breaking a list into multiple columns in Latex
By combining the multicol package and enumitem package packages it is easy to define environments that are multi-column analogues of the enumerate and itemize environments:
\documentclass{article}
\usepackage{enumitem}
\usepackage{multicol}
\newlist{multienum}{enumerate}{1}
\setlist[multienum]{
label=\alph*),
before=\begin{multicols}{2},
after=\end{multicols}
}
\newlist{multiitem}{itemize}{1}
\setlist[multiitem]{
label=\textbullet,
before=\begin{multicols}{2},
after=\end{multicols}
}
\begin{document}
\textsf{Two column enumerate}
\begin{multienum}
\item item 1
\item item 2
\item item 3
\item item 4
\item item 5
\item item 6
\end{multienum}
\textsf{Two column itemize}
\begin{multiitem}
\item item 1
\item item 2
\item item 3
\item item 4
\item item 5
\item item 6
\end{multiitem}
\end{document}
The output is what you would hope for:
Truncating Text in PHP?
$text="abc1234567890";
// truncate to 4 chars
echo substr(str_pad($text,4),0,4);
This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)
How can I specify a [DllImport] path at runtime?
As long as you know the directory where your C++ libraries could be found at run time, this should be simple. I can clearly see that this is the case in your code. Your myDll.dll
would be present inside myLibFolder
directory inside temporary folder of the current user.
string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";
Now you can continue using the DllImport statement using a const string as shown below:
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);
Just at run time before you call the DLLFunction
function (present in C++ library) add this line of code in C# code:
string assemblyProbeDirectory = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";
Directory.SetCurrentDirectory(assemblyProbeDirectory);
This simply instructs the CLR to look for the unmanaged C++ libraries at the directory path which you obtained at run time of your program. Directory.SetCurrentDirectory
call sets the application's current working directory to the specified directory. If your myDLL.dll
is present at path represented by assemblyProbeDirectory
path then it will get loaded and the desired function will get called through p/invoke.
Why do multiple-table joins produce duplicate rows?
When you have related tables you often have one-to-many or many-to-many relationships. So when you join to TableB each record in TableA many have multiple records in TableB. This is normal and expected.
Now at times you only need certain columns and those are all the same for all the records, then you would need to do some sort of group by or distinct to remove the duplicates. Let's look at an example:
TableA
Id Field1
1 test
2 another test
TableB
ID Field2 field3
1 Test1 something
1 test1 More something
2 Test2 Anything
So when you join them and select all the files you get:
select *
from tableA a
join tableb b on a.id = b.id
a.Id a.Field1 b.id b.field2 b.field3
1 test 1 Test1 something
1 test 1 Test1 More something
2 another test 2 2 Test2 Anything
These are not duplicates because the values of Field3 are different even though there are repeated values in the earlier fields. Now when you only select certain columns the same number of records are being joined together but since the columns with the different information is not being displayed they look like duplicates.
select a.Id, a.Field1, b.field2
from tableA a
join tableb b on a.id = b.id
a.Id a.Field1 b.field2
1 test Test1
1 test Test1
2 another test Test2
This appears to be duplicates but it is not because of the multiple records in TableB.
You normally fix this by using aggregates and group by, by using distinct or by filtering in the where clause to remove duplicates. How you solve this depends on exactly what your business rule is and how your database is designed and what kind of data is in there.
Android - Activity vs FragmentActivity?
If you use the Eclipse "New Android Project" wizard in a recent ADT bundle, you'll automatically get tabs implemented as a Fragments. This makes the conversion of your application to the tablet format much easier in the future.
For simple single screen layouts you may still use Activity
.
Splitting comma separated string in a PL/SQL stored proc
CREATE OR REPLACE PROCEDURE insert_into (
p_errcode OUT NUMBER,
p_errmesg OUT VARCHAR2,
p_rowsaffected OUT INTEGER
)
AS
v_param0 VARCHAR2 (30) := '0.25,2.25,33.689, abc, 99';
v_param1 VARCHAR2 (30) := '2.65,66.32, abc-def, 21.5';
BEGIN
FOR i IN (SELECT COLUMN_VALUE
FROM TABLE (SPLIT (v_param0, ',')))
LOOP
INSERT INTO tempo
(col1
)
VALUES (i.COLUMN_VALUE
);
END LOOP;
FOR i IN (SELECT COLUMN_VALUE
FROM TABLE (SPLIT (v_param1, ',')))
LOOP
INSERT INTO tempo
(col2
)
VALUES (i.COLUMN_VALUE
);
END LOOP;
END;
@Nullable annotation usage
It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.
It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.
Writing to a TextBox from another thread?
On your MainForm make a function to set the textbox the checks the InvokeRequired
public void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
return;
}
ActiveForm.Text += value;
}
although in your static method you can't just call.
WindowsFormsApplication1.Form1.AppendTextBox("hi. ");
you have to have a static reference to the Form1 somewhere, but this isn't really recommended or necessary, can you just make your SampleFunction not static if so then you can just call
AppendTextBox("hi. ");
It will append on a differnt thread and get marshalled to the UI using the Invoke call if required.
Full Sample
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread(SampleFunction).Start();
}
public void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
return;
}
textBox1.Text += value;
}
void SampleFunction()
{
// Gets executed on a seperate thread and
// doesn't block the UI while sleeping
for(int i = 0; i<5; i++)
{
AppendTextBox("hi. ");
Thread.Sleep(1000);
}
}
}
Updating a date in Oracle SQL table
If this SQL is being used in any peoplesoft specific code (Application Engine, SQLEXEC, SQLfetch, etc..) you could use %Datein metaSQL. Peopletools automatically converts the date to a format which would be accepted by the database platform the application is running on.
In case this SQL is being used to perform a backend update from a query analyzer (like SQLDeveloper, SQLTools), the date format that is being used is wrong. Oracle expects the date format to be DD-MMM-YYYY, where MMM could be JAN, FEB, MAR, etc..
Getting current directory in .NET web application
Use this code:
HttpContext.Current.Server.MapPath("~")
Detailed Reference:
Server.MapPath
specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".")
returns the current physical directory of the
file (e.g. aspx) being executed
Server.MapPath("..")
returns the parent directory
Server.MapPath("~")
returns the physical path to the root of the
application
Server.MapPath("/")
returns the physical path to the root of the
domain name (is not necessarily the same as the root of the
application)
An example:
Let's say you pointed a web site application (http://www.example.com/) to
C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
D:\WebApps\shop
For example, if you call Server.MapPath
in following request:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:
Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop
If Path starts with either a forward (/) or backward slash (), the MapPath
method returns a path as if Path were a full, virtual path.
If Path doesn't start with a slash, the MapPath
method returns a path relative to the directory of the request being processed.
Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.
Footnotes
Server.MapPath(null)
and Server.MapPath("")
will produce this effect too.
PHP display image BLOB from MySQL
Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:
echo "data: $mime" $result['$data']";
where:
mime
can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob
in database.
How to extract the nth word and count word occurrences in a MySQL string?
I used Brendan Bullen's answer as a starting point for a similar issue I had which was to retrive the value of a specific field in a JSON string. However, like I commented on his answer, it is not entirely accurate. If your left boundary isn't just a space like in the original question, then the discrepancy increases.
Corrected solution:
SUBSTRING(
sentence,
LOCATE(' ', sentence) + 1,
LOCATE(' ', sentence, (LOCATE(' ', sentence) + 1)) - LOCATE(' ', sentence) - 1
)
The two differences are the +1 in the SUBSTRING index parameter and the -1 in the length parameter.
For a more general solution to "find the first occurence of a string between two provided boundaries":
SUBSTRING(
haystack,
LOCATE('<leftBoundary>', haystack) + CHAR_LENGTH('<leftBoundary>'),
LOCATE(
'<rightBoundary>',
haystack,
LOCATE('<leftBoundary>', haystack) + CHAR_LENGTH('<leftBoundary>')
)
- (LOCATE('<leftBoundary>', haystack) + CHAR_LENGTH('<leftBoundary>'))
)
Event binding on dynamically created elements?
You can attach event to element when dynamically created using jQuery(html, attributes)
.
As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn
) can be used as a property of the object passed to the
second parameter:
_x000D_
_x000D_
function handleDynamicElementEvent(event) {_x000D_
console.log(event.type, this.value)_x000D_
}_x000D_
// create and attach event to dynamic element_x000D_
jQuery("<select>", {_x000D_
html: $.map(Array(3), function(_, index) {_x000D_
return new Option(index, index)_x000D_
}),_x000D_
on: {_x000D_
change: handleDynamicElementEvent_x000D_
}_x000D_
})_x000D_
.appendTo("body");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">_x000D_
</script>
_x000D_
_x000D_
_x000D_
How to detect online/offline event cross-browser?
I use the FALLBACK option in the HTML5 cache manifest to check if my html5 app is online or offline by:
FALLBACK:
/online.txt /offline.txt
In the html page i use javascript tot read the contents of the online/offline txt file:
<script>$.get( "urlto/online.txt", function( data ) {
$( ".result" ).html( data );
alert( data );
});</script>
When offline the script will read the contents of the offline.txt.
Based on the text in the files you can detect if the webpage is online of offline.
Find common substring between two strings
Its called Longest Common Substring problem. Here I present a simple, easy to understand but inefficient solution. It will take a long time to produce correct output for large strings, as the complexity of this algorithm is O(N^2).
def longestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
match = ""
for j in range(len2):
if (i + j < len1 and string1[i + j] == string2[j]):
match += string2[j]
else:
if (len(match) > len(answer)): answer = match
match = ""
return answer
print longestSubstringFinder("apple pie available", "apple pies")
print longestSubstringFinder("apples", "appleses")
print longestSubstringFinder("bapples", "cappleses")
Output
apple pie
apples
apples
How can I save multiple documents concurrently in Mongoose/Node.js?
Mongoose 4.4 added a method called insertMany
Shortcut for validating an array of documents and inserting them into
MongoDB if they're all valid. This function is faster than .create()
because it only sends one operation to the server, rather than one for each
document.
Quoting vkarpov15 from issue #723:
The tradeoffs are that insertMany() doesn't trigger pre-save hooks, but it should have better performance because it only makes 1 round-trip to the database rather than 1 for each document.
The method's signature is identical to create
:
Model.insertMany([ ... ], (err, docs) => {
...
})
Or, with promises:
Model.insertMany([ ... ]).then((docs) => {
...
}).catch((err) => {
...
})
What is the difference between MOV and LEA?
MOV can do same thing as LEA [label], but MOV instruction contain the effective address inside the instruction itself as an immediate constant (calculated in advance by the assembler). LEA uses PC-relative to calculate the effective address during the execution of the instruction.
JQuery confirm dialog
Try this one
$('<div></div>').appendTo('body')
.html('<div><h6>Yes or No?</h6></div>')
.dialog({
modal: true, title: 'message', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
doFunctionForYes();
$(this).dialog("close");
},
No: function () {
doFunctionForNo();
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
Fiddle
How to Replace Multiple Characters in SQL?
One option is to use a numbers/tally table to drive an iterative process via a pseudo-set based query.
The general idea of char replacement can be demonstrated with a simple character map table approach:
create table charMap (srcChar char(1), replaceChar char(1))
insert charMap values ('a', 'z')
insert charMap values ('b', 'y')
create table testChar(srcChar char(1))
insert testChar values ('1')
insert testChar values ('a')
insert testChar values ('2')
insert testChar values ('b')
select
coalesce(charMap.replaceChar, testChar.srcChar) as charData
from testChar left join charMap on testChar.srcChar = charMap.srcChar
Then you can bring in the tally table approach to do the lookup on each character position in the string.
create table tally (i int)
declare @i int
set @i = 1
while @i <= 256 begin
insert tally values (@i)
set @i = @i + 1
end
create table testData (testString char(10))
insert testData values ('123a456')
insert testData values ('123ab456')
insert testData values ('123b456')
select
i,
SUBSTRING(testString, i, 1) as srcChar,
coalesce(charMap.replaceChar, SUBSTRING(testString, i, 1)) as charData
from testData cross join tally
left join charMap on SUBSTRING(testString, i, 1) = charMap.srcChar
where i <= LEN(testString)
.NET code to send ZPL to Zebra printers
I use the combo of these two
Private Sub sendData(ByVal zpl As String)
Dim ns As System.Net.Sockets.NetworkStream = Nothing
Dim socket As System.Net.Sockets.Socket = Nothing
Dim printerIP As Net.IPEndPoint = Nothing
Dim toSend As Byte()
Try
If printerIP Is Nothing Then
'set the IP address
printerIP = New Net.IPEndPoint(IPAddress.Parse(IP_ADDRESS), 9100)
End If
'Create a TCP socket
socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
'Connect to the printer based on the IP address
socket.Connect(printerIP)
'create a new network stream based on the socket connection
ns = New NetworkStream(socket)
'convert the zpl command to a byte array
toSend = System.Text.Encoding.ASCII.GetBytes(zpl)
'send the zpl byte array over the networkstream to the connected printer
ns.Write(toSend, 0, toSend.Length)
Catch ex As Exception
MessageBox.Show(ex.Message, "Cable Printer", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
Finally
'close the networkstream and then the socket
If Not ns Is Nothing Then
ns.Close()
End If
If Not socket Is Nothing Then
socket.Close()
End If
End Try
End Sub
Private Function createString() As String
Dim command As String
command = "^XA"
command += "^LH20,25"
If rdoSmall.Checked = True Then
command += "^FO1,30^A0,N,25,25^FD"
ElseIf rdoNormal.Checked = True Then
command += "^FO1,30^A0,N,35,35^FD"
Else
command += "^FO1,30^A0,N,50,50^FD"
End If
command += txtInput.Text
command += "^FS"
command += "^XZ"
Return command
End Function
Angular Directive refresh on parameter change
Link function only gets called once, so it would not directly do what you are expecting. You need to use angular $watch
to watch a model variable.
This watch needs to be setup in the link function.
If you use isolated scope for directive then the scope would be
scope :{typeId:'@' }
In your link function then you add a watch like
link: function(scope, element, attrs) {
scope.$watch("typeId",function(newValue,oldValue) {
//This gets called when data changes.
});
}
If you are not using isolated scope use watch on some_prop
How to update/modify an XML file in python?
Useful Python XML parsers:
- Minidom - functional but limited
- ElementTree - decent performance, more functionality
- lxml - high-performance in most cases, high functionality including real xpath support
Any of those is better than trying to update the XML file as strings of text.
What that means to you:
Open your file with an XML parser of your choice, find the node you're interested in, replace the value, serialize the file back out.
Struct inheritance in C++
Other than what Alex and Evan have already stated, I would like to add that a C++ struct is not like a C struct.
In C++, a struct can have methods, inheritance, etc. just like a C++ class.
Find intersection of two nested lists?
We can use set methods for this:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
result = []
for li in c2:
res = set(li) & set(c1)
result.append(list(res))
print result
Counting no of rows returned by a select query
Try wrapping your entire select in brackets, then running a count(*) on that
select count(*)
from
(
select m.id
from Monitor as m
inner join Monitor_Request as mr
on mr.Company_ID=m.Company_id group by m.Company_id
having COUNT(m.Monitor_id)>=5
) myNewTable
Getting the thread ID from a thread
In C# when debugging threads for example, you can see each thread's ID.
This will be the Ids of the managed threads. ManagedThreadId
is a member of Thread
so you can get the Id from any Thread object. This will get you the current ManagedThreadID:
Thread.CurrentThread.ManagedThreadId
To get an OS thread by its OS thread ID (not ManagedThreadID), you can try a bit of linq.
int unmanagedId = 2345;
ProcessThread myThread = (from ProcessThread entry in Process.GetCurrentProcess().Threads
where entry.Id == unmanagedId
select entry).First();
It seems there is no way to enumerate the managed threads and no relation between ProcessThread and Thread, so getting a managed thread by its Id is a tough one.
For more details on Managed vs Unmanaged threading, see this MSDN article.
What is InputStream & Output Stream? Why and when do we use them?
From the Java Tutorial:
A stream is a sequence of data.
A program uses an input stream to read data from a source, one item at a time:
A program uses an output stream to write data to a destination, one item at time:
The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a network socket, or an array.
Sample code from oracle tutorial:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
This program uses byte streams to copy xanadu.txt file to outagain.txt , by writing one byte at a time
Have a look at this SE question to know more details about advanced Character streams, which are wrappers on top of Byte Streams :
byte stream and character stream
How do I set up cron to run a file just once at a specific time?
Your comment suggests you're trying to call this from a programming language. If that's the case, can your program fork a child process that calls sleep then does the work?
What about having your program calculate the number of seconds until the desired runtime, and have it call shell_exec("sleep ${secondsToWait) ; myCommandToRun");
How to select an item from a dropdown list using Selenium WebDriver with java?
public class checkBoxSel {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
EventFiringWebDriver dr = null ;
dr = new EventFiringWebDriver(driver);
dr.get("http://www.google.co.in/");
dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
dr.findElement(By.linkText("Gmail")).click() ;
Select sel = new Select(driver.findElement(By.tagName("select")));
sel.selectByValue("fil");
}
}
I am using GOOGLE LOGIN PAGE to test the seletion option. The above example was to find and select language "Filipino" from the drop down list. I am sure this will solve the problem.
Why is there no Constant feature in Java?
There is a way to create "const" variables in Java, but only for specific classes. Just define a class with final properties and subclass it. Then use the base class where you would want to use "const". Likewise, if you need to use "const" methods, add them to the base class. The compiler will not allow you to modify what it thinks is the final methods of the base class, but it will read and call methods on the subclass.
Can I pass parameters by reference in Java?
Another option is to use an array, e.g.
void method(SomeClass[] v) { v[0] = ...; }
but 1) the array must be initialized before method invoked, 2) still one cannot implement e.g. swap method in this way...
This way is used in JDK, e.g. in java.util.concurrent.atomic.AtomicMarkableReference.get(boolean[])
.
Write bytes to file
Try this:
private byte[] Hex2Bin(string hex)
{
if ((hex == null) || (hex.Length < 1)) {
return new byte[0];
}
int num = hex.Length / 2;
byte[] buffer = new byte[num];
num *= 2;
for (int i = 0; i < num; i++) {
int num3 = int.Parse(hex.Substring(i, 2), NumberStyles.HexNumber);
buffer[i / 2] = (byte) num3;
i++;
}
return buffer;
}
private string Bin2Hex(byte[] binary)
{
StringBuilder builder = new StringBuilder();
foreach(byte num in binary) {
if (num > 15) {
builder.AppendFormat("{0:X}", num);
} else {
builder.AppendFormat("0{0:X}", num); /////// ?? 15 ???? 0
}
}
return builder.ToString();
}
Pandas get topmost n records within each group
Did you try df.groupby('id').head(2)
Ouput generated:
>>> df.groupby('id').head(2)
id value
id
1 0 1 1
1 1 2
2 3 2 1
4 2 2
3 7 3 1
4 8 4 1
(Keep in mind that you might need to order/sort before, depending on your data)
EDIT: As mentioned by the questioner, use df.groupby('id').head(2).reset_index(drop=True)
to remove the multindex and flatten the results.
>>> df.groupby('id').head(2).reset_index(drop=True)
id value
0 1 1
1 1 2
2 2 1
3 2 2
4 3 1
5 4 1
How to exit from Python without traceback?
It's much better practise to avoid using sys.exit() and instead raise/handle exceptions to allow the program to finish cleanly. If you want to turn off traceback, simply use:
sys.trackbacklimit=0
You can set this at the top of your script to squash all traceback output, but I prefer to use it more sparingly, for example "known errors" where I want the output to be clean, e.g. in the file foo.py:
import sys
from subprocess import *
try:
check_call([ 'uptime', '--help' ])
except CalledProcessError:
sys.tracebacklimit=0
print "Process failed"
raise
print "This message should never follow an error."
If CalledProcessError is caught, the output will look like this:
[me@test01 dev]$ ./foo.py
usage: uptime [-V]
-V display version
Process failed
subprocess.CalledProcessError: Command '['uptime', '--help']' returned non-zero exit status 1
If any other error occurs, we still get the full traceback output.
How do you remove a Cookie in a Java Servlet
This is code that I have effectively used before, passing "/"
as the strPath parameter.
public static Cookie eraseCookie(String strCookieName, String strPath) {
Cookie cookie = new Cookie(strCookieName, "");
cookie.setMaxAge(0);
cookie.setPath(strPath);
return cookie;
}
Reading a JSP variable from JavaScript
The cleanest way, as far as I know:
- add your JSP variable to an HTML element's data-* attribute
- then read this value via Javascript when required
My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.
The HTML part without JSP:
<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
Here is your regular page main content
</body>
The HTML part when using JSP:
<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
Here is your regular page main content
</body>
The javascript part (using jQuery for simplicity):
<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
var valuePassedFromJSP = $("body").attr("data-customvalueone");
var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");
alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>
And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/
Resources:
Waiting until two async blocks are executed before starting another block
The first answer is essentially correct, but if you want the very simplest way to accomplish the desired result, here's a stand-alone code example demonstrating how to do it with a semaphore (which is also how dispatch groups work behind the scenes, JFYI):
#include <dispatch/dispatch.h>
#include <stdio.h>
main()
{
dispatch_queue_t myQ = dispatch_queue_create("my.conQ", DISPATCH_QUEUE_CONCURRENT);
dispatch_semaphore_t mySem = dispatch_semaphore_create(0);
dispatch_async(myQ, ^{ printf("Hi I'm block one!\n"); sleep(2); dispatch_semaphore_signal(mySem);});
dispatch_async(myQ, ^{ printf("Hi I'm block two!\n"); sleep(4); dispatch_semaphore_signal(mySem);});
dispatch_async(myQ, ^{ dispatch_semaphore_wait(mySem, DISPATCH_TIME_FOREVER); printf("Hi, I'm the final block!\n"); });
dispatch_main();
}
Passing variables to the next middleware using next() in Express.js
I don't think that best practice will be passing a variable like req.YOUR_VAR
. You might want to consider req.YOUR_APP_NAME.YOUR_VAR
or req.mw_params.YOUR_VAR
.
It will help you avoid overwriting other attributes.
Update May 31, 2020
res.locals is what you're looking for, the object is scoped to the request.
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia
Starting Webcam Video with different browsers
For Opera 12
window.navigator.getUserMedia(param, function(stream) {
video.src =window.URL.createObjectURL(stream);
}, videoError );
For Firefox Nightly 18.0
window.navigator.mozGetUserMedia(param, function(stream) {
video.mozSrcObject = stream;
}, videoError );
For Chrome 22
window.navigator.webkitGetUserMedia(param, function(stream) {
video.src =window.webkitURL.createObjectURL(stream);
}, videoError );
Stopping Webcam Video with different browsers
For Opera 12
video.pause();
video.src=null;
For Firefox Nightly 18.0
video.pause();
video.mozSrcObject=null;
For Chrome 22
video.pause();
video.src="";
With this the Webcam light go down everytime...
How do I know the script file name in a Bash script?
if your invoke shell script like
/home/mike/runme.sh
$0 is full name
/home/mike/runme.sh
basename $0 will get the base file name
runme.sh
and you need to put this basic name into a variable like
filename=$(basename $0)
and add your additional text
echo "You are running $filename"
so your scripts like
/home/mike/runme.sh
#!/bin/bash
filename=$(basename $0)
echo "You are running $filename"
How do you read a CSV file and display the results in a grid in Visual Basic 2010?
Do the following:
Dim dataTable1 As New DataTable
dataTable1.Columns.Add("FECHA")
dataTable1.Columns.Add("TT")
dataTable1.Columns.Add("DESCRIPCION")
dataTable1.Columns.Add("No. DOC")
dataTable1.Columns.Add("DEBE")
dataTable1.Columns.Add("HABER")
dataTable1.Columns.Add("SALDO")
For Each line As String In System.IO.File.ReadAllLines(objetos.url)
dataTable1.Rows.Add(line.Split(","))
Next
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
SQL: Select columns with NULL values only
Or did you want to just see if a column only has NULL values (and, thus, is probably unused)?
Further clarification of the question might help.
EDIT:
Ok.. here's some really rough code to get you going...
SET NOCOUNT ON
DECLARE @TableName Varchar(100)
SET @TableName='YourTableName'
CREATE TABLE #NullColumns (ColumnName Varchar(100), OnlyNulls BIT)
INSERT INTO #NullColumns (ColumnName, OnlyNulls) SELECT c.name, 0 FROM syscolumns c INNER JOIN sysobjects o ON c.id = o.id AND o.name = @TableName AND o.xtype = 'U'
DECLARE @DynamicSQL AS Nvarchar(2000)
DECLARE @ColumnName Varchar(100)
DECLARE @RC INT
SELECT TOP 1 @ColumnName = ColumnName FROM #NullColumns WHERE OnlyNulls=0
WHILE @@ROWCOUNT > 0
BEGIN
SET @RC=0
SET @DynamicSQL = 'SELECT TOP 1 1 As HasNonNulls FROM ' + @TableName + ' (nolock) WHERE ''' + @ColumnName + ''' IS NOT NULL'
EXEC sp_executesql @DynamicSQL
set @RC=@@rowcount
IF @RC=1
BEGIN
SET @DynamicSQL = 'UPDATE #NullColumns SET OnlyNulls=1 WHERE ColumnName=''' + @ColumnName + ''''
EXEC sp_executesql @DynamicSQL
END
ELSE
BEGIN
SET @DynamicSQL = 'DELETE FROM #NullColumns WHERE ColumnName=''' + @ColumnName+ ''''
EXEC sp_executesql @DynamicSQL
END
SELECT TOP 1 @ColumnName = ColumnName FROM #NullColumns WHERE OnlyNulls=0
END
SELECT * FROM #NullColumns
DROP TABLE #NullColumns
SET NOCOUNT OFF
Yes, there are easier ways, but I have a meeting to go to right now. Good luck!
ReportViewer Client Print Control "Unable to load client print control"?
Found a Fix:
First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).
If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.
Download and install the following update:
What is the (function() { } )() construct in JavaScript?
Self-executing anonymous function. It's executed as soon as it is created.
One short and dummy example where this is useful is:
function prepareList(el){
var list = (function(){
var l = [];
for(var i = 0; i < 9; i++){
l.push(i);
}
return l;
})();
return function (el){
for(var i = 0, l = list.length; i < l; i++){
if(list[i] == el) return list[i];
}
return null;
};
}
var search = prepareList();
search(2);
search(3);
So instead of creating a list each time, you create it only once (less overhead).
Stacked Tabs in Bootstrap 3
Left, Right and Below tabs were removed from Bootstrap 3, but you can add custom CSS to achieve this..
.tabs-below > .nav-tabs,
.tabs-right > .nav-tabs,
.tabs-left > .nav-tabs {
border-bottom: 0;
}
.tab-content > .tab-pane,
.pill-content > .pill-pane {
display: none;
}
.tab-content > .active,
.pill-content > .active {
display: block;
}
.tabs-below > .nav-tabs {
border-top: 1px solid #ddd;
}
.tabs-below > .nav-tabs > li {
margin-top: -1px;
margin-bottom: 0;
}
.tabs-below > .nav-tabs > li > a {
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
border-radius: 0 0 4px 4px;
}
.tabs-below > .nav-tabs > li > a:hover,
.tabs-below > .nav-tabs > li > a:focus {
border-top-color: #ddd;
border-bottom-color: transparent;
}
.tabs-below > .nav-tabs > .active > a,
.tabs-below > .nav-tabs > .active > a:hover,
.tabs-below > .nav-tabs > .active > a:focus {
border-color: transparent #ddd #ddd #ddd;
}
.tabs-left > .nav-tabs > li,
.tabs-right > .nav-tabs > li {
float: none;
}
.tabs-left > .nav-tabs > li > a,
.tabs-right > .nav-tabs > li > a {
min-width: 74px;
margin-right: 0;
margin-bottom: 3px;
}
.tabs-left > .nav-tabs {
float: left;
margin-right: 19px;
border-right: 1px solid #ddd;
}
.tabs-left > .nav-tabs > li > a {
margin-right: -1px;
-webkit-border-radius: 4px 0 0 4px;
-moz-border-radius: 4px 0 0 4px;
border-radius: 4px 0 0 4px;
}
.tabs-left > .nav-tabs > li > a:hover,
.tabs-left > .nav-tabs > li > a:focus {
border-color: #eeeeee #dddddd #eeeeee #eeeeee;
}
.tabs-left > .nav-tabs .active > a,
.tabs-left > .nav-tabs .active > a:hover,
.tabs-left > .nav-tabs .active > a:focus {
border-color: #ddd transparent #ddd #ddd;
*border-right-color: #ffffff;
}
.tabs-right > .nav-tabs {
float: right;
margin-left: 19px;
border-left: 1px solid #ddd;
}
.tabs-right > .nav-tabs > li > a {
margin-left: -1px;
-webkit-border-radius: 0 4px 4px 0;
-moz-border-radius: 0 4px 4px 0;
border-radius: 0 4px 4px 0;
}
.tabs-right > .nav-tabs > li > a:hover,
.tabs-right > .nav-tabs > li > a:focus {
border-color: #eeeeee #eeeeee #eeeeee #dddddd;
}
.tabs-right > .nav-tabs .active > a,
.tabs-right > .nav-tabs .active > a:hover,
.tabs-right > .nav-tabs .active > a:focus {
border-color: #ddd #ddd #ddd transparent;
*border-left-color: #ffffff;
}
Working example: http://bootply.com/74926
UPDATE
If you don't need the exact look of a tab (bordered appropriately on the left or right as each tab is activated), you can simple use nav-stacked
, along with Bootstrap col-*
to float the tabs to the left or right...
nav-stacked
demo: http://codeply.com/go/rv3Cvr0lZ4
<ul class="nav nav-pills nav-stacked col-md-3">
<li><a href="#a" data-toggle="tab">1</a></li>
<li><a href="#b" data-toggle="tab">2</a></li>
<li><a href="#c" data-toggle="tab">3</a></li>
</ul>
How to make blinking/flashing text with CSS 3
Late but wanted to add a new one with more keyframes ... here is an example on CodePen since there was an issue with the built-in code snippets:
_x000D_
_x000D_
.block{_x000D_
display:inline-block;_x000D_
padding:30px 50px;_x000D_
background:#000;_x000D_
}_x000D_
.flash-me {_x000D_
color:#fff;_x000D_
font-size:40px;_x000D_
-webkit-animation: flash linear 1.7s infinite;_x000D_
animation: flash linear 1.7s infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes flash {_x000D_
0% { opacity: 0; } _x000D_
80% { opacity: 1; color:#fff; } _x000D_
83% { opacity: 0; color:#fff; } _x000D_
86% { opacity: 1; color:#fff;} _x000D_
89% { opacity: 0} _x000D_
92% { opacity: 1; color:#fff;} _x000D_
95% { opacity: 0; color:#fff;}_x000D_
100% { opacity: 1; color:#fff;}_x000D_
}_x000D_
@keyframes flash {_x000D_
0% { opacity: 0; } _x000D_
80% { opacity: 1; color:#fff; } _x000D_
83% { opacity: 0; color:#fff; } _x000D_
86% { opacity: 1; color:#fff;} _x000D_
89% { opacity: 0} _x000D_
92% { opacity: 1; color:#fff;} _x000D_
95% { opacity: 0; color:#fff;}_x000D_
100% { opacity: 1; color:#fff;}_x000D_
}
_x000D_
<span class="block">_x000D_
<span class="flash-me">Flash Me Hard</span>_x000D_
</span>
_x000D_
_x000D_
_x000D_
CSS Circle with border
Here is a jsfiddle so you can see an example of this working.
HTML code:
<div class="circle"></div>
CSS code:
_x000D_
_x000D_
.circle {_x000D_
/*This creates a 1px solid red border around your element(div) */_x000D_
border:1px solid red;_x000D_
background-color: #FFFFFF;_x000D_
height: 100px;_x000D_
/* border-radius 50% will make it fully rounded. */_x000D_
border-radius: 50%;_x000D_
-moz-border-radius:50%;_x000D_
-webkit-border-radius: 50%;_x000D_
width: 100px;_x000D_
}
_x000D_
<div class='circle'></div>
_x000D_
_x000D_
_x000D_
LINQ Using Max() to select a single row
I don't see why you are grouping here.
Try this:
var maxValue = table.Max(x => x.Status)
var result = table.First(x => x.Status == maxValue);
An alternate approach that would iterate table
only once would be this:
var result = table.OrderByDescending(x => x.Status).First();
This is helpful if table
is an IEnumerable<T>
that is not present in memory or that is calculated on the fly.
java.net.URL read stream to byte[]
Here's a clean solution:
private byte[] downloadUrl(URL toDownload) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
byte[] chunk = new byte[4096];
int bytesRead;
InputStream stream = toDownload.openStream();
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return outputStream.toByteArray();
}
Could not open ServletContext resource
try with this code...
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>/social.properties</value>
</list>
</property>
</bean>
Is there a difference between "==" and "is"?
There is a simple rule of thumb to tell you when to use ==
or is
.
==
is for value equality. Use it when you would like to know if two objects have the same value.
is
is for reference equality. Use it when you would like to know if two references refer to the same object.
In general, when you are comparing something to a simple type, you are usually checking for value equality, so you should use ==
. For example, the intention of your example is probably to check whether x has a value equal to 2 (==
), not whether x
is literally referring to the same object as 2.
Something else to note: because of the way the CPython reference implementation works, you'll get unexpected and inconsistent results if you mistakenly use is
to compare for reference equality on integers:
>>> a = 500
>>> b = 500
>>> a == b
True
>>> a is b
False
That's pretty much what we expected: a
and b
have the same value, but are distinct entities. But what about this?
>>> c = 200
>>> d = 200
>>> c == d
True
>>> c is d
True
This is inconsistent with the earlier result. What's going on here? It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. Here's an example demonstrating this:
>>> for i in range(250, 260): a = i; print "%i: %s" % (i, a is int(str(i)));
...
250: True
251: True
252: True
253: True
254: True
255: True
256: True
257: False
258: False
259: False
This is another obvious reason not to use is
: the behavior is left up to implementations when you're erroneously using it for value equality.
Plotting in a non-blocking way with Matplotlib
You can avoid blocking execution by writing the plot to an array, then displaying the array in a different thread. Here is an example of generating and displaying plots simultaneously using pf.screen from pyformulas 0.2.8:
import pyformulas as pf
import matplotlib.pyplot as plt
import numpy as np
import time
fig = plt.figure()
canvas = np.zeros((480,640))
screen = pf.screen(canvas, 'Sinusoid')
start = time.time()
while True:
now = time.time() - start
x = np.linspace(now-2, now, 100)
y = np.sin(2*np.pi*x) + np.sin(3*np.pi*x)
plt.xlim(now-2,now+1)
plt.ylim(-3,3)
plt.plot(x, y, c='black')
# If we haven't already shown or saved the plot, then we need to draw the figure first...
fig.canvas.draw()
image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
screen.update(image)
#screen.close()
Result:
Disclaimer: I'm the maintainer for pyformulas.
Reference: Matplotlib: save plot to numpy array
How do I extract the contents of an rpm?
Most distributions have installed the GUI app file-roller which unpacks tar, zip, rpm and many more.
file-roller --extract-here package.rpm
This will extract the contents in the current directory.
C# - Print dictionary
There are so many ways to do this, here is some more:
string.Join(Environment.NewLine, dictionary.Select(a => $"{a.Key}: {a.Value}"))
dictionary.Select(a => $"{a.Key}: {a.Value}{Environment.NewLine}")).Aggregate((a,b)=>a+b)
new String(dictionary.SelectMany(a => $"{a.Key}: {a.Value} {Environment.NewLine}").ToArray())
Additionally, you can then use one of these and encapsulate it in an extension method:
public static class DictionaryExtensions
{
public static string ToReadable<T,V>(this Dictionary<T, V> d){
return string.Join(Environment.NewLine, d.Select(a => $"{a.Key}: {a.Value}"));
}
}
And use it like this: yourDictionary.ToReadable()
.
Checking the form field values before submitting that page
use return before calling the function, while you click the submit button, two events(form posting as you used submit button and function call for onclick) will happen, to prevent form posting you have to return false, you have did it, also you have to specify the return i.e, to expect a value from the function,
this is a code:
input type="submit" name="continue" value="submit" onClick="**return** checkform();"
Arduino IDE can't find ESP8266WiFi.h file
When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.
Open Arduino IDE and go to files and click on the preference in the Arduino IDE.
Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.
Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.
You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.
How to add data into ManyToMany field?
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
I need to convert an int variable to double
Either use casting as others have already said, or multiply one of the int variables by 1.0
:
double firstSolution = ((1.0* b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));
PHP parse/syntax errors; and how to solve them
Unexpected '='
This can be caused by having invalid characters in a variable name. Variables names must follow these rules:
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
final keyword in method parameters
final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense
How to specify line breaks in a multi-line flexbox layout?
_x000D_
_x000D_
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.item {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: gold;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
</div>_x000D_
<div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
</div>_x000D_
<div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
</div>_x000D_
<div class="item">10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
you could try wrapping the items in a dom element like here. with this you dont have to know a lot of css just having a good structure will solve the problem.
What is polymorphism, what is it for, and how is it used?
In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.
Export javascript data to CSV file without server interaction
@adeneo answer works for Firefox and chrome... For IE the below can be used.
_x000D_
_x000D_
if (window.navigator.msSaveOrOpenBlob) {_x000D_
var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
type: "text/csv;charset=utf-8;"_x000D_
});_x000D_
navigator.msSaveBlob(blob, 'FileName.csv');_x000D_
}
_x000D_
_x000D_
_x000D_
How to create a md5 hash of a string in C?
All of the existing answers use the deprecated MD5Init()
, MD5Update()
, and MD5Final()
.
Instead, use EVP_DigestInit_ex()
, EVP_DigestUpdate()
, and EVP_DigestFinal_ex()
, e.g.
// example.c
//
// gcc example.c -lssl -lcrypto -o example
#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>
void bytes2md5(const char *data, int len, char *md5buf) {
// Based on https://www.openssl.org/docs/manmaster/man3/EVP_DigestUpdate.html
EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
const EVP_MD *md = EVP_md5();
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len, i;
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, data, len);
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_free(mdctx);
for (i = 0; i < md_len; i++) {
snprintf(&(md5buf[i * 2]), 16 * 2, "%02x", md_value[i]);
}
}
int main(void) {
const char *hello = "hello";
char md5[33]; // 32 characters + null terminator
bytes2md5(hello, strlen(hello), md5);
printf("%s\n", md5);
}
Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues
To anyone else who tried most of the solutions and still having problems.
My solution is different from the others, which is located at the bottom of this post, but before you try it make sure you have exhausted the following lists. To be sure, I have tried all of them but to no avail.
Recompile and redeploy from scratch, don't update the existing app. SO Answer
Grant IIS_IUSRS full access to the directory "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files"
Keep in mind the framework version you are using. If your app is using impersonation, use that identity instead of IIS_IUSRS
Delete all contents of the directory "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files".
Keep in mind the framework version you are using
Change the identity of the AppPool that your app is using, from ApplicatonPoolIdentity to NetworkService.
IIS > Application Pools > Select current app pool > Advance Settings > Identity.
SO Answer (please restore to default if it doesn't work)
Verify IIS Version and AppPool .NET version compatibility with your app. Highly applicable to first time deployments. SO Answer
Verify impersonation configuration if applicable. SO Answer
My Solution:
I found out that certain anti-virus softwares are actively blocking compilations of DLLs within the directory "Temporary ASP.NET Files", mine was McAfee, the IT people failed to notify me of the installation.
As per advice by both McAfee experts and Microsoft, you need to exclude the directory "Temporary ASP.NET Files" in the real time scanning.
Sources:
Don't disable the Anti-Virus because it is only doing its job. Don't manually copy missing DLL files in the directory \Temporary ASP.NET Files{project name} because thats duct taping.
PUT and POST getting 405 Method Not Allowed Error for Restful Web Services
The problem is that POST method is forbidden for Nginx server's static files requests. Here is the workaround:
# Pass 405 as 200 for requested address:
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 404 /404.html;
error_page 403 /403.html;
error_page 405 =200 $uri;
}
If using proxy:
# If Nginx is like proxy for Apache:
error_page 405 =200 @405;
location @405 {
root /htdocs;
proxy_pass http://localhost:8080;
}
If using FastCGI:
location ~\.php(.*) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include /etc/nginx/fastcgi_params;
}
Browsers usually use GET, so you can use online tools like ApiTester to test your requests.
Source
how to load CSS file into jsp
css href link is incorrect. Use relative path instead:
<link href="../css/loginstyle.css" rel="stylesheet" type="text/css">
Changing the git user inside Visual Studio Code
I had the same problem as Daniel, setting the commit address and unsetting the credentials helper also worked for me.
git config --global user.email '<git-commit-address>'
git config --global --unset credential.helper
Dynamically Add Images React Webpack
If you are looking for a way to import all your images from the image
// Import all images in image folder
function importAll(r) {
let images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
return images;
}
const images = importAll(require.context('../images', false, /\.(gif|jpe?g|svg)$/));
Then:
<img src={images['image-01.jpg']}/>
You can find the original thread here: Dynamically import images from a directory using webpack
Python Save to file
In order to write into a file in Python, we need to open it in write w
, append a
or exclusive creation x
mode.
We need to be careful with the w
mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.
with open('Failed.py','w',encoding = 'utf-8') as f:
f.write("Write what you want to write in\n")
f.write("this file\n\n")
This program will create a new file named Failed.py
in the current directory if it does not exist. If it does exist, it is overwritten.
We must include the newline characters ourselves to distinguish the different lines.
How to echo xml file in php
The best solution is to add to your apache .htaccess
file the following line after RewriteEngine On
RewriteRule ^sitemap\.xml$ sitemap.php [L]
and then simply having a file sitemap.php
in your root folder that would be normally accessible via http://www.yoursite.com/sitemap.xml
, the default URL where all search engines will firstly search.
The file sitemap.php
shall start with
<?php
//Saturday, 11 January 2020 @kevin
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>https://www.yoursite.com/</loc>
<lastmod>2020-01-08T13:06:14+00:00</lastmod>
<priority>1.00</priority>
</url>
</urlset>
it works :)
Pass accepts header parameter to jquery ajax
You had already identified the accepts parameter as the one you wanted and keyur is right in showing you the correct way to set it, but if you set DataType to "json" then it will automatically set the default value of accepts to the value you want as per the jQuery reference. So all you need is:
jQuery.ajax({
url: _this.attr('href'),
dataType: "json"
});
Can we have multiple "WITH AS" in single sql - Oracle SQL
Yes you can...
WITH SET1 AS (SELECT SYSDATE FROM DUAL), -- SET1 initialised
SET2 AS (SELECT * FROM SET1) -- SET1 accessed
SELECT * FROM SET2; -- SET2 projected
10/29/2013 10:43:26 AM
Follow the order in which it should be initialized in Common Table Expressions
Checking for the correct number of arguments
You can check the total number of arguments which are passed in command line with "$#
"
Say for Example my shell script name is hello.sh
sh hello.sh hello-world
# I am passing hello-world as argument in command line which will b considered as 1 argument
if [ $# -eq 1 ]
then
echo $1
else
echo "invalid argument please pass only one argument "
fi
Output will be hello-world
Remove insignificant trailing zeros from a number?
I needed to solve this problem too when Django was displaying Decimal type values in a text field. E.g. when '1' was the value. It would show '1.00000000'. If '1.23' was the value, it would show '1.23000000' (In the case of a 'decimal_places' setting of 8)
Using parseFloat was not an option for me since it is possible it does not return the exact same value. toFixed was not an option since I did not want to round anything, so I created a function:
function removeTrailingZeros(value) {
value = value.toString();
# if not containing a dot, we do not need to do anything
if (value.indexOf('.') === -1) {
return value;
}
# as long as the last character is a 0 or a dot, remove it
while((value.slice(-1) === '0' || value.slice(-1) === '.') && value.indexOf('.') !== -1) {
value = value.substr(0, value.length - 1);
}
return value;
}
Is it possible to run .APK/Android apps on iPad/iPhone devices?
The app can't be run natively, but it could be run on an emulator. You can use ManyMo to embed them in a website and make users add your app to their home screen. This link should be useful for making the app more realistic. Users could then only press the share button and add the app to their home screen. All data will be deleted when the "app" is closed in their iOS devices so you should use the Internet/cloud for storage. It can't access camera or multi touch, but it may be useful.
iOS - Calling App Delegate method from ViewController
You can access the delegate like this:
MainClass *appDelegate = (MainClass *)[[UIApplication sharedApplication] delegate];
Replace MainClass with the name of your application class.
Then, provided you have a property for the other view controller, you can call something like:
[appDelegate.viewController someMethod];