<html>
<script language="javascript" type="text/javascript">
var scrt_var = 10;
openPage = function() {
location.href = "2.html?Key="+scrt_var;
}
</script>
this is a <a href ="javascript:openPage()">Link </a>
</html>
Use Css Selector for this, or learn more about Css Selector just go here
https://www.w3schools.com/cssref/css_selectors.asp
#main_text > .title {
/* Style goes here */
}
#main_text .title {
/* Style goes here */
}
While @AniketThakur's answer is very good. No one has answered the following question yet.
Can I only send pull requests via GitHub if I've forked a project?
No. If you are a contributor to a repository, you can: Make a local clone. Make a local branch. Add commits to that branch. Push the local branch back to github (creating a remote branch in the process). Make a pull request requesting for that branch to be merged into the master branch (or whatever branch you like).
I was running into the same issue when my callbacks would try to show a dialog.
I solved it with dedicated methods in the Activity - at the Activity instance member level - that use runOnUiThread(..)
public void showAuthProgressDialog() {
runOnUiThread(new Runnable() {
@Override
public void run() {
mAuthProgressDialog = DialogUtil.getVisibleProgressDialog(SignInActivity.this, "Loading ...");
}
});
}
public void dismissAuthProgressDialog() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mAuthProgressDialog == null || ! mAuthProgressDialog.isShowing()) {
return;
}
mAuthProgressDialog.dismiss();
}
});
}
I just checked with www.browserscope.org and with IE9 and Chrome 24 you can have 6 concurrent connections to a single domain, and up to 17 to multiple ones.
Quoting from the gcc website:
C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.
So probably you use a version of g++ which doesn't support -std=c++11
. Try -std=c++0x
instead.
Availability of C++11 features is for versions >= 4.3 only.
Actually, casting doesn't always work. If the object is not an instanceof
the class you're casting it to you will get a ClassCastException
at runtime.
This can happen if you call
.SingleOrDefault()
on an IEnumerable with 2 or more elements.
You could probably use a set object instead. Just add
numbers to the set. They inherently do not replicate.
Yes, it’s frustrating—sometimes type
and other programs
print gibberish, and sometimes they do not.
First of all, Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the default Raster Font.
But if the console font doesn’t contain the character you’re trying to display, you’ll see question marks instead of gibberish. When you get gibberish, there’s more going on than just font settings.
When programs use standard C-library I/O functions like printf
, the
program’s output encoding must match the console’s output encoding, or
you will get gibberish. chcp
shows and sets the current codepage. All
output using standard C-library I/O functions is treated as if it is in the
codepage displayed by chcp
.
Matching the program’s output encoding with the console’s output encoding can be accomplished in two different ways:
A program can get the console’s current codepage using chcp
or
GetConsoleOutputCP
, and configure itself to output in that encoding, or
You or a program can set the console’s current codepage using chcp
or
SetConsoleOutputCP
to match the default output encoding of the program.
However, programs that use Win32 APIs can write UTF-16LE strings directly
to the console with
WriteConsoleW
.
This is the only way to get correct output without setting codepages. And
even when using that function, if a string is not in the UTF-16LE encoding
to begin with, a Win32 program must pass the correct codepage to
MultiByteToWideChar
.
Also, WriteConsoleW
will not work if the program’s output is redirected;
more fiddling is needed in that case.
type
works some of the time because it checks the start of each file for
a UTF-16LE Byte Order Mark
(BOM), i.e. the bytes 0xFF 0xFE
.
If it finds such a
mark, it displays the Unicode characters in the file using WriteConsoleW
regardless of the current codepage. But when type
ing any file without a
UTF-16LE BOM, or for using non-ASCII characters with any command
that doesn’t call WriteConsoleW
—you will need to set the
console codepage and program output encoding to match each other.
How can we find this out?
Here’s a test file containing Unicode characters:
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
Here’s a Java program to print out the test file in a bunch of different
Unicode encodings. It could be in any programming language; it only prints
ASCII characters or encoded bytes to stdout
.
import java.io.*;
public class Foo {
private static final String BOM = "\ufeff";
private static final String TEST_STRING
= "ASCII abcde xyz\n"
+ "German äöü ÄÖÜ ß\n"
+ "Polish aezznl\n"
+ "Russian ??????? ???\n"
+ "CJK ??\n";
public static void main(String[] args)
throws Exception
{
String[] encodings = new String[] {
"UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" };
for (String encoding: encodings) {
System.out.println("== " + encoding);
for (boolean writeBom: new Boolean[] {false, true}) {
System.out.println(writeBom ? "= bom" : "= no bom");
String output = (writeBom ? BOM : "") + TEST_STRING;
byte[] bytes = output.getBytes(encoding);
System.out.write(bytes);
FileOutputStream out = new FileOutputStream("uc-test-"
+ encoding + (writeBom ? "-bom.txt" : "-nobom.txt"));
out.write(bytes);
out.close();
}
}
}
}
The output in the default codepage? Total garbage!
Z:\andrew\projects\sx\1259084>chcp
Active code page: 850
Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
= bom
´++ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
== UTF-16LE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
= bom
¦A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
== UTF-16BE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
= bom
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
== UTF-32LE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? z? |? D? B?
R u s s i a n 0? 1? 2? 3? 4? 5? 6? M? N
? O?
C J K `O }Y
= bom
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? z? |? D? B?
R u s s i a n 0? 1? 2? 3? 4? 5? 6? M? N
? O?
C J K `O }Y
== UTF-32BE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
= bom
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
However, what if we type
the files that got saved? They contain the exact
same bytes that were printed to the console.
Z:\andrew\projects\sx\1259084>type *.txt
uc-test-UTF-16BE-bom.txt
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
uc-test-UTF-16BE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
uc-test-UTF-16LE-bom.txt
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
uc-test-UTF-16LE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
uc-test-UTF-32BE-bom.txt
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
uc-test-UTF-32BE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
uc-test-UTF-32LE-bom.txt
A S C I I a b c d e x y z
G e r m a n ä ö ü Ä Ö Ü ß
P o l i s h a e z z n l
R u s s i a n ? ? ? ? ? ? ? ? ? ?
C J K ? ?
uc-test-UTF-32LE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? z? |? D? B?
R u s s i a n 0? 1? 2? 3? 4? 5? 6? M? N
? O?
C J K `O }Y
uc-test-UTF-8-bom.txt
´++ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
uc-test-UTF-8-nobom.txt
ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
The only thing that works is UTF-16LE file, with a BOM, printed to the
console via type
.
If we use anything other than type
to print the file, we get garbage:
Z:\andrew\projects\sx\1259084>copy uc-test-UTF-16LE-bom.txt CON
¦A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
1 file(s) copied.
From the fact that copy CON
does not display Unicode correctly, we can
conclude that the type
command has logic to detect a UTF-16LE BOM at the
start of the file, and use special Windows APIs to print it.
We can see this by opening cmd.exe
in a debugger when it goes to type
out a file:
After type
opens a file, it checks for a BOM of 0xFEFF
—i.e., the bytes
0xFF 0xFE
in little-endian—and if there is such a BOM, type
sets an
internal fOutputUnicode
flag. This flag is checked later to decide
whether to call WriteConsoleW
.
But that’s the only way to get type
to output Unicode, and only for files
that have BOMs and are in UTF-16LE. For all other files, and for programs
that don’t have special code to handle console output, your files will be
interpreted according to the current codepage, and will likely show up as
gibberish.
You can emulate how type
outputs Unicode to the console in your own programs like so:
#include <stdio.h>
#define UNICODE
#include <windows.h>
static LPCSTR lpcsTest =
"ASCII abcde xyz\n"
"German äöü ÄÖÜ ß\n"
"Polish aezznl\n"
"Russian ??????? ???\n"
"CJK ??\n";
int main() {
int n;
wchar_t buf[1024];
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
n = MultiByteToWideChar(CP_UTF8, 0,
lpcsTest, strlen(lpcsTest),
buf, sizeof(buf));
WriteConsole(hConsole, buf, n, &n, NULL);
return 0;
}
This program works for printing Unicode on the Windows console using the default codepage.
For the sample Java program, we can get a little bit of correct output by setting the codepage manually, though the output gets messed up in weird ways:
Z:\andrew\projects\sx\1259084>chcp 65001
Active code page: 65001
Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
? ???
CJK ??
??
?
?
= bom
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
?? ???
CJK ??
??
?
?
== UTF-16LE
= no bom
A S C I I a b c d e x y z
…
However, a C program that sets a Unicode UTF-8 codepage:
#include <stdio.h>
#include <windows.h>
int main() {
int c, n;
UINT oldCodePage;
char buf[1024];
oldCodePage = GetConsoleOutputCP();
if (!SetConsoleOutputCP(65001)) {
printf("error\n");
}
freopen("uc-test-UTF-8-nobom.txt", "rb", stdin);
n = fread(buf, sizeof(buf[0]), sizeof(buf), stdin);
fwrite(buf, sizeof(buf[0]), n, stdout);
SetConsoleOutputCP(oldCodePage);
return 0;
}
does have correct output:
Z:\andrew\projects\sx\1259084>.\test
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
The moral of the story?
type
can print UTF-16LE files with a BOM regardless of your current codepageWriteConsoleW
.chcp
, and will probably still get weird output.Please add this option:
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
(Reference: Chart.js)
N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion
There are two major libraries:
ZXing a library written in Java and then ported to Objective C / C++ (QR code only). And an other port to ObjC has been done, by TheLevelUp: ZXingObjC
ZBar an open source software for reading bar codes, C based.
According to my experiments, ZBar is far more accurate and fast than ZXing, at least on iPhone.
At the risk of getting negative marks, I want to suggest that the highest ranking solution (currently the first response) violates the latest SDK Agreement as of Nov 5, 2009. Our application was just rejected for using it. Here's the response from Apple:
"For security reasons, iPhone OS restricts an application (including its preferences and data) to a unique location in the file system. This restriction is part of the security feature known as the application's "sandbox." The sandbox is a set of fine-grained controls limiting an application's access to files, preferences, network resources, hardware, and so on."
The device's phone number is not available within your application's container. You will need to revise your application to read only within your directory container and resubmit your binary to iTunes Connect in order for your application to be reconsidered for the App Store.
This was a real disappointment since we wanted to spare the user having to enter their own phone number.
REST is not a specific web service but a design concept (architecture) for managing state information. The seminal paper on this was Roy Thomas Fielding's dissertation (2000), "Architectural Styles and the Design of Network-based Software Architectures" (available online from the University of California, Irvine).
First read Ryan Tomayko's post How I explained REST to my wife; it's a great starting point. Then read Fielding's actual dissertation. It's not that advanced, nor is it long (six chapters, 180 pages)! (I know you kids in school like it short).
EDIT: I feel it's pointless to try to explain REST. It has so many concepts like scalability, visibility (stateless) etc. that the reader needs to grasp, and the best source for understanding those are the actual dissertation. It's much more than POST/GET etc.
String methods return the modified string.
k = [x.replace(' ', '') for x in hello]
Completely untested, but this should work:
View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);
add android:configChanges="orientation|screenSize"
inside your activity in your manifest
If you are talking about syncing a forked repo then you can follow these steps.
How to sync a fork repository from git
check your current git branch
git branch
checkout to master if you are not on master
git checkout master
Fetch the upstream repository if you have correct access rights
git fetch upstream
If you are getting below error then run
git remote add upstream [email protected]:upstream_clone_repo_url/xyz.git
fatal: 'upstream/master' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.
Now run the below command.
git fetch upstream
Now if you are on master then merge the upstream/master into master branch
git merge upstream/master
That's it!!
Crosscheck via git remote
command, more specific git remote -v
If I also have commit rights to the upstream repo, I can create a local upstream branch and do work that will go upstream there.
I use this:
onClick({ target }: MouseEvent) => {
const targetDivElement: HTMLDivElement = target as HTMLDivElement;
const listFullHeight: number = targetDivElement.scrollHeight;
const listVisibleHeight: number = targetDivElement.offsetHeight;
const listTopScroll: number = targetDivElement.scrollTop;
}
First, learn the core concepts of Node.js:
Then, you're going to want to see what the community has to offer:
The gold standard for Node.js package management is NPM.
It is a command line tool for managing your project's dependencies.
NPM is also a registry of pretty much every Node.js package out there
Finally, you're going to want to know what some of the more popular packages are for various tasks:
Useful Tools for Every Project:
Unit Testing:
Web Frameworks:
Trails is a modern web application framework. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.
Danf is a full-stack OOP framework providing many features in order to produce a scalable, maintainable, testable and performant applications and allowing to code the same way on both the server (Node.js) and client (browser) sides.
Derbyjs is a reactive full-stack JavaScript framework. They are using patterns like reactive programming and isomorphic JavaScript for a long time.
Loopback.io is a powerful Node.js framework for creating APIs and easily connecting to backend data sources. It has an Angular.js SDK and provides SDKs for iOS and Android.
Web Framework Tools:
Networking:
Command Line Interaction:
Code Generators:
Work with streams:
Several options, in order of preference:
HKey_Current_User\Software\Microsoft\Windows\CurrentVersion\Run
registry key. The only problem here is it requires write access to the registry, which isn't always available.HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Run
registry key. The only problem here is it requires write access to the registry, which isn't always available.This answer is older now. Since I wrote this, Windows 10 was released, which changes how the Start Menu folders work... including the Startup
folder. It's not yet clear to me how easy it is to just add or remove a file in that folder without also referencing the internal database Windows uses for these locations.
Use the bootstrap classes col-xx-#
and col-xx-offset-#
So what is happening here is your screen is getting divided into 12 columns. In col-xx-#
, #
is the number of columns you cover and offset is the number of columns you leave.
For xx
, in a general website, md
is preferred and if you want your layout to look the same in a mobile device, xs
is preferred.
With what I can make of your requirement,
<div class="row">
<div class="col-md-4">First Div</div>
<div class="col-md-8">Second DIV </div>
</div>
Should do the trick.
Just go to the project Properties->Project Facets
Uncheck the dynamic module, click apply.
Maven->update the project.
Your main() method is static, but it is referencing two non-static members: con2 and getConnectionUrl2(). You need to do one of three things:
1) Make con2 and getConnectionUrl2() static.
2) Inside main(), create an instance of class testconnect and access con2 and getConnectionUrl2() off of that.
3) Break out a different class to hold con2 and getConnectionUrl2() so that testconnect only has main in it. It will still need to instantiate the different class and call the methods off that.
Option #3 is the best option. #1 is the worst.
But, you cannot access non-static members from within a static method.
For me this error was occuring because I changed the version number from 1 to 1.0 and build number from 6 to 1.1 as I pulled the code from source tree. I just changed it back and changed the build number from 6 to 7and it worked fine.
System.Single / float - 7 digits
System.Double / double - 15-16 digits
System.Decimal / decimal - 28-29 significant digits
The way I've been stung by using the wrong type (a good few years ago) is with large amounts:
You run out at 1 million for a float.
A 15 digit monetary value:
9 trillion with a double. But with division and comparisons it's more complicated (I'm definitely no expert in floating point and irrational numbers - see Marc's point). Mixing decimals and doubles causes issues:
A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used because the floating-point number might not exactly approximate the decimal number.
When should I use double instead of decimal? has some similar and more in depth answers.
Using double
instead of decimal
for monetary applications is a micro-optimization - that's the simplest way I look at it.
You can use the Firefox add-on called SQLite Manager to view the database's structure clearly.
If you're short of "fancy tools", e.g. in some minimal Linux distribution, there is a solution with just cat
, sort
and uniq
:
cat includes.txt excludes.txt excludes.txt | sort | uniq --unique
Test:
seq 1 1 7 | sort --random-sort > includes.txt
seq 3 1 9 | sort --random-sort > excludes.txt
cat includes.txt excludes.txt excludes.txt | sort | uniq --unique
# Output:
1
2
This is also relatively fast, compared to grep
.
I have the same issue , and I have resolved it using the steps mentioned above.but no when I have this issue again and i try the following,
RC(right click on web project) --> properties --> Deployment Assembly --> Add --> Java Build Path Entries --> Next -->
after clicking on next its only a blank window with the options Next and Fnish disabled.What can I do now?
In addition to Eric Leschinski's answer, and because this is stackoverflow, a programmatical solution:
Windows uses hidden file forks to mark content as "downloaded". Truncating these unblocks the file. The name of the stream used for CHM's is "Zone.Identifier". One can access streams by appending :streamname when opening the file. (keep backups the first time, in case your RTL messes that up!)
In Delphi it would look like this:
var f : file;
begin
writeln('unblocking ',s);
assignfile(f,'some.chm:Zone.Identifier');
rewrite(f,1);
truncate(f);
closefile(f);
end;
I'm told that on non forked filesystems (like FAT32) there are hidden files, but I haven't gotten to the bottom of that yet.
P.s. Delphi's DeleteFile() should also recognize forks.
i wrote a very(!) little helper method around the adobereader to bulk-print pdf from c#...:
public static bool Print(string file, string printer) {
try {
Process.Start(
Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Microsoft\Windows\CurrentVersion" +
@"\App Paths\AcroRd32.exe").GetValue("").ToString(),
string.Format("/h /t \"{0}\" \"{1}\"", file, printer));
return true;
} catch { }
return false;
}
one cannot rely on the return-value of the method btw...
When your ssh key is password protected run ssh-add
. npm probably hangs somewhere asking for your password.
variable
- named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable
, instance variable
, local variable
, method parameter
//pattern
<Java_type> <name> ;
//for example
int myInt;
String myString;
CustomClass myCustomClass;
field
- member variable or data member. It is a variable
inside a class
(class variable
or instance variable
)
attribute
- in some articles you can find that attribute
it is an object
representation of class variable
. Object
operates by attributes
which define a set of characteristics.
CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
property
- field
+ bounded getter/setter
. It has a field syntax but uses methods under the hood. Java
does not support it in pure form. Take a look at Objective-C
, Swift
, Kotlin
For example Kotlin
sample:
//field - Backing Field
class Person {
var name: String = "default name"
get() = field
set(value) { field = value }
}
//using
val person = Person()
person.name = "Alex" // setter is used
println(person.name) // getter is used
Currently, and with the new versions of Mysql can insert the current date automatically without adding a code in your PHP file. You can achieve that from Mysql while setting up your database as follows:
Now, any new post will automatically get a unique date and time. Hope this can help.
This could be a problem with IPV6 address SOAP UI picking. Adding the following JVM option fixed it for me:
-Djava.net.preferIPv4Stack=true
I added it here:
C:\Program Files\SmartBear\soapUI-4.5.2\bin\soapUI-4.5.2.vmoptions
following solution worked for me:
$("a[href^=#]").click(function(e)
{
e.preventDefault();
var aid = $(this).attr('href');
console.log(aid);
aid = aid.replace("#", "");
var aTag = $("a[name='"+ aid +"']");
if(aTag == null || aTag.offset() == null)
aTag = $("a[id='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top}, 1000);
}
);
Use the DateTime class instead, as it supports timezones. The DateTime equivalent of date()
is DateTime::format
.
An extremely helpful wrapper for DateTime is Carbon - definitely give it a look.
You'll want to store in the database as UTC and convert on the application level.
You can use Path API as follow:
var filenNme = Path.GetFileNameWithoutExtension([File Path]);
More info: Path.GetFileNameWithoutExtension
What you need is a jQuery UI Datepicker
Check out the demo and the source code.
PHP7, in php.ini file, remove the ";" before extension=openssl
You would cast it to an int (or float or double or what ever else you want to do with it) and store it in anoter variable.
Java 8: Base64 available:
MessageDigest md = MessageDigest.getInstance( "SHA-512" );
md.update( inbytes );
byte[] aMessageDigest = md.digest();
String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
return( outEncoded );
Create your own confirm box:
<div id="confirmBox">
<div class="message"></div>
<span class="yes">Yes</span>
<span class="no">No</span>
</div>
Create your own confirm()
method:
function doConfirm(msg, yesFn, noFn)
{
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Call it by your code:
doConfirm("Are you sure?", function yes()
{
form.submit();
}, function no()
{
// do nothing
});
You'll need to add CSS to style and position your confirm box appropriately.
Working demo: jsfiddle.net/Xtreu
I used this strategy: i excluded every field which is not marked with @SerializedName annotation, i.e.:
public class Dummy {
@SerializedName("VisibleValue")
final String visibleValue;
final String hiddenValue;
public Dummy(String visibleValue, String hiddenValue) {
this.visibleValue = visibleValue;
this.hiddenValue = hiddenValue;
}
}
public class SerializedNameOnlyStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(SerializedName.class) == null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
Gson gson = new GsonBuilder()
.setExclusionStrategies(new SerializedNameOnlyStrategy())
.create();
Dummy dummy = new Dummy("I will see this","I will not see this");
String json = gson.toJson(dummy);
It returns
{"VisibleValue":"I will see this"}
You can debug using browsers built in developer tools.
open developer tools in browser and go to source tab.
open the file do you want to debug using Ctrl+P and search file name
add break point on a line ny clicking on left side of the code.
refresh the page.
There are lot of plugin available for debugging you can refer for using chrome plugin Debug Angular Application using "Debugger for chrome" plugin
You can't access a MySQL DB from Android natively. EDIT: Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver
See
http://www.helloandroid.com/tutorials/connecting-mysql-database
Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.
http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html
For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.
The simplest solution I've found that doesn't require a plugin:
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null;
var yDown = null;
function handleTouchStart(evt) {
xDown = evt.touches[0].clientX;
yDown = evt.touches[0].clientY;
};
function handleTouchMove(evt) {
if ( ! xDown || ! yDown ) {
return;
}
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
if ( xDiff > 0 ) {
/* left swipe */
} else {
/* right swipe */
}
} else {
if ( yDiff > 0 ) {
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
xDown = null;
yDown = null;
};
You are setting self.name
to the string "get_thing"
, not the function get_thing
.
If you want self.name
to be a function, then you should set it to one:
setattr(self, 'name', self.get_thing)
However, that's completely unnecessary for your other code, because you could just call it directly:
value_returned = self.get_thing()
Simple:
st = "abcdefghij"
st = st[:-1]
There is also another way that shows how it is done with steps:
list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
This is also a way with user input:
list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
To make it take away the last word in a list:
list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)
The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:
try:
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
print 'Houston, we have a problem.'
raise
Which gives the following output that includes the offending statement and line number:
Houston, we have a problem.
Traceback (most recent call last):
File "/tmp/poop.py", line 2, in <module>
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie
Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):
import logging
try:
assert False == True
except AssertionError:
logging.error("Nothing is real but I can't quit...", exc_info=True)
Or even easier and without the need to create a filter: use PHP's mb_strimwidth
to truncate a string to a certain width (length). Just make sure you use one of the get_
syntaxes.
For example with the content:
<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>
This will cut the string at 400 characters and close it with ...
.
Just add a "read more"-link to the end by pointing to the permalink with get_permalink()
.
<a href="<?php the_permalink() ?>">Read more </a>
Of course you could also build the read more
in the first line. Than just replace '...'
with '<a href="' . get_permalink() . '">[Read more]</a>'
Just simply use isset($_POST['radio']) so that whenever i click any of the radio button, the one that is clicked is set to the post.
<form method="post" action="sample.php">
select sex:
<input type="radio" name="radio" value="male">
<input type="radio" name="radio" value="female">
<input type="submit" value="submit">
</form>
<?php
if (isset($_POST['radio'])){
$Sex = $_POST['radio'];
}
?>
I had pip
referring by default to pip3, which made me download the libs for python3. On the contrary I launched the shell as python
(which opened python 2) and the library wasn't installed there obviously.
Once I matched the names pip3 -> python3, pip -> python (2) all worked.
There is a way to create "const" variables in Java, but only for specific classes. Just define a class with final properties and subclass it. Then use the base class where you would want to use "const". Likewise, if you need to use "const" methods, add them to the base class. The compiler will not allow you to modify what it thinks is the final methods of the base class, but it will read and call methods on the subclass.
If you wanna maintain the same order in your list, say: your Map looks like:
map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")
and you want your list looks like
["msg1", "msg2", "msg3"] // same order as the map
you will have to iterate through the Map:
// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)
List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
list.add(entry.getKey(), entry.getValue());
}
In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.
The solution is quite simple ... you're reading getchar() which gives you the first character in the input buffer, and scanf just parsed it (really don't know why) to an integer, if you just forget the getchar for a second, it will read the full buffer until a newline char.
printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);
> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234
You can use sklearn.preprocessing:
from sklearn.preprocessing import normalize
data = np.array([
[1000, 10, 0.5],
[765, 5, 0.35],
[800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1. 1. 1. ]
[ 0.765 0.5 0.7 ]
[ 0.8 0.7 0.18 ]]
Last month I tried to configure iptables on a LXC VM container, but every time after reboot the iptables configuration was not automatically loaded.
The only way for me to get it working was by running the following command:
yum -y install iptables-services; systemctl disable firewalld; systemctl mask firewalld; service iptables restart; service iptables save
<style type="text/css">
#warning-message { display: none; }
@media only screen and (orientation:portrait){
#wrapper { display:none; }
#warning-message { display:block; }
}
@media only screen and (orientation:landscape){
#warning-message { display:none; }
}
</style>
....
<div id="wrapper">
<!-- your html for your website -->
</div>
<div id="warning-message">
this website is only viewable in landscape mode
</div>
You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.
I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.
Update
I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.
Another Update
So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.
"Easiest way is to use the built-in feature of SQL Management Studio" but... I have resolved it with a function and a couple of procedures. For example, to obtain the create table for a table named 'table_name', you have to execute just the procedure called sp_ppinScriptTabla:
Exec sp_ppinScriptTabla 'table_name'
Here is the tsql script code:
Use Master
GO
Create Function sp_ppinTipoLongitud
(
@xtype int,
@length int,
@isnullable int
)
Returns Varchar(512)
As
Begin
-- Función que a partir de un tipo de datos y una logitud, devuelve el texto del tipo.
-- Por ejemplo: para xtype=varchar y length=10 devolverá "varchar(10)"
Declare @ret varchar(512)
Set @ret = ''
Select @ret = t.name +
Case When name in ('varchar', 'nvarchar', 'char', 'nchar') Then '(' + Convert(varchar, @length) + ')' Else '' End + ' ' +
Case @isnullable When 1 Then 'NULL' Else 'NOT NULL' End
From systypes t
Where t.xtype = @xtype
Return @ret
End
GO
Create Procedure sp_ppinScriptLlavesForaneas
(
@vchTabla sysname,
@vchResultado varchar(8000) output
)
AS
Begin
DECLARE @tmpFK table(
TablaF sysname,
TablaR sysname,
ColF sysname,
ColR sysname,
FKName sysname)
-- obtengo las llaves foraneas en @vchForeign
Declare @vchForeign varchar(8000), @FKName sysname, @vchColumnasF varchar(4000), @vchColumnasR varchar(4000), @ColF sysname, @ColR sysname
Declare @vchTemp varchar(1000), @TablaR sysname
Insert into @tmpFK
Select TablaF.name AS TablaF, TablaR.name AS TablaR, ColF.name AS ColF, ColR.name AS ColR, ofk.name AS FKName
From sysforeignkeys fk, sysobjects ofk, sysobjects TablaF, sysobjects TablaR,
syscolumns ColF, syscolumns ColR
Where TablaF.name = @vchTabla
And ofk.id = fk.constid
And TablaF.id = fk.fkeyid
And TablaR.id = fk.rkeyid
And ColF.id = TablaF.id And ColF.colid = fk.fkey
And ColR.id = TablaR.id And ColR.colid = fk.rkey
order by FKName
Set @vchForeign = ''
While Exists ( Select * From @tmpFK )
Begin
Select Top 1 @FKName = FKName From @tmpFK
Set @vchColumnasF = ''
Set @vchColumnasR = ''
While Exists ( Select * From @tmpFK Where FKName = @FKName )
Begin
Select Top 1 @ColF = ColF, @ColR = ColR, @TablaR = TablaR From @tmpFK Where FKName = @FKName
Delete From @tmpFK Where ColF = @ColF And ColR = @ColR And TablaR = @TablaR And FKName = @FKName
Set @vchColumnasF = @vchColumnasF + @ColF + ', '
Set @vchColumnasR = @vchColumnasR + @ColR + ', '
End
Set @vchColumnasF = LEFT(@vchColumnasF, LEN(@vchColumnasF) - 1)
Set @vchColumnasR = LEFT(@vchColumnasR, LEN(@vchColumnasR) - 1)
Set @vchTemp = 'Constraint ' + @FKName + ' Foreign Key (' + @vchColumnasF + ') '
Set @vchTemp = @vchTemp + 'References ' + @TablaR + ' (' + @vchColumnasR + ')'
Set @vchForeign = @vchForeign + char(9) + @vchTemp + ',' + char(13)
End
Select @vchResultado = Case When Len(@vchForeign) >=2 Then Left(@vchForeign, Len(@vchForeign) - 2) Else @vchForeign End
End
GO
Create Procedure sp_ppinScriptTabla
(
@vchTabla sysname
)
AS
Set nocount on
-- Obtengo las foreign keys
Declare @foreign varchar(8000)
Exec sp_ppinScriptLlavesForaneas @vchTabla, @foreign output
-- SELECT que devuelve el script de Create Table de la tabla
Select 'Create ' +
Case o.xtype When 'U' Then 'Table' When 'P' Then 'Procedure' Else '??' End + ' ' +
@vchTabla + char(13) + '('
From sysobjects o
Where o.name = @vchTabla
Union all
-- Campos + identitys + DEFAULTS
select char(9) + c.name + ' ' + -- Nombre
dbo.sp_ppinTipoLongitud(t.xtype, c.length, c.isnullable) + -- Tipo(longitud)
Case When c.colstat & 1 = 1 -- Identity (si aplica)
Then ' Identity(' + convert(varchar, ident_seed(@vchTabla)) + ',' + Convert(varchar, ident_incr(@vchTabla)) + ')'
Else ''
End +
Case When not od.name is null -- Defaults (si aplica)
Then ' Constraint ' + od.name + ' Default ' + replace(replace(cd.text, '((', '('), '))', ')')
Else ''
End + ', '
from sysobjects o, syscolumns c
LEFT OUTER JOIN sysobjects od On od.id = c.cdefault LEFT OUTER join syscomments cd On cd.id = od.id,
systypes t
where o.id = object_id(@vchTabla)
and o.id = c.id
and c.xtype = t.xtype
Union all
-- Primary Keys y Unique keys
select char(9) + 'Constraint ' + o.name + ' ' +
Case o.xtype When 'PK' Then 'Primary Key' Else 'Unique' End + ' ' +
dbo.sp_ppinCamposIndice (db_name(), @vchTabla, i.indid) + ', '
from sysobjects o, sysindexes i
where o.parent_obj = object_id(@vchTabla)
and o.xtype in ('PK','UQ')
and i.id = o.parent_obj
and o.name = i.name
Union all
-- Check constraints
select char(9) + 'Constraint ' + o.name + ' Check ' + c.text + ', '
from sysobjects o, syscomments c
where o.parent_obj = object_id(@vchTabla)
and o.xtype in ('C')
and o.id = c.id
Union all
-- Foreign keys
Select @foreign
Union all
Select ')'
Set nocount off
GO
Have a look at ImmutableMap JavaDoc: doc
There is information about that there:
Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.
Quick and dirty universal jQuery version. Supports copy/paste.
$('textarea[maxlength]').on('keypress mouseup', function(){
return !($(this).val().length >= $(this).attr('maxlength'));
});
here's my solution (coffeescript) :
_.mixin
deepUniq: (coll) ->
result = []
remove_first_el_duplicates = (coll2) ->
rest = _.rest(coll2)
first = _.first(coll2)
result.push first
equalsFirst = (el) -> _.isEqual(el,first)
newColl = _.reject rest, equalsFirst
unless _.isEmpty newColl
remove_first_el_duplicates newColl
remove_first_el_duplicates(coll)
result
example:
_.deepUniq([ {a:1,b:12}, [ 2, 1, 2, 1 ], [ 1, 2, 1, 2 ],[ 2, 1, 2, 1 ], {a:1,b:12} ])
//=> [ { a: 1, b: 12 }, [ 2, 1, 2, 1 ], [ 1, 2, 1, 2 ] ]
This works fine in JAR files as well. You can obtain CodeSource
by ProtectionDomain#getCodeSource()
and the ProtectionDomain
in turn can be obtained by Class#getProtectionDomain()
.
public class Test {
public static void main(String... args) throws Exception {
URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println(location.getFile());
}
}
See below example of mocks vs stubs using C# and Moq framework. Moq doesn't have a special keyword for Stub but you can use Mock object to create stubs too.
namespace UnitTestProject2
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class UnitTest1
{
/// <summary>
/// Test using Mock to Verify that GetNameWithPrefix method calls Repository GetName method "once" when Id is greater than Zero
/// </summary>
[TestMethod]
public void GetNameWithPrefix_IdIsTwelve_GetNameCalledOnce()
{
// Arrange
var mockEntityRepository = new Mock<IEntityRepository>();
mockEntityRepository.Setup(m => m.GetName(It.IsAny<int>()));
var entity = new EntityClass(mockEntityRepository.Object);
// Act
var name = entity.GetNameWithPrefix(12);
// Assert
mockEntityRepository.Verify(m => m.GetName(It.IsAny<int>()), Times.Once);
}
/// <summary>
/// Test using Mock to Verify that GetNameWithPrefix method doesn't call Repository GetName method when Id is Zero
/// </summary>
[TestMethod]
public void GetNameWithPrefix_IdIsZero_GetNameNeverCalled()
{
// Arrange
var mockEntityRepository = new Mock<IEntityRepository>();
mockEntityRepository.Setup(m => m.GetName(It.IsAny<int>()));
var entity = new EntityClass(mockEntityRepository.Object);
// Act
var name = entity.GetNameWithPrefix(0);
// Assert
mockEntityRepository.Verify(m => m.GetName(It.IsAny<int>()), Times.Never);
}
/// <summary>
/// Test using Stub to Verify that GetNameWithPrefix method returns Name with a Prefix
/// </summary>
[TestMethod]
public void GetNameWithPrefix_IdIsTwelve_ReturnsNameWithPrefix()
{
// Arrange
var stubEntityRepository = new Mock<IEntityRepository>();
stubEntityRepository.Setup(m => m.GetName(It.IsAny<int>()))
.Returns("Stub");
const string EXPECTED_NAME_WITH_PREFIX = "Mr. Stub";
var entity = new EntityClass(stubEntityRepository.Object);
// Act
var name = entity.GetNameWithPrefix(12);
// Assert
Assert.AreEqual(EXPECTED_NAME_WITH_PREFIX, name);
}
}
public class EntityClass
{
private IEntityRepository _entityRepository;
public EntityClass(IEntityRepository entityRepository)
{
this._entityRepository = entityRepository;
}
public string Name { get; set; }
public string GetNameWithPrefix(int id)
{
string name = string.Empty;
if (id > 0)
{
name = this._entityRepository.GetName(id);
}
return "Mr. " + name;
}
}
public interface IEntityRepository
{
string GetName(int id);
}
public class EntityRepository:IEntityRepository
{
public string GetName(int id)
{
// Code to connect to DB and get name based on Id
return "NameFromDb";
}
}
}
I've been doing something similar a few weeks ago. Here's a possible solution, it's written from scratch, so it's kind of beta-release or something like that. I'll try to improve it by removing loops from code...
The main idea is to write a function that will take 2 (or 3) arguments. First one is a data.frame
which holds the data gathered from questionnaire, and the second one is a numeric vector with correct answers (this is only applicable for single choice questionnaire). Alternatively, you can add third argument that will return numeric vector with final score, or data.frame with embedded score.
fscore <- function(x, sol, output = 'numeric') {
if (ncol(x) != length(sol)) {
stop('Number of items differs from length of correct answers!')
} else {
inc <- matrix(ncol=ncol(x), nrow=nrow(x))
for (i in 1:ncol(x)) {
inc[,i] <- x[,i] == sol[i]
}
if (output == 'numeric') {
res <- rowSums(inc)
} else if (output == 'data.frame') {
res <- data.frame(x, result = rowSums(inc))
} else {
stop('Type not supported!')
}
}
return(res)
}
I'll try to do this in a more elegant manner with some *ply function. Notice that I didn't put na.rm
argument... Will do that
# create dummy data frame - values from 1 to 5
set.seed(100)
d <- as.data.frame(matrix(round(runif(200,1,5)), 10))
# create solution vector
sol <- round(runif(20, 1, 5))
Now apply a function:
> fscore(d, sol)
[1] 6 4 2 4 4 3 3 6 2 6
If you pass data.frame argument, it will return modified data.frame. I'll try to fix this one... Hope it helps!
You can do this with .htaccess:
php_value upload_max_filesize 20M
php_value post_max_size 20M
You should only have one <system.web>
in your Web.Config Configuration File
.
<?xml version="1.0"?>
<configuration>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true"/>
<authentication mode="None"/>
</system.web>
</configuration>
For calculating days in two dates difference, can be done like below:
import datetime
import math
issuedate = datetime(2019,5,9) #calculate the issue datetime
current_date = datetime.datetime.now() #calculate the current datetime
diff_date = current_date - issuedate #//calculate the date difference with time also
amount = fine #you want change
if diff_date.total_seconds() > 0.0: #its matching your condition
days = math.ceil(diff_date.total_seconds()/86400) #calculate days (in
one day 86400 seconds)
deductable_amount = round(amount,2)*days #calclulated fine for all days
Becuase if one second is more with the due date then we have to charge
Actually, it is worth noticing that git merge --abort
is only equivalent to git reset --merge
given that MERGE_HEAD
is present. This can be read in the git help for merge command.
git merge --abort # is equivalent to git reset --merge when MERGE_HEAD is present.
After a failed merge, when there is no MERGE_HEAD
, the failed merge can be undone with git reset --merge
but not necessarily with git merge --abort
, so they are not only old and new syntax for the same thing.
Personally I find git reset --merge
much more useful in everyday work.
I guess it is too late to answer but my help some people.
I don't have enough reputation to post images sorry.
Hope it can help
You are not refering to the temporary location where the file is saved.
Use tmp_name
to access the file.
You can always see what's getting posted using :
echo "<pre>";
print_r($_FILES);
If you see this files array you will have an better understanding and idea of what's going on.
I am a little late to party but you may want to consider using GetAwaiter.GetResult() to run your async code in sync context but as paralled as below;
Parallel.ForEach(ids, i =>
{
ICustomerRepo repo = new CustomerRepo();
// Run this in thread which Parallel library occupied.
var cust = repo.GetCustomer(i).GetAwaiter().GetResult();
customers.Add(cust);
});
System.Convert.IsDbNull][1](table.rows[0][0]);
IIRC, the (table.rows[0][0] == null)
won't work, as DbNull.Value != null;
I know i am probably the only one that will have this problem in this way. but if you deleted the mdf files in the C:/{user}/ directory, you will get this error too. restore it and you are golden
Install
npm i graph-fs
Use
const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");
directory.clear(); // <--
Generic FUNCTION
var getBrowseActive = function (browserName) {
return navigator.userAgent.indexOf(browserName) > -1;
};
these are the commands:
git fetch origin
git merge origin/somebranch somebranch
if you do this on the second line:
git merge origin somebranch
it will try to merge the local master into your current branch.
The question, as I've understood it, was you fetched already locally and want to now merge your branch to the latest of the same branch.
Making a class abstract
sends a message to the readers of your code that you want users of your abstract
class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.
Therefore, adding a private constructor is a better choice here. You should also make the class final
to disallow subclassing of your utility class.
The solution is :
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta
table. You can find the corresponding products within wp_posts
table.
The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:
abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))
Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value
abs(qt(0.01/2, 40)) # 99% confidence, 2 sided
Run it through a debugger. All will become clear.
The Observable Collection constructor will take an IList or an IEnumerable.
If you find that you are going to do this a lot you can make a simple extension method:
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable)
{
return new ObservableCollection<T>(enumerable);
}
String start_dt = "2011-01-01"; // Input String
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // Existing Pattern
Date getStartDt = formatter.parse(start_dt); //Returns Date Format according to existing pattern
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");// New Pattern
String formattedDate = simpleDateFormat.format(getStartDt); // Format given String to new pattern
System.out.println(formattedDate); //outputs: 01-01-2011
Have you tried JQuery? Vanilla javascript can be tough. Try using this:
$('.container-element').add('<div>Insert Div Content</div>');
.container-element
is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add()
function inserts HTML into the container-element.
If you're looking for a cross-platform GUI, then I'd highly recommend going with JRuby and Swing.
Also, take a look at the monkeybars library, which is a Ruby library for building MVC applications using JRuby and Swing, where you can also use the excellent Netbeans IDE to visually build your GUI.
you don't, declare an interface that declares the methods you would like to call:
public interface MyInterface
{
void doStuff();
}
public class MyClass implements MyInterface
{
public void doStuff()
{
System.Console.Writeln("done!");
}
}
then you use
MyInterface mobj = (myInterface)obj;
mobj.doStuff();
If MyClass
is not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).
Another option may be to store long strings in an external file and read the file into a string.
This error happens because your list lstpp
is empty (Nothing at index 0). So either there is a bug in your getResult()
function, or the empty list is normal and you need to handle this case (By checking the size of the list before, or catching the exception).
I did not have a .vimrc file in my home directory. I created one, added this line:
set number
and that solved the problem.
You don't pass n
itself, but rather range(n)
[the list of integers from 0 to n-1 included], from your view to your template, and in the latter you do {% for i in therange %}
(if you absolutely insist on 1-based rather than the normal 0-based index you can use forloop.counter
in the loop's body;-).
simple util function to calculate distance between two geopoints:
public static long getDistanceMeters(double lat1, double lng1, double lat2, double lng2) {
double l1 = toRadians(lat1);
double l2 = toRadians(lat2);
double g1 = toRadians(lng1);
double g2 = toRadians(lng2);
double dist = acos(sin(l1) * sin(l2) + cos(l1) * cos(l2) * cos(g1 - g2));
if(dist < 0) {
dist = dist + Math.PI;
}
return Math.round(dist * 6378100);
}
Add grid with defined height and width for columns and rows. Then add ScrollViewer
and inside it add the dataGrid.
A very old question I know but...
A pandas DataFrame seems to be the ideal option here.
http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.html
From the blurb
Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure
If you're using more recent Android APIs the Handler empty constructor has been deprecated and you should include a Looper. You can easily get one through Looper.getMainLooper()
.
Handler(Looper.getMainLooper()).postDelayed({
//Your code
}, 2000) //millis
If you want a CSS-only solution (no need to set cellspacing=0
in the HTML) that allows for 1px borders (which you can't do with the border-spacing: 0
solution), I prefer to do the following:
border-right
and border-bottom
for your table cells (td
and th
)border-top
border-left
first-child
and last-child
selectors, round the appropriate corners for the table cells in the four corners.Given the following HTML:
SEE example below:
_x000D_
_x000D_
.custom-table{margin:30px;}_x000D_
table {_x000D_
border-collapse: separate;_x000D_
border-spacing: 0;_x000D_
min-width: 350px;_x000D_
_x000D_
}_x000D_
table tr th,_x000D_
table tr td {_x000D_
border-right: 1px solid #bbb;_x000D_
border-bottom: 1px solid #bbb;_x000D_
padding: 5px;_x000D_
}_x000D_
table tr th:first-child, table tr th:last-child{_x000D_
border-top:solid 1px #bbb;}_x000D_
table tr th:first-child,_x000D_
table tr td:first-child {_x000D_
border-left: 1px solid #bbb;_x000D_
_x000D_
}_x000D_
table tr th:first-child,_x000D_
table tr td:first-child {_x000D_
border-left: 1px solid #bbb;_x000D_
}_x000D_
table tr th {_x000D_
background: #eee;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
table.Info tr th,_x000D_
table.Info tr:first-child td_x000D_
{_x000D_
border-top: 1px solid #bbb;_x000D_
}_x000D_
_x000D_
/* top-left border-radius */_x000D_
table tr:first-child th:first-child,_x000D_
table.Info tr:first-child td:first-child {_x000D_
border-top-left-radius: 6px;_x000D_
}_x000D_
_x000D_
/* top-right border-radius */_x000D_
table tr:first-child th:last-child,_x000D_
table.Info tr:first-child td:last-child {_x000D_
border-top-right-radius: 6px;_x000D_
}_x000D_
_x000D_
/* bottom-left border-radius */_x000D_
table tr:last-child td:first-child {_x000D_
border-bottom-left-radius: 6px;_x000D_
}_x000D_
_x000D_
/* bottom-right border-radius */_x000D_
table tr:last-child td:last-child {_x000D_
border-bottom-right-radius: 6px;_x000D_
}_x000D_
_x000D_
<div class="custom-table">_x000D_
<table>_x000D_
<tr>_x000D_
<th>item1</th>_x000D_
<th>item2</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>item1</td>_x000D_
<td>item2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>item1</td>_x000D_
<td>item2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>item1</td>_x000D_
<td>item2</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
from the cpython implementation source code:
def invmod(a, n):
b, c = 1, 0
while n:
q, r = divmod(a, n)
a, b, c, n = n, c, b - q*c, r
# at this point a is the gcd of the original inputs
if a == 1:
return b
raise ValueError("Not invertible")
according to the comment above this code, it can return small negative values, so you could potentially check if negative and add n when negative before returning b.
When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like
public interface Thunk { void apply(); }
somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.
In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.
In order to reduce the verbosity of the validation logic I have authored a library for Android. It takes care of most of the day to day validations using Annotations and built-in rules. There are constraints such as @TextRule
, @NumberRule
, @Required
, @Regex
, @Email
, @IpAddress
, @Password
, etc.,
You can add these annotations to your UI widget references and perform validations. It also allows you to perform validations asynchronously which is ideal for situations such as checking for unique username from a remote server.
There is a example on the project home page on how to use annotations. You can also read the associated blog post where I have written sample codes on how to write custom rules for validations.
Here is a simple example that depicts the usage of the library.
@Required(order = 1)
@Email(order = 2)
private EditText emailEditText;
@Password(order = 3)
@TextRule(order = 4, minLength = 6, message = "Enter at least 6 characters.")
private EditText passwordEditText;
@ConfirmPassword(order = 5)
private EditText confirmPasswordEditText;
@Checked(order = 6, message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;
The library is extendable, you can write your own rules by extending the Rule
class.
setSize()
or setBounds()
can be used when no layout manager is being used.
However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize()
methods like setPreferredSize()
and setMinimumSize()
etc.
And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout
, GridBagLayout
, and SpringLayout
managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout
and GridLayout
usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.
Use the Distinct operator:
var idList = yourList.Select(x=> x.ID).Distinct();
It's important to realize that while there are two classes, there is only one object.
So, yes, of course it inherited the private fields. They are, presumably, essential for proper object functionality, and while an object of the parent class is not an object of the derived class, an instance of the derived class is mostly definitely an instance of the parent class. It could't very well be that without all of the fields.
No, you can't directly access them. Yes, they are inherited. They have to be.
It's a good question!
Update:
Well, I guess we all learned something. Since the JLS originated the exact "not inherited" wording, it is correct to answer "no". Since the subclass can't access or modify the private fields, then, in other words, they are not inherited. But there really is just one object, it really does contain the private fields, and so if someone takes the JLS and tutorial wording the wrong way, it will be quite difficult to understand OOP, Java objects, and what is really happening.
Update to update:
The controversy here involves a fundamental ambiguity: what exactly is being discussed? The object? Or are we talking in some sense about the class itself? A lot of latitude is allowed when describing the class as opposed to the object. So the subclass does not inherit private fields, but an object that is an instance of the subclass certainly does contain the private fields.
New answer:
In HTML5 you can add the multiple
attribute to select more than 1 file.
<input type="file" name="filefield" multiple="multiple">
Old answer:
You can only select 1 file per
<input type="file" />
. If you want to send multiple files you will have to use multiple input tags or use Flash or Silverlight.
This can be caused by SELinux. If you don't want to disable SELinux completely, you need to set the db directory fcontext to httpd_sys_rw_content_t.
semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/railsapp/db(/.*)?"
restorecon -v /var/www/railsapp/db
It's just hash which is associated with user in database or some other way. That token can be used to authenticate and then authorize a user access related contents of the application. To retrieve this token on client side login is required. After first time login you need to save retrieved token not any other data like session, session id because here everything is token to access other resources of application.
Token is used to assure the authenticity of the user.
UPDATES: In current time, We have more advanced token based technology called JWT (Json Web Token). This technology helps to use same token in multiple systems and we call it single sign-on.
Basically JSON Based Token contains information about user details and token expiry details. So that information can be used to further authenticate or reject the request if token is invalid or expired based on details.
I DONT AGREE everything must be UTF-8, you can make it work perfectly with ISO 8859, I did, please read my response here.
I work with the guys that created Anaconda Python. You can install multiple versions of python and numpy without corrupting your system python. It's free and open source (OSX, linux, Windows). The paid packages are enhancements on top of the free version. Pandas is included.
conda create --name np17py27 anaconda=1.4 numpy=1.7 python=2.7
export PATH=~/anaconda/envs/np17py27/bin:$PATH
If you want numpy 1.6:
conda create --name np16py27 anaconda=1.4 numpy=1.6 python=2.7
Setting your PATH sets up where to find python and ipython. The environments (np17py27) can be named whatever you would like.
For reloading the page for a given route path :-
$location.path('/path1/path2');
$route.reload();
select *
from sysobjects
where xtype='pk' and
parent_obj in (select id from sysobjects where name='tablename')
this will work in sql 2005
tables + views + error reporting
SET SERVEROUT ON
DECLARE
o_type VARCHAR2(60) := '';
o_name VARCHAR2(60) := '';
o_owner VARCHAR2(60) := '';
l_error_message VARCHAR2(500) := '';
BEGIN
FOR R IN (SELECT owner, object_type, object_name
FROM all_objects
WHERE owner='SCHEMANAME'
AND object_type IN ('TABLE','VIEW')
ORDER BY 1,2,3) LOOP
BEGIN
o_type := r.object_type;
o_owner := r.owner;
o_name := r.object_name;
DBMS_OUTPUT.PUT_LINE(o_type||' '||o_owner||'.'||o_name);
EXECUTE IMMEDIATE 'grant select on '||o_owner||'.'||o_name||' to USERNAME';
EXCEPTION
WHEN OTHERS THEN
l_error_message := sqlerrm;
DBMS_OUTPUT.PUT_LINE('Error with '||o_type||' '||o_owner||'.'||o_name||': '|| l_error_message);
CONTINUE;
END;
END LOOP;
END;
/
Depends upon the version. The If
operator in VB.NET 2008 is a ternary operator (as well as a null coalescence operator). This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement
Example:
Dim foo as String = If(bar = buz, cat, dog)
[EDIT]
Prior to 2008 it was IIf
, which worked almost identically to the If
operator described Above.
Example:
Dim foo as String = IIf(bar = buz, cat, dog)
Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a struct
or union
.
Example program:
#include <stdio.h>
struct ccont
{
char array[32];
};
struct icont
{
int array[32];
};
int main()
{
int cnt;
char carray[32] = { 'A', 66, 6*11+1 }; // 'A', 'B', 'C', '\0', '\0', ...
int iarray[32] = { 67, 42, 25 };
struct ccont cc = { 0 };
struct icont ic = { 0 };
/* these don't work
carray = { [0]=1 }; // expected expression before '{' token
carray = { [0 ... 31]=1 }; // (likewise)
carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *'
iarray = (int[32]){ 1 }; // (likewise, but s/char/int/g)
*/
// but these perfectly work...
cc = (struct ccont){ .array='a' }; // 'a', '\0', '\0', '\0', ...
// the following is a gcc extension,
cc = (struct ccont){ .array={ [0 ... 2]='a' } }; // 'a', 'a', 'a', '\0', '\0', ...
ic = (struct icont){ .array={ 42,67 } }; // 42, 67, 0, 0, 0, ...
// index ranges can overlap, the latter override the former
// (no compiler warning with -Wall -Wextra)
ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ...
for (cnt=0; cnt<5; cnt++)
printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]);
return 0;
}
I usually use the .ToString() method on exceptions to present the full exception information (including the inner stack trace) in text:
catch (MyCustomException ex)
{
Debug.WriteLine(ex.ToString());
}
Sample output:
ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes!
at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24
at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14
--- End of inner exception stack trace ---
at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18
at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23
at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13
That's what executeUpdate
is for.
Here's a very brief summary of the difference: http://www.coderanch.com/t/301594/JDBC/java/Difference-between-execute-executeQuery-executeUpdate
You should explore SQL Server\Memory Manager performance counters.
Bootstrap still doesnt work with Jquery UI, for example the modal.Bootstrap has nice style but as a framework with Twitter behind isnt that good.
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
The problem is that jQuery doesn't trigger the native click
event for <a>
elements so that navigation doesn't happen (the normal behavior of an <a>
), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).
To trigger it manually, try:
var a = $("<a>")
.attr("href", "http://i.stack.imgur.com/L8rHf.png")
.attr("download", "img.png")
.appendTo("body");
a[0].click();
a.remove();
DEMO: http://jsfiddle.net/HTggQ/
Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
You can try this one it is short
SystemClock.sleep(7000);
WARNING: Never, ever, do this on a UI thread.
Use this to sleep eg. background thread.
Full solution for your problem will be: This is available API 1
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View button) {
button.setBackgroundResource(R.drawable.avatar_dead);
final long changeTime = 1000L;
button.postDelayed(new Runnable() {
@Override
public void run() {
button.setBackgroundResource(R.drawable.avatar_small);
}
}, changeTime);
}
});
Without creating tmp Handler. Also this solution is better than @tronman because we do not retain view by Handler. Also we don't have problem with Handler created at bad thread ;)
public static void sleep (long ms)
Added in API level 1
Waits a given number of milliseconds (of uptimeMillis) before returning. Similar to sleep(long), but does not throw InterruptedException; interrupt() events are deferred until the next interruptible operation. Does not return until at least the specified number of milliseconds has elapsed.
Parameters
ms to sleep before returning, in milliseconds of uptime.
Code for postDelayed from View class:
/**
* <p>Causes the Runnable to be added to the message queue, to be run
* after the specified amount of time elapses.
* The runnable will be run on the user interface thread.</p>
*
* @param action The Runnable that will be executed.
* @param delayMillis The delay (in milliseconds) until the Runnable
* will be executed.
*
* @return true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed --
* if the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*
* @see #post
* @see #removeCallbacks
*/
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Assume that post will succeed later
ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
return true;
}
Building on Varkhan's post that Pentium-specific native code would do better:
jBLAS: An alpha-stage project with JNI wrappers for Atlas: http://www.jblas.org.
MTJ: Another such project: http://code.google.com/p/matrix-toolkits-java/
Don't waste your time trying to resolve this issue, this was made clear by the makers themselves. Instead of cv2.imshow()
use this:
img = cv2.imread('path_to_image')
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
CREATE TABLE `admnih` (
`id` int(255) NOT NULL auto_increment,
`asim` varchar(255) NOT NULL default '',
`brid` varchar(255) NOT NULL default '',
`rwtbah` int(1) NOT NULL default '0',
`esmmwkeh` varchar(255) NOT NULL default '',
`mrwr` varchar(255) NOT NULL default '',
`tid` int(255) NOT NULL default '0',
`alksmfialdlil` int(255) NOT NULL default '0',
`tariktsjil` varchar(255) NOT NULL default '',
`aimwke` varchar(255) NOT NULL default '',
`twkie` text NOT NULL,
`rwtbahkasah` int(255) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
import React, { Component } from "react";
import axios from "axios";
const CancelToken = axios.CancelToken;
let cancel;
class Abc extends Component {
componentDidMount() {
this.Api();
}
Api() {
// Cancel previous request
if (cancel !== undefined) {
cancel();
}
axios.post(URL, reqBody, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
})
.then((response) => {
//responce Body
})
.catch((error) => {
if (axios.isCancel(error)) {
console.log("post Request canceled");
}
});
}
render() {
return <h2>cancel Axios Request</h2>;
}
}
export default Abc;
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8001,suspend=y -jar target/cxf-boot-simple-0.0.1-SNAPSHOT.jar
address
specifies the port at which it will allow to debug
**Debug Spring Boot app with Maven:
mvn spring-boot:run -Drun.jvmArguments=**"-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8001"
For System.Timers.Timer
, according to MSDN documentation, http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx:
If the interval is set after the Timer has started, the count is reset. For example, if you set the interval to 5 seconds and then set the Enabled property to true, the count starts at the time Enabled is set. If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true.
So,
const double TIMEOUT = 5000; // milliseconds
aTimer = new System.Timers.Timer(TIMEOUT);
aTimer.Start(); // timer start running
:
:
aTimer.Interval = TIMEOUT; // restart the timer
I faced the same problem but the issue was very silly, By mistake I have given wrong relationship I have given relationship between 2 Ids.
While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.
public class Simple {
public Simple() {
this(null);
}
public Simple(Resource r) {
this(r, null);
}
public Simple(Resource r1, Resource r2) {
// Guard statements, initialize resources or throw exceptions if
// the resources are wrong
if (r1 == null) {
r1 = new Resource();
}
if (r2 == null) {
r2 = new Resource();
}
// do whatever with resources
}
}
From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:
public class SimpleParams {
Resource r1;
Resource r2;
// Imagine there are setters and getters here but I'm too lazy
// to write it out. you can make it the parameter class
// "immutable" if you don't have setters and only set the
// resources through the SimpleParams constructor
}
The constructor in Simple only either needs to split the SimpleParams
parameter:
public Simple(SimpleParams params) {
this(params.getR1(), params.getR2());
}
…or make SimpleParams
an attribute:
public Simple(Resource r1, Resource r2) {
this(new SimpleParams(r1, r2));
}
public Simple(SimpleParams params) {
this.params = params;
}
Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:
public interface ResourceFactory {
public Resource createR1();
public Resource createR2();
}
The constructor is then done in the same manner as with the parameter class:
public Simple(ResourceFactory factory) {
this(factory.createR1(), factory.createR2());
}
Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple
class that they're used the same way.
add the parameter -expandproperty after the select-object, it will return only data without header.
Ajax (also AJAX) an acronym for Asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously Below is example code:
Jsp page java script function to submit data to servlet with two variable firstName and lastName:
function onChangeSubmitCallWebServiceAJAX()
{
createXmlHttpRequest();
var firstName=document.getElementById("firstName").value;
var lastName=document.getElementById("lastName").value;
xmlHttp.open("GET","/AJAXServletCallSample/AjaxServlet?firstName="
+firstName+"&lastName="+lastName,true)
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
Servlet to read data send back to jsp in xml format ( You could use text as well. Just you need to change response content to text and render data on javascript function.)
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<details>");
response.getWriter().write("<firstName>"+firstName+"</firstName>");
response.getWriter().write("<lastName>"+lastName+"</lastName>");
response.getWriter().write("</details>");
}
Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml", "result.html");
(Sorry for posing this as an answer, but the code block
support in comments is rather limited.)
In VB.NET, you don't even need a variable:
With New XslCompiledTransform()
.Load("stylesheet.xsl")
.Transform("source.xml", "result.html")
End With
In C, single-quotes such as 'a'
indicate character constants whereas "a"
is an array of characters, always terminated with the \0
character
Thank you for inspiration.
I had the same problem and instead of just copy-pasting some function from the Internet, I wrote an open source tool for it. Feel free to use it or provide feedback!
https://github.com/BrandEmbassy/php-memory
Just install it using Composer and then you get the current PHP memory limit like this:
$configuration = new \BrandEmbassy\Memory\MemoryConfiguration();
$limitProvider = new \BrandEmbassy\Memory\MemoryLimitProvider($configuration);
$limitInBytes = $memoryLimitProvider->getLimitInBytes();
The following are equivalent and result in a two dimensional array:
$array = array(
array(0, 1, 2),
array(3, 4, 5),
);
or
$array = array();
$array[] = array(0, 1, 2);
$array[] = array(3, 4, 5);
This should do it (where df is your dataframe)
df$JoiningDate <- as.Date(df$JoiningDate , format = "%m/%d/%y")
df[order(df$JoiningDate ),]
A Windows load event fires when all the content on your page is fully loaded including the DOM (document object model) content and asynchronous JavaScript, frames and images. You can also use body onload=. Both are the same; window.onload = function(){}
and <body onload="func();">
are different ways of using the same event.
jQuery $document.ready
function event executes a bit earlier than window.onload
and is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.
Taken from the following article:
how $document.ready()
is different from window.onload()
I had difficulty with this problem as well. I code mainly in Actionscript 3.0 which is base coding for the Adobe Flash Platform, but there are simularities in the Languages:
The solution I came up with is the following:
//Code for Rounding to the nearest 0.05
var r:Number = Math.random() * 10; // NUMBER - Input Your Number here
var n:int = r * 10; // INTEGER - Shift Decimal 2 places to right
var f:int = Math.round(r * 10 - n) * 5;// INTEGER - Test 1 or 0 then convert to 5
var d:Number = (n + (f / 10)) / 10; // NUMBER - Re-assemble the number
trace("ORG No: " + r);
trace("NEW No: " + d);
Thats pretty much it. Note the use of 'Numbers' and 'Integers' and the way they are processed.
Good Luck!
I know it's been eight years but I wanted to share this piece of code found in MRuby that shows how __declspec()
can bee used at the same level as the export keyword
.
/** Declare a public MRuby API function. */
#if defined(MRB_BUILD_AS_DLL)
#if defined(MRB_CORE) || defined(MRB_LIB)
# define MRB_API __declspec(dllexport)
#else
# define MRB_API __declspec(dllimport)
#endif
#else
# define MRB_API extern
#endif
I had come across this problem many times. There is cl.exe
but for some strange reason pip
couldn't find it, even if we run the command from the bin
folder where cl.exe
is present. Try using conda installer, it worked fine for me.
As you can see in the following image, pip
is not able to find the cl.exe
. Then I tried installing using conda
And to my surprise it gets installed without an error once you have the right version of vs cpp build tools installed, i.e. v14.0 in the right directory.
Does Retrofit have any method to achieve this? If not, how I can do that?
YES
Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.
For more information refer the following link
https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial
[edited]when we have two functions say functionA and functionB,if functionA depends on functionB.
then we call functionB as a callback function.this is widely used in Spring framework.
Instead of using align-self: center
use align-items: center
.
There's no need to change flex-direction
or use text-align
.
Here's your code, with one adjustment, to make it all work:
ul {
height: 100%;
}
li {
display: flex;
justify-content: center;
/* align-self: center; <---- REMOVE */
align-items: center; /* <---- NEW */
background: silver;
width: 100%;
height: 20%;
}
The align-self
property applies to flex items. Except your li
is not a flex item because its parent – the ul
– does not have display: flex
or display: inline-flex
applied.
Therefore, the ul
is not a flex container, the li
is not a flex item, and align-self
has no effect.
The align-items
property is similar to align-self
, except it applies to flex containers.
Since the li
is a flex container, align-items
can be used to vertically center the child elements.
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
html, body {_x000D_
height: 100%;_x000D_
}_x000D_
ul {_x000D_
height: 100%;_x000D_
}_x000D_
li {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
/* align-self: center; */_x000D_
align-items: center;_x000D_
background: silver;_x000D_
width: 100%;_x000D_
height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
<li>This is the text</li>_x000D_
</ul>
_x000D_
Technically, here's how align-items
and align-self
work...
The align-items
property (on the container) sets the default value of align-self
(on the items). Therefore, align-items: center
means all flex items will be set to align-self: center
.
But you can override this default by adjusting the align-self
on individual items.
For example, you may want equal height columns, so the container is set to align-items: stretch
. However, one item must be pinned to the top, so it is set to align-self: flex-start
.
How is the text a flex item?
Some people may be wondering how a run of text...
<li>This is the text</li>
is a child element of the li
.
The reason is that text that is not explicitly wrapped by an inline-level element is algorithmically wrapped by an inline box. This makes it an anonymous inline element and child of the parent.
From the CSS spec:
9.2.2.1 Anonymous inline boxes
Any text that is directly contained inside a block container element must be treated as an anonymous inline element.
The flexbox specification provides for similar behavior.
Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item.
Hence, the text in the li
is a flex item.
Extract unique words sorted ASC from a list of phrases:
List<String> phrases = Arrays.asList(
"sporadic perjury",
"confounded skimming",
"incumbent jailer",
"confounded jailer");
List<String> uniqueWords = phrases
.stream()
.flatMap(phrase -> Stream.of(phrase.split("\\s+")))
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println("Unique words: " + uniqueWords);
... and the output:
Unique words: [confounded, incumbent, jailer, perjury, skimming, sporadic]
This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.
<GridTile
key={video_id}
title={video_title}
containerElement={<Link to={`/player/${video_id}`}/>}
>
ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )
You can call clear, and that will destroy all the objects, but that will not free the memory. Looping through the individual elements will not help either (what action would you even propose to take on the objects?) What you can do is this:
vector<tempObject>().swap(tempVector);
That will create an empty vector with no memory allocated and swap it with tempVector, effectively deallocating the memory.
C++11 also has the function shrink_to_fit
, which you could call after the call to clear(), and it would theoretically shrink the capacity to fit the size (which is now 0). This is however, a non-binding request, and your implementation is free to ignore it.
Another way to do this in Notepad++ is all in the Find/Replace dialog and with regex:
Ctrl + h to bring up the find replace dialog.
In the Find what:
text box include your regex: .*help.*\r?\n
(where the \r
is optional in case the file doesn't have Windows line endings).
Leave the Replace with:
text box empty.
Make sure the Regular expression radio button in the Search Mode area is selected. Then click Replace All
and voila! All lines containing your search term help
have been removed.
Though all the answers on the page will return the desired result, they all have performance issues. Never perform calculations on fields in the WHERE
clause (including a DATE()
calculation) as that calculation must be performed on all rows in the table.
The BETWEEN ... AND
construct is inclusive for both border conditions, requiring one to specify the 23:59:59 syntax on the end date which itself has other issues (microsecond transactions, which I believe MySQL did not support in 2009 when the question was asked).
The proper way to query a MySQL timestamp
field for a particular day is to check for Greater-Than-Equals against the desired date, and Less-Than for the day after, with no hour specified.
WHERE datetime>='2009-10-20' AND datetime<'2009-10-21'
This is the fastest-performing, lowest-memory, least-resource intensive method, and additionally supports all MySQL features and corner-cases such as sub-second timestamp precision. Additionally, it is future proof.
Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value.
An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this:
RRRR RGGG GGGB BBBB
You could then use bit masking to retrieve the colour components as follows:
const unsigned short redMask = 0xF800;
const unsigned short greenMask = 0x07E0;
const unsigned short blueMask = 0x001F;
unsigned short lightGray = 0x7BEF;
unsigned short redComponent = (lightGray & redMask) >> 11;
unsigned short greenComponent = (lightGray & greenMask) >> 5;
unsigned short blueComponent = (lightGray & blueMask);
var number = parseInt($(this).find('.number').text());
var current = 600;
if (current > number)
{
// do something
}
func registerForKeyboardNotifications()
{
//Keyboard
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWasShown), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIKeyboardDidHideNotification, object: nil)
}
func deregisterFromKeyboardNotifications(){
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWasShown(notification: NSNotification){
let userInfo: NSDictionary = notification.userInfo!
let keyboardInfoFrame = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue()
let windowFrame:CGRect = (UIApplication.sharedApplication().keyWindow!.convertRect(self.view.frame, fromView:self.view))
let keyboardFrame = CGRectIntersection(windowFrame, keyboardInfoFrame!)
let coveredFrame = UIApplication.sharedApplication().keyWindow!.convertRect(keyboardFrame, toView:self.view)
let contentInsets = UIEdgeInsetsMake(0, 0, (coveredFrame.size.height), 0.0)
self.scrollViewInAddCase .contentInset = contentInsets;
self.scrollViewInAddCase.scrollIndicatorInsets = contentInsets;
self.scrollViewInAddCase.contentSize = CGSizeMake((self.scrollViewInAddCase.contentSize.width), (self.scrollViewInAddCase.contentSize.height))
}
/**
this method will fire when keyboard was hidden
- parameter notification: contains keyboard details
*/
func keyboardWillBeHidden (notification: NSNotification) {
self.scrollViewInAddCase.contentInset = UIEdgeInsetsZero
self.scrollViewInAddCase.scrollIndicatorInsets = UIEdgeInsetsZero
}
Using test
if test ! -z "$(docker images -q <name:tag>)"; then
echo "Exist"
fi
or in one line
test ! -z "$(docker images -q <name:tag>)" && echo exist
Got it! JSBeautifier does exactly this, and you even have options for the auto-formatting.
A good workaround in some cases may be to move the variables and code to another function:
def print_data(data):
print data
def main():
data = [4, 5, 6]
print_data(data)
main()
I have a lib what use https://requests.readthedocs.io/en/master/ what use https://pypi.org/project/certifi/ but I have a custom CA included in my /etc/ssl/certs
.
So I solved my problem like this:
# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like again)
export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt"
# If you have a virtualenv:
. ./.venv/bin/activate
# Get the current certifi CA bundle
CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'`
test -L $CERTFI_PATH || rm $CERTFI_PATH
test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH
Et voilà !
You can also use =OFFSET([@column];-1;0)
if you are in a named table.
In-case if someone wants a little dynamic search.
let searchInArray=(searchQuery, array, objectKey=null)=>{
return array.filter(d=>{
let data =objectKey? d[objectKey] : d //Incase If It's Array Of Objects.
let dataWords= typeof data=="string" && data?.split(" ")?.map(b=>b&&b.toLowerCase().trim()).filter(b=>b)
let searchWords = typeof searchQuery=="string"&&searchQuery?.split(" ").map(b=>b&&b.toLowerCase().trim()).filter(b=>b)
let matchingWords = searchWords.filter(word=>dataWords.includes(word))
return matchingWords.length
})
}
For an Array of strings:
let arrayOfStr = [
"Search for words",
"inside an array",
"dynamic searching",
"match rate 90%"
]
searchInArray("dynamic search", arrayOfStr)
//Results: [ "Search for words", "dynamic searching" ]
For an Array of Objects:
let arrayOfObject = [
{
"address": "Karachi Pakistan"
},
{
"address": "UK London"
},
{
"address": "Pakistan Lahore"
}
]
searchInArray("Pakistan", arrayOfObject,"address")
//Results: [ { "address": "Karachi Pakistan" }, { "address": "Pakistan Lahore" } ]
Make sure you use the right doctype.
eg.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
or just
<!doctype html>
and also read and understand how compatibility modes and developer toolbar for IE work and set modes for IE:
Prerequisite:
Your APK needs to be signed by system as correctly pointed out earlier. One way to achieve that is building the AOSP image yourself and adding the source code into the build.
Code:
Once installed as a system app, you can use the package manager methods to install and uninstall an APK as following:
Install:
public boolean install(final String apkPath, final Context context) {
Log.d(TAG, "Installing apk at " + apkPath);
try {
final Uri apkUri = Uri.fromFile(new File(apkPath));
final String installerPackageName = "MyInstaller";
context.getPackageManager().installPackage(apkUri, installObserver, PackageManager.INSTALL_REPLACE_EXISTING, installerPackageName);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Uninstall:
public boolean uninstall(final String packageName, final Context context) {
Log.d(TAG, "Uninstalling package " + packageName);
try {
context.getPackageManager().deletePackage(packageName, deleteObserver, PackageManager.DELETE_ALL_USERS);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
To have a callback once your APK is installed/uninstalled you can use this:
/**
* Callback after a package was installed be it success or failure.
*/
private class InstallObserver implements IPackageInstallObserver {
@Override
public void packageInstalled(String packageName, int returnCode) throws RemoteException {
if (packageName != null) {
Log.d(TAG, "Successfully installed package " + packageName);
callback.onAppInstalled(true, packageName);
} else {
Log.e(TAG, "Failed to install package.");
callback.onAppInstalled(false, null);
}
}
@Override
public IBinder asBinder() {
return null;
}
}
/**
* Callback after a package was deleted be it success or failure.
*/
private class DeleteObserver implements IPackageDeleteObserver {
@Override
public void packageDeleted(String packageName, int returnCode) throws RemoteException {
if (packageName != null) {
Log.d(TAG, "Successfully uninstalled package " + packageName);
callback.onAppUninstalled(true, packageName);
} else {
Log.e(TAG, "Failed to uninstall package.");
callback.onAppUninstalled(false, null);
}
}
@Override
public IBinder asBinder() {
return null;
}
}
/**
* Callback to give the flow back to the calling class.
*/
public interface InstallerCallback {
void onAppInstalled(final boolean success, final String packageName);
void onAppUninstalled(final boolean success, final String packageName);
}
===> Tested on Android 8.1 and worked well.
<i class="fa" v-bind:class="cravings"></i>
and add in computed :
computed: {
cravings: function() {
return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
}
}
Another alternative is to use Pycharm IDE. For each project, you can set the Project Interpreter in Settings.
For example, if anaconda is installed in /home/user/anaconda2/bin/python, you can select the Project Interpreter and set to this folder.
Since the whole project is set to Anaconda's path, you can import any module which is packaged within Anaconda.
Objective-C
NSString *str = @"Hello World";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
Swift
let str = "Hello World"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
Use --table
to tell pg_dump
what table it has to backup:
pg_dump --host localhost --port 5432 --username postgres --format plain --verbose --file "<abstract_file_path>" --table public.tablename dbname
As of Laravel 5.2+, you can fetch it directly with $request->input('item')
as well.
Retrieving JSON Input Values
When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig deeper into JSON arrays:
$name = $request->input('user.name');
https://laravel.com/docs/5.2/requests
As noted above, the content-type header must be set to application/json
so the jQuery ajax call would need to include contentType: "application/json",
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
contentType: "application/json",
success:function(data) {
$('#save_message').html(data.message);
}
});
By fixing the AJAX call, $request->all()
should work.
Check if the scrollable element is already scrolled to the top when trying to scroll up or to the bottom when trying to scroll down and then preventing the default action to stop the entire page from moving.
var touchStartEvent;
$('.scrollable').on({
touchstart: function(e) {
touchStartEvent = e;
},
touchmove: function(e) {
if ((e.originalEvent.pageY > touchStartEvent.originalEvent.pageY && this.scrollTop == 0) ||
(e.originalEvent.pageY < touchStartEvent.originalEvent.pageY && this.scrollTop + this.offsetHeight >= this.scrollHeight))
e.preventDefault();
}
});
Since I link with gcc why ld is being called, as the error message suggests?
gcc calls ld internally when it is in linking mode.
If this example can help, adds a "custom confirm popin" on some links (I keep the code of "$.ui.Modal.confirm", it's just an exemple for the callback that executes the original action) :
//Register "custom confirm popin" on click on specific links
$(document).on(
"click",
"A.confirm",
function(event){
//prevent default click action
event.preventDefault();
//show "custom confirm popin"
$.ui.Modal.confirm(
//popin text
"Do you confirm ?",
//action on click 'ok'
function() {
//Unregister handler (prevent loop)
$(document).off("click", "A.confirm");
//Do default click action
$(event.target)[0].click();
}
);
}
);
The + operator can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.
The concat operator can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.
Except this, the code you provided does the same stuff.
If the return
in the try
block is reached, it transfers control to the finally
block, and the function eventually returns normally (not a throw).
If an exception occurs, but then the code reaches a return
from the catch
block, control is transferred to the finally
block and the function eventually returns normally (not a throw).
In your example, you have a return
in the finally
, and so regardless of what happens, the function will return 34
, because finally
has the final (if you will) word.
Although not covered in your example, this would be true even if you didn't have the catch
and if an exception were thrown in the try
block and not caught. By doing a return
from the finally
block, you suppress the exception entirely. Consider:
public class FinallyReturn {
public static final void main(String[] args) {
System.out.println(foo(args));
}
private static int foo(String[] args) {
try {
int n = Integer.parseInt(args[0]);
return n;
}
finally {
return 42;
}
}
}
If you run that without supplying any arguments:
$ java FinallyReturn
...the code in foo
throws an ArrayIndexOutOfBoundsException
. But because the finally
block does a return
, that exception gets suppressed.
This is one reason why it's best to avoid using return
in finally
.
You can pass a function to the onScroll
event on the React element: https://facebook.github.io/react/docs/events.html#ui-events
<ScrollableComponent
onScroll={this.handleScroll}
/>
Another answer that is similar: https://stackoverflow.com/a/36207913/1255973
I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even
SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;
Boost Preprocessor actually has this as of Boost 1.49, as BOOST_PP_VARIADIC_SIZE(...)
. It works up to size 64.
Under the hood, it's basically the same as Kornel Kisielewicz's answer.
Posting answer to my own question as I found it here and was hidden in bottom somewhere -
This is because the OS failed to install the required update Windows8.1-KB2999226-x64.msu.
However, you can install it by extracting that update to a folder (e.g. XXXX), and execute following cmdlet. You can find the Windows8.1-KB2999226-x64.msu at below.
C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu
copy this file to a folder you like, and
Create a folder XXXX in that and execute following commands from Admin command propmt
wusa.exe Windows8.1-KB2999226-x64.msu /extract:XXXX
DISM.exe /Online /Add-Package /PackagePath:XXXX\Windows8.1-KB2999226-x64.cab
vc_redist.x64.exe /repair
(last command need not be run. Just execute vc_redist.x64.exe once again)
this worked for me.
I found that for IE, you must add the draggable="false" attribute to images and anchors to prevent dragging. the CSS options work for all other browsers. I did this in jQuery:
$("a").attr('draggable', false);
$("img").attr('draggable', false);
This might be an alternative solution. Paste the following code into the new module:
Public Function ModDate()
ModDate =
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm")
End Function
Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.
Paste the following code into the cell where you want to display the last modification time:
=ModDate()
I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel
As others have posted, you can use recursion/dfs to print the nested dictionary data and call recursively if it is a dictionary; otherwise print the data.
def print_json(data):
if type(data) == dict:
for k, v in data.items():
print k
print_json(v)
else:
print data
Yes, you can add a UNIQUE constraint after the fact. However, if you have non-unique entries in your table Postgres will complain about it until you correct them.
Yes, you can do a 3 table join for an update statement. Here is an example :
UPDATE customer_table c
JOIN
employee_table e
ON c.city_id = e.city_id
JOIN
anyother_ table a
ON a.someID = e.someID
SET c.active = "Yes"
WHERE c.city = "New york";
Use .AddRange
to append any Enumrable collection to the list.
The effect of the volatile
keyword is approximately that each individual read or write operation on that variable is atomic.
Notably, however, an operation that requires more than one read/write -- such as i++
, which is equivalent to i = i + 1
, which does one read and one write -- is not atomic, since another thread may write to i
between the read and the write.
The Atomic
classes, like AtomicInteger
and AtomicReference
, provide a wider variety of operations atomically, specifically including increment for AtomicInteger
.
Use below code snippet This worked for me
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"symbol\":\"ABCD\}";
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Trade trade = objectMapper.readValue(jsonString, new TypeReference<Symbol>() {});
Model Class
@JsonIgnoreProperties public class Symbol {
@JsonProperty("symbol")
private String symbol;
}
Please note that for Chrome to work properly it needs to be autocomplete="false"
what's your opinion on this one?
function giveitauniquename()
{
so this is a comment
echo "there's no need to further escape apostrophes/etc if you are commenting your code this way"
the drawback is it will be stored in memory as a function as long as your script runs unless you explicitly unset it
only valid-ish bash allowed inside for instance these would not work without the "pound" signs:
1, for #((
2, this #wouldn't work either
function giveitadifferentuniquename()
{
echo nestable
}
}
Go from this:
config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
To this:
config.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
Hence, you can now specify which action (method) you want to send your HTTP request to.
posting to "http://localhost:8383/api/Command/PostCreateUser" invokes:
public bool PostCreateUser(CreateUserCommand command)
{
//* ... *//
return true;
}
and posting to "http://localhost:8383/api/Command/PostMakeBooking" invokes:
public bool PostMakeBooking(MakeBookingCommand command)
{
//* ... *//
return true;
}
I tried this in a self hosted WEB API service application and it works like a charm :)
You can also do this - Since you want one function to be used everywhere, you can do so by directly calling JqueryObject.function(). For example if you want to create your own function to manipulate any CSS on an element:
jQuery.fn.doSomething = function () {
this.css("position","absolute");
return this;
}
And the way to call it:
$("#someRandomDiv").doSomething();
Try
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: 'http://imageshack.us/a/img826/9489/x1my.png',
map: map
});
from here
https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom
I moved VS Code from Downloads folder to Applications, and then i was able to run code in the terminal. I guess, it might help you too.
Use StringUtils.isEmpty
instead, it will also check for null.
Examples are:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
See more on official Documentation on String Utils.
The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.
Borrowing from this answer, you could do something like this without moment.js:
controller
var app1 = angular.module('app1',[]);
app1.controller('ctrl',['$scope',function($scope){
var toUTCDate = function(date){
var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return _utc;
};
var millisToUTCDate = function(millis){
return toUTCDate(new Date(millis));
};
$scope.toUTCDate = toUTCDate;
$scope.millisToUTCDate = millisToUTCDate;
}]);
template
<html ng-app="app1">
<head>
<script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ctrl">
<div>
utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
</div>
<div>
local {{1400167800 | date:'dd-M-yyyy H:mm'}}
</div>
</div>
</body>
</html>
here's plunker to play with it
Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.
In my case the issue was resolved by installing Oracle's official JDK 10 as opposed to using the default OpenJDK that came with my Ubuntu. This is the guide I followed: https://www.linuxuprising.com/2018/04/install-oracle-java-10-in-ubuntu-or.html
Note for anybody who may have had problems with the cvWaitKey( )
function. If you are finding that cvWaitKey(x)
is not waiting at all, make sure you actually have a window open (i.e. cvNamedWindow(...)
). Put the cvNamedWindow(...)
declaration BEFORE any cvWaitKey()
function calls.
You can try this :
=COUNTIF(Data!A2:A300,"<>"&"")
Thanks for the info, think I see the problem. This is a bug in hive-go
that only shows up when you add a host. The last lines of it are:
app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);
When you add the host on the first line, it is crashing when it calls app.address().port
.
The problem is the potentially asynchronous nature of .listen()
. Really it should be doing that console.log
call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.
Try this:
app.listen(3001, 'localhost', function() {
console.log("... port %d in %s mode", app.address().port, app.settings.env);
});
The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element
to do DOM operations. The method defined in the directive controller is accessible in the main controller.
Example, finding a child element:
var app = angular.module('myapp', []);
app.directive("testDir", function () {
function link(scope, element) {
}
return {
restrict: "AE",
link: link,
controller:function($scope,$element){
$scope.name2 = 'this is second name';
var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
}
};
})
app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});
There is no such operator in Python, but it is trivial to implement on your own. In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one.
This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
@model TestProject.Models.TestModel
<script>
function testButton_Click(){
var javaModel ={
ModelId: '@Model.TestId',
CreatedDate: '@Model.CreatedDate.ToShortDateString()',
TestDescription: '@Model.TestDescription',
//Here I am using a Kendo editor and I want to bind the text value to my javascript
//object. This may be different for you depending on what controls you use.
TestStatus: ($('#StatusTextBox'))[0].value,
TestType: '@Model.TestType'
}
//Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
//selected value. This puzzled me due to the conversion to Json object in the Ajax call.
//By parsing the Type to an int this worked.
javaModel.TestType = parseInt(javaModel.TestType);
$.ajax({
//This is where you want to post to.
url:'@Url.Action("TestModelUpdate","TestController")',
async:true,
type:"POST",
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(javaModel)
});
}
</script>
//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.
[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
TestModel.UpdateTestModel(newTestModel);
return //do some return action;
}
Maybe not very elegant, but it does the job:
exec(open("script.py").read())
Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.
function indexToChar(i) {
return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a',
// i=1 returns 'b', etc
}
According to @jaiswal Rajan in his answer. You can do a pushViewController like this:
let storyBoard: UIStoryboard = UIStoryboard(name: "NewBotStoryboard", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "NewViewController") as! NewViewController
self.navigationController?.pushViewController(newViewController, animated: true)