I use
SELECT st.NAME, sc.NAME, sc.system_type_id
FROM sys.tables st
INNER JOIN sys.columns sc ON st.object_id = sc.object_id
WHERE st.name LIKE '%Tablename%'
Copy your SDK folder and paste it in another folder without spaces (for example: "D: / Android / Sdk"), then open the SDK Manager, and change the Android SDK Location to the location of your new SDK folder
I create this Methode and call it by closing the application:
public void deleteFiles(){
File f = new File("log");
File[] fileArray = f.listFiles();
double timenow = System.currentTimeMillis();
double olderTenDays = timenow - 864000000;// MS for ten days
for (int i = 0; i < fileArray.length; i++) {
if(fileArray[i].lastModified()< olderTenDays )
fileArray[i].delete();
}
}
I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.
Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.
You could do below:
select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20,
iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30,
iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40,
50 ) ) ) as commission
from table
It is possible with PowerShell 4.
Get-Service *spool* | select name,starttype | ft -AutoSize
.erb-image-wrapper img{
max-width:100% !important;
height:auto;
display:block;
}
Worked for me.
Thanks for MrMisterMan for his assistance.
That was happened when i suddenly renamed class of old migration that already exist in db. I checked VCS history, determined that and renamed back. All worked afterwards.
I've been trying to achieve something really simple and failed miserably, probably I'm stupid.
Anyway, if you have a script/Dockerfile
which download a python package zip file (e.g. from GitHub) and you then want to install it you can use the file:///
prefix to install it as shown in the following example:
$ wget https://example.com/mypackage.zip
$ echo "${MYPACKAGE_MD5} mypackage.zip" | md5sum --check -
$ pip install file:///.mypackage.zip
NOTE: I know you could install the package straight away using pip install https://example.com/mypackage.zip
but in my case I wanted to verify the checksum (never paranoid enough) and I failed miserably when trying to use the various options that pip provides/the #md5
fragment.
It's been surprisingly frustrating to do something so simple directly with pip
. I just wanted to pass a checksum and have pip
verify that the zip was matching before installing it.
I was probably doing something very stupid but in the end I gave up and opted for this. I hope it helps others trying to do something similar.
object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
You can also use select(2) if you want microsecond precision (this works on platform that don't have usleep(3))
The following code will wait for 1.5 second:
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>`
int main() {
struct timeval t;
t.tv_sec = 1;
t.tv_usec = 500000;
select(0, NULL, NULL, NULL, &t);
}
`
Because you can break out of a do/while loop, let us "do" one round. With a while(false) at the end, the condition is never true and will not repeat, again.
do
{
$subjectText = trim(filter_input(INPUT_POST, 'subject'));
if(!$subjectText)
{
$smallInfo = 'Please give a subject.';
break;
}
$messageText = trim(filter_input(INPUT_POST, 'message'));
if(!$messageText)
{
$smallInfo = 'Please supply a message.';
break;
}
} while(false);
The easiest way is:
var oldstr="Angular isn't easy";
var newstr=oldstr.toString().replace("isn't","is");
alos check the level of access to the shared drive. if the access to the shared drive is read only the file will open in read only format.
You can do this:
If your tomcat installation is default and you have not done any changes, then the default war will be ROOT.war
. Thus whenever you will call http://yourserver.example.com/
, it will call the index.html
or index.jsp
of your default WAR file. Make the following changes in your webapp/ROOT
folder for redirecting requests to http://yourserver.example.com/somewhere/else
:
Open webapp/ROOT/WEB-INF/web.xml
,
remove any servlet mapping with path /index.html
or /index.jsp
,
and save.
Remove webapp/ROOT/index.html
, if it exists.
Create the file webapp/ROOT/index.jsp
with this line of content:
<% response.sendRedirect("/some/where"); %>
or if you want to direct to a different server,
<% response.sendRedirect("http://otherserver.example.com/some/where"); %>
That's it.
well.. even though this is outdated, let me add my 2 cents here :-)
class ConstDict(dict):
def __init__(self, *args, **kwargs):
super(ConstDict, self).__init__(*args, **kwargs)
def __setitem__(self, key, value):
if key in self:
raise ValueError("Value %s already exists" % (key))
super(ConstDict, self).__setitem__(key, value)
Instead of ValueError to break, you can prevent any update happening there. One advantage of this is that you can add constants dynamically in the program but you cannot change once a constant is set. Also you can add any rule or whatsoever before setting a constant(something like key must be a string or a lower case string or upper case string and so on before setting the key)
However, I do not see any importance of setting constants in Python. No optimizations can happen like in C and hence it is something that is not required, I guess.
It works if id value and name value are different:
<input type="password" class="form-control"name="password" id="mainpassword">
password: { required: true, } ,
cpassword: {required: true, equalTo: '#mainpassword' },
try ppretty:
from ppretty import ppretty
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
print ppretty(Animal(), seq_length=10)
Output:
__main__.Animal(age = 10, color = 'Spotted', kids = 0, legs = 2, name = 'Dog', smell = 'Alot')
Get all the outdated packages and create a batch file with the following commands pip install xxx --upgrade for each outdated packages
For latest browser, like Chrome, you can use the File API as in this tutorial:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 5*1024*1024 /*5MB*/, saveFile, errorHandler);
Just as an alternative, you can use ancestor
.
//*[title="50"]/ancestor::store
It's more powerful than parent
since it can get even the grandparent or great great grandparent
The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.
15.1.2 UAS Behavior==> BYE Handling in RFC 3261
The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.
First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]
Basically this question has the title ...Visual Studio 2012 / 2013
What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.
So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj
project. Now this computer does not yet have sql server installed on it yet.
Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates
Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.
In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396
SELECT SUBSTRING(subject, 1, 10) FROM tbl
Ascx-files are called User Controls and are meant for reusability and also for making complex aspx-pages less complex (lift out some part of the page). They could also be beneficial for something called donut caching, that is when you would like to cache a certain part of a page.
If triangle.lborderA
is indeed a long then the test in the original code is trivially true, and there is no way to test it. It is also useless.
However, if triangle.lborderA
is a double, the comparison is useful and can be tested. isBiggerThanMaxLong(1e300)
does return true.
public static boolean isBiggerThanMaxLong(double in){
return in > Long.MAX_VALUE;
}
I got this error when I only updated the jquery library without updating the jqueryui library in parallel. I was using jquery 1.8.3 with jqueryui 1.9.0. However, when I updated jquery 1.8.3 to 1.9.1 I got the above error. When I commented out the offending .close
method lines, it then threw an error about not finding .browser
in the jquery library which was deprecated in jquery 1.8.3 and removed from jquery 1.9.1. So bascially, the jquery 1.9.1 library was not compatible with the jquery ui 1.9.0 library despite the jquery ui download page saying it works with jquery 1.6+. Essentially, there are unreported bugs when trying to use differing versions of the two. If you use the jquery version that comes bundled with the jqueryui download, I'm sure you'll be fine, but it's when you start using different versions that you off the beaten path and get errors like this. So, in summary, this error is from mis-matched versions (in my case anyway).
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
after passing the vector by reference
swap(vector[position],vector[otherPosition]);
will produce the expected result.
As others said, if means nothing as of C++14, so let's consider the __restrict__
GCC extension which does the same as the C99 restrict
.
C99
restrict
says that two pointers cannot point to overlapping memory regions. The most common usage is for function arguments.
This restricts how the function can be called, but allows for more compile optimizations.
If the caller does not follow the restrict
contract, undefined behavior.
The C99 N1256 draft 6.7.3/7 "Type qualifiers" says:
The intended use of the restrict qualifier (like the register storage class) is to promote optimization, and deleting all instances of the qualifier from all preprocessing translation units composing a conforming program does not change its meaning (i.e., observable behavior).
and 6.7.3.1 "Formal definition of restrict" gives the gory details.
A possible optimization
The Wikipedia example is very illuminating.
It clearly shows how as it allows to save one assembly instruction.
Without restrict:
void f(int *a, int *b, int *x) {
*a += *x;
*b += *x;
}
Pseudo assembly:
load R1 ? *x ; Load the value of x pointer
load R2 ? *a ; Load the value of a pointer
add R2 += R1 ; Perform Addition
set R2 ? *a ; Update the value of a pointer
; Similarly for b, note that x is loaded twice,
; because x may point to a (a aliased by x) thus
; the value of x will change when the value of a
; changes.
load R1 ? *x
load R2 ? *b
add R2 += R1
set R2 ? *b
With restrict:
void fr(int *restrict a, int *restrict b, int *restrict x);
Pseudo assembly:
load R1 ? *x
load R2 ? *a
add R2 += R1
set R2 ? *a
; Note that x is not reloaded,
; because the compiler knows it is unchanged
; "load R1 ? *x" is no longer needed.
load R2 ? *b
add R2 += R1
set R2 ? *b
Does GCC really do it?
g++
4.8 Linux x86-64:
g++ -g -std=gnu++98 -O0 -c main.cpp
objdump -S main.o
With -O0
, they are the same.
With -O3
:
void f(int *a, int *b, int *x) {
*a += *x;
0: 8b 02 mov (%rdx),%eax
2: 01 07 add %eax,(%rdi)
*b += *x;
4: 8b 02 mov (%rdx),%eax
6: 01 06 add %eax,(%rsi)
void fr(int *__restrict__ a, int *__restrict__ b, int *__restrict__ x) {
*a += *x;
10: 8b 02 mov (%rdx),%eax
12: 01 07 add %eax,(%rdi)
*b += *x;
14: 01 06 add %eax,(%rsi)
For the uninitiated, the calling convention is:
rdi
= first parameterrsi
= second parameterrdx
= third parameterGCC output was even clearer than the wiki article: 4 instructions vs 3 instructions.
Arrays
So far we have single instruction savings, but if pointer represent arrays to be looped over, a common use case, then a bunch of instructions could be saved, as mentioned by supercat and michael.
Consider for example:
void f(char *restrict p1, char *restrict p2, size_t size) {
for (size_t i = 0; i < size; i++) {
p1[i] = 4;
p2[i] = 9;
}
}
Because of restrict
, a smart compiler (or human), could optimize that to:
memset(p1, 4, size);
memset(p2, 9, size);
Which is potentially much more efficient as it may be assembly optimized on a decent libc implementation (like glibc) Is it better to use std::memcpy() or std::copy() in terms to performance?, possibly with SIMD instructions.
Without, restrict, this optimization could not be done, e.g. consider:
char p1[4];
char *p2 = &p1[1];
f(p1, p2, 3);
Then for
version makes:
p1 == {4, 4, 4, 9}
while the memset
version makes:
p1 == {4, 9, 9, 9}
Does GCC really do it?
GCC 5.2.1.Linux x86-64 Ubuntu 15.10:
gcc -g -std=c99 -O0 -c main.c
objdump -dr main.o
With -O0
, both are the same.
With -O3
:
with restrict:
3f0: 48 85 d2 test %rdx,%rdx
3f3: 74 33 je 428 <fr+0x38>
3f5: 55 push %rbp
3f6: 53 push %rbx
3f7: 48 89 f5 mov %rsi,%rbp
3fa: be 04 00 00 00 mov $0x4,%esi
3ff: 48 89 d3 mov %rdx,%rbx
402: 48 83 ec 08 sub $0x8,%rsp
406: e8 00 00 00 00 callq 40b <fr+0x1b>
407: R_X86_64_PC32 memset-0x4
40b: 48 83 c4 08 add $0x8,%rsp
40f: 48 89 da mov %rbx,%rdx
412: 48 89 ef mov %rbp,%rdi
415: 5b pop %rbx
416: 5d pop %rbp
417: be 09 00 00 00 mov $0x9,%esi
41c: e9 00 00 00 00 jmpq 421 <fr+0x31>
41d: R_X86_64_PC32 memset-0x4
421: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
428: f3 c3 repz retq
Two memset
calls as expected.
without restrict: no stdlib calls, just a 16 iteration wide loop unrolling which I do not intend to reproduce here :-)
I haven't had the patience to benchmark them, but I believe that the restrict version will be faster.
Strict aliasing rule
The restrict
keyword only affects pointers of compatible types (e.g. two int*
) because the strict aliasing rules says that aliasing incompatible types is undefined behavior by default, and so compilers can assume it does not happen and optimize away.
See: What is the strict aliasing rule?
Does it work for references?
According to the GCC docs it does: https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Restricted-Pointers.html with syntax:
int &__restrict__ rref
There is even a version for this
of member functions:
void T::fn () __restrict__
Actually, drop rows 0 and 1 only requires (any observations containing matched A and C is kept.):
In [335]:
df['AC']=df.A+df.C
In [336]:
print df.drop_duplicates('C', take_last=True) #this dataset is a special case, in general, one may need to first drop_duplicates by 'c' and then by 'a'.
A B C AC
2 foo 1 B fooB
3 bar 1 A barA
[2 rows x 4 columns]
But I suspect what you really want is this (one observation containing matched A and C is kept.):
In [337]:
print df.drop_duplicates('AC')
A B C AC
0 foo 0 A fooA
2 foo 1 B fooB
3 bar 1 A barA
[3 rows x 4 columns]
Now it is much clearer, therefore:
In [352]:
DG=df.groupby(['A', 'C'])
print pd.concat([DG.get_group(item) for item, value in DG.groups.items() if len(value)==1])
A B C
2 foo 1 B
3 bar 1 A
[2 rows x 3 columns]
A lot of great answers here...
Let me add another alternative:
import { interval } from "rxjs";
import { takeUntil } from "rxjs/operators";
import { Component } from "@angular/core";
import { Destroyable } from "@bespunky/angular-zen/core";
@Component({
selector: 'app-no-leak-demo',
template: ' Destroyable component rendered. Unload me and watch me cleanup...'
})
export class NoLeakComponent extends Destroyable
{
constructor()
{
super();
this.subscribeToInterval();
}
private subscribeToInterval(): void
{
const value = interval(1000);
const observer = {
next : value => console.log(` Destroyable: ${value}`),
complete: () => console.log(' Observable completed.')
};
// ==== Comment one and uncomment the other to see the difference ====
// Subscribe using the inherited subscribe method
this.subscribe(value, observer);
// ... or pipe-in the inherited destroyed subject
//value.pipe(takeUntil(this.destroyed)).subscribe(observer);
}
}
The component/service extends Destroyable
(which comes from a library called @bespunky/angular-zen
).
The class can now simply use this.subscribe()
or takeUntil(this.destroyed)
without any additional boilerplate code.
To install the library use:
> npm install @bespunky/angular-zen
In addition of github/hub
, which acts as a proxy to Git, you now (February 2020) have cli/cli
:
See "Supercharge your command line experience: GitHub CLI is now in beta"
Create a pull request
Create a branch, make several commits to fix the bug described in the issue, and use gh to create a pull request to share your contribution.
By using GitHub CLI to create pull requests, it also automatically creates a fork when you don’t already have one, and it pushes your branch and creates your pull request to get your change merged.
And in April 2020: "GitHub CLI now supports autofilling pull requests and custom configuration"
GitHub CLI 0.7 is out with several of the most highly requested enhancements from the feedback our beta users have provided.
Since the last minor release, 0.6, there are three main features:
- Configure
gh
to use your preferred editor withgh config set editor [editor]
.- Configure
gh
to default to SSH withgh config set git_protocol ssh
.
The default Git protocol is HTTPS.- Autofill the title and body of a pull request from your commits with
gh pr create --fill
.
So:
gh pr create --fill
Here is an example I think that will help you
<!DOCTYPE html>
<html>
<head>
<script src="js/min.js"></script>
<script src="js/pdf.js"></script>
<script>
$(function(){
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
var table = tableToJson($('#StudentInfoListTable').get(0))
var doc = new jsPDF('p','pt', 'a4', true);
doc.cellInitialize();
$.each(table, function (i, row){
console.debug(row);
$.each(row, function (j, cell){
doc.cell(10, 50,120, 50, cell, i); // 2nd parameter=top margin,1st=left margin 3rd=row cell width 4th=Row height
})
})
doc.save('sample-file.pdf');
});
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=0; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
});
</script>
</head>
<body>
<div id="table">
<table id="StudentInfoListTable">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Track</th>
<th>S.S.C Roll</th>
<th>S.S.C Division</th>
<th>H.S.C Roll</th>
<th>H.S.C Division</th>
<th>District</th>
</tr>
</thead>
<tbody>
<tr>
<td>alimon </td>
<td>Email</td>
<td>1</td>
<td>2222</td>
<td>as</td>
<td>3333</td>
<td>dd</td>
<td>33</td>
</tr>
</tbody>
</table>
<button id="cmd">Submit</button>
</body>
</html>
Here the output
Use a secure URL for your initial connection, i.e. instead of "http://" use "https://". If the WebSocket transport is chosen, then Socket.IO should automatically use "wss://" (SSL) for the WebSocket connection too.
Update:
You can also try creating the connection using the 'secure' option:
var socket = io.connect('https://localhost', {secure: true});
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
Using QPainter
and QImage
to paint on a window-widget (QMainWindow
) (just another method)
class MainWindow : public QMainWindow
{
public:
MainWindow();
protected:
void paintEvent(QPaintEvent* event) override;
protected:
QImage image = QImage("/path/to/image.jpg");
};
// for convenience resize window to image size
MainWindow::MainWindow()
{
setMinimumSize(image.size());
}
void MainWindow::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
QRect rect = event->rect();
painter.drawImage(rect, image, rect);
}
int main(int argc, char** argv)
{
QApplication a(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return a.exec();
}
I have written a class to handle common functions for working with the binomial coefficient, which is the type of problem that your problem falls under. It performs the following tasks:
Outputs all the K-indexes in a nice format for any N choose K to a file. The K-indexes can be substituted with more descriptive strings or letters. This method makes solving this type of problem quite trivial.
Converts the K-indexes to the proper index of an entry in the sorted binomial coefficient table. This technique is much faster than older published techniques that rely on iteration. It does this by using a mathematical property inherent in Pascal's Triangle. My paper talks about this. I believe I am the first to discover and publish this technique, but I could be wrong.
Converts the index in a sorted binomial coefficient table to the corresponding K-indexes.
Uses Mark Dominus method to calculate the binomial coefficient, which is much less likely to overflow and works with larger numbers.
The class is written in .NET C# and provides a way to manage the objects related to the problem (if any) by using a generic list. The constructor of this class takes a bool value called InitTable that when true will create a generic list to hold the objects to be managed. If this value is false, then it will not create the table. The table does not need to be created in order to perform the 4 above methods. Accessor methods are provided to access the table.
There is an associated test class which shows how to use the class and its methods. It has been extensively tested with 2 cases and there are no known bugs.
To read about this class and download the code, see Tablizing The Binomial Coeffieicent.
It should not be hard to convert this class to C++.
Update: This is no longer a bug or a workaround, it is required if your app targets API Level 28 (Android 9.0) or above and uses the Google Maps SDK for Android 16.0.0 or below (or if your app uses the Apache HTTP Legacy library). It is now included in the official docs. The public issue has been closed as intended behavior.
This is a bug on the Google Play Services side, until it's fixed, you should be able to workaround by adding this to your AndroidManifest.xml
inside the <application>
tag:
<uses-library android:name="org.apache.http.legacy" android:required="false" />
I recently needed to do this as well... here's how I got to it:
$_product->getMediaGalleryImages()->getItemByColumnValue('label', 'LABEL_NAME')->getUrl();
Hope that helps you!
Use this code to click:
$("#gift-close").click();
The following function should do what you want exactly:
hush=function(code){
sink("NUL") # use /dev/null in UNIX
tmp = code
sink()
return(tmp)
}
For example with the function here:
foo=function(){
print("BAR!")
return(42)
}
running
x = hush(foo())
Will assign 42 to x but will not print "BAR!" to STDOUT
Note than in a UNIX OS you will need to replace "NUL" with "/dev/null"
A double primitive in Java can never be null. It will be initialized to 0.0 if no value has been given for it (except when declaring a local double variable and not assigning a value, but this will produce a compile-time error).
More info on default primitive values here.
If the order of element is not important, you can
select
id, elem, row_number() over (partition by id) as nr
from (
select
id,
unnest(string_to_array(elements, ',')) AS elem
from myTable
) a
Here is a safe and reusable function for adding script to head section if its not already exist there.
see working example here: Example
<!DOCTYPE html>
<html>
<head>
<base href="/"/>
<style>
</style>
</head>
<body>
<input type="button" id="" style='width:250px;height:50px;font-size:1.5em;' value="Add Script" onClick="addScript('myscript')"/>
<script>
function addScript(filename)
{
// house-keeping: if script is allready exist do nothing
if(document.getElementsByTagName('head')[0].innerHTML.toString().includes(filename + ".js"))
{
alert("script is allready exist in head tag!")
}
else
{
// add the script
loadScript('/',filename + ".js");
}
}
function loadScript(baseurl,filename)
{
var node = document.createElement('script');
node.src = baseurl + filename;
document.getElementsByTagName('head')[0].appendChild(node);
alert("script added");
}
</script>
</body>
</html>
Here is something that i have been trying.(Insertion sort- not the best way to sort but does the work)
def sort(list):
for index in range(1,len(list)):
value = list[index]
i = index-1
while i>=0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i -= 1
else:
break
Late to the party, but why use third party for such a simple problem?
You could either do it as @Huw Davies mentioned - the best way
1. <i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>
2. <i className={[styles['foo-bar-baz'], 'fa fa-user', 'fa-2x'].join(' ')}
Both are good. But writing can become complex for a large app. To make it optimal, I do the same above things but put it in a helper class
Using my below helper function, allows me to keep the logic separate for future editing, and also gives me multiple ways to add the classes
classNames(styles['foo-bar-baz], 'fa fa-user', 'fa-2x')
or
classNames([styles['foo-bar-baz], 'fa fa-user', 'fa-2x'])
This is my helper function below. I've put it in a helper.js where I keep all my common methods. Being such a simple function, I avoided using 3rd party to keep control
export function classNames (classes) {
if(classes && classes.constructor === Array) {
return classes.join(' ')
} else if(arguments[0] !== undefined) {
return [...arguments].join(' ')
}
return ''
}
Surprised no one mentioned:
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
Sounds like you only installed the MySQL Client Tools (MySQL Workbench). You have to install the MySQL Database server, configure and start it.
http://dev.mysql.com/downloads/
You probably want the MySQL Community Server download.
Your problem looks like you are mixing DML & DDL operations. See this URL which explains this issue:
To check if the index is defined: isset($something['say'])
Note that GCC has an extension to the designated initializer notation which is very useful for the context. It is also allowed by clang
without comment (in part because it tries to be compatible with GCC).
The extension notation allows you to use ...
to designate a range of elements to be initialized with the following value. For example:
#include <stdio.h>
enum { ROW = 5, COLUMN = 10 };
int array[ROW][COLUMN] = { [0 ... ROW-1] = { [0 ... COLUMN-1] = 1 } };
int main(void)
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COLUMN; j++)
printf("%2d", array[i][j]);
putchar('\n');
}
return 0;
}
The output is, unsurprisingly:
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
Note that Fortran 66 (Fortran IV) had repeat counts for initializers for arrays; it's always struck me as odd that C didn't get them when designated initializers were added to the language. And Pascal uses the 0..9
notation to designate the range from 0 to 9 inclusive, but C doesn't use ..
as a token, so it is not surprising that was not used.
Note that the spaces around the ...
notation are essentially mandatory; if they're attached to numbers, then the number is interpreted as a floating point number. For example, 0...9
would be tokenized as 0.
, .
, .9
, and floating point numbers aren't allowed as array subscripts.
With the named constants, ...ROW-1
would not cause trouble, but it is better to get into the safe habits.
Addenda:
I note in passing that GCC 7.3.0 rejects:
int array[ROW][COLUMN] = { [0 ... ROW-1] = { [0 ... COLUMN-1] = { 1 } } };
where there's an extra set of braces around the scalar initializer 1
(error: braces around scalar initializer [-Werror]
). I'm not sure that's correct given that you can normally specify braces around a scalar in int a = { 1 };
, which is explicitly allowed by the standard. I'm not certain it's incorrect, either.
I also wonder if a better notation would be [0]...[9]
— that is unambiguous, cannot be confused with any other valid syntax, and avoids confusion with floating point numbers.
int array[ROW][COLUMN] = { [0]...[4] = { [0]...[9] = 1 } };
Maybe the standards committee would consider that?
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
<?php
for ($i=0; $i < 100; $i++) {
if (i%2 == 0) {
include(do_this_for_even.php);
}
else {
include(do_this_for_odd.php);
}
}
?>
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here
I think this should point you towards the right direction:
import java.beans.*
for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
System.out.println(pd.getReadMethod().invoke(foo));
}
Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for
// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);
However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.
Here is one approach. ifelse
is vectorized and it checks all rows for zero values of b
and replaces est
with (a - 5)/2.53
if that is the case.
df <- transform(df, est = ifelse(b == 0, (a - 5)/2.53, est))
Another issue i faced with was, ssh.exe was not looking at the %userprofile%/.ssh
folder for the key files. Instead it was looking to the folder C:\Program Files (x86)\Git\.ssh
which was empty and which causes a hang due to ssh authentication prompt on the machine where git repo located.
We just copied the key files under %userprofile%/.ssh
to C:\Program Files (x86)\Git\.ssh
and the problem is resolved.
Take a look at example and do in similar way
(sorce from http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/):
ssh.connect('127.0.0.1', username='jesse',
password='lol')
stdin, stdout, stderr = ssh.exec_command(
"sudo dmesg")
stdin.write('lol\n')
stdin.flush()
data = stdout.read.splitlines()
for line in data:
if line.split(':')[0] == 'AirPort':
print line
does mail.exampleserver.com exist ??? , if not try the following code (you must have gmail account)
$mail->SMTPSecure = "ssl";
$mail->Host='smtp.gmail.com';
$mail->Port='465';
$mail->Username = '[email protected]'; // SMTP account username
$mail->Password = 'your gmail password';
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->CharSet = 'utf-8';
$mail->SMTPDebug = 0;
Like others mentioned, CPython can use threads only for I/O waits due to GIL.
If you want to benefit from multiple cores for CPU-bound tasks, use multiprocessing:
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
You can use typeof
, like this:
if (typeof something != "undefined") {
// ...
}
If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width
CSS property.
You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:
<div id="container" style="float: left">
<div id="spacer" style="height: 1px; width: 300px"></div>
<button>Button 1 text</button>
<button>Button 2 text</button>
</div>
The earth is an annoyingly irregular surface, so there is no simple formula to do this exactly. You have to live with an approximate model of the earth, and project your coordinates onto it. The model I typically see used for this is WGS 84. This is what GPS devices usually use to solve the exact same problem.
NOAA has some software you can download to help with this on their website.
There might be times when you explicitly want to only assign the click handler to objects which already exist, and handle new objects differently. But more commonly, live doesn't always work. It doesn't work with chained jQuery statements such as:
$(this).children().live('click',doSomething);
It needs a selector to work properly because of the way events bubble up the DOM tree.
Edit: Someone just upvoted this, so obviously people are still looking at it. I should point out that live
and bind
are both deprecated. You can perform both with .on()
, which IMO is a much clearer syntax. To replace bind
:
$(selector).on('click', function () {
...
});
and to replace live
:
$(document).on('click', selector, function () {
...
});
Instead of using $(document)
, you can use any jQuery object which contains all the elements you're monitoring the clicks on, but the corresponding element must exist when you call it.
As per your request I have put this in an answer for you.
As Hieu Nguyen suggested in his answer, you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:
Everything else is described in the documentation linked above. Happy coding!
P.S. Here is an example that should work. (I have not tested)
Front end:
<script type="text/javascript">
jQuery.ajax({
url: ajaxurl,
data: {
action: 'my_action_name'
},
type: 'GET'
});
</script>
Back end:
<?php
function my_ajax_callback_function() {
// Implement ajax function here
}
add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' ); // If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' ); // If called from front end
?>
UPDATE Even though this is an old answer, it seems to keep getting thumbs up from people - which is great! I think this may be of use to some people.
WordPress has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:
var translation = {
success: "Success!",
failure: "Failure!",
error: "Error!",
...
};
So this simply loads an object into the HTML head tag. This can be utilized in the following way:
Backend:
wp_localize_script( 'FrontEndAjax', 'ajax', array(
'url' => admin_url( 'admin-ajax.php' )
) );
The advantage of this method is that it may be used in both themes AND plugins, as you are not hard-coding the ajax URL variable into the theme.
On the front end, the URL is now accessible via ajax.url
, rather than simply ajaxurl
in the previous examples.
Too many constructors is a sign of a broken design. Better a class with few constructors and the ability to set properties. If you really need control over the properties, consider a factory in the same namespace and make the property setters internal. Let the factory decide how to instantiate the class and set its properties. The factory can have methods that take as many parameters as necessary to configure the object properly.
string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
The way I resolved this was setup error logs correctly, first
<VirtualHost *:80>
DocumentRoot "D:/websites/test/"
ServerName test.dev
ErrorLog "D:/websites/test/logs/error.log"
CustomLog "D:/websites/test/logs/access.log" common
<Directory D:/websites/test/>
AllowOverride none
Require all granted
</Directory>
</VirtualHost>
After this error are being logged into "D:/websites/test/logs/" make sure to create logs folder yourself. The exact error that was recorded in error log was
AH01630: client denied by server configuration:
Which pointed me to correct solution using this link which said for the above error
Require all granted
is required. My sample sample code above fixes the problem by the way.
Select a Random sample from a tibble type in R:
library("tibble")
a <- your_tibble[sample(1:nrow(your_tibble), 150),]
nrow takes a tibble and returns the number of rows. The first parameter passed to sample
is a range from 1 to the end of your tibble. The second parameter passed to sample, 150, is how many random samplings you want. The square bracket slicing specifies the rows of the indices returned. Variable 'a' gets the value of the random sampling.
@Erik's answer didn't fly for me.
Following did:
@Html.TextBoxFor(m => m.ShortName, new { data_val_required = "You need me" })
plus doing this manually under field I had to add error message container
@Html.ValidationMessageFor(m => m.ShortName, null, new { @class = "field-validation-error", data_valmsg_for = "ShortName" })
Hope this saves you some time.
Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss
).
Also, you need to specify H
instead of h
if you are using 24 hour times:
DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)
See here for more information:
If you want to localize string later, then those answers aren't enough, I would suggest something like:
<TextBlock>
<Hyperlink NavigateUri="http://labsii.com/">
<Hyperlink.Inlines>
<Run Text="Click here"/>
</Hyperlink.Inlines>
</Hyperlink>
</TextBlock>
I use something like this
>>> import datetime
>>> regex = datetime.datetime.strptime
>>>
>>> # TEST
>>> assert regex('2020-08-03', '%Y-%m-%d')
>>>
>>> assert regex('2020-08', '%Y-%m-%d')
ValueError: time data '2020-08' does not match format '%Y-%m-%d'
>>> assert regex('08/03/20', '%m/%d/%y')
>>>
>>> assert regex('08-03-2020', '%m/%d/%y')
ValueError: time data '08-03-2020' does not match format '%m/%d/%y'
We can prove it mathematically which is something I was missing in the above answers.
It can dramatically help you understand how to calculate any method. I recommend reading it from top to bottom to fully understand how to do it:
T(n) = T(n-1) + 1
It means that the time it takes for the method to finish is equal to the same method but with n-1 which is T(n-1)
and we now add + 1
because it's the time it takes for the general operations to be completed (except T(n-1)
).
Now, we are going to find T(n-1)
as follow: T(n-1) = T(n-1-1) + 1
. It looks like we can now form a function that can give us some sort of repetition so we can fully understand. We will place the right side of T(n-1) = ...
instead of T(n-1)
inside the method T(n) = ...
which will give us: T(n) = T(n-1-1) + 1 + 1
which is T(n) = T(n-2) + 2
or in other words we need to find our missing k
: T(n) = T(n-k) + k
. The next step is to take n-k
and claim that n-k = 1
because at the end of the recursion it will take exactly O(1) when n<=0
. From this simple equation we now know that k = n - 1
. Let's place k
in our final method: T(n) = T(n-k) + k
which will give us: T(n) = 1 + n - 1
which is exactly n
or O(n)
.O(n)
.T(n) = T(n/5) + 1
as before, the time for this method to finish equals to the time the same method but with n/5
which is why it is bounded to T(n/5)
. Let's find T(n/5)
like in 1: T(n/5) = T(n/5/5) + 1
which is T(n/5) = T(n/5^2) + 1
.
Let's place T(n/5)
inside T(n)
for the final calculation: T(n) = T(n/5^k) + k
. Again as before, n/5^k = 1
which is n = 5^k
which is exactly as asking what in power of 5, will give us n, the answer is log5n = k
(log of base 5). Let's place our findings in T(n) = T(n/5^k) + k
as follow: T(n) = 1 + logn
which is O(logn)
T(n) = 2T(n-1) + 1
what we have here is basically the same as before but this time we are invoking the method recursively 2 times thus we multiple it by 2. Let's find T(n-1) = 2T(n-1-1) + 1
which is T(n-1) = 2T(n-2) + 1
. Our next place as before, let's place our finding: T(n) = 2(2T(n-2)) + 1 + 1
which is T(n) = 2^2T(n-2) + 2
that gives us T(n) = 2^kT(n-k) + k
. Let's find k
by claiming that n-k = 1
which is k = n - 1
. Let's place k
as follow: T(n) = 2^(n-1) + n - 1
which is roughly O(2^n)
T(n) = T(n-5) + n + 1
It's almost the same as 4 but now we add n
because we have one for
loop. Let's find T(n-5) = T(n-5-5) + n + 1
which is T(n-5) = T(n - 2*5) + n + 1
. Let's place it: T(n) = T(n-2*5) + n + n + 1 + 1)
which is T(n) = T(n-2*5) + 2n + 2)
and for the k: T(n) = T(n-k*5) + kn + k)
again: n-5k = 1
which is n = 5k + 1
that is roughly n = k
. This will give us: T(n) = T(0) + n^2 + n
which is roughly O(n^2)
.I now recommend reading the rest of the answers which now, will give you a better perspective. Good luck winning those big O's :)
for specific tag name
$ docker images --filter reference='<REPOSITORY>:TAG'
for "like clause" tagname:my_image_tag --> start my_ima*
$ docker images --filter reference='<REPOSITORY>:my_ima*'
if you want to someting "the image" for example delete all images tag started "my_ima" try this
docker rmi -f $(docker images -q --filter reference='myreponame:my_ima*')
It's pretty straightforward using [
to extract:
grep
will give you the position in which it matched your search pattern (unless you use value = TRUE
).
grep("^G45", My.Data$x)
# [1] 2
Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [
(where you would use My.Data[rows, cols]
to get specific rows and columns).
My.Data[grep("^G45", My.Data$x), ]
# x y
# 2 G459 2
The help-page for subset
shows how you can use grep
and grepl
with subset
if you prefer using this function over [
. Here's an example.
subset(My.Data, grepl("^G45", My.Data$x))
# x y
# 2 G459 2
As of R 3.3, there's now also the startsWith
function, which you can again use with subset
(or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring
or grepl
.
subset(My.Data, startsWith(as.character(x), "G45"))
# x y
# 2 G459 2
Yield: It is a hint (not guaranteed) to the scheduler that you have done enough and that some other thread of same priority might run and use the CPU.
Thread.sleep();
Sleep: It blocks the execution of that particular thread for a given time.
TimeUnit.MILLISECONDS.sleep(1000);
I know this is a late entry but even in 2016 I am surprised by the complete lack of IE support for flex (currently 11 is the only one to support it and its majorly buggy at that http://caniuse.com/#feat=flexbox) which from a business perspective is not great! So I think until IE is shut down the best solution and most cross-browser friendly one surely must be a JS/Jquery one?
Most sites already use Jquery and a very simple example (for my code) is:
$('#auto_height_item').height($(window).height() - $('#header').height());
You can obviously replace window and header and let the basic math do the work. Personally I'm still not convinced about flex yet...
Based on GetForegroundWindow function | Microsoft Docs:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowTextLength(IntPtr hWnd);
private string GetCaptionOfActiveWindow()
{
var strTitle = string.Empty;
var handle = GetForegroundWindow();
// Obtain the length of the text
var intLength = GetWindowTextLength(handle) + 1;
var stringBuilder = new StringBuilder(intLength);
if (GetWindowText(handle, stringBuilder, intLength) > 0)
{
strTitle = stringBuilder.ToString();
}
return strTitle;
}
It supports UTF8 characters.
If you see the 5 folders (Include
,Lib
,Scripts
,tcl
,pip-selfcheck
) after using the virtualenv yourenvname
command, change directory to Scripts
folder in the cmd itself and simply use "activate" command.
If []byte is ASCII byte numbers then first convert the []byte to string and use the strconv
package Atoi
method which convert string to int.
package main
import (
"fmt"
"strconv"
)
func main() {
byteNumber := []byte("14")
byteToInt, _ := strconv.Atoi(string(byteNumber))
fmt.Println(byteToInt)
}
go playground - https://play.golang.org/p/gEzxva8-BGP
Split the screen and run command term ++curwin
to run the terminal inside the Vim buffer. Following command does both and worked for me:
:bo 10sp | term ++curwin
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
From the spring boot docs https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
YAML lists are represented as property keys with [index] dereferencers, for example this YAML:
my:
servers:
- dev.bar.com
- foo.bar.com
Would be transformed into these properties:
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
To bind to properties like that using the Spring DataBinder utilities (which is what @ConfigurationProperties
does) you need to have a property in the target bean of type java.util.List
and you either need to provide a setter, or initialize it with a mutable value, e.g. this will bind to the properties above. Here is what the question's code would look like.
@ConfigurationProperties(prefix="ignore")
public class Filenames {
private List<String> ignoredFilenames = new ArrayList<String>();
public List<String> getFilenames() {
return this.ignoredFilenames;
}
}
If you need to set your width or height to match_parent
(as big as its parent) or wrap_content
(large enough to fit its own internal content), then ViewGroup.LayoutParams
has this two constants:
imageView.setLayoutParams(
new ViewGroup.LayoutParams(
// or ViewGroup.LayoutParams.WRAP_CONTENT
ViewGroup.LayoutParams.MATCH_PARENT,
// or ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.MATCH_PARENT ) );
Or you can set them like in Hakem Zaied's answer:
imageView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
//...
Open the Command Palette
Ctrl + Shift + P
Then type:
Reload Window
The following snippet will return the public ip of the remote machine and also default ip(i.e: LAN)
This will print ip's in quotes also to avoid confusion in using config files.
>> main.yml_x000D_
_x000D_
---_x000D_
- hosts: localhost_x000D_
tasks:_x000D_
- name: ipify_x000D_
ipify_facts:_x000D_
- debug: var=hostvars[inventory_hostname]['ipify_public_ip']_x000D_
- debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']_x000D_
- name: template_x000D_
template:_x000D_
src: debug.j2_x000D_
dest: /tmp/debug.ansible_x000D_
_x000D_
>> templates/debug.j2_x000D_
_x000D_
public_ip={{ hostvars[inventory_hostname]['ipify_public_ip'] }}_x000D_
public_ip_in_quotes="{{ hostvars[inventory_hostname]['ipify_public_ip'] }}"_x000D_
_x000D_
default_ipv4={{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}_x000D_
default_ipv4_in_quotes="{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"
_x000D_
$("input").click(function(){
var name = $(this).attr("name");
$('input[name="' + name + '"]').hide();
});
Also works with ID:
var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();
when, (sometimes)
$('input#' + id).hide();
does not work, as it should.
You can even do both:
$('input[name="' + name + '"][id="' + id + '"]').hide();
This is very simple in LinQ... You can use the select statement to get an Enumerable of properties of the objects.
var mySkus = myLines.Select(x => x.Sku);
Or if you want it as an Array just do...
var mySkus = myLines.Select(x => x.Sku).ToArray();
I haven't seen any answer with this one yet...
public static string[] Split(this string value, string regexPattern)
{
return value.Split(regexPattern, RegexOptions.None);
}
public static string[] Split(this string value, string regexPattern,
RegexOptions options)
{
return Regex.Split(value, regexPattern, options);
}
Usage:
var obj = "test1,test2,test3";
string[] arrays = obj.Split(",");
It is not true that quicksort is better. ALso, it depends on what you mean better, memory consumption, or speed.
In terms of memory consumption, in worst case, but quicksort can use n^2 memory (i.e. each partition is 1 to n-1), whereas merge sort uses nlogn.
The above follows in terms of speed.
Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)
Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
If myDataGridView.SelectedRows.Count > 0 Then
'you may want to add a confirmation message, and if the user confirms delete
myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
Else
MessageBox.Show("Select 1 row before you hit Delete")
End If
End Sub
Note that this will not delete the row form the database until you perform the delete in the database.
According to the previous answers, it seems that mathematically, we simply think in a higher order. Instead of thinking a value x having type X, we think of a function x: T ? X, where T is the type of time, be it the natural numbers, the integers or the continuum. Now when we write y := x + 1 in the programming language, we actually mean the equation y(t) = x(t) + 1.
What if modifying the markup isn't an option?
Here's a solution that has no requirements for a wrapper: it uses an SVG in a background-image. You may need to use an HTML entity decoder to understand how to change the fill colour.
-moz-appearance: none;
-webkit-appearance: none;
appearance: none;
background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23000000%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E');
background-repeat: no-repeat;
background-position: right .7em top 50%;
background-size: .65em auto;
Pinched from CSS-Tricks.
Bootstrap 4 progress bar
<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Javascript
change progress bar on next/previous page actions
var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');
This is an old post but...
You can reference the working directory (the folder the .html file is located in) with ./
, and the directory above that with ../
Example directory structure:
/html/public/
- index.html
- script2.js
- js/
- script.js
To load script.js from inside index.html:
<script type="text/javascript" src="./js/script.js">
This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.
You could also specify ../
to go one directory above the working directory, to load things from there. But that is unusual.
You can use length to see if your selector matched anything.
if ($('#MyId').length) {
// do your stuff
}
You can simply add the below code in onchange and it will detect change. you can write a function on X click or something to remove file data..
document.getElementById(id).value = "";
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection
, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection
to HttpURLConnection
, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create
, not having point.c will cause the compilation to fail.
I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:
gcc point.c testpoint.c
As others have pointed out, you also need to remove one of your main
functions, since you can only have one.
All the other solutions require you to know the format in advance. I needed to detect(!) the format in every case and this is what I end up with.
function detectFloat(source) {
let float = accounting.unformat(source);
let posComma = source.indexOf(',');
if (posComma > -1) {
let posDot = source.indexOf('.');
if (posDot > -1 && posComma > posDot) {
let germanFloat = accounting.unformat(source, ',');
if (Math.abs(germanFloat) > Math.abs(float)) {
float = germanFloat;
}
} else {
// source = source.replace(/,/g, '.');
float = accounting.unformat(source, ',');
}
}
return float;
}
This was tested with the following cases:
const cases = {
"0": 0,
"10.12": 10.12,
"222.20": 222.20,
"-222.20": -222.20,
"+222,20": 222.20,
"-222,20": -222.20,
"-2.222,20": -2222.20,
"-11.111,20": -11111.20,
};
Suggestions welcome.
use buildSrc with Gradle Kotlin DSL see full worked example here: GitHub daggerok/spring-fu-jafu-example buildSrc/src/main/java/Globals.kt
If everything is fine with your ConnectionString
check your DbSet collection name in you db context file. If that and database table names aren't matching you will also get this error.
So, for example, Categories, Products
public class ProductContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
should match with actual database table names:
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
I came here with the same requirements but @lvc and @Preet's answers seems more inline with what column -t
produces in that columns have different widths:
>>> rows = [ ['a', 'b', 'c', 'd']
... , ['aaaaaaaaaa', 'b', 'c', 'd']
... , ['a', 'bbbbbbbbbb', 'c', 'd']
... ]
...
>>> widths = [max(map(len, col)) for col in zip(*rows)]
>>> for row in rows:
... print " ".join((val.ljust(width) for val, width in zip(row, widths)))
...
a b c d
aaaaaaaaaa b c d
a bbbbbbbbbb c d
Note to other people finding this: The heart of the solution to make nginx not manipulate the URL, is to remove the slash at the end of the Copy: proxy_pass directive. http://my_app_upstream vs http://my_app_upstream/ – Hugo Josefson
I found this above in the comments but I think it really should be an answer.
Just add autofocus
in first input or textarea.
<input type="text" name="name" id="xax" autofocus="autofocus" />
One can use PrintWriter
to wrap the FileWriter
, as it has many additional useful methods.
try(PrintWriter pw = new PrintWriter(new FileWriter(new File("file.txt"), false))){
pw.println();//new line
pw.print("text");//print without new line
pw.println(10);//print with new line
pw.printf("%2.f", 0.567);//print double to 2 decimal places (without new line)
}
If you're using Blend, to make it extra easy and not have any trouble getting the correct path for the Source attribute, just drag and drop the image from the Project panel onto the designer.
This saves you having to duplicate the link in the tr - just fish it out of the first a.
$(".link-first-found").click(function() {
var href;
href = $(this).find("a").attr("href");
if (href !== "") {
return document.location = href;
}
});
Recommendedations from the Python 2.7 docs for the time
module
I think that you are looking for the ngCloak
directive: https://docs.angularjs.org/api/ng/directive/ngCloak
From the documentation:
The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.
The directive can be applied to the
<body>
element, but the preferred usage is to apply multiplengCloak
directives to small portions of the page to permit progressive rendering of the browser view
Try changing your deployment target to something higher than an armv6 processor. The settings for xCode are referencing the operating system level, for instance: iOS version#{3.1, 3.2, 4.0, 4.1, 4.2, 4.3, 5.0, 5.1}
(i)You can set this in the build settings tab or the summary tab. Start at the top left of the window in the Project Navigator, with all the files listed in it. Click the top-most one which has a blue icon.
(ii)If you are planning on using the programmable shader line circuitry, which is accessed and controlled through openGL ES 2.0 API, then you should set your "Deployment Version" to about 4.3, which I believe is only available on devices such as the 3GS or newer. xCode is reporting that iOS 4.2.5 or higher is needed run armv7 code. And once again, this processor, I believe, started with the 3GS.* iOS 4.3 seems to be the choice for me, for now.
you can do this in different ways:
see here for more details on the second case:
http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14
and here for details on the last case:
A good weekly update to the Ruby on Rails world: Rails Envy.
The thestacktrace is good general programming podcast, which covers every thing from git to Scala.
I would like to add a design pattern that has been applied in Android Framework. This is Half Sync Half Async pattern used in the Asynctask implementation. See my discussion at
https://docs.google.com/document/d/1_zihWXAwgTAdJc013-bOLUHPMrjeUBZnDuPkzMxEEj0/edit?usp=sharing
obj={};
$.each(obj, function (key, value) {
console.log(key+ ' : ' + value); //push the object value
});
for (var i in obj) {
nameList += "" + obj[i] + "";//display the object value
}
$("id/class").html($(nameList).length);//display the length of object.
Truth be told there are many, many resources explaining how to do this already out on the web:
Git: how to reverse-merge a commit?
Git: how to reverse-merge a commit?
Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)
So I guess I'll just summarize some of these:
git revert <merge commit hash>
This creates an extra "revert" commit saying you undid a merge
git reset --hard <commit hash *before* the merge>
This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick
them on to afterwards.
But honestly this guide here is better than anything I can explain, with diagrams! :)
Well, found a solution to my problem; Updating all rows using a SQL query and a SQL Task in SSIS Like Below. May help others if they face same challenge in future.
update Original
set Original.Vaal= t.vaal
from Original join (select * from staging1 union select * from staging2) t
on Original.id=t.id
Back in computer class in high school, myself and a couple of friends taught the class how to program with Delphi. The class was mostly focused on programming with Pascal, so Delphi was a good next step. We demonstrated the event driven nature of Delphi and its RAD capabilities. At the end of the lesson we showed the class a sample application and asked them to reproduce it. The application asked "Are you drunk?" with two buttons Yes and No. ...I think you know what is coming next...the No button changed locations on mouse over and was almost impossible to click.
The students and teacher got a good kick out of it.
The program only required a few lines of user-written code with a simple equation to calculate where to move the button. I don't think any of the other students figured it out, but a few were close.
in case if your table has tbody
let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)
Yes, LINQ to Objects supports this with Enumerable.Concat
:
var together = first.Concat(second);
NB: Should first
or second
be null you would receive a ArgumentNullException
. To avoid this & treat nulls as you would an empty set, use the null coalescing operator like so:
var together = (first ?? Enumerable.Empty<string>()).Concat(second ?? Enumerable.Empty<string>()); //amending `<string>` to the appropriate type
You could use the TIMEDIFF()
and the TIME_TO_SEC()
functions as follows:
SELECT TIME_TO_SEC(TIMEDIFF('2010-08-20 12:01:00', '2010-08-20 12:00:00')) diff;
+------+
| diff |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
You could also use the UNIX_TIMESTAMP()
function as @Amber suggested in an other answer:
SELECT UNIX_TIMESTAMP('2010-08-20 12:01:00') -
UNIX_TIMESTAMP('2010-08-20 12:00:00') diff;
+------+
| diff |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
If you are using the TIMESTAMP
data type, I guess that the UNIX_TIMESTAMP()
solution would be slightly faster, since TIMESTAMP
values are already stored as an integer representing the number of seconds since the epoch (Source). Quoting the docs:
When
UNIX_TIMESTAMP()
is used on aTIMESTAMP
column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.Keep in mind that
TIMEDIFF()
return data type ofTIME
.TIME
values may range from '-838:59:59' to '838:59:59' (roughly 34.96 days)
The URI to open a specific channel in Slack app is:
slack://channel?id=<CHANNEL-ID>&team=<TEAM-ID>
You will probably need these resources of the Slack API to get IDs of your team and channel:
Here's the full documentation from Slack
Your going to need CURL for that task I'm afraid. Nice easy way to do it here: http://davidwalsh.name/execute-http-post-php-curl
Hope that helps
Change your data to that formats to use sqlite datetime formats.
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD
SELECT * FROM test WHERE date BETWEEN '2011-01-11' AND '2011-08-11'
since 2 images are getting uploaded! one with file extension and other file without extension. to delete tmp_path (file without extension)
after
src.pipe(dest);
add below code
fs.unlink(tmp_path); //deleting the tmp_path
Once you have the flattened DataFrame
obtained by the accepted answer, you can make the columns a MultiIndex
("fancy multiline header") like this:
df.columns = pd.MultiIndex.from_tuples([tuple(c.split('.')) for c in df.columns])
remap
is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:
:map
and :noremap
are recursive and non-recursive versions of the various mapping commands. For example, if we run:
:map j gg (moves cursor to first line)
:map Q j (moves cursor to first line)
:noremap W j (moves cursor down one line)
Then:
j
will be mapped to gg
.Q
will also be mapped to gg
, because j
will be expanded for the recursive mapping.W
will be mapped to j
(and not to gg
) because j
will not be expanded for the non-recursive mapping.Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.
For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map
and :noremap
), one that works in normal mode (:nmap
and :nnoremap
), one in visual mode (:vmap
and :vnoremap
) and so on.
For more guidance on this, see:
:help :map
:help :noremap
:help recursive_mapping
:help :map-modes
Old Answer (July 2016):
You can't directly debug Chrome for iOS due to restrictions on the published WKWebView
apps, but there are a few options already discussed in other SO threads:
If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.
WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.
You could try and create a simple WKWebView
browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.
There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView
, Chrome for iOS would be debuggable.
Update January 2018:
Since my answer back in 2016, some work has been done to improve things.
There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.
Check out the getting started guide in the repo, which is quite detailed.
If you are interesting, you can read up on the background and architecture here.
Your code looks pretty good.
Be careful, however, for your call to Range("H5")
is a shortcut command to Application.Range("H5")
, which is equivalent to Application.ActiveSheet.Range("H5")
. This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.
With this in mind, I would utilize Target.Worksheet.Range("H5")
:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub
Or you can use Me.Range("H5")
, if the event handler is on the code page for the worksheet in question (it usually is):
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub
Hope this helps...
On debian where bsd-mailx
is installed by default, the -r
option does not work. However you can use mailx -s subject [email protected] -- -f [email protected]
instead. According to man page, you can specify sendmail options after --
.
The best option I've found was using the savetxt
from the numpy
module:
import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)
In case you have multiple lists that need to be stacked
np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)
The 'script' command under Unix should do the trick. Just run it at the start of your new console and you should be good.
net stop w32time
w32tm /config /syncfromflags:manual /manualpeerlist:"0.it.pool.ntp.org 1.it.pool.ntp.org 2.it.pool.ntp.org 3.it.pool.ntp.org"
net start w32time
w32tm /config /update
w32tm /resync /rediscover
.BAT Sample File: https://gist.github.com/thedom85/dbeb58627adfb3d5c3af
I also recommend this program: http://www.timesynctool.com/
@CommonsWare's answer doesn't not actually work. I found that this is working properly :
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.88,151.21), 15));
Regarding Fred the Fantastic's answer:
Not every JPEG marker between C0
-CF
are SOF
markers; I excluded DHT (C4
), DNL (C8
) and DAC (CC
). Note that I haven't looked into whether it is even possible to parse any frames other than C0
and C2
in this manner. However, the other ones seem to be fairly rare (I personally haven't encountered any other than C0
and C2
).
Either way, this solves the problem mentioned in comments by Malandy with Bangles.jpg
(DHT erroneously parsed as SOF).
The other problem mentioned with 1431588037-WgsI3vK.jpg
is due to imghdr
only being able detect the APP0 (EXIF) and APP1 (JFIF) headers.
This can be fixed by adding a more lax test to imghdr (e.g. simply FFD8
or maybe FFD8FF
?) or something much more complex (possibly even data validation). With a more complex approach I've only found issues with: APP14 (FFEE
) (Adobe); the first marker being DQT (FFDB
); and APP2 and issues with embedded ICC_PROFILEs.
Revised code below, also altered the call to imghdr.what()
slightly:
import struct
import imghdr
def test_jpeg(h, f):
# SOI APP2 + ICC_PROFILE
if h[0:4] == '\xff\xd8\xff\xe2' and h[6:17] == b'ICC_PROFILE':
print "A"
return 'jpeg'
# SOI APP14 + Adobe
if h[0:4] == '\xff\xd8\xff\xee' and h[6:11] == b'Adobe':
return 'jpeg'
# SOI DQT
if h[0:4] == '\xff\xd8\xff\xdb':
return 'jpeg'
imghdr.tests.append(test_jpeg)
def get_image_size(fname):
'''Determine the image type of fhandle and return its size.
from draco'''
with open(fname, 'rb') as fhandle:
head = fhandle.read(24)
if len(head) != 24:
return
what = imghdr.what(None, head)
if what == 'png':
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
return
width, height = struct.unpack('>ii', head[16:24])
elif what == 'gif':
width, height = struct.unpack('<HH', head[6:10])
elif what == 'jpeg':
try:
fhandle.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf or ftype in (0xc4, 0xc8, 0xcc):
fhandle.seek(size, 1)
byte = fhandle.read(1)
while ord(byte) == 0xff:
byte = fhandle.read(1)
ftype = ord(byte)
size = struct.unpack('>H', fhandle.read(2))[0] - 2
# We are at a SOFn block
fhandle.seek(1, 1) # Skip `precision' byte.
height, width = struct.unpack('>HH', fhandle.read(4))
except Exception: #IGNORE:W0703
return
else:
return
return width, height
Note: Created a full answer instead of a comment, since I'm not yet allowed to.
Set rs = me.RecordsetClone
rs.Bookmark = me.Bookmark
Do
rs.movenext
Loop until rs.eof
You could subtract the total length from the count of non-nan values:
count_nan = len(df) - df.count()
You should time it on your data. For small Series got a 3x speed up in comparison with the isnull
solution.
(2018) the new python requests library has simplified this process, we can use the 'files' variable to signal that we want to upload a multipart-encoded file
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
r.text
easiest way:
Dim newBook As Workbook
Set newBook = Workbooks.Add
Sheets("Sheet1").Copy Before:=newBook.Sheets(1)
If you hava a fact png (1MB for 400x400 etc.):
__import__("importlib").import_module("PIL.Image").open("out.png").save("out.png")
A working method in android to populates the mapping list mime types.
private static void fileMimeTypeMapping() {
MIMETYPE_MAPPING.put("3gp", Collections.list("video/3gpp"));
MIMETYPE_MAPPING.put("7z", Collections.list("application/x-7z-compressed"));
MIMETYPE_MAPPING.put("accdb", Collections.list("application/msaccess"));
MIMETYPE_MAPPING.put("ai", Collections.list("application/illustrator"));
MIMETYPE_MAPPING.put("apk", Collections.list("application/vnd.android.package-archive"));
MIMETYPE_MAPPING.put("arw", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("avi", Collections.list("video/x-msvideo"));
MIMETYPE_MAPPING.put("bash", Collections.list("text/x-shellscript"));
MIMETYPE_MAPPING.put("bat", Collections.list("application/x-msdos-program"));
MIMETYPE_MAPPING.put("blend", Collections.list("application/x-blender"));
MIMETYPE_MAPPING.put("bin", Collections.list("application/x-bin"));
MIMETYPE_MAPPING.put("bmp", Collections.list("image/bmp"));
MIMETYPE_MAPPING.put("bpg", Collections.list("image/bpg"));
MIMETYPE_MAPPING.put("bz2", Collections.list("application/x-bzip2"));
MIMETYPE_MAPPING.put("cb7", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cba", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cbr", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cbt", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cbtc", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cbz", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cc", Collections.list("text/x-c"));
MIMETYPE_MAPPING.put("cdr", Collections.list("application/coreldraw"));
MIMETYPE_MAPPING.put("class", Collections.list("application/java"));
MIMETYPE_MAPPING.put("cnf", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("conf", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("cpp", Collections.list("text/x-c++src"));
MIMETYPE_MAPPING.put("cr2", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("css", Collections.list("text/css"));
MIMETYPE_MAPPING.put("csv", Collections.list("text/csv"));
MIMETYPE_MAPPING.put("cvbdl", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("c", Collections.list("text/x-c"));
MIMETYPE_MAPPING.put("c++", Collections.list("text/x-c++src"));
MIMETYPE_MAPPING.put("dcr", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("deb", Collections.list("application/x-deb"));
MIMETYPE_MAPPING.put("dng", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("doc", Collections.list("application/msword"));
MIMETYPE_MAPPING.put("docm", Collections.list("application/vnd.ms-word.document.macroEnabled.12"));
MIMETYPE_MAPPING.put("docx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
MIMETYPE_MAPPING.put("dot", Collections.list("application/msword"));
MIMETYPE_MAPPING.put("dotx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.template"));
MIMETYPE_MAPPING.put("dv", Collections.list("video/dv"));
MIMETYPE_MAPPING.put("eot", Collections.list("application/vnd.ms-fontobject"));
MIMETYPE_MAPPING.put("epub", Collections.list("application/epub+zip"));
MIMETYPE_MAPPING.put("eps", Collections.list("application/postscript"));
MIMETYPE_MAPPING.put("erf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("exe", Collections.list("application/x-ms-dos-executable"));
MIMETYPE_MAPPING.put("flac", Collections.list("audio/flac"));
MIMETYPE_MAPPING.put("flv", Collections.list("video/x-flv"));
MIMETYPE_MAPPING.put("gif", Collections.list("image/gif"));
MIMETYPE_MAPPING.put("gpx", Collections.list("application/gpx+xml"));
MIMETYPE_MAPPING.put("gz", Collections.list("application/gzip"));
MIMETYPE_MAPPING.put("gzip", Collections.list("application/gzip"));
MIMETYPE_MAPPING.put("h", Collections.list("text/x-h"));
MIMETYPE_MAPPING.put("heic", Collections.list("image/heic"));
MIMETYPE_MAPPING.put("heif", Collections.list("image/heif"));
MIMETYPE_MAPPING.put("hh", Collections.list("text/x-h"));
MIMETYPE_MAPPING.put("hpp", Collections.list("text/x-h"));
MIMETYPE_MAPPING.put("htaccess", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("ical", Collections.list("text/calendar"));
MIMETYPE_MAPPING.put("ics", Collections.list("text/calendar"));
MIMETYPE_MAPPING.put("iiq", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("impress", Collections.list("text/impress"));
MIMETYPE_MAPPING.put("java", Collections.list("text/x-java-source"));
MIMETYPE_MAPPING.put("jp2", Collections.list("image/jp2"));
MIMETYPE_MAPPING.put("jpeg", Collections.list("image/jpeg"));
MIMETYPE_MAPPING.put("jpg", Collections.list("image/jpeg"));
MIMETYPE_MAPPING.put("jps", Collections.list("image/jpeg"));
MIMETYPE_MAPPING.put("k25", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("kdc", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("key", Collections.list("application/x-iwork-keynote-sffkey"));
MIMETYPE_MAPPING.put("keynote", Collections.list("application/x-iwork-keynote-sffkey"));
MIMETYPE_MAPPING.put("kml", Collections.list("application/vnd.google-earth.kml+xml"));
MIMETYPE_MAPPING.put("kmz", Collections.list("application/vnd.google-earth.kmz"));
MIMETYPE_MAPPING.put("kra", Collections.list("application/x-krita"));
MIMETYPE_MAPPING.put("ldif", Collections.list("text/x-ldif"));
MIMETYPE_MAPPING.put("love", Collections.list("application/x-love-game"));
MIMETYPE_MAPPING.put("lwp", Collections.list("application/vnd.lotus-wordpro"));
MIMETYPE_MAPPING.put("m2t", Collections.list("video/mp2t"));
MIMETYPE_MAPPING.put("m3u", Collections.list("audio/mpegurl"));
MIMETYPE_MAPPING.put("m3u8", Collections.list("audio/mpegurl"));
MIMETYPE_MAPPING.put("m4a", Collections.list("audio/mp4"));
MIMETYPE_MAPPING.put("m4b", Collections.list("audio/m4b"));
MIMETYPE_MAPPING.put("m4v", Collections.list("video/mp4"));
MIMETYPE_MAPPING.put("markdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("mdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("md", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("mdb", Collections.list("application/msaccess"));
MIMETYPE_MAPPING.put("mdwn", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("mkd", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("mef", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("mkv", Collections.list("video/x-matroska"));
MIMETYPE_MAPPING.put("mobi", Collections.list("application/x-mobipocket-ebook"));
MIMETYPE_MAPPING.put("mov", Collections.list("video/quicktime"));
MIMETYPE_MAPPING.put("mp3", Collections.list("audio/mpeg"));
MIMETYPE_MAPPING.put("mp4", Collections.list("video/mp4"));
MIMETYPE_MAPPING.put("mpeg", Collections.list("video/mpeg"));
MIMETYPE_MAPPING.put("mpg", Collections.list("video/mpeg"));
MIMETYPE_MAPPING.put("mpo", Collections.list("image/jpeg"));
MIMETYPE_MAPPING.put("msi", Collections.list("application/x-msi"));
MIMETYPE_MAPPING.put("mts", Collections.list("video/MP2T"));
MIMETYPE_MAPPING.put("mt2s", Collections.list("video/MP2T"));
MIMETYPE_MAPPING.put("nef", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("numbers", Collections.list("application/x-iwork-numbers-sffnumbers"));
MIMETYPE_MAPPING.put("odf", Collections.list("application/vnd.oasis.opendocument.formula"));
MIMETYPE_MAPPING.put("odg", Collections.list("application/vnd.oasis.opendocument.graphics"));
MIMETYPE_MAPPING.put("odp", Collections.list("application/vnd.oasis.opendocument.presentation"));
MIMETYPE_MAPPING.put("ods", Collections.list("application/vnd.oasis.opendocument.spreadsheet"));
MIMETYPE_MAPPING.put("odt", Collections.list("application/vnd.oasis.opendocument.text"));
MIMETYPE_MAPPING.put("oga", Collections.list("audio/ogg"));
MIMETYPE_MAPPING.put("ogg", Collections.list("audio/ogg"));
MIMETYPE_MAPPING.put("ogv", Collections.list("video/ogg"));
MIMETYPE_MAPPING.put("one", Collections.list("application/msonenote"));
MIMETYPE_MAPPING.put("opus", Collections.list("audio/ogg"));
MIMETYPE_MAPPING.put("orf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("otf", Collections.list("application/font-sfnt"));
MIMETYPE_MAPPING.put("pages", Collections.list("application/x-iwork-pages-sffpages"));
MIMETYPE_MAPPING.put("pdf", Collections.list("application/pdf"));
MIMETYPE_MAPPING.put("pfb", Collections.list("application/x-font"));
MIMETYPE_MAPPING.put("pef", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("php", Collections.list("application/x-php"));
MIMETYPE_MAPPING.put("pl", Collections.list("application/x-perl"));
MIMETYPE_MAPPING.put("pls", Collections.list("audio/x-scpls"));
MIMETYPE_MAPPING.put("png", Collections.list("image/png"));
MIMETYPE_MAPPING.put("pot", Collections.list("application/vnd.ms-powerpoint"));
MIMETYPE_MAPPING.put("potm", Collections.list("application/vnd.ms-powerpoint.template.macroEnabled.12"));
MIMETYPE_MAPPING.put("potx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.template"));
MIMETYPE_MAPPING.put("ppa", Collections.list("application/vnd.ms-powerpoint"));
MIMETYPE_MAPPING.put("ppam", Collections.list("application/vnd.ms-powerpoint.addin.macroEnabled.12"));
MIMETYPE_MAPPING.put("pps", Collections.list("application/vnd.ms-powerpoint"));
MIMETYPE_MAPPING.put("ppsm", Collections.list("application/vnd.ms-powerpoint.slideshow.macroEnabled.12"));
MIMETYPE_MAPPING.put("ppsx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.slideshow"));
MIMETYPE_MAPPING.put("ppt", Collections.list("application/vnd.ms-powerpoint"));
MIMETYPE_MAPPING.put("pptm", Collections.list("application/vnd.ms-powerpoint.presentation.macroEnabled.12"));
MIMETYPE_MAPPING.put("pptx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.presentation"));
MIMETYPE_MAPPING.put("ps", Collections.list("application/postscript"));
MIMETYPE_MAPPING.put("psd", Collections.list("application/x-photoshop"));
MIMETYPE_MAPPING.put("py", Collections.list("text/x-python"));
MIMETYPE_MAPPING.put("raf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("rar", Collections.list("application/x-rar-compressed"));
MIMETYPE_MAPPING.put("reveal", Collections.list("text/reveal"));
MIMETYPE_MAPPING.put("rss", Collections.list("application/rss+xml"));
MIMETYPE_MAPPING.put("rtf", Collections.list("application/rtf"));
MIMETYPE_MAPPING.put("rw2", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("schema", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("sgf", Collections.list("application/sgf"));
MIMETYPE_MAPPING.put("sh-lib", Collections.list("text/x-shellscript"));
MIMETYPE_MAPPING.put("sh", Collections.list("text/x-shellscript"));
MIMETYPE_MAPPING.put("srf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("sr2", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("tar", Collections.list("application/x-tar"));
MIMETYPE_MAPPING.put("tar.bz2", Collections.list("application/x-bzip2"));
MIMETYPE_MAPPING.put("tar.gz", Collections.list("application/x-compressed"));
MIMETYPE_MAPPING.put("tbz2", Collections.list("application/x-bzip2"));
MIMETYPE_MAPPING.put("tcx", Collections.list("application/vnd.garmin.tcx+xml"));
MIMETYPE_MAPPING.put("tex", Collections.list("application/x-tex"));
MIMETYPE_MAPPING.put("tgz", Collections.list("application/x-compressed"));
MIMETYPE_MAPPING.put("tiff", Collections.list("image/tiff"));
MIMETYPE_MAPPING.put("tif", Collections.list("image/tiff"));
MIMETYPE_MAPPING.put("ttf", Collections.list("application/font-sfnt"));
MIMETYPE_MAPPING.put("txt", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("vcard", Collections.list("text/vcard"));
MIMETYPE_MAPPING.put("vcf", Collections.list("text/vcard"));
MIMETYPE_MAPPING.put("vob", Collections.list("video/dvd"));
MIMETYPE_MAPPING.put("vsd", Collections.list("application/vnd.visio"));
MIMETYPE_MAPPING.put("vsdm", Collections.list("application/vnd.ms-visio.drawing.macroEnabled.12"));
MIMETYPE_MAPPING.put("vsdx", Collections.list("application/vnd.ms-visio.drawing"));
MIMETYPE_MAPPING.put("vssm", Collections.list("application/vnd.ms-visio.stencil.macroEnabled.12"));
MIMETYPE_MAPPING.put("vssx", Collections.list("application/vnd.ms-visio.stencil"));
MIMETYPE_MAPPING.put("vstm", Collections.list("application/vnd.ms-visio.template.macroEnabled.12"));
MIMETYPE_MAPPING.put("vstx", Collections.list("application/vnd.ms-visio.template"));
MIMETYPE_MAPPING.put("wav", Collections.list("audio/wav"));
MIMETYPE_MAPPING.put("webm", Collections.list("video/webm"));
MIMETYPE_MAPPING.put("woff", Collections.list("application/font-woff"));
MIMETYPE_MAPPING.put("wpd", Collections.list("application/vnd.wordperfect"));
MIMETYPE_MAPPING.put("wmv", Collections.list("video/x-ms-wmv"));
MIMETYPE_MAPPING.put("xcf", Collections.list("application/x-gimp"));
MIMETYPE_MAPPING.put("xla", Collections.list("application/vnd.ms-excel"));
MIMETYPE_MAPPING.put("xlam", Collections.list("application/vnd.ms-excel.addin.macroEnabled.12"));
MIMETYPE_MAPPING.put("xls", Collections.list("application/vnd.ms-excel"));
MIMETYPE_MAPPING.put("xlsb", Collections.list("application/vnd.ms-excel.sheet.binary.macroEnabled.12"));
MIMETYPE_MAPPING.put("xlsm", Collections.list("application/vnd.ms-excel.sheet.macroEnabled.12"));
MIMETYPE_MAPPING.put("xlsx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
MIMETYPE_MAPPING.put("xlt", Collections.list("application/vnd.ms-excel"));
MIMETYPE_MAPPING.put("xltm", Collections.list("application/vnd.ms-excel.template.macroEnabled.12"));
MIMETYPE_MAPPING.put("xltx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.template"));
MIMETYPE_MAPPING.put("xrf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("yaml", Arrays.asList("application/yaml", "text/plain"));
MIMETYPE_MAPPING.put("yml", Arrays.asList("application/yaml", "text/plain"));
MIMETYPE_MAPPING.put("zip", Collections.list("application/zip"));
MIMETYPE_MAPPING.put("url", Collections.list("application/internet-shortcut"));
MIMETYPE_MAPPING.put("webloc", Collections.list("application/internet-shortcut"));
MIMETYPE_MAPPING.put("js", Arrays.asList("application/javascript", "text/plain"));
MIMETYPE_MAPPING.put("json", Arrays.asList("application/json", "text/plain"));
MIMETYPE_MAPPING.put("fb2", Arrays.asList("application/x-fictionbook+xml", "text/plain"));
MIMETYPE_MAPPING.put("html", Arrays.asList("text/html", "text/plain"));
MIMETYPE_MAPPING.put("htm", Arrays.asList("text/html", "text/plain"));
MIMETYPE_MAPPING.put("m", Arrays.asList("text/x-matlab", "text/plain"));
MIMETYPE_MAPPING.put("svg", Arrays.asList("image/svg+xml", "text/plain"));
MIMETYPE_MAPPING.put("swf", Arrays.asList("application/x-shockwave-flash", "application/octet-stream"));
MIMETYPE_MAPPING.put("xml", Arrays.asList("application/xml", "text/plain"));
}
ORDER BY article_rating, article_time DESC
will sort by article_time only if there are two articles with the same rating. From all I can see in your example, this is exactly what happens.
? primary sort secondary sort ?
1. 50 | This article rocks | Feb 4, 2009 3.
2. 35 | This article is pretty good | Feb 1, 2009 2.
3. 5 | This Article isn't so hot | Jan 25, 2009 1.
but consider:
? primary sort secondary sort ?
1. 50 | This article rocks | Feb 2, 2009 3.
1. 50 | This article rocks, too | Feb 4, 2009 4.
2. 35 | This article is pretty good | Feb 1, 2009 2.
3. 5 | This Article isn't so hot | Jan 25, 2009 1.
Are you sure your newline is not CHR(13) + CHR(10)
, in which case, you are ending up with CHR(13) + '_'
, which might still look like a newline?
Try REPLACE(col_name, CHR(13) + CHR(10), '')
None of the current answers show the InputStream
being closed (this will leak a file descriptor), and/or don't deal with .getResourceAsStream()
returning null when the resource is not found (this will lead to a NullPointerException
with the confusing message, "inStream parameter is null"
). You need something like the following:
String propertiesFilename = "server.properties";
Properties prop = new Properties();
try (var inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFilename)) {
if (inputStream == null) {
throw new FileNotFoundException(propertiesFilename);
}
prop.load(inputStream);
} catch (IOException e) {
throw new RuntimeException(
"Could not read " + propertiesFilename + " resource file: " + e);
}
I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
Session state is saved on the server, ViewState is saved in the page.
Session state is usually cleared after a period of inactivity from the user (no request happened containing the session id in the request cookies).
The view state is posted on subsequent post back in a hidden field.
git-pull - Fetch from and integrate with another repository or a local branch GIT PULL
Basically you are pulling remote branch to your local, example:
git pull origin master
Will pull master branch into your local repository
git-rebase - Forward-port local commits to the updated upstream head GIT REBASE
This one is putting your local changes on top of changes done remotely by other users. For example:
SOME-FEATURE
Now you want to see his and your changes on your local branch.
So then you checkout master
branch:
git checkout master
then you can pull:
git pull origin master
and then you go to your branch:
git checkout SOME-FEATURE
and you can do rebase master
to get lastest changes from it and put your branch commits on top:
git rebase master
I hope now it's a bit more clear for you.
[Fixed] Server version: 10.1.38-MariaDB - mariadb.org binary distribution
Go to: C:\xampp\mysql\bin open my.ini in notepad and find [mysqld] (line number 27) then after this line(line no 28) just type: skip-grant-tables
save the file and then reload the phpmyadmin page.It worked for me.
To remove from all tables, (add this to the head or external style sheet)
<style type="text/css">
table td{
border:none;
}
</style>
Running the command prompt or Powershell ISE as an administrator fixed this for me.
Following is a summarization and curation from many different sources on this topic including code example and quotes from selected blog posts. The complete list of best practices can be found here
TL;DR: Handling async errors in callback style is probably the fastest way to hell (a.k.a the pyramid of doom). The best gift you can give to your code is using instead a reputable promise library which provides much compact and familiar code syntax like try-catch
Otherwise: Node.JS callback style, function(err, response), is a promising way to un-maintainable code due to the mix of error handling with casual code, excessive nesting and awkward coding patterns
Code example - good
doWork()
.then(doWork)
.then(doError)
.then(doWork)
.catch(errorHandler)
.then(verify);
code example anti pattern – callback style error handling
getData(someParameter, function(err, result){
if(err != null)
//do something like calling the given callback function and pass the error
getMoreData(a, function(err, result){
if(err != null)
//do something like calling the given callback function and pass the error
getMoreData(b, function(c){
getMoreData(d, function(e){
...
});
});
});
});
});
Blog quote: "We have a problem with promises" (From the blog pouchdb, ranked 11 for the keywords "Node Promises")
"…And in fact, callbacks do something even more sinister: they deprive us of the stack, which is something we usually take for granted in programming languages. Writing code without a stack is a lot like driving a car without a brake pedal: you don’t realize how badly you need it, until you reach for it and it’s not there. The whole point of promises is to give us back the language fundamentals we lost when we went async: return, throw, and the stack. But you have to know how to use promises correctly in order to take advantage of them."
TL;DR: It pretty common to see code that throws errors as string or as a custom type – this complicates the error handling logic and the interoperability between modules. Whether you reject a promise, throw exception or emit error – using Node.JS built-in Error object increases uniformity and prevents loss of error information
Otherwise: When executing some module, being uncertain which type of errors come in return – makes it much harder to reason about the coming exception and handle it. Even worth, using custom types to describe errors might lead to loss of critical error information like the stack trace!
Code example - doing it right
//throwing an Error from typical function, whether sync or async
if(!productToAdd)
throw new Error("How can I add new product when no value provided?");
//'throwing' an Error from EventEmitter
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
//'throwing' an Error from a Promise
return new promise(function (resolve, reject) {
DAL.getProduct(productToAdd.id).then((existingProduct) =>{
if(existingProduct != null)
return reject(new Error("Why fooling us and trying to add an existing product?"));
code example anti pattern
//throwing a String lacks any stack trace information and other important properties
if(!productToAdd)
throw ("How can I add new product when no value provided?");
Blog quote: "A string is not an error" (From the blog devthought, ranked 6 for the keywords “Node.JS error object”)
"…passing a string instead of an error results in reduced interoperability between modules. It breaks contracts with APIs that might be performing instanceof Error checks, or that want to know more about the error. Error objects, as we’ll see, have very interesting properties in modern JavaScript engines besides holding the message passed to the constructor.."
TL;DR: Operations errors (e.g. API received an invalid input) refer to known cases where the error impact is fully understood and can be handled thoughtfully. On the other hand, programmer error (e.g. trying to read undefined variable) refers to unknown code failures that dictate to gracefully restart the application
Otherwise: You may always restart the application when an error appear, but why letting ~5000 online users down because of a minor and predicted error (operational error)? the opposite is also not ideal – keeping the application up when unknown issue (programmer error) occurred might lead unpredicted behavior. Differentiating the two allows acting tactfully and applying a balanced approach based on the given context
Code example - doing it right
//throwing an Error from typical function, whether sync or async
if(!productToAdd)
throw new Error("How can I add new product when no value provided?");
//'throwing' an Error from EventEmitter
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
//'throwing' an Error from a Promise
return new promise(function (resolve, reject) {
DAL.getProduct(productToAdd.id).then((existingProduct) =>{
if(existingProduct != null)
return reject(new Error("Why fooling us and trying to add an existing product?"));
code example - marking an error as operational (trusted)
//marking an error object as operational
var myError = new Error("How can I add new product when no value provided?");
myError.isOperational = true;
//or if you're using some centralized error factory (see other examples at the bullet "Use only the built-in Error object")
function appError(commonType, description, isOperational) {
Error.call(this);
Error.captureStackTrace(this);
this.commonType = commonType;
this.description = description;
this.isOperational = isOperational;
};
throw new appError(errorManagement.commonErrors.InvalidInput, "Describe here what happened", true);
//error handling code within middleware
process.on('uncaughtException', function(error) {
if(!error.isOperational)
process.exit(1);
});
Blog Quote: "Otherwise you risk the state" (From the blog debugable, ranked 3 for the keywords "Node.JS uncaught exception")
"…By the very nature of how throw works in JavaScript, there is almost never any way to safely “pick up where you left off”, without leaking references, or creating some other sort of undefined brittle state. The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, you might have many connections open, and it is not reasonable to abruptly shut those down because an error was triggered by someone else. The better approach is to send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker"
TL;DR: Error handling logic such as mail to admin and logging should be encapsulated in a dedicated and centralized object that all end-points (e.g. Express middleware, cron jobs, unit-testing) call when an error comes in.
Otherwise: Not handling errors within a single place will lead to code duplication and probably to errors that are handled improperly
Code example - a typical error flow
//DAL layer, we don't handle errors here
DB.addDocument(newCustomer, (error, result) => {
if (error)
throw new Error("Great error explanation comes here", other useful parameters)
});
//API route code, we catch both sync and async errors and forward to the middleware
try {
customerService.addNew(req.body).then(function (result) {
res.status(200).json(result);
}).catch((error) => {
next(error)
});
}
catch (error) {
next(error);
}
//Error handling middleware, we delegate the handling to the centrzlied error handler
app.use(function (err, req, res, next) {
errorHandler.handleError(err).then((isOperationalError) => {
if (!isOperationalError)
next(err);
});
});
Blog quote: "Sometimes lower levels can’t do anything useful except propagate the error to their caller" (From the blog Joyent, ranked 1 for the keywords “Node.JS error handling”)
"…You may end up handling the same error at several levels of the stack. This happens when lower levels can’t do anything useful except propagate the error to their caller, which propagates the error to its caller, and so on. Often, only the top-level caller knows what the appropriate response is, whether that’s to retry the operation, report an error to the user, or something else. But that doesn’t mean you should try to report all errors to a single top-level callback, because that callback itself can’t know in what context the error occurred"
TL;DR: Let your API callers know which errors might come in return so they can handle these thoughtfully without crashing. This is usually done with REST API documentation frameworks like Swagger
Otherwise: An API client might decide to crash and restart only because he received back an error he couldn’t understand. Note: the caller of your API might be you (very typical in a microservices environment)
Blog quote: "You have to tell your callers what errors can happen" (From the blog Joyent, ranked 1 for the keywords “Node.JS logging”)
…We’ve talked about how to handle errors, but when you’re writing a new function, how do you deliver errors to the code that called your function? …If you don’t know what errors can happen or don’t know what they mean, then your program cannot be correct except by accident. So if you’re writing a new function, you have to tell your callers what errors can happen and what they mea
TL;DR: When an unknown error occurs (a developer error, see best practice number #3)- there is uncertainty about the application healthiness. A common practice suggests restarting the process carefully using a ‘restarter’ tool like Forever and PM2
Otherwise: When an unfamiliar exception is caught, some object might be in a faulty state (e.g an event emitter which is used globally and not firing events anymore due to some internal failure) and all future requests might fail or behave crazily
Code example - deciding whether to crash
//deciding whether to crash when an uncaught exception arrives
//Assuming developers mark known operational errors with error.isOperational=true, read best practice #3
process.on('uncaughtException', function(error) {
errorManagement.handler.handleError(error);
if(!errorManagement.handler.isTrustedError(error))
process.exit(1)
});
//centralized error handler encapsulates error-handling related logic
function errorHandler(){
this.handleError = function (error) {
return logger.logError(err).then(sendMailToAdminIfCritical).then(saveInOpsQueueIfCritical).then(determineIfOperationalError);
}
this.isTrustedError = function(error)
{
return error.isOperational;
}
Blog quote: "There are three schools of thoughts on error handling" (From the blog jsrecipes)
…There are primarily three schools of thoughts on error handling: 1. Let the application crash and restart it. 2. Handle all possible errors and never crash. 3. Balanced approach between the two
TL;DR: A set of mature logging tools like Winston, Bunyan or Log4J, will speed-up error discovery and understanding. So forget about console.log.
Otherwise: Skimming through console.logs or manually through messy text file without querying tools or a decent log viewer might keep you busy at work until late
Code example - Winston logger in action
//your centralized logger object
var logger = new winston.Logger({
level: 'info',
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'somefile.log' })
]
});
//custom code somewhere using the logger
logger.log('info', 'Test Log Message with some parameter %s', 'some parameter', { anything: 'This is metadata' });
Blog quote: "Lets identify a few requirements (for a logger):" (From the blog strongblog)
…Lets identify a few requirements (for a logger): 1. Time stamp each log line. This one is pretty self explanatory – you should be able to tell when each log entry occured. 2. Logging format should be easily digestible by humans as well as machines. 3. Allows for multiple configurable destination streams. For example, you might be writing trace logs to one file but when an error is encountered, write to the same file, then into error file and send an email at the same time…
TL;DR: Monitoring and performance products (a.k.a APM) proactively gauge your codebase or API so they can auto-magically highlight errors, crashes and slow parts that you were missing
Otherwise: You might spend great effort on measuring API performance and downtimes, probably you’ll never be aware which are your slowest code parts under real world scenario and how these affects the UX
Blog quote: "APM products segments" (From the blog Yoni Goldberg)
"…APM products constitutes 3 major segments:1. Website or API monitoring – external services that constantly monitor uptime and performance via HTTP requests. Can be setup in few minutes. Following are few selected contenders: Pingdom, Uptime Robot, and New Relic 2. Code instrumentation – products family which require to embed an agent within the application to benefit feature slow code detection, exceptions statistics, performance monitoring and many more. Following are few selected contenders: New Relic, App Dynamics 3. Operational intelligence dashboard – these line of products are focused on facilitating the ops team with metrics and curated content that helps to easily stay on top of application performance. This is usually involves aggregating multiple sources of information (application logs, DB logs, servers log, etc) and upfront dashboard design work. Following are few selected contenders: Datadog, Splunk"
The above is a shortened version - see here more best practices and examples
On Windows, if you don't want to put your password in .gitconfig in the plain text, you can use
It authenticates you against normal or even Windows NTLM proxy and starts localhost-proxy without authentication.
In order to get it run:
Point git to your new localhost proxy:
[http]
proxy = http://localhost:3128 # change port as necessary
This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:
$inputs = [
'email' => 'foo',
'password' => 'bar',
];
$rules = [
'email' => 'required|email',
'password' => [
'required',
'string',
'min:10', // must be at least 10 characters in length
'regex:/[a-z]/', // must contain at least one lowercase letter
'regex:/[A-Z]/', // must contain at least one uppercase letter
'regex:/[0-9]/', // must contain at least one digit
'regex:/[@$!%*#?&]/', // must contain a special character
],
];
$validation = \Validator::make( $inputs, $rules );
if ( $validation->fails() ) {
print_r( $validation->errors()->all() );
}
Would output:
[
'The email must be a valid email address.',
'The password must be at least 10 characters.',
'The password format is invalid.',
]
(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)
There is a nice form plugin that allows you to send an HTML form asynchroniously.
$(document).ready(function() {
$('#myForm1').ajaxForm();
});
or
$("select").change(function(){
$('#myForm1').ajaxSubmit();
});
to submit the form immediately
I had this issue when leaving a view (pop back to the previous view).
the reason was having
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
view.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
view.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
view.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
])
Change safeAreaLayoutGuide
to self
solve the issue.
Meaning aligns the view with the superview's leading, trailing, top, bottom instead of to safe area)
String target = "27-09-1991 20:29:30";
DateFormat df = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
Date result = df.parse(target);
System.out.println(result);
This works fine?
If you have already exported a .sql
file, the best thing to do is to Find and Replace the following if you have them in your file:
utf8mb4_0900_ai_ci
to utf8_unicode_ci
utf8mb4
to utf8
utf8_unicode_520_ci
to utf8_unicode_ci
It will replace utf8mb4_unicode_ci
to utf8_unicode_ci
. Now you go to your phpMyAdmin cPanel and set the DB collation to utf8_unicode_ci
through Operations > Collation.
If you are exporting to a .sql
, it's better to change the format on how you're exporting the file. Check out Evster's anwer (it's in the same page as this)
Had the same issue that the client_max_body_size
directive was ignored.
My silly error was, that I put a file inside /etc/nginx/conf.d
which did not end with .conf
. Nginx will not load these by default.
It is a basic sequence that display or get a output of 1 1 2 3 5 8 it is a sequence that the sum of previous number the current number will be display next.
Try to watch link below Java Recursive Fibonacci sequence Tutorial
public static long getFibonacci(int number){
if(number<=1) return number;
else return getFibonacci(number-1) + getFibonacci(number-2);
}
Click Here Watch Java Recursive Fibonacci sequence Tutorial for spoon feeding
Here's a utility class I use to convert the newer java.time
classes to java.util.Date
objects and vice versa:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateUtils {
public static Date asDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date asDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate asLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static LocalDateTime asLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
Edited based on @Oliv comment.
we can create a class to pass more than one key or value and the object of this class can be used as a parameter in map.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class key1 {
String b;
String a;
key1(String a,String b)
{
this.a=a;
this.b=b;
}
}
public class read2 {
private static final String FILENAME = "E:/studies/JAVA/ReadFile_Project/nn.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
Map<key1,String> map=new HashMap<key1,String>();
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
while ((sCurrentLine = br.readLine()) != null) {
String[] s1 = sCurrentLine.split(",");
key1 k1 = new key1(s1[0],s1[2]);
map.put(k1,s1[2]);
}
for(Map.Entry<key1,String> m:map.entrySet()){
key1 key = m.getKey();
String s3 = m.getValue();
System.out.println(key.a+","+key.b+" : "+s3);
}
// }
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
If you need the port number also, you can use
Request.Url.Authority
Example:
string url = Request.Url.Authority + HttpContext.Current.Request.RawUrl.ToString();
if (Request.ServerVariables["HTTPS"] == "on")
{
url = "https://" + url;
}
else
{
url = "http://" + url;
}
This does not do what you expect:
if var is 'stringone' or 'stringtwo':
dosomething()
It is the same as:
if (var is 'stringone') or 'stringtwo':
dosomething()
Which is always true, since 'stringtwo'
is considered a "true" value.
There are two alternatives:
if var in ('stringone', 'stringtwo'):
dosomething()
Or you can write separate equality tests,
if var == 'stringone' or var == 'stringtwo':
dosomething()
Don't use is
, because is
compares object identity. You might get away with it sometimes because Python interns a lot of strings, just like you might get away with it in Java because Java interns a lot of strings. But don't use is
unless you really want object identity.
>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True # but could be False
you can use key to reload child component using key
<component :is="child1" :filter="filter" :key="componentKey"></component>
If you want to reload component with new filter, if button click filter the child component
reloadData() {
this.filter = ['filter1','filter2']
this.componentKey += 1;
},
and use the filter to trigger the function
In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw
alone does not produce the plot (at least with the qt backend).
The following works for me:
import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
#Suppose we know the x range
min_x = 0
max_x = 10
def on_launch(self):
#Set up plot
self.figure, self.ax = plt.subplots()
self.lines, = self.ax.plot([],[], 'o')
#Autoscale on unknown axis and known lims on the other
self.ax.set_autoscaley_on(True)
self.ax.set_xlim(self.min_x, self.max_x)
#Other stuff
self.ax.grid()
...
def on_running(self, xdata, ydata):
#Update data (with the new _and_ the old points)
self.lines.set_xdata(xdata)
self.lines.set_ydata(ydata)
#Need both of these in order to rescale
self.ax.relim()
self.ax.autoscale_view()
#We need to draw *and* flush
self.figure.canvas.draw()
self.figure.canvas.flush_events()
#Example
def __call__(self):
import numpy as np
import time
self.on_launch()
xdata = []
ydata = []
for x in np.arange(0,10,0.5):
xdata.append(x)
ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
self.on_running(xdata, ydata)
time.sleep(1)
return xdata, ydata
d = DynamicUpdate()
d()
The syntax to disable an HTML input is as follows:
<input type="text" id="input_id" DISABLED />
If you are using angular-cli
, simply use command:
ng v
You can do it like this,
$('.ads_Checkbox:checked')
You can iterate through them with each()
and fill the array with checkedbox values.
To get the values of selected checkboxes in array
var i = 0;
$('#save_value').click(function () {
var arr = [];
$('.ads_Checkbox:checked').each(function () {
arr[i++] = $(this).val();
});
});
Edit, using .map()
You can also use jQuery.map with get()
to get the array of selected checkboxe values.
As a side note using this.value
instead of $(this).val()
would give better performance.
$('#save_value').click(function(){
var arr = $('.ads_Checkbox:checked').map(function(){
return this.value;
}).get();
});
Note: Ruby >= 1.9.2 has an order-preserving hash: the order keys are inserted will be the order they are enumerated. The below applies to older versions or to backward-compatible code.
There is no concept of a sorted hash. So no, what you're doing isn't right.
If you want it sorted for display, return a string:
"{" + h.sort.map{|k,v| "#{k.inspect}=>#{v.inspect}"}.join(", ") + "}"
or, if you want the keys in order:
h.keys.sort
or, if you want to access the elements in order:
h.sort.map do |key,value|
# keys will arrive in order to this block, with their associated value.
end
but in summary, it makes no sense to talk about a sorted hash. From the docs, "The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order." So inserting keys in a specific order into the hash won't help.
I believe that there are plenty of circumstances in which it does make sense and it simplifies programming to have some globals that are known across several (tightly coupled) modules. In this spirit, I would like to elaborate a bit on the idea of having a module of globals which is imported by those modules which need to reference them.
When there is only one such module, I name it "g". In it, I assign default values for every variable I intend to treat as global. In each module that uses any of them, I do not use "from g import var", as this only results in a local variable which is initialized from g only at the time of the import. I make most references in the form g.var, and the "g." serves as a constant reminder that I am dealing with a variable that is potentially accessible to other modules.
If the value of such a global variable is to be used frequently in some function in a module, then that function can make a local copy: var = g.var. However, it is important to realize that assignments to var are local, and global g.var cannot be updated without referencing g.var explicitly in an assignment.
Note that you can also have multiple such globals modules shared by different subsets of your modules to keep things a little more tightly controlled. The reason I use short names for my globals modules is to avoid cluttering up the code too much with occurrences of them. With only a little experience, they become mnemonic enough with only 1 or 2 characters.
It is still possible to make an assignment to, say, g.x when x was not already defined in g, and a different module can then access g.x. However, even though the interpreter permits it, this approach is not so transparent, and I do avoid it. There is still the possibility of accidentally creating a new variable in g as a result of a typo in the variable name for an assignment. Sometimes an examination of dir(g) is useful to discover any surprise names that may have arisen by such accident.
Character set conversion is done implicitly on the database connection level. You can force automatic conversion off in the ODBC or ADODB connection string with the parameter "Auto Translate=False". This is NOT recommended. See: https://msdn.microsoft.com/en-us/library/ms130822.aspx
There has been a codepage incompatibility in SQL Server 2005 when Database and Client codepage did not match. https://support.microsoft.com/kb/KbView/904803
SQL-Management Console 2008 and upwards is a UNICODE application. All values entered or requested are interpreted as such on the application level. Conversation to and from the column collation is done implicitly. You can verify this with:
SELECT CAST(N'±' as varbinary(10)) AS Result
This will return 0xB100
which is the Unicode character U+00B1 (as entered in the Management Console window). You cannot turn off "Auto Translate" for Management Studio.
If you specify a different collation in the select, you eventually end up in a double conversion (with possible data loss) as long as "Auto Translate" is still active. The original character is first transformed to the new collation during the select, which in turn gets "Auto Translated" to the "proper" application codepage. That's why your various COLLATION tests still show all the same result.
You can verify that specifying the collation DOES have an effect in the select, if you cast the result as VARBINARY
instead of VARCHAR
so the SQL Server transformation is not invalidated by the client before it is presented:
SELECT cast(columnName COLLATE SQL_Latin1_General_CP850_BIN2 as varbinary(10)) from tableName
SELECT cast(columnName COLLATE SQL_Latin1_General_CP1_CI_AS as varbinary(10)) from tableName
This will get you 0xF1
or 0xB1
respectively if columnName
contains just the character '±'
You still might get the correct result and yet a wrong character, if the font you are using does not provide the proper glyph.
Please double check the actual internal representation of your character by casting the query to VARBINARY
on a proper sample and verify whether this code indeed corresponds to the defined database collation SQL_Latin1_General_CP850_BIN2
SELECT CAST(columnName as varbinary(10)) from tableName
Differences in application collation and database collation might go unnoticed as long as the conversion is always done the same way in and out. Troubles emerge as soon as you add a client with a different collation. Then you might find that the internal conversion is unable to match the characters correctly.
All that said, you should keep in mind that Management Studio usually is not the final reference when interpreting result sets. Even if it looks gibberish in MS, it still might be the correct output. The question is whether the records show up correctly in your applications.
I removed this issue by adding the following lines
add
multiDexEnabled true
in android>app>build.gradle inside defaultConfigadd
implementation 'com.android.support:multidex:1.0.3'
in android>app>build.gradle inside dependencies
Use arithmetic expressions.
#!/bin/bash
false=0
true=1
((false)) && echo false
((true)) && echo true
((!false)) && echo not false
((!true)) && echo not true
Output:
true
not false
Before using (strongly type html helper into view) this line
@Html.TextBoxFor(p => p.Product.Name)
You should include your model into you page for making strongly type view.
@model SampleModel
Sounds like you really want a Dictionary<int, string>
or possibly a switch
statement...
You can do it with the conditional operator though:
userType = user.Type == 0 ? "Admin"
: user.Type == 1 ? "User"
: user.Type == 2 ? "Employee"
: "The default you didn't specify";
While you could put that in one line, I'd strongly urge you not to.
I would normally only do this for different conditions though - not just several different possible values, which is better handled in a map.
The paths for msysgit are:
Windows XP -C:\Documents and Settings\<user_name>\.gitconfig
Windows Vista+ C:\Users\<user_name>\.gitconfig
I reverse-engineered and made an open source (re)implementation of UIStoryboard's segues: https://github.com/acoomans/Segway
With that library, you can define segues programmatically (without any storyboard).
Hope it may help.
you could also specify multiple style values like this
$('#navigation ul li').css({'display': 'inline-block','background-color': '#ff0000', 'color': '#ffffff'});
You use like that onclickListener in kotlin
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
...
}
How about trying:
select * from 'test_table'
where end_date < CAST('2009-12-15' AS DATE)
or start_date > CAST('2010-01-02' AS DATE)
which will return all date ranges which do not overlap your date range at all.
To avoid problems of side effects after changing env
, especially using multiple nodes, it is better to set a temporary context.
One safe way to alter the environment is:
withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
sh '$MYTOOL_HOME/bin/start'
}
This approach does not poison the env after the command execution.
It's been awhile since I've done anything with batch files but I think that the following works:
find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done
This is really a proof of concept; clean up as it suits your needs. The key is that find
returns an errorlevel
of 1
if string
is not in file
. We branch to notfound
in this case otherwise we handle the found
case.
They are bit shift operator which exists in many mainstream programming languages, <<
is the left shift and >>
is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.
| operate | bit value | octal value | description |
| ------- | --------- | ----------- | -------------------------------------------------------- |
| | 00000100 | 4 | |
| 4 << 2 | 00010000 | 16 | move all bits to left 2 bits, filled with 0 at the right |
| 16 >> 2 | 00000100 | 4 | move all bits to right 2 bits, filled with 0 at the left |
you can use putExtra(Serializable..) and getSerializableExtra() methods to pass and retrieve objects of your class type; you will have to mark your class Serializable and make sure that all your member variables are serializable too...
I suggest you use the mousedown event, which is called BEFORE the click event. That way, the browser handles the click event naturally, which avoids any code weirdness:
(function ($) {
// with this solution, the browser handles the download link naturally (tested in chrome and firefox)
$(document).ready(function () {
var url = '/private/downloads/myfile123.pdf';
$("a#someID").on('mousedown', function () {
$(this).attr("href", url);
});
});
})(jQuery);
I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.
The code below was simplyfied.
List<SelectListItem> items = new List<SelectListItem>();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("Texto", "1");
dictionary.Add("Foto", "2");
dictionary.Add("Vídeo", "3");
foreach (KeyValuePair<string, string> pair in objBLL.GetTiposPost())
{
items.Add(new SelectListItem() { Text = pair.Key, Value = pair.Value, Selected = false });
}
ViewBag.TiposPost = new SelectList(items, "Value", "Text");
In the View, I used a foreach to build a radiobutton.
<div class="form-group">
<div class="col-sm-10">
@foreach (var item in (SelectList)ViewBag.TiposPost)
{
@Html.RadioButtonFor(model => model.IDTipoPost, item.Value, false)
<label class="control-label">@item.Text</label>
}
</div>
</div>
Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.
Hope it's useful!
I know its been a while since the original post but I like using CTE's and this worked for me:
WITH cte_table_a
AS
(
SELECT [id] [id]
, MAX([value]) [value]
FROM table_a
GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN cte_table_a
ON table_b.id = cte_table_a.id
These variables are constants, i.e. private static final
whether they're named in all caps or not. The all-caps convention simply makes it more obvious that these variables are meant to be constants, but it isn't required. I've seen
private static final Logger log = Logger.getLogger(MyClass.class);
in lowercase before, and I'm fine with it because I know to only use the logger to log messages, but it does violate the convention. You could argue that naming it log
is a sub-convention, I suppose. But in general, naming constants in uppercase isn't the One Right Way, but it is The Best Way.
So many ways to do it.
From Workbench: File > Run SQL Script -- then follow prompts
From Windows Command Line:
Option 1: mysql -u usr -p
mysql> source file_path.sql
Option 2: mysql -u usr -p '-e source file_path.sql'
Option 3: mysql -u usr -p < file_path.sql
Option 4: put multiple 'source' statements inside of file_path.sql (I do this to drop and recreate schemas/databases which requires multiple files to be run)
mysql -u usr -p < file_path.sql
If you get errors from the command line, make sure you have previously run
cd {!!>>mysqld.exe home directory here<<!!}
mysqld.exe --initialize
This must be run from within the mysqld.exe directory, hence the CD.
Hope this is helpful and not just redundant.
Try this to reload jqGrid with new data
jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
<script type="text/javascript">
$(function(){
$('#areaCode,#firstNum,#secNum').keyup(function(e){
if($(this).val().length==$(this).attr('maxlength'))
$(this).next(':input').focus()
})
})
</script>
<body>
<input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />-
<input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />-
<input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />
</body>
DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'
IF PATINDEX('%[0-9]%', @str) > 0
PRINT 'YES, The string has numbers'
ELSE
PRINT 'NO, The string does not have numbers'
I've been searching the internet for RNG for a while now. Everything I saw was either TOO complex or was just not what I was looking for. After reading a few articles I was able to come up with this simple code.
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)])
}
Simple explanation,
This works well.
To obtain a random number less than 100 use
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
int[] d = new int[10] { 9, 4, 7, 2, 8, 0, 5, 1, 3, 4 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)]) + Convert.ToString(d[rnd.Next(10)]);
}
and so on for 3, 4, 5, and 6 ... digit random numbers.
Hope this assists someone positively.