<img id="uxcMyImageId" src"myImage" width="100" height="100" />
specifying width and height in the image tag is a good practice..this way when the page loads there is space allocated for the image and the layout does not suffer any jerks even if the image takes a long time to load.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials()
);
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
After much searching and frustration a combo of setting height, line height and no padding worked for me when using a fixed height (24px) background image for a text input field.
.form-text {
color: white;
outline: none;
background-image: url(input_text.png);
border-width: 0px;
padding: 0px 10px 0px 10px;
margin: 0px;
width: 274px;
height: 24px;
line-height: 24px;
vertical-align: middle;
}
<?php
$array = Array();
for( $i = 65; $i < 91; $i++){
$array[] = chr($i);
}
foreach( $array as $k => $v){
echo "$k $v \n";
}
?>
$ php loop.php
0 A
1 B
2 C
3 D
4 E
5 F
6 G
7 H
...
Just in case somebody needs to check the condition from session.Usage of or
<c:if test="${sessionScope['roleid'] == 1 || sessionScope['roleid'] == 4}">
Update: The answer previously posted here linked to a custom script that is no longer available, solely because the OP indicated that date +'%s'
didn't work for him. Please see UberAlex' answer and cadrian's answer for proper solutions. In short:
For the number of seconds since the Unix epoch use date(1)
as follows:
date +'%s'
For the number of days since the Unix epoch divide the result by the number of seconds in a day (mind the double parentheses!):
echo $(($(date +%s) / 60 / 60 / 24))
As it happens I was just reading about this this morning on my way to work in Java Concurrency In Practice by Brian Goetz. Basically he says you should do one of three things
Propagate the InterruptedException
- Declare your method to throw the checked InterruptedException
so that your caller has to deal with it.
Restore the Interrupt - Sometimes you cannot throw InterruptedException
. In these cases you should catch the InterruptedException
and restore the interrupt status by calling the interrupt()
method on the currentThread
so the code higher up the call stack can see that an interrupt was issued, and quickly return from the method. Note: this is only applicable when your method has "try" or "best effort" semantics, i. e. nothing critical would happen if the method doesn't accomplish its goal. For example, log()
or sendMetric()
may be such method, or boolean tryTransferMoney()
, but not void transferMoney()
. See here for more details.
Uninterruptibles
. Uninterruptibles
take over the boilerplate code like in the Noncancelable Task example in JCIP § 7.1.3.$('#myId').val()
should do it, failing that I would try:
$('#myId option:selected').val()
One solution is to use matplotlib histogram directly on each grouped data frame. You can loop through the groups obtained in a loop. Each group is a dataframe. And you can create a histogram for each one.
from pandas import DataFrame
import numpy as np
x = ['A']*300 + ['B']*400 + ['C']*300
y = np.random.randn(1000)
df = DataFrame({'Letter':x, 'N':y})
grouped = df.groupby('Letter')
for group in grouped:
figure()
matplotlib.pyplot.hist(group[1].N)
show()
Package php-dom is a virtual package provided by:
php7.1-xml 7.1.3+-3+deb.sury.org~xenial+1
php7.0-xml 7.0.17-3+deb.sury.org~xenial+1
php5.6-xml 5.6.30-9+deb.sury.org~xenial+1
You should explicitly select one to install.
In case anyone using 5.6 versions then go with this way
sudo apt-get install php5.6-xml
For Php Ver PHP7, Ubuntu:
sudo apt-get install php7.1-xml
or by
yum install php-xml
Pitfall:
<my-directive></my-directive>
wont work on IE8 without workaround (https://docs.angularjs.org/guide/ie)<div data-my-directive="ValueOfTheFirstParameter"></div>
Instead of this:
<my-directive my-param="ValueOfTheFirstParameter"></my-directive>
We dont use custom html elements, because if this 2 facts.
Every directive by third party framework can be written in two ways:
<my-directive></my-directive>
or
<div data-my-directive></div>
does the same.
Here is a workaround to copy all the objects from one arrayList to another:
ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();
myObject.addAll(myTempObject.subList(0, myTempObject.size()));
subList is intended to return a List with a range of data. so you can copy the whole arrayList or part of it.
In my particular case I was rendering a Rails partial without render layout: false
which was re-rendering the entire layout, including all of the scripts in the <head>
tag. Adding render layout: false
to the controller action fixed the problem.
If you are using jQuery, you don't have to do anything special. Handlers added via $(document).ready()
don't overwrite each other, but rather execute in turn:
$(document).ready(func1)
...
$(document).ready(func2)
If you are not using jQuery, you could use addEventListener
, as demonstrated by Karaxuna, plus attachEvent
for IE<9.
Note that onload
is not equivalent to $(document).ready()
- the former waits for CSS, images... as well, while the latter waits for the DOM tree only. Modern browsers (and IE since IE9) support the DOMContentLoaded
event on the document, which corresponds to the jQuery ready
event, but IE<9 does not.
if(window.addEventListener){
window.addEventListener('load', func1)
}else{
window.attachEvent('onload', func1)
}
...
if(window.addEventListener){
window.addEventListener('load', func2)
}else{
window.attachEvent('onload', func2)
}
If neither option is available (for example, you are not dealing with DOM nodes), you can still do this (I am using onload
as an example, but other options are available for onload
):
var oldOnload1=window.onload;
window.onload=function(){
oldOnload1 && oldOnload1();
func1();
}
...
var oldOnload2=window.onload;
window.onload=function(){
oldOnload2 && oldOnload2();
func2();
}
or, to avoid polluting the global namespace (and likely encountering namespace collisions), using the import/export IIFE pattern:
window.onload=(function(oldLoad){
return function(){
oldLoad && oldLoad();
func1();
}
})(window.onload)
...
window.onload=(function(oldLoad){
return function(){
oldLoad && oldLoad();
func2();
}
})(window.onload)
Edit: note that this answer is 3+ years old. For newer versions of apache, please see the answer by sp00n. Leaving this answer for users of older versions of apache.
For debugging mod_rewrite issues, you'll want to use RewriteLogLevel and RewriteLog:
RewriteLogLevel 3
RewriteLog "/usr/local/var/apache/logs/rewrite.log"
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
I found a bug in shermy's vanilla C# 3.5 .NET solution which otherwise works a charm. I have also incorporated Damian Leszczynski - Vash's SecureString idea here but you can use an ordinary string if you prefer.
THE BUG: If you press backspace during the password prompt and the current length of the password is 0 then an asterisk is incorrectly inserted in the password mask. To fix this bug modify the following method.
public static string ReadPassword(char mask)
{
const int ENTER = 13, BACKSP = 8, CTRLBACKSP = 127;
int[] FILTERED = { 0, 27, 9, 10 /*, 32 space, if you care */ }; // const
SecureString securePass = new SecureString();
char chr = (char)0;
while ((chr = System.Console.ReadKey(true).KeyChar) != ENTER)
{
if (((chr == BACKSP) || (chr == CTRLBACKSP))
&& (securePass.Length > 0))
{
System.Console.Write("\b \b");
securePass.RemoveAt(securePass.Length - 1);
}
// Don't append * when length is 0 and backspace is selected
else if (((chr == BACKSP) || (chr == CTRLBACKSP)) && (securePass.Length == 0))
{
}
// Don't append when a filtered char is detected
else if (FILTERED.Count(x => chr == x) > 0)
{
}
// Append and write * mask
else
{
securePass.AppendChar(chr);
System.Console.Write(mask);
}
}
System.Console.WriteLine();
IntPtr ptr = new IntPtr();
ptr = Marshal.SecureStringToBSTR(securePass);
string plainPass = Marshal.PtrToStringBSTR(ptr);
Marshal.ZeroFreeBSTR(ptr);
return plainPass;
}
There's no dedicated "character type" in C language. char
is an integer type, same (in that regard) as int
, short
and other integer types. char
just happens to be the smallest integer type. So, just like any other integer type, it can be signed or unsigned.
It is true that (as the name suggests) char
is mostly intended to be used to represent characters. But characters in C are represented by their integer "codes", so there's nothing unusual in the fact that an integer type char
is used to serve that purpose.
The only general difference between char
and other integer types is that plain char
is not synonymous with signed char
, while with other integer types the signed
modifier is optional/implied.
Webrtc is a part of peer to peer connection. We all know that before creating peer to peer connection, it requires handshaking process to establish peer to peer connection. And websockets play the role of handshaking process.
Try running this code in your script.
document.getElementById("dummy").remove();
And it will hopefully remove the element/button.
Try:
<xsl:value-of select="count(preceding-sibling::*) + 1" />
Edit - had a brain freeze there, position() is more straightforward!
You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder
The only restrictions/limitations:
IEDriverServer.exe
- should be downloaded separately and placed near SwdPageRecorder.exe
Another way to get current boost version (Linux Ubuntu):
~$ dpkg -s libboost-dev | grep Version
Version: 1.58.0.1ubuntu1
Ref: https://www.osetc.com/en/how-to-install-boost-on-ubuntu-16-04-18-04-linux.html
Create elegant extension for UIColor
:
extension UIColor {
convenience init(string: String) {
var uppercasedString = string.uppercased()
uppercasedString.remove(at: string.startIndex)
var rgbValue: UInt32 = 0
Scanner(string: uppercasedString).scanHexInt32(&rgbValue)
let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
let blue = CGFloat(rgbValue & 0x0000FF) / 255.0
self.init(red: red, green: green, blue: blue, alpha: 1)
}
}
Create red color:
let red = UIColor(string: "#ff0000")
First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:
raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it
freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Then you need to create a data frame out of it, melt it and plot it:
Names=c("Food","Music","People") # create list of names
data=data.frame(cbind(freq),Names) # combine them into a data frame
data=data[,c(5,3,1,2,4)] # sort columns
# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')
# plot everything
ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")
Is this what you're after?
To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:
> head(df)
ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1 1 A 1980 450 338 154 36 13 9
2 2 A 2000 288 407 212 54 16 23
3 3 A 2020 196 434 246 68 19 36
4 4 B 1980 111 326 441 90 21 11
5 5 B 2000 63 298 443 133 42 21
6 6 B 2020 36 257 462 162 55 30
Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape
and plotted.
For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw))
to get this:
> data
Names Very.Bad Bad Good Very.Good
1 Food 7 6 5 2
2 Music 5 5 7 3
3 People 6 3 7 4
Just imagine you have Very.Bad
, Bad
, Good
and so on instead of X1PCE
, X2PCE
, X3PCE
. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw))
.
table{
height:1px;
}
table > td{
height:100%;
}
table > td > .inner{
height:100%;
}
Confirmed working on:
The easiest way to do this in my experience is with the Cloudmersive free native PHP library, just call convertDocumentDocxToPdf:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\ConvertDocumentApi(
new GuzzleHttp\Client(),
$config
);
$input_file = "/path/to/file.txt"; // \SplFileObject | Input file to perform the operation on.
try {
$result = $apiInstance->convertDocumentDocxToPdf($input_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertDocumentApi->convertDocumentDocxToPdf: ', $e->getMessage(), PHP_EOL;
}
?>
Be sure to replace $input_file with the appropriate file path. You can also configure it to use a byte array if you prefer to do it that way. The result will be the bytes of the converted PDF file.
After a bit of trial and error... as mentioned in the possible answers, it turned out to require xfs_growfs
rather than resize2fs
.
CentOS 7,
fdisk /dev/xvda
Create new primary partition, set type as linux lvm
.
n
p
3
t
8e
w
Create a new primary volume and extend the volume group to the new volume.
partprobe
pvcreate /dev/xvda3
vgextend /dev/centos /dev/xvda3
Check the physical volume for free space, extend the logical volume with the free space.
vgdisplay -v
lvextend -l+288 /dev/centos/root
Finally perform an online resize to resize the logical volume, then check the available space.
xfs_growfs /dev/centos/root
df -h
My answer is very similar to Ricardo's answer, but I feel that my approach is a little more straightforward simply because there is so much going on in his using
function that I'm not even sure how exactly it works on a lower level.
So for those who want a simple and clean solution that creates a database for you where you know exactly what is happening under the hood, this is for you:
public Startup(IHostingEnvironment env)
{
using (var client = new TargetsContext())
{
client.Database.EnsureCreated();
}
}
This pretty much means that within the DbContext
that you created (in this case, mine is called TargetsContext
), you can use an instance of the DbContext
to ensure that the tables defined with in the class are created when Startup.cs is run in your application.
UPDATE 2019-06-24
Based on the @Jodiug comment if you have a 1.15
version you can use the command:
kubectl rollout restart deployment/demo
Read more on the issue:
https://github.com/kubernetes/kubernetes/issues/13488
Well there is an interesting discussion about this subject on the kubernetes GitHub project. See the issue: https://github.com/kubernetes/kubernetes/issues/33664
From the solutions described there, I would suggest one of two.
1.Prepare deployment
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: demo
spec:
replicas: 1
template:
metadata:
labels:
app: demo
spec:
containers:
- name: demo
image: registry.example.com/apps/demo:master
imagePullPolicy: Always
env:
- name: FOR_GODS_SAKE_PLEASE_REDEPLOY
value: 'THIS_STRING_IS_REPLACED_DURING_BUILD'
2.Deploy
sed -ie "s/THIS_STRING_IS_REPLACED_DURING_BUILD/$(date)/g" deployment.yml
kubectl apply -f deployment.yml
kubectl patch deployment web -p \
"{\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"`date +'%s'`\"}}}}}"
Of course the imagePullPolicy: Always
is required on both cases.
\b
matches a word-boundary. \B
matches non-word-boundaries, and is equivalent to [^\b]
(?!\b)
(thanks to @Alan Moore for the correction!). Both are zero-width.
See http://www.regular-expressions.info/wordboundaries.html for details. The site is extremely useful for many basic regex questions.
I was looking for the solution to show the label dynamically from database like this:
checkbox1 : Option 1 text from database
checkbox2 : Option 2 text from database
checkbox3 : Option 3 text from database
checkbox4 : Option 4 text from database
So none of the above solution worked for me so I used like this:
@Html.CheckBoxFor(m => m.Option1, new { @class = "options" })
<label for="Option1">@Model.Option1Text</label>
@Html.CheckBoxFor(m => m.Option2, new { @class = "options" })
<label for="Option2">@Mode2.Option1Text</label>
In this way when user will click on label, checkbox will be selected.
Might be it can help someone.
There is a whole bunch of useful low level tools from SysSnternals.
And psinfo
may be the most useful.
I used the following psinfo switches:
-h Show installed hotfixes.
-d Show disk volume information.
Sample output is this:
c:> psinfo \\development -h -d
PsInfo v1.6 - local and remote system information viewer
Copyright (C) 2001-2004 Mark Russinovich
Sysinternals - www.sysinternals.com
System information for \\DEVELOPMENT:
Uptime: 28 days, 0 hours, 15 minutes, 12 seconds
Kernel version: Microsoft Windows XP, Multiprocessor Free
Product type Professional
Product version: 5.1
Service pack: 0
Kernel build number: 2600
Registered organization: Sysinternals
Registered owner: Mark Russinovich
Install date: 1/2/2002, 5:29:21 PM
Activation status: Activated
IE version: 6.0000
System root: C:\WINDOWS
Processors: 2
Processor speed: 1.0 GHz
Processor type: Intel Pentium III
Physical memory: 1024 MB
Volume Type Format Label Size Free Free
A: Removable 0%
C: Fixed NTFS WINXP 7.8 GB 1.3 GB 16%
D: Fixed NTFS DEV 10.7 GB 809.7 MB 7%
E: Fixed NTFS SRC 4.5 GB 1.8 GB 41%
F: Fixed NTFS MSDN 2.4 GB 587.5 MB 24%
G: Fixed NTFS GAMES 8.0 GB 1.0 GB 13%
H: CD-ROM CDFS JEDIOUTCAST 633.6 MB 0%
I: CD-ROM 0% Q: Remote 0%
T: Fixed NTFS Test 502.0 MB 496.7 MB 99%
OS Hot Fix Installed
Q147222 1/2/2002
Q309521 1/4/2002
Q311889 1/4/2002
Q313484 1/4/2002
Q314147 3/6/2002
Q314862 3/13/2002
Q315000 1/8/2002
Q315403 3/13/2002
Q317277 3/20/2002
In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.
The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:
set rowcount @top
select * from sometable
set rowcount 0
Hope this helps
Oisin.
(edited to replace @@rowcount with rowcount - thanks augustlights)
As an extension to Jonathan Leffler's Unix to DOS solution, to safely convert to DOS when you're unsure of the file's current line endings:
sed '/^M$/! s/$/^M/'
This checks that the line does not already end in CRLF before converting to CRLF.
the "algorithmic" way:
import math
def isPalindrome(inputString):
if inputString == None:
return False
strLength = len(inputString)
for i in range(math.floor(strLength)):
if inputString[i] != inputString[strLength - 1 - i]:
return False
return True
Make sure to also add "C:\Python27\Scripts" to your path. pip.exe should be in that folder. Then you can just run:
C:\> pip install modulename
The best way is to check and then delete
if (ctx.Employ.Any(r=>r.Id == entity.Id))
{
Employ rec = new Employ() { Id = entity.Id };
ctx.Entry(rec).State = EntityState.Deleted;
ctx.SaveChanges();
}
If you are brave enough (and have node
installed), you can always do something like:
echo "console.log(require('./package.json').version);" | node
This will print the version of the current package. You can also modify it to go insane, like this:
echo "eval('var result='+require('child_process').execSync('npm version',{encoding:'utf8'})); console.log(result.WHATEVER_PACKAGE_NAME);" | node
That will print the version of WHATEVER_PACKAGE_NAME
package, that is seen by npm version
.
Yeild
keyword in javaScript function makes it generator,
what is generator in javaScript?
A generator is a function that produces a sequence of results instead of a single value, i.e you generate ?a series of values
Meaning generators helps us work asynchronously with the help iterators, Oh now what the hack iterators are? really?
Iterators are mean through which we are able to access items one at a time
from where iterator help us accessing item one at a time? it help us accessing items through generator functions,
generator functions are those in which we use yeild
keyword, yield keyword help us in pausing and resuming execution of function
here is quick example
function *getMeDrink() {
let question1 = yield 'soda or beer' // execution will pause here because of yield
if (question1 == 'soda') {
return 'here you get your soda'
}
if (question1 == 'beer') {
let question2 = yield 'Whats your age' // execution will pause here because of yield
if (question2 > 18) {
return "ok you are eligible for it"
} else {
return 'Shhhh!!!!'
}
}
}
let _getMeDrink = getMeDrink() // initialize it
_getMeDrink.next().value // "soda or beer"
_getMeDrink.next('beer').value // "Whats your age"
_getMeDrink.next('20').value // "ok you are eligible for it"
_getMeDrink.next().value // undefined
let me brifly explain what is going on
you noticed execution is being paused at each yeild
keyword
and we are able to access first yield
with help of iterator .next()
this iterates to all yield
keywords one at a time and then returns undefined when there is no more yield
keywords left
in simple words you can say yield
keyword is break point where function each time pauses and only resume when call it using iterator
for our case: _getMeDrink.next()
this is example of iterator that is helping us accessing each break point in function
Example of Generators:
async/await
if you see implementation of async/await
you will see generator functions & promises
are used to make async/await
work
please point out any suggestions is welcomed
In CSS: #clear_div{clear:both;}
After the div tag of the inner div add this new following div
<div id="clear_div"></div>
http://www.w3schools.com/cssref/pr_class_clear.asp : for more information
function bot_detected() {
if(preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT']){
return true;
}
else{
return false;
}
}
If is ok for you to index the array you can do this:
<form>
<input type="text" class="form-control" placeholder="Titel" name="levels[0][level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[0][build_time]">
<input type="text" class="form-control" placeholder="Titel" name="levels[1][level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[1][build_time]">
<input type="text" class="form-control" placeholder="Titel" name="levels[2][level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[2][build_time]">
</form>
... to achieve that:
[levels] => Array (
[0] => Array (
[level] => 1
[build_time] => 2
)
[1] => Array (
[level] => 234
[build_time] => 456
)
[2] => Array (
[level] => 111
[build_time] => 222
)
)
But if you remove one pair of inputs (dynamically, I suppose) from the middle of the form then you'll get holes in your array, unless you update the input names...
You can use Jasypt to encrypt properties, so you could have your property like this:
db.password=ENC(XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=)
Jasypt allows you to encrypt your properties using different algorithms, once you get the encrypted property you put inside the ENC(...)
. For instance, you can encrypt this way through Jasypt using the terminal:
encrypted-pwd$ java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="contactspassword" password=supersecretz algorithm=PBEWithMD5AndDES
----ENVIRONMENT-----------------
Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 24.45-b08
----ARGUMENTS-------------------
algorithm: PBEWithMD5AndDES
input: contactspassword
password: supersecretz
----OUTPUT----------------------
XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=
To easily configure it with Spring Boot you can use its starter jasypt-spring-boot-starter with group ID com.github.ulisesbocchio
Keep in mind, that you will need to start your application using the same password you used to encrypt the properties. So, you can start your app this way:
mvn -Djasypt.encryptor.password=supersecretz spring-boot:run
Or using the environment variable (thanks to spring boot relaxed binding):
export JASYPT_ENCRYPTOR_PASSWORD=supersecretz
mvn spring-boot:run
You can check below link for more details:
https://www.ricston.com/blog/encrypting-properties-in-spring-boot-with-jasypt-spring-boot/
To use your encrypted properties in your app just use it as usual, use either method you like (Spring Boot wires the magic, anyway the property must be of course in the classpath):
Using @Value
annotation
@Value("${db.password}")
private String password;
Or using Environment
@Autowired
private Environment environment;
public void doSomething(Environment env) {
System.out.println(env.getProperty("db.password"));
}
Update: for production environment, to avoid exposing the password in the command line, since you can query the processes with ps
, previous commands with history
, etc etc. You could:
touch setEnv.sh
setEnv.sh
to export the JASYPT_ENCRYPTOR_PASSWORD
variable
#!/bin/bash
export JASYPT_ENCRYPTOR_PASSWORD=supersecretz
. setEnv.sh
mvn spring-boot:run &
setEnv.sh
unset JASYPT_ENCRYPTOR_PASSWORD
Maybe something changed but this gave back a list of ndarrays which did what I needed.
list(df.values)
You need to decode data from input string into unicode, before using it, to avoid encoding problems.
field.text = data.decode("utf8")
I recomend this one-liner
List<Video> videos = Arrays.asList(new Gson().fromJson(json, Video[].class));
Warning: the list of videos
, returned by Arrays.asList
is immutable - you can't insert new values. If you need to modify it, wrap in new ArrayList<>(...)
.
Reference:
json
may be of type JsonElement
, Reader
, or String
)Pure javascript version of Vidas's answer, el$
is the DOM node of the plane you are scrolling.
function onlyScrollElement(event, el$) {
var delta = event.wheelDelta || -event.detail;
el$.scrollTop += (delta < 0 ? 1 : -1) * 10;
event.preventDefault();
}
Make sure you dont attach the even multiple times! Here is an example,
var ul$ = document.getElementById('yo-list');
// IE9, Chrome, Safari, Opera
ul$.removeEventListener('mousewheel', onlyScrollElement);
ul$.addEventListener('mousewheel', onlyScrollElement);
// Firefox
ul$.removeEventListener('DOMMouseScroll', onlyScrollElement);
ul$.addEventListener('DOMMouseScroll', onlyScrollElement);
Word of caution, the function there needs to be a constant, if you reinitialize the function each time before attaching it, ie. var func = function (...)
the removeEventListener
will not work.
Another approach I have used is to change a private method to package private or protected then complement it with the @VisibleForTesting annotation of the Google Guava library.
This will tell anybody using this method to take caution and not access it directly even in a package. Also a test class need not be in same package physically, but in the same package under the test folder.
For example, if a method to be tested is in src/main/java/mypackage/MyClass.java
then your test call should be placed in src/test/java/mypackage/MyClassTest.java
. That way, you got access to the test method in your test class.
For those who use ASP.NET Identity 2.1 and have changed the primary key from the default string
to either int
or Guid
, if you're still getting
EntityType 'xxxxUserLogin' has no key defined. Define the key for this EntityType.
EntityType 'xxxxUserRole' has no key defined. Define the key for this EntityType.
you probably just forgot to specify the new key type on IdentityDbContext
:
public class AppIdentityDbContext : IdentityDbContext<
AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
{
public AppIdentityDbContext()
: base("MY_CONNECTION_STRING")
{
}
......
}
If you just have
public class AppIdentityDbContext : IdentityDbContext
{
......
}
or even
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
......
}
you will get that 'no key defined' error when you are trying to add migrations or update the database.
This is not valid TypeScript code. You can not have method invocations in the body of a class.
// INVALID CODE
export class AppComponent {
public n: number = 1;
setTimeout(function() {
n = n + 10;
}, 1000);
}
Instead move the setTimeout
call to the constructor
of the class. Additionally, use the arrow function =>
to gain access to this
.
export class AppComponent {
public n: number = 1;
constructor() {
setTimeout(() => {
this.n = this.n + 10;
}, 1000);
}
}
In TypeScript, you can only refer to class properties or methods via this
. That's why the arrow function =>
is important.
I just went through this and configured it with the following:
Ubuntu 16.04
Tomcat 8.5.9
Apache2.4.25
APR 1.5.2
Tomcat-native 1.2.10
Java 8
These are the steps i used based on the older posts here:
sudo apt-get update
sudo apt-get install libtcnative-1
sudo apt-get install make
sudo apt-get install gcc
sudo apt-get install openssl
sudo apt-get install libssl-dev
cd /opt/tomcat/bin
sudo wget http://apache.mirror.anlx.net//apr/apr-1.5.2.tar.gz
sudo tar -xzvf apr-1.5.2.tar.gz
cd apr-1.5.2
sudo ./configure
sudo make
sudo make install
cd /usr/local/apr/lib/
ls
libapr-1.la
cd /opt/tomcat/bin
sudo wget https://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.10/source/tomcat-native-1.2.10-src.tar.gz
sudo tar -xzvf tomcat-native-1.2.10-src.tar.gz
cd tomcat-native-1.2.10-src/native
sudo pico ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
source ~/.bashrc
sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
sudo make
sudo make install
sudo pico /opt/tomcat/bin/setenv.sh
export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'
sudo service tomcat restart
You are getting AttributeError
because you're calling groups
on None
, which hasn't any methods.
regex.search
returning None
means the regex couldn't find anything matching the pattern from supplied string.
when using regex, it is nice to check whether a match has been made:
Result = re.search(SearchStr, htmlString)
if Result:
print Result.groups()
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
I was successfully available to get Application User By Following Piece of Code
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = manager.FindById(User.Identity.GetUserId());
ApplicationUser EmpUser = user;
private static Double _MilesToKilometers = 1.609344;
private static Double _MilesToNautical = 0.8684;
/// <summary>
/// Calculates the distance between two points of latitude and longitude.
/// Great Link - http://www.movable-type.co.uk/scripts/latlong.html
/// </summary>
/// <param name="coordinate1">First coordinate.</param>
/// <param name="coordinate2">Second coordinate.</param>
/// <param name="unitsOfLength">Sets the return value unit of length.</param>
public static Double Distance(Coordinate coordinate1, Coordinate coordinate2, UnitsOfLength unitsOfLength)
{
double theta = coordinate1.getLongitude() - coordinate2.getLongitude();
double distance = Math.sin(ToRadian(coordinate1.getLatitude())) * Math.sin(ToRadian(coordinate2.getLatitude())) +
Math.cos(ToRadian(coordinate1.getLatitude())) * Math.cos(ToRadian(coordinate2.getLatitude())) *
Math.cos(ToRadian(theta));
distance = Math.acos(distance);
distance = ToDegree(distance);
distance = distance * 60 * 1.1515;
if (unitsOfLength == UnitsOfLength.Kilometer)
distance = distance * _MilesToKilometers;
else if (unitsOfLength == UnitsOfLength.NauticalMiles)
distance = distance * _MilesToNautical;
return (distance);
}
here a concatenation solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 10
int main() {
char *text = calloc(1,1), buffer[BUFFERSIZE];
printf("Enter a message: \n");
while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */
{
text = realloc( text, strlen(text)+1+strlen(buffer) );
if( !text ) ... /* error handling */
strcat( text, buffer ); /* note a '\n' is appended here everytime */
printf("%s\n", buffer);
}
printf("\ntext:\n%s",text);
return 0;
}
This is based on KoZm0kNoT's answer. I modified it to work across drives.
@echo off
pushd "%~d0"
pushd "%~dp0"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
popd
The two pushd/popds are necessary in case the user's cwd is on a different drive. Without the outer set, the cwd on the drive with the script will get lost.
include() needs a full file path, relative to the file system's root directory.
This should work:
include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");
There are several ways:
Instantiating the array:
var arr;
arr = new Array(); // empty array
// ---
arr = []; // empty array
// ---
arr = new Array(3);
alert(arr.length); // 3
alert(arr[0]); // undefined
// ---
arr = [3];
alert(arr.length); // 1
alert(arr[0]); // 3
Pushing to the array:
arr = [3]; // arr == [3]
arr[1] = 4; // arr == [3, 4]
arr[2] = 5; // arr == [3, 4, 5]
arr[4] = 7; // arr == [3, 4, 5, undefined, 7]
// ---
arr = [3];
arr.push(4); // arr == [3, 4]
arr.push(5); // arr == [3, 4, 5]
arr.push(6, 7, 8); // arr == [3, 4, 5, 6, 7, 8]
Using .push()
is the better way to add to an array, since you don't need to know how many items are already there, and you can add many items in one function call.
A good rule of thumb when constructing arguments for use in conditional statements (IF, WHILE, etc.) is to always use the &&/|| forms, unless there's a very good reason not to. There are two reasons...
Doing this, rather than relying on MATLAB's resolution of vectors in & and |, leads to code that's a little bit more verbose, but a LOT safer and easier to maintain.
MySQL: ERROR 1040: Too many connections
This basically tells that MySQL handles the maximum number of connections simultaneously and by default it handles 100 connections simultaneously.
These following reasons cause MySQL to run out connections.
Slow Queries
Data Storage Techniques
Bad MySQL configuration
I was able to overcome this issues by doing the followings.
Open MySQL command line tool
and type,
show variables like "max_connections";
This will return you something like this.
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 100 |
+-----------------+-------+
You can change the setting to e.g. 200 by issuing the following command without having to restart the MySQL server.
set global max_connections = 200;
Now when you restart MySQL the next time it will use this setting instead of the default.
Keep in mind that increase of the number of connections will increase the amount of RAM required for MySQL to run.
A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs :
Declare @XMLList xml
SET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)
SELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))
All credit goes to Guru Brad Schulz's Blog
Sounds like a job for the UNIX command split:
split MyBigFile.csv
Just split my 55 GB csv file in 21k chunks in less than 10 minutes.
It's not native to PowerShell though, but comes with, for instance, the git for windows package https://git-scm.com/download/win
c is the new dictionary, and a is your original dictionary, {'z','w'} are the keys you want to remove from a
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
Also check: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01.html
It complains because it needs to use ssh
instead of https
but your git is still configured with https. so basically as others mentioned previously you need to either enable prompts or to configure git to use ssh
instead of https
. a simple way to do this by running the following:
git config --global --add url."[email protected]:".insteadOf "https://github.com/"
or if you already use ssh
with git
in your machine, you can safely edit ~/.gitconfig
and add the following line at the very bottom
Note: This covers all SVC, source version control, that depends on what you exactly use, github, gitlab, bitbucket)
# Enforce SSH
[url "ssh://[email protected]/"]
insteadOf = https://github.com/
[url "ssh://[email protected]/"]
insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
insteadOf = https://bitbucket.org/
If you want to keep password pompts disabled, you need to cache password. For more information on how to cache your github password on mac, windows or linux, please visit this page.
For more information on how to add ssh to your github account, please visit this page.
Also, more importantly, if this is a private repository for a company or for your self, you may need to skip using proxy or checksum database for such repos to avoid exposing them publicly.
To do this, you need to set GOPRIVATE
environment variable that controls which modules the go command considers to be private (not available publicly) and should therefore NOT use the proxy or checksum database.
The variable is a comma-separated list of patterns (same syntax of Go's path.Match
) of module path prefixes. For example,
export GOPRIVATE=*.corp.example.com,github.com/mycompany/*
Or
go env -w GOPRIVATE=github.com/mycompany/*
One last thing not to forget to mention, you can still configure go get
to authenticate and fetch over https
, all you need to do is to add the following line to $HOME/.netrc
machine github.com login USERNAME password APIKEY
I hope this helps the community and saves others' time to solve described issues quickly. please feel free to leave a comment in case you want more support or help.
Steps to start Apache httpd.exe (I am using x64 VC11 example here)
http://www.apachelounge.com/download/VC11/
Be sure that you have installed Visual C++ Redistributable for Visual Studio 2012 : VC11 vcredist_x64/86.exe
http://www.microsoft.com/en-us/download/details.aspx?id=30679
You may need to have Visual Studio 2012 Update 3 (VS2012.3)
http://www.microsoft.com/en-us/download/details.aspx?id=30679 (vcredirect.exe)
http://support.microsoft.com/kb/2835600
Unzip httpd-2.4.4-win64-VC11.zip and copy paste in
C:\Apache24
Unzip modules-2.4-win64-VC11.zip and copy paste them in
C:\Apache24\modules
http://www.apachelounge.com/viewtopic.php?p=25091
For further info on the modules see the Apache Lounge VC10 Win64 download page and/or the readme in the .zip's there.
http://www.apachelounge.com/download/win64/
In
C:\Apache24\conf\httpd.conf
un-comment (remove # sign) starting below this like copy pasted list in here
# Example:
# LoadModule foo_module modules/mod_foo.so
LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule authz_dbd_module modules/mod_authz_dbd.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule buffer_module modules/mod_buffer.so
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule charset_lite_module modules/mod_charset_lite.so
LoadModule data_module modules/mod_data.so
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule dav_lock_module modules/mod_dav_lock.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule env_module modules/mod_env.so
LoadModule expires_module modules/mod_expires.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule filter_module modules/mod_filter.so
LoadModule headers_module modules/mod_headers.so
LoadModule heartbeat_module modules/mod_heartbeat.so
LoadModule heartmonitor_module modules/mod_heartmonitor.so
LoadModule ident_module modules/mod_ident.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule include_module modules/mod_include.so
LoadModule info_module modules/mod_info.so
LoadModule isapi_module modules/mod_isapi.so
LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule logio_module modules/mod_logio.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_debug_module modules/mod_log_debug.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule lua_module modules/mod_lua.so
LoadModule mime_module modules/mod_mime.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_express_module modules/mod_proxy_express.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_html_module modules/mod_proxy_html.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
LoadModule ratelimit_module modules/mod_ratelimit.so
LoadModule reflector_module modules/mod_reflector.so
LoadModule remoteip_module modules/mod_remoteip.so
LoadModule request_module modules/mod_request.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule sed_module modules/mod_sed.so
LoadModule session_module modules/mod_session.so
LoadModule session_cookie_module modules/mod_session_cookie.so
LoadModule session_crypto_module modules/mod_session_crypto.so
LoadModule session_dbd_module modules/mod_session_dbd.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
LoadModule socache_dbm_module modules/mod_socache_dbm.so
LoadModule socache_memcache_module modules/mod_socache_memcache.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
LoadModule speling_module modules/mod_speling.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule status_module modules/mod_status.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule version_module modules/mod_version.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule watchdog_module modules/mod_watchdog.so
LoadModule xml2enc_module modules/mod_xml2enc.so
Then find
C:\Apache24\bin\ApacheMonitor.exe
and double click on it.
Then in Command Prompt (CMD.exe) type
C:\Apache24\bin\httpd.exe
and press enter. It shows any error remaining.
Build with the latest Update 3 Visual Studio® 2012 aka VC11. VC11 has improvements, fixes and optimizations over VC10 in areas like Performance, MemoryManagement and Stability. For example code quality tuning and improvements done across different code generation areas for "speed". And makes more use of modern processors and win7, win8, 2008 and Server 2012 internal features.
The VC11 binaries loads VC11, VC10 and VC9 modules, and does not run on XP and 2003. Minimum system required: Windows 7 SP1, Windows 8 / 8.1, Windows Vista SP2, Windows Server 2008 R2 SP1, Windows Server 2012 / R2
After you have downloaded and before you attempt to install it, you should make sure that it is intact and has not been tampered with. Use the PGP Signature and/or the SHA Checksums to verify the integrity.
Thank you
It is easy to write file :
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
I got the same error. In my case, I was using a mapped drive to edit code off of a second computer, that computer was running linux. Not sure exactly why gulp-watch relies on operating system compatibility prior to install (I would assume it has to do with security purposes). Essentially the error is checking against your operating system and the operating system calling the node module, in my case the two operating systems were not the same so it threw it error. Which from the looks of your error is the same as mine.
The Error
Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
How I fixed it?
I logged into the linux computer directly and ran
npm install --save-dev <module-name>
Then went back into my coding environment and everything was fine after that.
Hope that helps!
See: http://jsfiddle.net/thirtydot/cMNX2/8/
input {
-webkit-box-shadow: 0 0 5px 2px #fff;
-moz-box-shadow: 0 0 5px 2px #fff;
box-shadow: 0 0 5px 2px #fff;
}
It's simple, use $.getJSON()
function and in your URL just include
callback=?
as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/
In Ubuntu 16.04 default PHP version is 7.0, if you want to use different version then you need to install PHP package according to PHP version:
sudo apt-get install php7.4-curl
sudo apt-get install php7.3-curl
sudo apt-get install php7.2-curl
sudo apt-get install php7.1-curl
sudo apt-get install php7.0-curl
sudo apt-get install php5.6-curl
sudo apt-get install php5.5-curl
You can try to delete the emulator and reinstall it this usually does the trick for me. Sometimes you also run into hiccups on your computer so try restarting your computer. Your computer may not be able to handle android studio if so there is nothing you can do. Consequently, you may not have the right ram requirements. Finally, If all else fails you can try to delete then reinstall android studio.
Enumeration(?):
Enumeration e = new Vector(set).elements();
while (e.hasMoreElements())
{
System.out.println(e.nextElement());
}
Another way (java.util.Collections.enumeration()):
for (Enumeration e1 = Collections.enumeration(set); e1.hasMoreElements();)
{
System.out.println(e1.nextElement());
}
Java 8:
set.forEach(element -> System.out.println(element));
or
set.stream().forEach((elem) -> {
System.out.println(elem);
});
The simplest and also the most compact solution (for v2.3.3):
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(obj)
Below are some of the tools which you can use to perform reverse engineering from an APK file to source code :
The findandbind
npm addresses this for express/restify/connect: https://github.com/gyllstromk/node-find-and-bind
There are no conventions. There are some logical structure.
The only one thing that I can say: Never use camelCase file and directory names. Why? It works but on Mac and Windows there are no different between someAction and some action. I met this problem, and not once. I require'd a file like this:
var isHidden = require('./lib/isHidden');
But sadly I created a file with full of lowercase: lib/ishidden.js
. It worked for me on mac. It worked fine on mac of my co-worker. Tests run without errors. After deploy we got a huge error:
Error: Cannot find module './lib/isHidden'
Oh yeah. It's a linux box. So camelCase directory structure could be dangerous. It's enough for a colleague who is developing on Windows or Mac.
So use underscore (_) or dash (-) separator if you need.
It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.
For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.
To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.
Pseudo code
ratio = 300.0 / 72.0 // 4.167
image.width * ratio
image.height * ratio
Try this code ...
Integer perc = 5;
BigDecimal spread = BigDecimal.ZERO;
BigDecimal perc = spread.setScale(perc,BigDecimal.ROUND_HALF_UP);
System.out.println(perc);
Result: 0.00000
When I installed Android Studio 1.0 it ended up in
/Library/Android/sdk/
ng-pristine ($pristine)
Boolean True if the form/input has not been used yet (not modified by the user)
ng-dirty ($dirty)
Boolean True if the form/input has been used (modified by the user)
$setDirty(); Sets the form to a dirty state. This method can be called to add the 'ng-dirty' class and set the form to a dirty state (ng-dirty class). This method will propagate current state to parent forms.
$setPristine(); Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false. This method will also propagate to all the controls contained in this form.
Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.
Checkout HTML5 imports via Html5rocks tutorial and at polymer-project
For example:
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
Stopwatch
is designed for this purpose and is one of the best ways to measure time execution in .NET.
var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Do not use DateTime to measure time execution in .NET.
UPDATE:
As pointed out by @series0ne in the comments section: If you want a real precise measurement of the execution of some code, you will have to use the performance counters that's built into the operating system. The following answer contains a nice overview.
Swift 4.2
self.navigationController?.navigationBar.titleTextAttributes =
[NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "LemonMilklight", size: 21)!]
Rather than explaining the theoretical part, I'll give a simple example.
>>> from collections import OrderedDict
>>> my_dictionary=OrderedDict()
>>> my_dictionary['foo']=3
>>> my_dictionary['aol']=1
>>> my_dictionary
OrderedDict([('foo', 3), ('aol', 1)])
>>> dict(my_dictionary)
{'foo': 3, 'aol': 1}
Your query apparently returned all correct dates, even considering the time.
If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.
Make sure your mydate
column is a datetime
type.
SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID
If you use Modernizr, it is very easy to use Modernizr.touch
as mentioned earlier.
However, I prefer using a combination of Modernizr.touch
and user agent testing, just to be safe.
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
If you don't use Modernizr, you can simply replace the Modernizr.touch
function above with ('ontouchstart' in document.documentElement)
Also note that testing the user agent iemobile
will give you broader range of detected Microsoft mobile devices than Windows Phone
.
File
> Import
> General
> Existing Projects into workspace
.
Select the root folder that has your project(s). It lists all the projects available in the selected folder. Select the ones you would like to import and click Finish
. This should work just fine.
In IE and FireFox the favicon.ico is only being requested at the first page visited on the site, which means that if the favicon.ico requires log-in (for example your site is a closed site and requires log in) then the icon will not be displayed.
The solution is to add an exception for the favicon.ico, for example in ASP.Net you add in the web.config:
<location path="favicon.ico">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
It's example from great MSDN article about using ExpandoObject for creating dynamic ad-hoc types for incoming structured data (i.e XML, Json).
We can also assign delegate to ExpandoObject's dynamic property:
dynamic person = new ExpandoObject();
person.FirstName = "Dino";
person.LastName = "Esposito";
person.GetFullName = (Func<String>)(() => {
return String.Format("{0}, {1}",
person.LastName, person.FirstName);
});
var name = person.GetFullName();
Console.WriteLine(name);
Thus it allows us to inject some logic into dynamic object at runtime. Therefore, together with lambda expressions, closures, dynamic keyword and DynamicObject class, we can introduce some elements of functional programming into our C# code, which we knows from dynamic languages as like JavaScript or PHP.
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE
.
Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES()
function to make sure the proper values are used when updating the other columns.
Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE
syntax for MySQL:
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
A lot of the answers are providing custom examples because of the accepted answer's dependency on System.Web. From the Microsoft.AspNet.WebApi.Client NuGet package there is a UriExtensions.ParseQueryString, method that can also be used:
var uri = new Uri("https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8");
NameValueCollection query = uri.ParseQueryString();
So if you want to avoid the System.Web dependency and don't want to roll your own, this is a good option.
I don't know I used random.shuffle()
but it return 'None' to me, so I wrote this, might helpful to someone
def shuffle(arr):
for n in range(len(arr) - 1):
rnd = random.randint(0, (len(arr) - 1))
val1 = arr[rnd]
val2 = arr[rnd - 1]
arr[rnd - 1] = val1
arr[rnd] = val2
return arr
Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.
OpenSessionInViewFilter
calls the openSession
method of the underlying SessionFactory
and obtains a new Session
.Session
is bound to the TransactionSynchronizationManager
.OpenSessionInViewFilter
calls the doFilter
of the javax.servlet.FilterChain
object reference and the request is further processedDispatcherServlet
is called, and it routes the HTTP request to the underlying PostController
.PostController
calls the PostService
to get a list of Post
entities.PostService
opens a new transaction, and the HibernateTransactionManager
reuses the same Session
that was opened by the OpenSessionInViewFilter
.PostDAO
fetches the list of Post
entities without initializing any lazy association.PostService
commits the underlying transaction, but the Session
is not closed because it was opened externally.DispatcherServlet
starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.OpenSessionInViewFilter
can close the Session
, and the underlying database connection is released as well.At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.
The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection
as read-only which would allow the database server to avoid writing to the transaction log.
There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.
The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize
for fetching associations in batches, and FetchMode.SUBSELECT
to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.
Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.
Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.
So, make sure that in the application.properties
configuration file, you have the following entry:
spring.jpa.open-in-view=false
This will disable OSIV so that you can handle the LazyInitializationException
the right way.
Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.
How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in
operator (or in your specific case, not in
). As mentioned in the documentation,
The operators
in
andnot in
test for membership.x in s
evaluates toTrue
ifx
is a member ofs
, andFalse
otherwise.x not in s
returns the negation ofx in s
.
Additionally,
The operator
not in
is defined to have the inverse true value ofin
.
y not in x
is logically the same as not y in x
.
Here are a few examples:
'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):
(1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS defines a __contains__()
method, in
will internally call it, as noted in the last paragraph of the Comparisons section of the docs.
...
in
andnot in
, are supported by types that are iterable or implement the__contains__()
method. For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in
short-circuits, so if your element is at the start of the list, in
evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options:
list.index
can be used to retrieve the index of an item. If that element does not exist, a ValueError
is raised.list.count
can be used if you want to count the occurrences.set
s?Ask yourself these questions:
hash
on them?If you answered "yes" to these questions, you should be using a set
instead. An in
membership test on list
s is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.
set
objects, on the other hand, hash their values for constant time membership check. The check is also done using in
:
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:
l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__
.
According to this helpful list of operators [an operator can be thought of as a mathematical expression] found here, you can tell the batch compiler that you are manipulating variables instead of fixed numbers by using the += operator instead of the + operator.
Hope I Helped!
Epsilon is the value that the 2 numbers can be off by. So it will assert to true as long as Math.abs(expected - actual) < epsilon
I had this exact problem today and the problem was that the version I was trying to release:perform was already in the Nexus repo.
In my case this was likely due to a network disconnect during an earlier invocation of release:perform. Even though I lost my connection, it appears the release succeeded.
if(new File("/sdcard/your_filename.txt").exists())){
// Your code goes here...
}
Please go through the link given below msdn.microsoft.com/en-us/library/ms836794.aspx It covers both the similarity and difference between C# and java
Try this:
.rowhighlight > td { background: green;}
Do not use the *
selector as that will apply to all elements on the page. Suppose you have a structure like this:
...
<body>
<div id="content">
<b>This is the main container.</b>
</div>
</body>
</html>
You can then center the #content
div using:
#content {
width: 400px;
margin: 0 auto;
background-color: #66ffff;
}
Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; }
snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.
Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:
You can also add the --cached
flag to auco's answer to maintain local .DS_store files, as Edward Newell mentioned in his original answer. The modified command looks like this: find . -name .DS_Store -print0 | xargs -0 git rm --cached --ignore-unmatch
..cheers and thanks!
First, check whether the table exists or not. Accordingly, create table if doesn't exist.
var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";
using (SqlCommand command = new SqlCommand(commandStr, con))
command.ExecuteNonQuery();
To fix this issue I just run one query in my mysql
console.
For this login to mysql console using this
mysql -u {username} -p{password}
After this I just run one query as given below:-
ALTER user '{USERNAME}'@'localhost' identified with mysql_native_password by '{PASSWORD}';
when I run this query I got message that query executed. Then login to PHPMYADMIN with username/password.
Updated for Bootstrap 4.1+
Bootstrap 4 the navbar now uses flexbox so the Website Name
can be centered using mx-auto
. The left and right side menus don't require floats.
<nav class="navbar navbar-expand-md navbar-fixed-top navbar-dark bg-dark main-nav">
<div class="container">
<ul class="nav navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Download</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Register</a>
</li>
</ul>
<ul class="nav navbar-nav mx-auto">
<li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
</ul>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Rates</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
Navbar center with mx-auto
Demo
If the Navbar only has a single navbar-nav
, then justify-content-center
can also be used to center.
In the solution above, the Website Name
is centered relative to the left and right navbar-nav
so if the width of these adjacent navs are different the Website Name
is no longer centered.
To resolve this, one of the flexbox workarounds for absolute centering can be used...
Option 1 - Use position:absolute;
Since it's ok to use absolute positioning in flexbox, one option is to use this on the item to be centered.
.abs-center-x {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Navbar center with absolute position Demo
Option 2 - Use flexbox nesting
Finally, another option is to make the centered item also display:flexbox
(using d-flex
) and center justified. In this case each navbar component must have flex-grow:1
As of Bootstrap 4 Beta, the Navbar is now display:flex
. Bootstrap 4.1.0 includes a new flex-fill
class to make each nav section fill the width:
<nav class="navbar navbar-expand-sm navbar-dark bg-dark main-nav">
<div class="container justify-content-center">
<ul class="nav navbar-nav flex-fill w-100 flex-nowrap">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Download</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">More</a>
</li>
</ul>
<ul class="nav navbar-nav flex-fill justify-content-center">
<li class="nav-item"><a class="nav-link" href="#">Center</a></li>
</ul>
<ul class="nav navbar-nav flex-fill w-100 justify-content-end">
<li class="nav-item">
<a class="nav-link" href="#">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
Navbar center with flexbox nesting Demo
Prior to Bootstrap 4.1.0 you can add the flex-fill class like this...
.flex-fill {
flex:1
}
As of 4.1 flex-fill
is included in Bootstrap.
Bootstrap 4 Navbar center demos
More centering demos
Center links on desktop, left align on mobile
Related:
How to center nav-items in Bootstrap?
Bootstrap NavBar with left, center or right aligned items
How move 'nav' element under 'navbar-brand' in my Navbar
Well, switch
probably wasn't really meant to work like this, but you can:
AA = 'foo'
switch(AA,
foo={
# case 'foo' here...
print('foo')
},
bar={
# case 'bar' here...
print('bar')
},
{
print('default')
}
)
...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...
xxhdpi was not specified before but now new devices S4, HTC one are surely comes inside xxhdpi .These device dpi are around 440. I do not know exact limit for xxhdpi See how to develop android application for xxhdpi device Samsung S4 I know this is late answer but as thing had change since the question asked
Note Google Nexus 10 need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.
The fact that the first digit has to be in the range 5-9
only applies in case of two digits. So, check for that in the case of 2 digits, and allow any more digits directly:
^([5-9]\d|\d{3,})$
This regexp has beginning/ending anchors to make sure you're checking all digits, and the string actually represents a number. The |
means "or", so either [5-9]\d
or any number with 3 or more digits. \d
is simply a shortcut for [0-9]
.
Edit: To disallow numbers like 001
:
^([5-9]\d|[1-9]\d{2,})$
This forces the first digit to be not a zero in the case of 3 or more digits.
Highlight the column and then Ctrl + F.
Find and replace
Find ".com"
Replace ".com, "
And then one for .in
Find and replace
Find ".in"
Replace ".in, "
There are methods like WriteAllText
in the File
class for common operations on files.
Use the MapPath
method to get the physical path for a file in your web application.
File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);
foo.bars.one.counter=1
foo.bars.one.active=false
foo.bars[two].id=IdOfBarWithKeyTwo
public class Foo {
private Map<String, Bar> bars = new HashMap<>();
public Map<String, Bar> getBars() { .... }
}
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding
In bash to print a Unicode character to output use \x,\u or \U (first for 2 digit hex, second for 4 digit hex, third for any length)
echo -e '\U1f602'
I you want to assign it to a variable use $'...' syntax
x=$'\U1f602'
echo $x
I've found it useful to monkey-patch unittest
as follows:
def assertMayRaise(self, exception, expr):
if exception is None:
try:
expr()
except:
info = sys.exc_info()
self.fail('%s raised' % repr(info[0]))
else:
self.assertRaises(exception, expr)
unittest.TestCase.assertMayRaise = assertMayRaise
This clarifies intent when testing for the absence of an exception:
self.assertMayRaise(None, does_not_raise)
This also simplifies testing in a loop, which I often find myself doing:
# ValueError is raised only for op(x,x), op(y,y) and op(z,z).
for i,(a,b) in enumerate(itertools.product([x,y,z], [x,y,z])):
self.assertMayRaise(None if i%4 else ValueError, lambda: op(a, b))
You have the alias inside of the case, it needs to be outside of the END
:
Insert into TblStuff (FullName,Address,City,Zip)
Select
Case
When Middle is Null
Then Fname + LName
Else Fname +' ' + Middle + ' '+ Lname
End as FullName,
Case
When Address2 is Null Then Address1
else Address1 +', ' + Address2
End as Address,
City as City,
Zip as Zip
from tblImport
I just had the same error with Visual Studio 2013 and EF6. I had to use a NewGet packed Entity Framework and done the job perfectly
The easiest way is to install the plugin is from the Eclipse Marketplace. Go to Help?Eclipse Marketplace, then search for Eclipse Color Theme and install it.
Wildcard Characters are used with like clause to sort records.
if we want to search a string which is starts with B then code is like the following:
select * from tablename where colname like 'B%' order by columnname ;
if we want to search a string which is ends with B then code is like the following: select * from tablename where colname like '%B' order by columnname ;
if we want to search a string which is contains B then code is like the following: select * from tablename where colname like '%B%' order by columnname ;
if we want to search a string in which second character is B then code is like the following: select * from tablename where colname like '_B%' order by columnname ;
if we want to search a string in which third character is B then code is like the following: select * from tablename where colname like '__B%' order by columnname ;
note : one underscore for one character.
InetAddress class can be used to store IP addresses in IPv4 as well as IPv6 formats. You can store the IP address to the object using either InetAddress.getByName()
or InetAddress.getByAddress()
methods.
In the following code snippet, I am using InetAddress.getByName()
method to store IPv4 and IPv6 addresses.
InetAddress IPv4 = InetAddress.getByName("127.0.0.1");
InetAddress IPv6 = InetAddress.getByName("2001:db8:3333:4444:5555:6666:1.2.3.4");
You can also use InetAddress.getByAddress()
to create object by providing the byte array.
InetAddress addr = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
Furthermore, you can use InetAddress.getLoopbackAddress()
to get the local address and InetAddress.getLocalHost()
to get the address registered with the machine name.
InetAddress loopback = InetAddress.getLoopbackAddress(); // output: localhost/127.0.0.1
InetAddress local = InetAddress.getLocalHost(); // output: <machine-name>/<ip address on network>
Note- make sure to surround your code by try/catch because InetAddress
methods return java.net.UnknownHostException
Here Update
html
{
height:100%;
}
body{
min-height: 100%;
position:absolute;
margin:0;
padding:0;
}
These are steps for the same problem with MySQL5.7 and MySQL8.0 on Windows 10
A new byte array will automatically be initialized with all zeroes. You don't have to do anything.
The more general approach to initializing with other values, is to use the Arrays
class.
import java.util.Arrays;
byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );
Well there are a bunch of different utilities for this, e.g. Apache Commons Lang String Utils
but in the end, it has to loop over the string to count the occurrences one way or another.
Note also that the countMatches
method above has the following signature so will work for substrings as well.
public static int countMatches(String str, String sub)
The source for this is (from here):
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != -1) {
count++;
idx += sub.length();
}
return count;
}
I was curious if they were iterating over the string or using Regex.
Add this to your Activity
@Override
protected void onSaveInstanceState(Bundle oldInstanceState) {
super.onSaveInstanceState(oldInstanceState);
oldInstanceState.clear();
}
It works for me hope also it will help you
columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect.
Try:
In the controller:
ViewBag.Accounts= new SelectList(db.Accounts, "AccountId", "AccountName");
In the View:
@Html.DropDownList("AccountId", (IEnumerable<SelectListItem>)ViewBag.Accounts, null, new { @class ="form-control" })
or you can replace the "null" with whatever you want display as default selector, i.e. "Select Account".
In addition to the previous answers, here is a way to calculate the distance inside a SELECT:
CREATE FUNCTION Get_Distance
(
@La1 float , @Lo1 float , @La2 float, @Lo2 float
)
RETURNS TABLE
AS
RETURN
-- Distance in Meters
SELECT GEOGRAPHY::Point(@La1, @Lo1, 4326).STDistance(GEOGRAPHY::Point(@La2, @Lo2, 4326))
AS Distance
GO
Usage:
select Distance
from Place P1,
Place P2,
outer apply dbo.Get_Distance(P1.latitude, P1.longitude, P2.latitude, P2.longitude)
Scalar functions also work but they are very inefficient when computing large amount of data.
I hope this might help someone.
The corners are actually in .modal-content
So you may try this:
.modal-content {
background-color: #0480be;
}
.modal-body {
background-color: #fff;
}
If you change the color of the header or footer, the rounded corners will be drawn over.
If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.
Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
You could use iotop. It doesn't rely on a kernel patch. It Works with stock Ubuntu kernel
There is a package for it in the Ubuntu repos. You can install it using
sudo apt-get install iotop
I used the advice from this article to get an assembly from the GAC.
Get DLL Out of The GAC
DLLs once deployed in GAC (normally located at c:\windows\assembly) can’t be viewed or used as a normal DLL file. They can’t be directly referenced from VS project. Developers usually keep a copy of the original DLL file and refer to it in the project at development (design) time, which uses the assembly from GAC during run-time of the project.
During execution (run-time) if the assembly is found to be signed and deployed in GAC the CLR automatically picks up the assembly from the GAC instead of the DLL referenced during design time in VS. In case the developer has deleted the original DLL or don't have it for some reason, there is a way to get the DLL file from GAC. Follow the following steps to copy DLL from GAC
Run regsvr32 /u C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\shfusion.dll
- shfusion.dll is an explorer extension DLL that gives a distinct look to the GAC folder. Unregistering this file will remove the assembly cache viewer and the GAC folder will be then visible as any normal folder in explorer.
Open “%windir%\assembly\GAC_MSIL”.
Browse to your DLL folder into the deep to find your DLL.
Copy the DLL somewhere on your hard disk and refer it from there in your project
Run "regsvr32 %windir%\Microsoft.NET\Framework\<.NET version directory> \shfusion.dll" to re-register the shfusion.dll file and regain the original distinct view of the GAC.
Using requests and json makes it simple.
json.loads
functionRequests module provides you useful function to loop for success and failure.
if(Response.ok)
: will help help you determine if your API call is successful (Response code - 200)
Response.raise_for_status()
will help you fetch the http code that is returned from the API.
Below is a sample code for making such API calls. Also can be found in github. The code assumes that the API makes use of digest authentication. You can either skip this or use other appropriate authentication modules to authenticate the client invoking the API.
#Python 2.7.6
#RestfulClient.py
import requests
from requests.auth import HTTPDigestAuth
import json
# Replace with the correct URL
url = "http://api_url"
# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)
# For successful API call, response code will be 200 (OK)
if(myResponse.ok):
# Loading the response data into a dict variable
# json.loads takes in only binary or string variables so using content to fetch binary content
# Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
jData = json.loads(myResponse.content)
print("The response contains {0} properties".format(len(jData)))
print("\n")
for key in jData:
print key + " : " + jData[key]
else:
# If response code is not ok (200), print the resulting http error code with description
myResponse.raise_for_status()
var temp="/yourapp/";
$(location).attr('href','http://abcd.com'+temp);
Try this... used as an alternative
As for second question - you can use Fiddler filters to set response X-Frame-Options
header manually to something like ALLOW-FROM *
. But, of course, this trick will work only for you - other users still won't be able to see iframe content(if they not do the same).
The problem is the import of ProjectsListComponent
in your ProjectsModule
. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule
.
Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule
anywhere else but in your AppModule
. Use the CommonModule
to get access to the *ngIf, *ngFor...etc
directives:
@NgModule({
declarations: [
ProjectsListComponent
],
imports: [
CommonModule,
RouterModule.forChild(ProjectRoutes)
],
exports: [
ProjectsListComponent
]
})
export class ProjectsModule {}
project.routes.ts
export const ProjectRoutes: Routes = [
{ path: 'projects', component: ProjectsListComponent }
]
for ( i = 0; i < total.length; i++ ); // remove this
{
if (total[i]!=0)
System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}
The for loop loops until i=26
(where 26 is total.length
) and then your if
is executed, going over the bounds of the array. Remove the ;
at the end of the for
loop.
if you use the site http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python , download the file:
mysqlclient-1.3.6-cp34-none-win32.whl or
mysqlclient-1.3.6-cp34-none-win_amd64.whl
depending on the version of python you have (these are for python 3.4) and the type of windows you have (x64 or x32)
extract this file into C:\Python34\Lib\site-packages and your project will work
If using Django, you can use the timezone.localtime
method:
from django.utils import timezone
date
# datetime.datetime(2014, 8, 1, 20, 15, 0, 513000, tzinfo=<UTC>)
timezone.localtime(date)
# datetime.datetime(2014, 8, 1, 16, 15, 0, 513000, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
$ git rev-parse --abbrev-ref HEAD
master
This should work with Git 1.6.3 or newer.
If the reason you ask this question is because you want to use Core Bluetooth to advertise as an iBeacon rather than using the standard API, you can easily do so by advertising an NSDictionary such as:
{
kCBAdvDataAppleBeaconKey = <a7c4c5fa a8dd4ba1 b9a8a240 584f02d3 00040fa0 c5>;
}
See this answer for more information.
I think you need to have strings as the data values. It's likely something internally within jQuery that isn't encoding/serializing correctly the To & From Objects.
Try:
var data = {
from : from.val(),
to : to.val(),
speed : speed
};
Notice also on the lines:
$(from).css(...
$(to).css(
You don't need the jQuery wrapper as To & From are already jQuery objects.
To enable zoom controls in a WebView, add the following line:
webView.getSettings().setBuiltInZoomControls(true);
With this line of code, you get the zoom enabled in your WebView, if you want to remove the zoom in and zoom out buttons provided, add the following line of code:
webView.getSettings().setDisplayZoomControls(false);
In my use case, I wanted to asynchronously retrieve a url, and then follow that url to an external resource in a new window. A directive seemed overkill because I don't need reusability, so I simply did:
<button (click)="navigateToResource()">Navigate</button>
And in my component.ts
navigateToResource(): void {
this.service.getUrl((result: any) => window.open(result.url));
}
Routing to a link indirectly like this will likely trigger the browser's popup blocker.
The performance impact depends on the way you lock. You can find a good list of optimizations here: http://www.thinkingparallel.com/2007/07/31/10-ways-to-reduce-lock-contention-in-threaded-programs/
Basically you should try to lock as little as possible, since it puts your waiting code to sleep. If you have some heavy calculations or long lasting code (e.g. file upload) in a lock it results in a huge performance loss.
We can use enum type for this.We don't require a library. For example
enum {false,true};
the value for false
will be 0 and the value for true
will be 1.
you can get it with using this url : you will get the picture HD (max size)
https://graph.facebook.com/{userID}?fields=picture.width(720).height(720)&redirect=false
don't forget redirect=false or it will return an error
select
c.name as [column name],
t.name as [type name],
tbl.name as [table name]
from sys.columns c
inner join sys.types t
on c.system_type_id = t.system_type_id
inner join sys.tables tbl
on c.object_id = tbl.object_id
where
c.object_id = OBJECT_ID('YourTableName1')
and
t.name like '%YourSearchDataType%'
union
(select
c.name as [column name],
t.name as [type name],
tbl.name as [table name]
from sys.columns c
inner join sys.types t
on c.system_type_id = t.system_type_id
inner join sys.tables tbl
on c.object_id = tbl.object_id
where
c.object_id = OBJECT_ID('YourTableName2')
and
t.name like '%YourSearchDataType%')
union
(select
c.name as [column name],
t.name as [type name],
tbl.name as [table name]
from sys.columns c
inner join sys.types t
on c.system_type_id = t.system_type_id
inner join sys.tables tbl
on c.object_id = tbl.object_id
where
c.object_id = OBJECT_ID('YourTableName3')
and
t.name like '%YourSearchDataType%')
order by tbl.name
To search which column is in which table based on your search data type for three different table in one database. This query is expandable to 'n' tables.
Override the values present in the outer UL with values in inner UL.
You can use the test construct, [[ ]]
, along with the regular expression match operator, =~
, to check if a string matches a regex pattern.
For your specific case, you can write:
[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"
Or more a accurate test:
[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
# |^^^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
# | | ^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ |
# | | | | |
# | | \ | |
# | --year-- --month-- --day-- |
# | either 01...09 either 01..09 end of line
# start of line or 10,11,12 or 10..29
# or 30, 31
That is, you can define a regex in Bash matching the format you want. This way you can do:
[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"
where commands after &&
are executed if the test is successful, and commands after ||
are executed if the test is unsuccessful.
Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.
In other shells you can use grep. If your shell is POSIX compliant, do
(echo "$date" | grep -Eq ^regex$) && echo "matched" || echo "did not match"
In fish, which is not POSIX-compliant, you can do
echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"
It is not good practice to hard code strings into your layout files. You should add them to a string resource file and then reference them from your layout.
This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings.xml file.
It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language.
example: XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="yellow">Yellow</string>
</resources>
This layout XML applies a string to a View:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/yellow" />
Similarly colors should be stored in colors.xml and then referenced by using @color/color_name
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="Black">#000000</color>
</resources>
In your invoke web request just use the parameter -UseBasicParsing
e.g. in your script (line 2) you should use:
$rss = Invoke-WebRequest -UseBasicParsing
According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.
Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.
You may need to add a JDK (Java Development Kit) to the installed JRE's within Eclipse
Go to Window->Preferences->Java->Installed JRE's
In the Name column if you do not have a JDK as your default, then you will need to add it.
Click the "Add" Button and locate the JDK on your machine.
You may find it in this location: C:\Program Files\Java\jdk1.x.y
Where x and y are numbers.
If there are no JDK's installed on your machine then download and install the Java SE (Standard Edition) from the Oracle website.
Then do the steps above again. Be sure that it is set as the default JRE to use.
Then go back to the Projects->Generate Javadoc... dialog
Now it should work.
Good Luck.
Note in Python 2.6+ and Py3K, the %f character catches microseconds.
>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
See issue here
We can set the width for ul tag then it will align center.
#header ul {
display: block;
margin: 0 auto;
width: 420px;
max-width: 100%;
}
Consider:
int[] myArray = new int[10];
String myString = "hello world!";
List<int> myList = new ArrayList<int>();
myArray.length // Gives the length of the array
myString.length() // Gives the length of the string
myList.size() // Gives the length of the list
It's very likely that strings and arrays were designed at different times and hence ended up using different conventions. One justification is that since Strings use arrays internally, a method, length()
, was used to avoid duplication of the same information. Another is that using a method length()
helps emphasize the immutability of strings, even though the size of an array is also unchangeable.
Ultimately this is just an inconsistency that evolved that would definitely be fixed if the language were ever redesigned from the ground up. As far as I know no other languages (C#, Python, Scala, etc.) do the same thing, so this is likely just a slight flaw that ended up as part of the language.
You'll get an error if you use the wrong one anyway.
How do I change Android Studio editor's background color?
Changing Editor's Background
Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there
IDE will display a dialog like this, Press 'No'
Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?
Changing IDE's Theme
Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there
Press OK. Android Studio will ask you to restart the IDE.
The only way to really protect your php-applications from other, is to not share the source code. If you post you code somewhere online, or send it to you customers by some medium, other people than you have access to the code.
You could add an unique watermark to every single copy of your code. That way you can trace leaks back to a singe customer. (But will that help you, since the code already are outside of your control?)
Most code I see comes with a licence and maybe a warranty. A line at the top of the script telling people not to alter the script, will maybe be enought. Self; when I find non-open source code, I won't use it in my projects. Maybe I'm a bit dupe, but I expect ppl not to use my none-OSS code!
Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8
or other encoder that can represent your data. Then you can print it to sys.stdout
.
First, run following code in the console:
chcp 65001
set PYTHONIOENCODING=utf-8
Then, start python
do anything you want.
I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:
var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
.Select(r => new ResultGrouping {
IdObj1= r.Key.IdObj1,
IdObj2= r.Key.IdObj2,
IdObj3= r.Key.IdObj3,
Results = r.ToArray(),
Count = r.Count()
});
private class ResultGrouping
{
public short IdObj1{ get; set; }
public short IdObj2{ get; set; }
public int IdObj3{ get; set; }
public ResultCsvImport[] Results { get; set; }
public int Count { get; set; }
}
Where resultRecords
is my initial list I'm grouping, and its a List<ResultCsvImport>
. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3
The FileNameExtensionFilter
class is intended for Swing to be used in a JFileChooser
.
Try using a FilenameFilter
instead. For example:
File dir = new File("/users/blah/dirname");
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
table { width: 100%; }
Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.
$("#tableid").width($(window).width());
If not, use this snippet
<style>
body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
<tr>
<td>Just a Test
</td>
</tr>
</table>
You will notice that the width is perfectly covering the page.
The main thing is too nullify the margin
and padding
as I have shown at the body, then you are set.
Inside your function for the click action use
$( "#tabs" ).tabs({ active: # });
Where # is replaced by the tab index you want to select.
Edit: change from selected to active, selected is deprecated
@Overflowh I tried the above answer also with no luck. I changed php version from 5.3.24 to 5.5.8 as this setting will only work in php 5.3.7 and above. I then found this http://flwebsites.biz/posts/how-fix-curl-error-60-ssl-issue I downloaded the cacert.pem from there and replaced the one I had download/made from curl.hxxx.se linked above and it all started working. I was trying to get paypal sandbox IPN to verify. Happy to say after the .pem swap all is ok using curl.cainfo setting in php.ini which still was not in 5.3.24.
Current working directory is defined differently in different Java implementations. For certain version prior to Java 7 there was no consistent way to get the working directory. You could work around this by launching Java file with -D
and defining a variable to hold the info
Something like
java -D com.mycompany.workingDir="%0"
That's not quite right, but you get the idea. Then System.getProperty("com.mycompany.workingDir")
...
Use the CSS :overflow
property
.noscroll {
width: 150px;
height: 150px;
overflow: auto; /* Or hidden, or visible */
}
Here are some more examples:
My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:
For eg. consider a slight modification of your case:
@JsonProperty("fileName")
private String fileName;
@JsonProperty("fileName")
public String getFileName()
{
return fileName;
}
@JsonProperty("fileName1")
public void setFileName(String fileName)
{
this.fileName = fileName;
}
Both fileName
field, and method getFileName
, have the correct property name of fileName
and setFileName
has a different one fileName1
, in this case Jackson will look for a fileName1
attribute in json at the point of deserialization and will create a attribute called fileName1
at the point of serialization.
Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName
, it would just pick one of them as the attribute(FILENAME
), and had any on of the three differed, it would have thrown an exception:
java.lang.IllegalStateException: Conflicting property name definitions
have you tried with a condition in ng-class like here : http://jsfiddle.net/DotDotDot/zvLvg/ ?
<span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
<span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>
CREATE TABLE UserGroup
(
[User_Id] INT NOT NULL,
[Group_Id] INT NOT NULL
CONSTRAINT PK_UserGroup PRIMARY KEY NONCLUSTERED ([User_Id], [Group_Id])
)
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
Following examples work for me, please note "is_user_defined" NOT "is_table_type"
IF TYPE_ID(N'idType') IS NULL
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
IF not EXISTS (SELECT * FROM sys.types WHERE is_user_defined = 1 AND name = 'idType')
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
I had a similar problem, where I couldn't even install local::lib
I created an installer that installed the module somewhere relative to the .pl files
The install goes like:
perl Makefile.PL PREFIX=./modulos
make
make install
Then, in the .pl file that requires the module, which is in ./
use lib qw(./modulos/share/perl/5.8.8/); # You may need to change this path
use module::name;
The rest of the files (makefile.pl, module.pm, etc) require no changes.
You can call the .pl file with just
perl file.pl
I made a CSS approach to this that is sized by the viewport width, but maxes out at 100% of the viewport height. It doesn't require box-sizing:border-box
. If a pseudo element cannot be used, the pseudo-code's CSS can be applied to a child. Demo
.container {
position: relative;
max-width:100vh;
max-height:100%;
margin:0 auto;
overflow: hidden;
}
.container:before {
content: "";
display: block;
margin-top: 100%;
}
.child {
position: absolute;
top: 0;
left: 0;
}
Support table for viewport units
I wrote about this approach and others in a CSS-Tricks article on scaling responsive animations that you should check out.
When you create a cookie via PHP die Default Value is 0, from the manual:
If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes)
Otherwise you can set the cookies lifetime in seconds as the third parameter:
http://www.php.net/manual/en/function.setcookie.php
But if you mean to get the remaining lifetime of an already existing cookie, i fear that, is not possible (at least not in a direct way).
As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.
You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.
All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.
This simply works. Thanks MailChimp!
I needed this a couple of years ago for a specific situation: Two people who know their network passwords access the same machine at the same time to sign a legal agreement.
You don't want either password saved in that situation because saving a password is a legal issue, not a technical one where both the physical and temporal presence of both individuals is mandatory. Now, I'll agree that this is a rare situation to encounter, but such situations do exist and built-in password managers in web browsers are unhelpful.
My technical solution to the above was to swap between password
and text
types and make the background color match the text color when the field is a plain text field (thereby continuing to hide the password). Browsers don't ask to save passwords that are stored in plain text fields.
jQuery plugin:
Relevant source code from the above link:
(function($) {
$.fn.StopPasswordManager = function() {
return this.each(function() {
var $this = $(this);
$this.addClass('no-print');
$this.attr('data-background-color', $this.css('background-color'));
$this.css('background-color', $this.css('color'));
$this.attr('type', 'text');
$this.attr('autocomplete', 'off');
$this.focus(function() {
$this.attr('type', 'password');
$this.css('background-color', $this.attr('data-background-color'));
});
$this.blur(function() {
$this.css('background-color', $this.css('color'));
$this.attr('type', 'text');
$this[0].selectionStart = $this[0].selectionEnd;
});
$this.on('keydown', function(e) {
if (e.keyCode == 13)
{
$this.css('background-color', $this.css('color'));
$this.attr('type', 'text');
$this[0].selectionStart = $this[0].selectionEnd;
}
});
});
}
}(jQuery));
Demo:
https://barebonescms.com/demos/admin_pack/admin.php
Click "Add Entry" in the menu and then scroll to the bottom of the page to "Module: Stop Password Manager".
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
You can configure logging in your settings.py
file.
One example:
if DEBUG:
# will output to your console
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
)
else:
# will output to logging file
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
filename = '/my_log_file.log',
filemode = 'a'
)
However that's dependent upon setting DEBUG, and maybe you don't want to have to worry about how it's set up. See this answer on How can I tell whether my Django application is running on development server or not? for a better way of writing that conditional. Edit: the example above is from a Django 1.1 project, logging configuration in Django has changed somewhat since that version.
You can use the length()
method on File
which returns the size in bytes.
Try to check if the div has a class attribute first, like this:
soup = BeautifulSoup(sdata)
mydivs = soup.findAll('div')
for div in mydivs:
if "class" in div:
if (div["class"]=="stylelistrow"):
print div
you could use fopen() function.
some example:
$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';
$newfname = $destination_folder .'myfile.mp4'; //set your file ext
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "a"); // to overwrite existing file
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
You can declare trk by the following ways : - either
trk : [{
lat : String,
lng : String
}]
or
trk : { type : Array , "default" : [] }
In the second case during insertion make the object and push it into the array like
db.update({'Searching criteria goes here'},
{
$push : {
trk : {
"lat": 50.3293714,
"lng": 6.9389939
} //inserted data is the object to be inserted
}
});
or you can set the Array of object by
db.update ({'seraching criteria goes here ' },
{
$set : {
trk : [ {
"lat": 50.3293714,
"lng": 6.9389939
},
{
"lat": 50.3293284,
"lng": 6.9389634
}
]//'inserted Array containing the list of object'
}
});
I've created an eclipse plugin for this, because I had the same problem. Feel free to download it and contribute to it.
It's still in early development, but it does its job already for me.
if you need it in rails you can use first (source code)
'1234567890'.first(5) # => "12345"
there is also last (source code)
'1234567890'.last(2) # => "90"
alternatively check from/to (source code):
"hello".from(1).to(-2) # => "ell"
The following code works fine with me:
brew install zbar
pip install pyqrcode
pip install pyzbar
For QR code image creation:
import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)
For QR code decoding:
from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)
that prints the result:
[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]
Date
itself is not deprecated. It's just a lot of its methods are. See here for details.
Use java.util.Calendar
instead.
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
one way i have found:
try to insert this field into your generated form code:
<input type='hidden' name='rm' value='2'>
rm means return method;
2 means (post)
Than after user purchases and returns to your site url, then that url gets the POST parameters as well
p.s. if using php, try to insert var_dump($_POST);
in your return url(script),then make a test purchase and when you return back to your site you will see what variables are got on your url.
Please make sure your MySql server is running on localhost.
On Linux
To check if MySql server is running:
sudo service mysql status
To run MySql server:
sudo service mysql start
On Windows
To check if MySql server is running:
C:\Windows\system32>net start
If MySql is not in list, you have to start/run MySql.
To run MySql server:
C:\Windows\system32>net start mysql
Hope this helps.
The simplest way is to use the JsonPrimitive
class, which derives from JsonElement
, as shown below:
JsonElement element = new JsonPrimitive(yourString);
JsonObject result = element.getAsJsonObject();
<div class="form-group">
<div class="input-group col-md-5">
<div class="input-group-addon">
<span class="glyphicon glyphicon-envelope"></span>
</div>
<input class="form-control" type="text" name="text" placeholder="Enter Your Email Id" width="50px">
</div>
<input type="button" name="SIGNUP" value="SIGNUP">
</div>
You could do this:
InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));
Note the UTF-8
encoding. You should specify the character set that you want the bytes encoded into. It's common to choose UTF-8
if you don't specifically need anything else. Otherwise if you select nothing you'll get the default encoding that can vary between systems. From the JavaDoc:
The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.
no, there is no way to make array length dynamic in java. you can use ArrayList
or other List
implementations instead.
What's missing from all the explanations is the fact that Java has a strict rule of class name = file name. Meaning if you have a class "Person", is must be in a file named "Person.java". Therefore, if one class tries to access "Person" the filename is not necessary, because it has got to be "Person.java".
Coming for C/C++, I have exact same issue. The answer is to create a new class (in a new file matching class name) and create a public string. This will be your "header" file. Then use that in your main file by using "extends" keyword.
Here is your answer:
Create a file called Include.java. In this file, add this:
public class Include {
public static String MyLongString= "abcdef";
}
Create another file, say, User.java. In this file, put:
import java.io.*;
public class User extends Include {
System.out.println(Include.MyLongString);
}