To print a vector which possibly has complex numbers-
fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));
I had a similar issue last week. It was easy to fix in my IDE (PyCharm).
Here was my fix:
Starting from PyCharm menu bar: File -> Settings... -> Editor -> File Encodings, then set: "IDE Encoding", "Project Encoding" and "Default encoding for properties files" ALL to UTF-8 and she now works like a charm.
Hope this helps!
I know that this is an old question but I wanted to write my answer for visual learners. I couldn't find any diagrams explaining output buffering on the worldwide-web so I made a diagram myself in Windows mspaint.exe
.
If output buffering is turned off, then echo
will send data immediately to the Browser.
If output buffering is turned on, then an echo
will send data to the output buffer before sending it to the Browser.
phpinfo
To see whether Output buffering is turned on / off please refer to phpinfo at the core section. The output_buffering
directive will tell you if Output buffering is on/off.
In this case the output_buffering
value is 4096 which means that the buffer size is 4 KB. It also means that Output buffering is turned on, on the Web server.
php.ini
It's possible to turn on/off and change buffer size by changing the value of the output_buffering
directive. Just find it in php.ini
, change it to the setting of your choice, and restart the Web server. You can find a sample of my php.ini
below.
; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
; functions.
; Possible Values:
; On = Enabled and buffer is unlimited. (Use with caution)
; Off = Disabled
; Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096
The directive output_buffering
is not the only configurable directive regarding Output buffering. You can find other configurable Output buffering directives here: http://php.net/manual/en/outcontrol.configuration.php
Example: ob_get_clean()
Below you can see how to capture an echo
and manipulate it before sending it to the browser.
// Turn on output buffering
ob_start();
echo 'Hello World'; // save to output buffer
$output = ob_get_clean(); // Get content from the output buffer, and discard the output buffer ...
$output = strtoupper($output); // manipulate the output
echo $output; // send to output stream / Browser
// OUTPUT:
HELLO WORLD
Examples: Hackingwithphp.com
More info about Output buffer with examples can be found here:
Benoit's solution works, but you really don't need to incur the overhead to draw a shape. Since colors can be drawables, just define a color in a /res/values/colors.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="semitransparent_white">#77ffffff</color>
</resources>
And then use as such in your selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@color/semitransparent_white" />
</selector>
This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:
git checkout some-branch # where some-branch can be replaced by any other branch
git branch base-branch -D # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch # recreating branch with correct commits
Note: You can combine these all by putting && between them
Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?
Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.
Ex:
git checkout feature-old # some branch with the extra commits
git log # gives commits (write down the id of the ones you want)
git checkout base-branch # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch
Now feature-new is your branch without the extra (possibly bad) commits!
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
Updated for Swift 3
Create two View Controllers with a button on each. For the second view controller, set the class name to SecondViewController
and the storyboard ID to secondVC
.
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBAction func presentButtonTapped(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myModalViewController = storyboard.instantiateViewController(withIdentifier: "secondVC")
myModalViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
myModalViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(myModalViewController, animated: true, completion: nil)
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
@IBAction func dismissButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
Source:
I'm probably going a million miles in the wrong direct (but i'm only young :P ). but couldn't you add the graphic to a panel and then a mouselistener to the graphic object so that when the user on the graphic your action is preformed.
var arr=[{"username":"sai","email":"[email protected],"}]
localStorage.setItem('logInArr', JSON.stringfy(arr))
first, you have to create Models. default model is sakila, so you have to create one. if you already created the new one, go to Database > Forward Engineer. then, your model will exist in local instance:80
Forward engineer is to create database in your choosed host!
This is based on @Reid's solution. Except:
Array
prototype.undefined
items, it just moves the item to the right-most position.Function:
function move(array, oldIndex, newIndex) {
if (newIndex >= array.length) {
newIndex = array.length - 1;
}
array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
return array;
}
Unit tests:
describe('ArrayHelper', function () {
it('Move right', function () {
let array = [1, 2, 3];
arrayHelper.move(array, 0, 1);
assert.equal(array[0], 2);
assert.equal(array[1], 1);
assert.equal(array[2], 3);
})
it('Move left', function () {
let array = [1, 2, 3];
arrayHelper.move(array, 1, 0);
assert.equal(array[0], 2);
assert.equal(array[1], 1);
assert.equal(array[2], 3);
});
it('Move out of bounds to the left', function () {
let array = [1, 2, 3];
arrayHelper.move(array, 1, -2);
assert.equal(array[0], 2);
assert.equal(array[1], 1);
assert.equal(array[2], 3);
});
it('Move out of bounds to the right', function () {
let array = [1, 2, 3];
arrayHelper.move(array, 1, 4);
assert.equal(array[0], 1);
assert.equal(array[1], 3);
assert.equal(array[2], 2);
});
});
A simple trick to change a particular point marker shape, size... is to first plot it with all the other data then plot one more plot only with that point (or set of points if you want to change the style of multiple points). Suppose we want to change the marker shape of second point:
x = [1,2,3,4,5]
y = [2,1,3,6,7]
plt.plot(x, y, "-o")
x0 = [2]
y0 = [1]
plt.plot(x0, y0, "s")
plt.show()
Result is: Plot with multiple markers
With momentjs:
/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
That's how I've added mine in profiles json table,
{
"guid": "{00000000-0000-0000-ba54-000000000002}",
"name": "Git",
"commandline": "C:/Program Files/Git/bin/bash.exe --login",
"icon": "%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico",
"startingDirectory": "%USERPROFILE%",
"hidden": false
}
You could pass in the command-line option -v
with a variable name (v
) and a value (=
) of the environment variable ("${v}"
):
% awk -vv="${v}" 'BEGIN { print v }'
123test
Or to make it clearer (with far fewer v
s):
% environment_variable=123test
% awk -vawk_variable="${environment_variable}" 'BEGIN { print awk_variable }'
123test
Use a memory stream
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, ...);
return ms.ToArray();
}
Use this
Intent i1=new Intent(getApplicationContext(),StartUp_Page.class);
i1.setAction(Intent.ACTION_MAIN);
i1.addCategory(Intent.CATEGORY_HOME);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i1);
finish();
Based on quick inspection of google web, this would be CSS path to links in page list
ol[id="rso"] h3[class="r"] a
So you should do something like
String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();
However you could also use xpath
which is not really recommended as a best practice and also JQuery locators but I am not sure if you can use them aynywhere else except inArquillian Graphene
In addition to the awesome answers above, 2 more points may be added:
1. Semantic difference:
Promises may be already resolved upon creation. This means they guarantee conditions rather than events. If they are resolved already, the resolved function passed to it is still called.
Conversely, callbacks handle events. So, if the event you are interested in has happened before the callback has been registered, the callback is not called.
2. Inversion of control
Callbacks involve inversion of control. When you register a callback function with any API, the Javascript runtime stores the callback function and calls it from the event loop once it is ready to be run.
Refer The Javascript Event loop for an explanation.
With Promises, control resides with the calling program. The .then() method may be called at any time if we store the promise object.
You can use mysql_real_escape_string. mysql_real_escape_string()
does not escape %
and _
, so you should escape MySQL wildcards (%
and _
) separately.
Yes, there are many well documented algorithms like:
A good summary ("Sam's String Metrics") can be found here (original link dead, so it links to Internet Archive)
Also check these projects:
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
Use:
public static class FileInfoExtensions
{
/// <summary>
/// Behavior when a new filename exists.
/// </summary>
public enum FileExistBehavior
{
/// <summary>
/// None: throw IOException "The destination file already exists."
/// </summary>
None = 0,
/// <summary>
/// Replace: replace the file in the destination.
/// </summary>
Replace = 1,
/// <summary>
/// Skip: skip this file.
/// </summary>
Skip = 2,
/// <summary>
/// Rename: rename the file (like a window behavior)
/// </summary>
Rename = 3
}
/// <summary>
/// Rename the file.
/// </summary>
/// <param name="fileInfo">the target file.</param>
/// <param name="newFileName">new filename with extension.</param>
/// <param name="fileExistBehavior">behavior when new filename is exist.</param>
public static void Rename(this System.IO.FileInfo fileInfo, string newFileName, FileExistBehavior fileExistBehavior = FileExistBehavior.None)
{
string newFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(newFileName);
string newFileNameExtension = System.IO.Path.GetExtension(newFileName);
string newFilePath = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileName);
if (System.IO.File.Exists(newFilePath))
{
switch (fileExistBehavior)
{
case FileExistBehavior.None:
throw new System.IO.IOException("The destination file already exists.");
case FileExistBehavior.Replace:
System.IO.File.Delete(newFilePath);
break;
case FileExistBehavior.Rename:
int dupplicate_count = 0;
string newFileNameWithDupplicateIndex;
string newFilePathWithDupplicateIndex;
do
{
dupplicate_count++;
newFileNameWithDupplicateIndex = newFileNameWithoutExtension + " (" + dupplicate_count + ")" + newFileNameExtension;
newFilePathWithDupplicateIndex = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileNameWithDupplicateIndex);
}
while (System.IO.File.Exists(newFilePathWithDupplicateIndex));
newFilePath = newFilePathWithDupplicateIndex;
break;
case FileExistBehavior.Skip:
return;
}
}
System.IO.File.Move(fileInfo.FullName, newFilePath);
}
}
class Program
{
static void Main(string[] args)
{
string targetFile = System.IO.Path.Combine(@"D://test", "New Text Document.txt");
string newFileName = "Foo.txt";
// Full pattern
System.IO.FileInfo fileInfo = new System.IO.FileInfo(targetFile);
fileInfo.Rename(newFileName);
// Or short form
new System.IO.FileInfo(targetFile).Rename(newFileName);
}
}
I had a similar issue. I was using jQuery.map but I forgot to use jQuery.map(...).get() at the end to work with a normal array.
You will need to link to the file relative to the file that includes eventManager.php
(Page A)
Change your code from
require_once('../includes/dbconn.inc');
To
require_once('../mysite/php/includes/dbconn.inc');
As said in the comments, the problem lies in your script. Actually, there are 2 problems:
None
somewhere. Maybe due to the defaultdict ?show()
after each subplot. show()
should be called once at the end of your script. The alternative is to use interactive mode, look for ion
in matplotlib's documentation.For my Case in 'Path'
variable there was a parameter added like 'C:\ProgramData\Oracle\Java\javapath;
'.
This location was having java.exe
, javaw.exe
and javaws.exe
from java 8 which is newly installed via jdk.exe
from Oracle.
I've removed this text from Path where my Path already having %JAVA_HOME%\bin
with it.
Now, the variable 'JAVA_HOME'
is controlling my Java version which is I wanted.
try
<div style="width:100%;">
<div style="width:50px; float: left;"><img src="myleftimage" /></div>
<div style="width:50px; float: right;"><img src="myrightimage" /></div>
<div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>
or
<div style="width:100%; border:2px solid #dadada;">
<div style="width:50px; float: left;"><img src="myleftimage" /></div>
<div style="width:50px; float: right;"><img src="myrightimage" /></div>
<div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>
</div>
<div class="collapse in " [ngClass]="(active_tab=='assignservice' || active_tab=='manage')?'show':''" id="collapseExampleOrganization" aria-expanded="true" style="">_x000D_
<ul> <li class="nav-item" [ngClass]="{'active': active_tab=='manage'}">_x000D_
<a routerLink="/main/organization/manage" (click)="activemenu('manage')"> <i class="la la-building-o"></i>_x000D_
<p>Manage</p></a></li> _x000D_
<li class="nav-item" [ngClass]="{'active': active_tab=='assignservice'}"><a routerLink="/main/organization/assignservice" (click)="activemenu('assignservice')"><i class="la la-user"></i><p>Add organization</p></a></li>_x000D_
</ul></div>
_x000D_
Code is good example of ngClass if else condition.
[ngClass]="(active_tab=='assignservice' || active_tab=='manage')?'show':''"
[ngClass]="{'active': active_tab=='assignservice'}"
In Mvc using plain html in View Page with java script onclick
<input type="button" value="GO BACK" class="btn btn-primary"
onclick="location.href='@Request.UrlReferrer'" />
This works great. hope helps someone.
@JuanPieterse has already answered using @Html.ActionLink
so if possible someone can comment or answer using @Url.Action
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
If you don't use parallel()
this will work
List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = new ArrayList<Long>();
sourceLongList.stream().peek(i->targetLongList.add(i)).collect(Collectors.toList());
What do you consider "special" characters, just simple punctuation? You should be able to use the Replace
function: Replace("p.k","."," ")
.
Sub Test()
Dim myString as String
Dim newString as String
myString = "p.k"
newString = replace(myString, ".", " ")
MsgBox newString
End Sub
If you have several characters, you can do this in a custom function or a simple chained series of Replace
functions, etc.
Sub Test()
Dim myString as String
Dim newString as String
myString = "!p.k"
newString = Replace(Replace(myString, ".", " "), "!", " ")
'## OR, if it is easier for you to interpret, you can do two sequential statements:
'newString = replace(myString, ".", " ")
'newString = replace(newString, "!", " ")
MsgBox newString
End Sub
If you have a lot of potential special characters (non-English accented ascii for example?) you can do a custom function or iteration over an array.
Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?" 'modify as needed
Sub test()
Dim myString as String
Dim newString as String
Dim char as Variant
myString = "!p#*@)k{kdfhouef3829J"
newString = myString
For each char in Split(SpecialCharacters, ",")
newString = Replace(newString, char, " ")
Next
End Sub
You cat use setVisible ()
method of JFrame (and set visibility to false
) or dispose ()
method which is more similar to close
operation.
Simply, change
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;"></textarea>
to
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;" data-role="none"></textarea>
ie, add:
data-role="none"
For those have HashMap based spinner :
((HashMap)((Spinner)findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
If you are in a Fragment, an Adaptor or a Class other than main activities , use this:
((HashMap)((Spinner)YourInflatedLayoutOrView.findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
It's just for guidance; you should find your view's id before onClick method.
Pyparsing can be used to parse mathematical expressions. In particular, fourFn.py shows how to parse basic arithmetic expressions. Below, I've rewrapped fourFn into a numeric parser class for easier reuse.
from __future__ import division
from pyparsing import (Literal, CaselessLiteral, Word, Combine, Group, Optional,
ZeroOrMore, Forward, nums, alphas, oneOf)
import math
import operator
__author__ = 'Paul McGuire'
__version__ = '$Revision: 0.0 $'
__date__ = '$Date: 2009-03-20 $'
__source__ = '''http://pyparsing.wikispaces.com/file/view/fourFn.py
http://pyparsing.wikispaces.com/message/view/home/15549426
'''
__note__ = '''
All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it
more easily in other places.
'''
class NumericStringParser(object):
'''
Most of this code comes from the fourFn.py pyparsing example
'''
def pushFirst(self, strg, loc, toks):
self.exprStack.append(toks[0])
def pushUMinus(self, strg, loc, toks):
if toks and toks[0] == '-':
self.exprStack.append('unary -')
def __init__(self):
"""
expop :: '^'
multop :: '*' | '/'
addop :: '+' | '-'
integer :: ['+' | '-'] '0'..'9'+
atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'
factor :: atom [ expop factor ]*
term :: factor [ multop factor ]*
expr :: term [ addop term ]*
"""
point = Literal(".")
e = CaselessLiteral("E")
fnumber = Combine(Word("+-" + nums, nums) +
Optional(point + Optional(Word(nums))) +
Optional(e + Word("+-" + nums, nums)))
ident = Word(alphas, alphas + nums + "_$")
plus = Literal("+")
minus = Literal("-")
mult = Literal("*")
div = Literal("/")
lpar = Literal("(").suppress()
rpar = Literal(")").suppress()
addop = plus | minus
multop = mult | div
expop = Literal("^")
pi = CaselessLiteral("PI")
expr = Forward()
atom = ((Optional(oneOf("- +")) +
(ident + lpar + expr + rpar | pi | e | fnumber).setParseAction(self.pushFirst))
| Optional(oneOf("- +")) + Group(lpar + expr + rpar)
).setParseAction(self.pushUMinus)
# by defining exponentiation as "atom [ ^ factor ]..." instead of
# "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right
# that is, 2^3^2 = 2^(3^2), not (2^3)^2.
factor = Forward()
factor << atom + \
ZeroOrMore((expop + factor).setParseAction(self.pushFirst))
term = factor + \
ZeroOrMore((multop + factor).setParseAction(self.pushFirst))
expr << term + \
ZeroOrMore((addop + term).setParseAction(self.pushFirst))
# addop_term = ( addop + term ).setParseAction( self.pushFirst )
# general_term = term + ZeroOrMore( addop_term ) | OneOrMore( addop_term)
# expr << general_term
self.bnf = expr
# map operator symbols to corresponding arithmetic operations
epsilon = 1e-12
self.opn = {"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
"^": operator.pow}
self.fn = {"sin": math.sin,
"cos": math.cos,
"tan": math.tan,
"exp": math.exp,
"abs": abs,
"trunc": lambda a: int(a),
"round": round,
"sgn": lambda a: abs(a) > epsilon and cmp(a, 0) or 0}
def evaluateStack(self, s):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack(s)
if op in "+-*/^":
op2 = self.evaluateStack(s)
op1 = self.evaluateStack(s)
return self.opn[op](op1, op2)
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op](self.evaluateStack(s))
elif op[0].isalpha():
return 0
else:
return float(op)
def eval(self, num_string, parseAll=True):
self.exprStack = []
results = self.bnf.parseString(num_string, parseAll)
val = self.evaluateStack(self.exprStack[:])
return val
You can use it like this
nsp = NumericStringParser()
result = nsp.eval('2^4')
print(result)
# 16.0
result = nsp.eval('exp(2^4)')
print(result)
# 8886110.520507872
The directory doesn't exist. Make sure it exists as open
won't create those dirs for you.
I ran into this myself a while back.
Use PE Explorer click here to know more and download
Just for sake of completeness, you can also use the same technique above with excel tables.
In the example below, I'm looking of a text in any cell of a Excel Table named "tblConfig", place in the sheet named Config that normally is set to be hidden. I'm accepting the defaults of the Find method.
Dim list As ListObject
Dim config As Worksheet
Dim cell as Range
Set config = Sheets("Config")
Set list = config.ListObjects("tblConfig")
'search in any cell of the data range of excel table
Set cell = list.DataBodyRange.Find(searchTerm)
If cell Is Nothing Then
'when information is not found
Else
'when information is found
End If
I did that in the following way for an image, you should be able to do it for text using similar steps.
// folder & name of image on PC
File fileObj = new File("C:\\Displayable\\imgcopy.jpg");
Boolean testB = fileObj.createNewFile();
System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);
// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg");
InputStream webIS = url.openStream();
FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
c = webIS.read();
System.out.println("==============> " + c);
if (c !=-1) {
fo.write((byte) c);
}
} while(c != -1);
webIS.close();
fo.close();
Here is a simple customview for display circle progress. You can modify and optimize more to suitable for your project.
class CircleProgressBar @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val backgroundWidth = 10f
private val progressWidth = 20f
private val backgroundPaint = Paint().apply {
color = Color.LTGRAY
style = Paint.Style.STROKE
strokeWidth = backgroundWidth
isAntiAlias = true
}
private val progressPaint = Paint().apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = progressWidth
isAntiAlias = true
}
var progress: Float = 0f
set(value) {
field = value
invalidate()
}
private val oval = RectF()
private var centerX: Float = 0f
private var centerY: Float = 0f
private var radius: Float = 0f
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
centerX = w.toFloat() / 2
centerY = h.toFloat() / 2
radius = w.toFloat() / 2 - progressWidth
oval.set(centerX - radius,
centerY - radius,
centerX + radius,
centerY + radius)
super.onSizeChanged(w, h, oldw, oldh)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(centerX, centerY, radius, backgroundPaint)
canvas?.drawArc(oval, 270f, 360f * progress, false, progressPaint)
}
}
Example using
xml
<com.example.androidcircleprogressbar.CircleProgressBar
android:id="@+id/circle_progress"
android:layout_width="200dp"
android:layout_height="200dp" />
kotlin
class MainActivity : AppCompatActivity() {
val TOTAL_TIME = 10 * 1000L
override fun onCreate(savedInstanceState: Bundle?) {
...
timeOutRemoveTimer.start()
}
private var timeOutRemoveTimer = object : CountDownTimer(TOTAL_TIME, 10) {
override fun onFinish() {
circle_progress.progress = 1f
}
override fun onTick(millisUntilFinished: Long) {
circle_progress.progress = (TOTAL_TIME - millisUntilFinished).toFloat() / TOTAL_TIME
}
}
}
Result
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
You can convert BigDecimal
to double
using .doubleValue()
. But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal
objects directly. Precision loss in these calculations are big time problems in currency related calculations.
These do the same thing:
window.location.assign(url);
window.location = url;
window.location.href = url;
They simply navigate to the new URL. The replace
method on the other hand navigates to the URL without adding a new record to the history.
So, what you have read in those many forums is not correct. The assign
method does add a new record to the history.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location
SSLHandshakeException can be resolved 2 ways.
Incorporating SSL
Get the SSL (by asking the source system administrator, can also be downloaded by openssl command, or any browsers downloads the certificates)
Add the certificate into truststore (cacerts) located at JRE/lib/security
provide the truststore location in vm arguments as "-Djavax.net.ssl.trustStore="
Ignoring SSL
For this #2, please visit my other answer on another stackoverflow website: How to ingore SSL verification Ignore SSL Certificate Errors with Java
I have resolved the issue by adding below code snippet into node.js file.
app.get("/*", function (request, response) {
console.log('Unknown API called');
response.redirect('/#' + request.url);
});
Note : when we refresh the page, it will look for the API instead of Angular page (Because of no # tag in URL.) . Using the above code, I am redirecting to the url with #
It labels whatever input is the parameter for the for
attribute.
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
For encoding to base64 in Angular2, you can use btoa() function.
Example:-
console.log(btoa("stringAngular2"));
// Output:- c3RyaW5nQW5ndWxhcjI=
For decoding from base64 in Angular2, you can use atob() function.
Example:-
console.log(atob("c3RyaW5nQW5ndWxhcjI="));
// Output:- stringAngular2
To access services in two different namespaces you can use url like this:
HTTP://<your-service-name>.<namespace-with-that-service>.svc.cluster.local
To list out all your namespaces you can use:
kubectl get namespace
And for service in that namespace you can simply use:
kubectl get services -n <namespace-name>
this will help you.
Try changing the this.getElementsByTagName("td")[0])
line to read row.getElementsByTagName("td")[0];
. That should capture the row
reference in a closure, and it should work as expected.
Edit: The above is wrong, since row is a global variable -- as others have said, allocate a new variable and then use THAT in the closure.
You can also use the AWS Data Wrangler:
import awswrangler as wr
wr.s3.to_csv(
df=df,
path="s3://...",
)
Note that it will handle multipart upload for you to make the upload faster.
Try this?
encodeURIComponent('space word').replace(/%20/g,'+')
$db->getProfiler()->setEnabled(true);
// your code
$this->update('table', $data, $where);
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQuery());
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQueryParams());
$db->getProfiler()->setEnabled(false);
Illustration of @Jan Philip Matuschek excellent explanation.(Please up-vote his answer, not this; I am adding this as I took a little time in understanding the original answer)
The bounding box technique of optimizing of finding nearest neighbors would need to derive the minimum and maximum latitude,longitude pairs, for a point P at distance d . All points that fall outside these are definitely at a distance greater than d from the point. One thing to note here is the calculation of latitude of intersection as is highlighted in Jan Philip Matuschek explanation. The latitude of intersection is not at the latitude of point P but slightly offset from it. This is a often missed but important part in determining the correct minimum and maximum bounding longitude for point P for the distance d.This is also useful in verification.
The haversine distance between (latitude of intersection,longitude high) to (latitude,longitude) of P is equal to distance d.
Python gist here https://gist.github.com/alexcpn/f95ae83a7ee0293a5225
An approximation of what I was doing:
import module.submodule
class MyClass:
constant = submodule.constant
To which pylint said:
E: 4,15: Undefined variable 'submodule' (undefined-variable)
from module.submodule import CONSTANT
class MyClass:
constant = CONSTANT
Note: I also renamed by imported variable to have an uppercase name to reflect its constant nature.
You can do it this way. It needs to go in the maven format:
repositories {
maven { url uri('folderName')}
}
And then your AAR needs to go in a folder structure for a group id "com.example":
folderName/
com/
example/
verion/
myaar-version.aar
Then reference as a dependency:
compile 'com.example:myaar:version@aar'
Where version
is the version of your aar file (ie, 3.0, etc)
For my suggestion, please read the last section: “When to use SO_LINGER with timeout 0”.
Before we come to that a little lecture about:
TIME_WAIT
FIN
, ACK
and RST
The normal TCP termination sequence looks like this (simplified):
We have two peers: A and B
close()
FIN
to BFIN_WAIT_1
stateFIN
ACK
to ACLOSE_WAIT
stateACK
FIN_WAIT_2
stateclose()
FIN
to ALAST_ACK
stateFIN
ACK
to BTIME_WAIT
stateACK
CLOSED
state – i.e. is removed from the socket tablesSo the peer that initiates the termination – i.e. calls close()
first – will end up in the TIME_WAIT
state.
To understand why the TIME_WAIT
state is our friend, please read section 2.7 in "UNIX Network Programming" third edition by Stevens et al (page 43).
However, it can be a problem with lots of sockets in TIME_WAIT
state on a server as it could eventually prevent new connections from being accepted.
To work around this problem, I have seen many suggesting to set the SO_LINGER socket option with timeout 0 before calling close()
. However, this is a bad solution as it causes the TCP connection to be terminated with an error.
Instead, design your application protocol so the connection termination is always initiated from the client side. If the client always knows when it has read all remaining data it can initiate the termination sequence. As an example, a browser knows from the Content-Length
HTTP header when it has read all data and can initiate the close. (I know that in HTTP 1.1 it will keep it open for a while for a possible reuse, and then close it.)
If the server needs to close the connection, design the application protocol so the server asks the client to call close()
.
Again, according to "UNIX Network Programming" third edition page 202-203, setting SO_LINGER
with timeout 0 prior to calling close()
will cause the normal termination sequence not to be initiated.
Instead, the peer setting this option and calling close()
will send a RST
(connection reset) which indicates an error condition and this is how it will be perceived at the other end. You will typically see errors like "Connection reset by peer".
Therefore, in the normal situation it is a really bad idea to set SO_LINGER
with timeout 0 prior to calling close()
– from now on called abortive close – in a server application.
However, certain situation warrants doing so anyway:
CLOSE_WAIT
or ending up in the TIME_WAIT
state.TIME_WAIT
(when calling close()
from the server end) as this might prevent the server from getting available ports for new client connections after being restarted.CLOSE_WAIT
trying to deliver data to a stuck terminal port, but would properly reset the stuck port if it got an RST
to discard the pending data."I would recommend this long article which I believe gives a very good answer to your question.
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
div { margin: auto; }
This will center your div.
Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.
You need to use gdb's memory-display commands. The basic one is x
, for examine. There's an example on the linked-to page that uses
gdb> x/4xw $sp
to print "four words (w
) of memory above the stack pointer (here, $sp
) in hexadecimal (x
)". The quotation is slightly paraphrased.
Use console.log(JSON.stringify(result))
to get the JSON in a string format.
EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty
and access the property if it does exist:
var obj = {id : "007", name : "James Bond"};
console.log(obj); // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj)); //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
console.log(obj.id); //007
}
No, the dataType
option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify
and set the processData
option to false
.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON
object, and although jQuery has .parseJSON
, it has no stringifier included; you'll need another polyfill library.
ref: NSUserdefault objectTypes
Store
UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key") //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject
Retrieve
UserDefaults.standard.bool(forKey: "Key")
UserDefaults.standard.integer(forKey: "Key")
UserDefaults.standard.string(forKey: "Key")
Remove
UserDefaults.standard.removeObject(forKey: "Key")
Remove all Keys
if let appDomain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: appDomain)
}
Store
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "yourkey")
NSUserDefaults.standardUserDefaults().synchronize()
Retrieve
var returnValue: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("yourkey") as? [NSString]
Remove
NSUserDefaults.standardUserDefaults().removeObjectForKey("yourkey")
registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them.
Default values from Defaults Configuration Files will automatically be registered.
for example detect the app from launch , create the struct for save launch
struct DetectLaunch {
static let keyforLaunch = "validateFirstlunch"
static var isFirst: Bool {
get {
return UserDefaults.standard.bool(forKey: keyforLaunch)
}
set {
UserDefaults.standard.set(newValue, forKey: keyforLaunch)
}
}
}
Register default values on app launch:
UserDefaults.standard.register(defaults: [
DetectLaunch.isFirst: true
])
remove the value on app termination:
func applicationWillTerminate(_ application: UIApplication) {
DetectLaunch.isFirst = false
}
and check the condition as
if DetectLaunch.isFirst {
// app launched from first
}
another one property suite name, mostly its used for App Groups concept, the example scenario I taken from here :
The use case is that I want to separate my UserDefaults (different business logic may require Userdefaults to be grouped separately) by an identifier just like Android's SharedPreferences. For example, when a user in my app clicks on logout button, I would want to clear his account related defaults but not location of the the device.
let user = UserDefaults(suiteName:"User")
use of userDefaults synchronize, the detail info has added in the duplicate answer.
The $
is just a function. It is actually an alias for the function called jQuery
, so your code can be written like this with the exact same results:
jQuery('#Text').click(function () {
jQuery('#Text').css('color', 'red');
});
module.exports = function isset () {
// discuss at: http://locutus.io/php/isset/
// original by: Kevin van Zonneveld (http://kvz.io)
// improved by: FremyCompany
// improved by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Rafal Kukawski (http://blog.kukawski.pl)
// example 1: isset( undefined, true)
// returns 1: false
// example 2: isset( 'Kevin van Zonneveld' )
// returns 2: true
var a = arguments
var l = a.length
var i = 0
var undef
if (l === 0) {
throw new Error('Empty isset')
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false
}
i++
}
return true
}
phpjs.org is mostly retired in favor of locutus Here is the new link http://locutus.io/php/var/isset
select nvl(max(1), 0) from mytable;
This statement yields 0 if there are no rows, 1 if you have at least one row in that table. It's way faster than doing a select count(*). The optimizer "sees" that only a single row needs to be fetched to answer the question.
Here's a (verbose) little example:
declare
YES constant signtype := 1;
NO constant signtype := 0;
v_table_has_rows signtype;
begin
select nvl(max(YES), NO)
into v_table_has_rows
from mytable -- where ...
;
if v_table_has_rows = YES then
DBMS_OUTPUT.PUT_LINE ('mytable has at least one row');
end if;
end;
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.
There isn't so much an advantage or disadvantage aside from "do I want this variable, function, class, etc. to be public or private?"
I can't find anything in the conda
specs which allow you to export an environment file without the prefix: ...
line. However, as Alex pointed out in the comments, conda doesn't seem to care about the prefix line when creating an environment from file.
With that in mind, if you want the other user to have no knowledge of your default install path, you can remove the prefix line with grep
before writing to environment.yml
.
conda env export | grep -v "^prefix: " > environment.yml
Either way, the other user then runs:
conda env create -f environment.yml
and the environment will get installed in their default conda environment path.
If you want to specify a different install path than the default for your system (not related to 'prefix' in the environment.yml), just use the -p
flag followed by the required path.
conda env create -f environment.yml -p /home/user/anaconda3/envs/env_name
Note that Conda recommends creating the environment.yml
by hand, which is especially important if you are wanting to share your environment across platforms (Windows/Linux/Mac). In this case, you can just leave out the prefix
line.
if u want to write a JSON object to the response then change the header content type to application/json
response.writeHead(200, {"Content-Type": "application/json"});
var d = new Date(parseURL.query.iso);
var postData = {
"hour" : d.getHours(),
"minute" : d.getMinutes(),
"second" : d.getSeconds()
}
response.write(postData)
response.end();
Python dicts are not sorted, by definition. You cannot sort one, nor control the order of its elements by how you insert them. You might want to look at collections.OrderDict, which even comes with a little tutorial for almost exactly what you're trying to do: http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes
You simply type vim
into the terminal to open it and start a new file.
You can pass a filename as an option and it will open that file, e.g. vim main.c
. You can open multiple files by passing multiple file arguments.
Vim has different modes, unlike most editors you have probably used. You begin in NORMAL
mode, which is where you will spend most of your time once you become familiar with vim.
To return to NORMAL
mode after changing to a different mode, press Esc. It's a good idea to map your Caps Lock key to Esc, as it's closer and nobody really uses the Caps Lock key.
The first mode to try is INSERT
mode, which is entered with a for append after cursor, or i for insert before cursor.
To enter VISUAL
mode, where you can select text, use v. There are many other variants of this mode, which you will discover as you learn more about vim.
To save your file, ensure you're in NORMAL
mode and then enter the command :w
. When you press :
, you will see your command appear in the bottom status bar. To save and exit, use :x
. To quit without saving, use :q
. If you had made a change you wanted to discard, use :q!
.
You can edit your ~/.vimrc
file to configure vim to your liking. It's best to look at a few first (here's mine) and then decide which options suits your style.
This is how mine looks:
To get the file explorer on the left, use NERDTree. For the status bar, use vim-airline. Finally, the color scheme is solarized.
You can use man vim
for some help inside the terminal. Alternatively, run vimtutor
which is a good hands-on starting point.
It's a good idea to print out a Vim Cheatsheet and keep it in front of you while you're learning vim.
Good luck!
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
Create file version.properties
MAJOR=1
MINOR=3
PATCH=6
VERSION_CODE=1
Change build.gradle
:
android {
def _versionCode=0
def _major=0
def _minor=0
def _patch=0
def _applicationId = "com.example.test"
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
_patch = versionProps['PATCH'].toInteger() + 1
_major = versionProps['MAJOR'].toInteger()
_minor = versionProps['MINOR'].toInteger()
_versionCode= versionProps['VERSION_CODE'].toInteger()+1
if(_patch==99)
{
_patch=0
_minor=_minor+1
}
if(_major==99){
_major=0
_major=_major+1
}
versionProps['MAJOR']=_major.toString()
versionProps['MINOR']=_minor.toString()
versionProps['PATCH']=_patch.toString()
versionProps['VERSION_CODE']=_versionCode.toString()
versionProps.store(versionPropsFile.newWriter(), null)
}
else {
throw new GradleException("Could not read version.properties!")
}
def _versionName = "${_major}.${_versionCode}.${_minor}.${_patch}"
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId _applicationId
minSdkVersion 11
targetSdkVersion 23
versionCode _versionCode
versionName _versionName
}
}
Output : 1.1.3.6
Try Ctrl+Alt+Shift+? / ?, without mouse, or hold "alt" and click on all the lines you want.
Note: Tested on Windows.
My Code to insert data is not working. It showing no error but data is not showing in my database.
public partial class Form1 : Form { OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString); public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_add_Click(object sender, EventArgs e)
{
OleDbDataAdapter items = new OleDbDataAdapter();
connection.Open();
OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName, SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
command.CommandType = CommandType.Text;
command.ExecuteReader();
connection.Close();
MessageBox.Show("Insertd!");
}
}
In terms of bytecode, in
saves a LOAD_ATTR
and replaces a CALL_FUNCTION
with a COMPARE_OP
.
>>> dis.dis(indict)
2 0 LOAD_GLOBAL 0 (name)
3 LOAD_GLOBAL 1 (d)
6 COMPARE_OP 6 (in)
9 POP_TOP
>>> dis.dis(haskey)
2 0 LOAD_GLOBAL 0 (d)
3 LOAD_ATTR 1 (haskey)
6 LOAD_GLOBAL 2 (name)
9 CALL_FUNCTION 1
12 POP_TOP
My feelings are that in
is much more readable and is to be preferred in every case that I can think of.
In terms of performance, the timing reflects the opcode
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
10000000 loops, best of 3: 0.11 usec per loop
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
1000000 loops, best of 3: 0.205 usec per loop
in
is almost twice as fast.
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
You can simply add another join like this:
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
However be aware that, because it is an INNER JOIN
, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN
which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
LEFT OUTER JOIN images
ON dashboard_messages.image_id = images.image_id
Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT
i.e 204 No Content as in place of HttpStatus.OK
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
Any value of T will be ignored for 204, but not for 404
public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$
if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
} else {
LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
}
}
Your best bet is probably something like so:
>>> import sys
>>> sys.version_info
(2, 6, 4, 'final', 0)
>>> if not sys.version_info[:2] == (2, 6):
... print "Error, I need python 2.6"
... else:
... from my_module import twoPointSixCode
>>>
Additionally, you can always wrap your imports in a simple try, which should catch syntax errors. And, to @Heikki's point, this code will be compatible with much older versions of python:
>>> try:
... from my_module import twoPointSixCode
... except Exception:
... print "can't import, probably because your python is too old!"
>>>
The accepted answer here does not mention a fact that if you have a null string ToLower() will throw an exception. The safer way would be to do:
fi => (fi.DESCRIPTION ?? string.Empty).ToLower().Contains((description ?? string.Empty).ToLower())
Be sure your file permissions are correct. If apache doesn't have permission to read the file then it can't write to the log.
This file will serve you as a good sendfile
example : http://tldp.org/LDP/LGNET/91/misc/tranter/server.c.txt
You can use the following for an unbiased result:
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
Note: random.nextInt(2) means that the number 2 is the bound. the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!
If you want to give more probability to your result to be true (or false) you can adjust the above as following!
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;
//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;
The answers here do an excellent job in defining both monoids and monads, however, they still don't seem to answer the question:
And on a less important note, is this true and if so could you give an explanation (hopefully one that can be understood by someone who doesn't have much Haskell experience)?
The crux of the matter that is missing here, is the different notion of "monoid", the so-called categorification more precisely -- the one of monoid in a monoidal category. Sadly Mac Lane's book itself makes it very confusing:
All told, a monad in
X
is just a monoid in the category of endofunctors ofX
, with product×
replaced by composition of endofunctors and unit set by the identity endofunctor.
Why is this confusing? Because it does not define what is "monoid in the category of endofunctors" of X
. Instead, this sentence suggests taking a monoid inside the set of all endofunctors together with the functor composition as binary operation and the identity functor as a monoidal unit. Which works perfectly fine and turns into a monoid any subset of endofunctors that contains the identity functor and is closed under functor composition.
Yet this is not the correct interpretation, which the book fails to make clear at that stage. A Monad f
is a fixed endofunctor, not a subset of endofunctors closed under composition. A common construction is to use f
to generate a monoid by taking the set of all k
-fold compositions f^k = f(f(...))
of f
with itself, including k=0
that corresponds to the identity f^0 = id
. And now the set S
of all these powers for all k>=0
is indeed a monoid "with product × replaced by composition of endofunctors and unit set by the identity endofunctor".
And yet:
S
can be defined for any functor f
or even literally for any self-map of X
. It is the monoid generated by f
.S
given by the functor composition and the identity functor has nothing do with f
being or not being a monad.And to make things more confusing, the definition of "monoid in monoidal category" comes later in the book as you can see from the table of contents. And yet understanding this notion is absolutely critical to understanding the connection with monads.
Going to Chapter VII on Monoids (which comes later than Chapter VI on Monads), we find the definition of the so-called strict monoidal category as triple (B, *, e)
, where B
is a category, *: B x B-> B
a bifunctor (functor with respect to each component with other component fixed) and e
is a unit object in B
, satisfying the associativity and unit laws:
(a * b) * c = a * (b * c)
a * e = e * a = a
for any objects a,b,c
of B
, and the same identities for any morphisms a,b,c
with e
replaced by id_e
, the identity morphism of e
. It is now instructive to observe that in our case of interest, where B
is the category of endofunctors of X
with natural transformations as morphisms, *
the functor composition and e
the identity functor, all these laws are satisfied, as can be directly verified.
What comes after in the book is the definition of the "relaxed" monoidal category, where the laws only hold modulo some fixed natural transformations satisfying so-called coherence relations, which is however not important for our cases of the endofunctor categories.
Finally, in section 3 "Monoids" of Chapter VII, the actual definition is given:
A monoid
c
in a monoidal category(B, *, e)
is an object ofB
with two arrows (morphisms)
mu: c * c -> c
nu: e -> c
making 3 diagrams commutative. Recall that in our case, these are morphisms in the category of endofunctors, which are natural transformations corresponding to precisely join
and return
for a monad. The connection becomes even clearer when we make the composition *
more explicit, replacing c * c
by c^2
, where c
is our monad.
Finally, notice that the 3 commutative diagrams (in the definition of a monoid in monoidal category) are written for general (non-strict) monoidal categories, while in our case all natural transformations arising as part of the monoidal category are actually identities. That will make the diagrams exactly the same as the ones in the definition of a monad, making the correspondence complete.
In summary, any monad is by definition an endofunctor, hence an object in the category of endofunctors, where the monadic join
and return
operators satisfy the definition of a monoid in that particular (strict) monoidal category. Vice versa, any monoid in the monoidal category of endofunctors is by definition a triple (c, mu, nu)
consisting of an object and two arrows, e.g. natural transformations in our case, satisfying the same laws as a monad.
Finally, note the key difference between the (classical) monoids and the more general monoids in monoidal categories. The two arrows mu
and nu
above are not anymore a binary operation and a unit in a set. Instead, you have one fixed endofunctor c
. The functor composition *
and the identity functor alone do not provide the complete structure needed for the monad, despite that confusing remark in the book.
Another approach would be to compare with the standard monoid C
of all self-maps of a set A
, where the binary operation is the composition, that can be seen to map the standard cartesian product C x C
into C
. Passing to the categorified monoid, we are replacing the cartesian product x
with the functor composition *
, and the binary operation gets replaced with the natural transformation mu
from
c * c
to c
, that is a collection of the join
operators
join: c(c(T))->c(T)
for every object T
(type in programming). And the identity elements in classical monoids, which can be identified with images of maps from a fixed one-point-set, get replaced with the collection of the return
operators
return: T->c(T)
But now there are no more cartesian products, so no pairs of elements and thus no binary operations.
Well, this is simple. The above for
loops are semantically equivalent to
int i = 0;
while(i < 5) {
printf("%d", i);
i++;
}
and
int i = 0;
while(i < 5) {
printf("%d", i);
++i;
}
Note that the lines i++;
and ++i;
have the same semantics FROM THE PERSPECTIVE OF THIS BLOCK OF CODE. They both have the same effect on the value of i
(increment it by one) and therefore have the same effect on the behavior of these loops.
Note that there would be a difference if the loop was rewritten as
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = ++i;
}
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = i++;
}
This is because in first block of code j
sees the value of i
after the increment (i
is incremented first, or pre-incremented, hence the name) and in the second block of code j
sees the value of i
before the increment.
you can set them in the body tag
body
{
font-size:xxx;
font-family:yyyy;
}
If you have lots of columns and only one is different you could do:
In[1]: grouper = df.groupby('Company Name')
In[2]: res = grouper.count()
In[3]: res['Amount'] = grouper.Amount.sum()
In[4]: res
Out[4]:
Organisation Name Amount
Company Name
Vifor Pharma UK Ltd 5 4207.93
Note you can then rename the Organisation Name column as you wish.
connect to the admin database and run db.serverStatus()
:
> var status = db.serverStatus()
> status.connections
{"current" : 21, "available" : 15979}
>
You can directly get by querying
db.serverStatus().connections
To understand what does MongoDb's db.serverStatus().connections
response mean, read the documentation here.
connections
"connections" : { "current" : <num>, "available" : <num>, "totalCreated" : NumberLong(<num>) },
connections A document that reports on the status of the connections. Use these values to assess the current load and capacity requirements of the server.
connections.current The number of incoming connections from clients to the database server . This number includes the current shell session. Consider the value of connections.available to add more context to this datum.
The value will include all incoming connections including any shell connections or connections from other servers, such as replica set members or mongos instances.
connections.available The number of unused incoming connections available. Consider this value in combination with the value of connections.current to understand the connection load on the database, and the UNIX ulimit Settings document for more information about system thresholds on available connections.
connections.totalCreated Count of all incoming connections created to the server. This number includes connections that have since closed.
This Code Is working Fine :
txtTimer.setText(String.format("%02d:%02d:%02d",(SecondsCounter/3600), ((SecondsCounter % 3600)/60), (SecondsCounter % 60)));
Even I faced the same issue - when checked on dashboard I found following Error. As the data was coming through Flume and had interrupted in between due to which may be there was inconsistency in few files.
Caused by: org.apache.hadoop.hive.serde2.SerDeException: org.codehaus.jackson.JsonParseException: Unexpected end-of-input within/between OBJECT entries
Running on fewer files it worked. Format consistency was the reason in my case.
system
The system
method calls a system program. You have to provide the command as a string argument to this method. For example:
>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true
The invoked program will use the current STDIN
, STDOUT
and STDERR
objects of your Ruby program. In fact, the actual return value is either true
, false
or nil
. In the example the date was printed through the IO object of STDIN
. The method will return true
if the process exited with a zero status, false
if the process exited with a non-zero status and nil
if the execution failed.
As of Ruby 2.6, passing exception: true
will raise an exception instead of returning false
or nil
:
>> system('invalid')
=> nil
>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)
Another side effect is that the global variable $?
is set to a Process::Status
object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.
>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>
Backticks
Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.
>> `date`
=> Wed Sep 4 22:22:51 CEST 2013
The global variable $?
is set through the backticks, too. With backticks you can also make use string interpolation.
%x()
Using %x
is an alternative to the backticks style. It will return the output, too. Like its relatives %w
and %q
(among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date)
, %x{date}
and %x-date-
are all synonyms. Like backticks %x
can make use of string interpolation.
exec
By using Kernel#exec
the current process (your Ruby script) is replaced with the process invoked through exec
. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.
Open3.popen3
Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3
comes in handy:
require 'open3'
Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
pid = thread.pid
puts stdout.read.chomp
end
I did the following in Eclipse with the Android Support Library (APL) project and the Main Project (MP):
Ensured both APL and MP had the same minSdkVersion
and targetSdkVersion
.
Added APL as a build dependency for MP:
Going into "Properties > Java Build Path" of MP, and then
Selecting the "Projects" tab and adding APL.
In the properties of MP, under "Android", added a reference to APL under library.
1 and 2 got the references to Java classes working fine...however I still saw the error in the manifest.xml
for MP when trying to reference @style/Theme.AppCompat.Light
from APL. This only went away when I performed step 3.
I think that a fast answer for get the first character could be:
let firstCharacter = aString[aString.startIndex]
It's so much elegant and performance than:
let firstCharacter = Array(aString.characters).first
But.. if you want manipulate and do more operations with strings you could think create an extension..here is one extension with this approach, it's quite similar to that already posted here:
extension String {
var length : Int {
return self.characters.count
}
subscript(integerIndex: Int) -> Character {
let index = startIndex.advancedBy(integerIndex)
return self[index]
}
subscript(integerRange: Range<Int>) -> String {
let start = startIndex.advancedBy(integerRange.startIndex)
let end = startIndex.advancedBy(integerRange.endIndex)
let range = start..<end
return self[range]
}
}
BUT IT'S A TERRIBLE IDEA!!
The extension below is horribly inefficient. Every time a string is accessed with an integer, an O(n) function to advance its starting index is run. Running a linear loop inside another linear loop means this for loop is accidentally O(n2) — as the length of the string increases, the time this loop takes increases quadratically.
Instead of doing that you could use the characters's string collection.
The reason is that php cannot find the correct path of mysql.sock
.
Please make sure that your mysql is running first.
Then, please confirm that which path is the mysql.sock
located, for example /tmp/mysql.sock
then add this path string to php.ini:
Finally, restart Apache.
I would recommend against mixing camel case and underscore separation (like you proposed for struct members). This is confusing. You'd think, hey I have get_length
so I should probably have make_subset
and then you find out it's actually makeSubset
. Use the principle of least astonishment, and be consistent.
I do find CamelCase useful to type names, like structs, typedefs and enums. That's about all, though. For all the rest (function names, struct member names, etc.) I use underscore_separation.
Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :
The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.
So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.
C language leaves compiler some freedom about the location of the structural elements in the memory:
The C language provides some assurance to the programmer of the elements layout in the structure:
Problems related to the elements alignment:
How alignment works:
p.s More detailed info are available here: "Samuel P.Harbison, Guy L.Steele C A Reference, (5.6.2 - 5.6.7)"
One is a column (aka Series), while the other is a DataFrame:
In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [2]: df
Out[2]:
a b
0 1 2
1 3 4
The column 'b' (aka Series):
In [3]: df['b']
Out[3]:
0 2
1 4
Name: b, dtype: int64
The subdataframe with columns (position) in [1]:
In [4]: df[[1]]
Out[4]:
b
0 2
1 4
Note: it's preferable (and less ambiguous) to specify whether you're talking about the column name e.g. ['b'] or the integer location, since sometimes you can have columns named as integers:
In [5]: df.iloc[:, [1]]
Out[5]:
b
0 2
1 4
In [6]: df.loc[:, ['b']]
Out[6]:
b
0 2
1 4
In [7]: df.loc[:, 'b']
Out[7]:
0 2
1 4
Name: b, dtype: int64
As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root
for git rebase
:
"git rebase [-i] --root $tip
" can now be used to rewrite all the history leading to "$tip
" down to the root commit.
That new behavior was initially discussed here:
I personally think "
git rebase -i --root
" should be made to just work without requiring "--onto
" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.
The patch followed.
(original answer, February 2010)
As mentioned in the Git FAQ (and this SO question), the idea is:
git reset --hard
Rebase branch on top of changed commit, using:
git rebase --onto <tmp branch> <commit after changed> <branch>`
The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter
to make sure the content of that file does not contain in any commit the sensible information.
In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.
The idea behind StandardScaler
is that it will transform your data such that its distribution will have a mean value 0 and standard deviation of 1.
In case of multivariate data, this is done feature-wise (in other words independently for each column of the data).
Given the distribution of the data, each value in the dataset will have the mean value subtracted, and then divided by the standard deviation of the whole dataset (or feature in the multivariate case).
Define the class before you use it:
class Something:
def out(self):
print("it works")
s = Something()
s.out()
You need to pass self
as the first argument to all instance methods.
You can loop over the properties of your object as follows:
for(var prop in ad) {
if (ad.hasOwnProperty(prop)) {
// handle prop as required
}
}
It is important to use the hasOwnProperty()
method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.
From the comments: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment
In C++11
for (auto i = path.begin(); i != path.end(); ++i)
std::cout << *i << ' ';
for(int i=0; i<path.size(); ++i)
std::cout << path[i] << ' ';
Or simply run this comment to add the server Certificate to your database:
echo $(echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpGilabPort 2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p') >> /etc/ssl/certs/ca-certificates.crt
Then do git clone again.
I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.
Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None)
)
There is no definite way to do that. JS may have the API, but the browser vendor may choose not to implement it or implement it in another way.
Also, as far as I remember, Opera even provides the user preferences to prevent JS from making such changes, like have the window move, change status bar content, and stuff like that.
I'm partial to AdeptSQL. It's clean and intuitive and it DOESN'T have the one feature that scares the hell out of me on a lot of similar programs. One giant button that it you push it will automatically synchronize EVERYTHING without so much as a by-your-leave. If you want to sync the changes you have to do it yourself and I like that.
I clone libgdx
demo, can't import project. it also reminds like this.
Env:
Eclipse(Android-ADT)
window 7
so I create local.properties file at the project root, like following
sdk.dir = D:/adt-bundle-windows-x86/sdk
I hope this can help others!
I was getting error while ExecuteNonQuery() resolved with adding AutoIncrement to Primary Key of my table. In your case if you don't want to add primary key then we must need to assign value to primary key.
ALTER TABLE `t1`
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;
Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...
Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);
You can also use TextAttribute.
Map<TextAttribute, Object> attributes = new HashMap<>();
attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);
g.setFont(myFont);
The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.
One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.
To collapse all code blocks Ctrl + Shift+ /
To expand all code blocks Ctrl + Shift+ *
pydev:
To collapse all code blocks : Ctrl + 0
To collapse all code blocks : Ctrl + 9
Is there a way to collapse all code blocks in Eclipse?
by @partizanos and @bummi
In my test the better performance is ENUM > MAP > SWITCH > IF/ELSE IF in Windows7.
import java.util.HashMap;
import java.util.Map;
public class StringsInSwitch {
public static void main(String[] args) {
String doSomething = null;
//METHOD_1 : SWITCH
long start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
switch (input) {
case "Hello World0":
doSomething = "Hello World0";
break;
case "Hello World1":
doSomething = "Hello World0";
break;
case "Hello World2":
doSomething = "Hello World0";
break;
case "Hello World3":
doSomething = "Hello World0";
break;
case "Hello World4":
doSomething = "Hello World0";
break;
case "Hello World5":
doSomething = "Hello World0";
break;
case "Hello World6":
doSomething = "Hello World0";
break;
case "Hello World7":
doSomething = "Hello World0";
break;
case "Hello World8":
doSomething = "Hello World0";
break;
case "Hello World9":
doSomething = "Hello World0";
break;
case "Hello World10":
doSomething = "Hello World0";
break;
case "Hello World11":
doSomething = "Hello World0";
break;
case "Hello World12":
doSomething = "Hello World0";
break;
case "Hello World13":
doSomething = "Hello World0";
break;
case "Hello World14":
doSomething = "Hello World0";
break;
case "Hello World15":
doSomething = "Hello World0";
break;
}
}
System.out.println("Time taken for String in Switch :"+ (System.currentTimeMillis() - start));
//METHOD_2 : IF/ELSE IF
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
if(input.equals("Hello World0")){
doSomething = "Hello World0";
} else if(input.equals("Hello World1")){
doSomething = "Hello World0";
} else if(input.equals("Hello World2")){
doSomething = "Hello World0";
} else if(input.equals("Hello World3")){
doSomething = "Hello World0";
} else if(input.equals("Hello World4")){
doSomething = "Hello World0";
} else if(input.equals("Hello World5")){
doSomething = "Hello World0";
} else if(input.equals("Hello World6")){
doSomething = "Hello World0";
} else if(input.equals("Hello World7")){
doSomething = "Hello World0";
} else if(input.equals("Hello World8")){
doSomething = "Hello World0";
} else if(input.equals("Hello World9")){
doSomething = "Hello World0";
} else if(input.equals("Hello World10")){
doSomething = "Hello World0";
} else if(input.equals("Hello World11")){
doSomething = "Hello World0";
} else if(input.equals("Hello World12")){
doSomething = "Hello World0";
} else if(input.equals("Hello World13")){
doSomething = "Hello World0";
} else if(input.equals("Hello World14")){
doSomething = "Hello World0";
} else if(input.equals("Hello World15")){
doSomething = "Hello World0";
}
}
System.out.println("Time taken for String in if/else if :"+ (System.currentTimeMillis() - start));
//METHOD_3 : MAP
//Create and build Map
Map<String, ExecutableClass> map = new HashMap<String, ExecutableClass>();
for (int i = 0; i <= 15; i++) {
String input = "Hello World" + (i & 0xF);
map.put(input, new ExecutableClass(){
public void execute(String doSomething){
doSomething = "Hello World0";
}
});
}
//Start test map
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "Hello World" + (i & 0xF);
map.get(input).execute(doSomething);
}
System.out.println("Time taken for String in Map :"+ (System.currentTimeMillis() - start));
//METHOD_4 : ENUM (This doesn't use muliple string with space.)
start = System.currentTimeMillis();
for (int i = 0; i < 99999999; i++) {
String input = "HW" + (i & 0xF);
HelloWorld.valueOf(input).execute(doSomething);
}
System.out.println("Time taken for String in ENUM :"+ (System.currentTimeMillis() - start));
}
}
interface ExecutableClass
{
public void execute(String doSomething);
}
// Enum version
enum HelloWorld {
HW0("Hello World0"), HW1("Hello World1"), HW2("Hello World2"), HW3(
"Hello World3"), HW4("Hello World4"), HW5("Hello World5"), HW6(
"Hello World6"), HW7("Hello World7"), HW8("Hello World8"), HW9(
"Hello World9"), HW10("Hello World10"), HW11("Hello World11"), HW12(
"Hello World12"), HW13("Hello World13"), HW14("Hello World4"), HW15(
"Hello World15");
private String name = null;
private HelloWorld(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void execute(String doSomething){
doSomething = "Hello World0";
}
public static HelloWorld fromString(String input) {
for (HelloWorld hw : HelloWorld.values()) {
if (input.equals(hw.getName())) {
return hw;
}
}
return null;
}
}
//Enum version for betterment on coding format compare to interface ExecutableClass
enum HelloWorld1 {
HW0("Hello World0") {
public void execute(String doSomething){
doSomething = "Hello World0";
}
},
HW1("Hello World1"){
public void execute(String doSomething){
doSomething = "Hello World0";
}
};
private String name = null;
private HelloWorld1(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void execute(String doSomething){
// super call, nothing here
}
}
/*
* http://stackoverflow.com/questions/338206/why-cant-i-switch-on-a-string
* https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10
* http://forums.xkcd.com/viewtopic.php?f=11&t=33524
*/
createuser postgres --interactive
or make a superuser postgresl just with
createuser postgres -s
The included utility that installs to /usr/local/bin/charm
did not work for me on OS X, so I hacked together this utility instead. It actually works!
#!/usr/bin/env bash
if [ -z "$1" ]
then
echo ""
echo "Usage: charm <filename>"
exit
fi
FILENAME=$1
function myreadlink() {
(
cd $(dirname $1) # or cd ${1%/*}
echo $PWD/$(basename $1) # or echo $PWD/${1##*/}
)
}
FULL_FILE=`myreadlink $FILENAME`;
/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm $FULL_FILE
I'm very late to this and I have no idea if this is a good idea, but you can include the $attrs
injectable in the controller function allowing the controller to be initialized using "arguments" provided on an element, e.g.
app.controller('modelController', function($scope, $attrs) {
if (!$attrs.model) throw new Error("No model for modelController");
// Initialize $scope using the value of the model attribute, e.g.,
$scope.url = "http://example.com/fetch?model="+$attrs.model;
})
<div ng-controller="modelController" model="foobar">
<a href="{{url}}">Click here</a>
</div>
Again, no idea if this is a good idea, but it seems to work and is another alternative.
Here what you are looking for !!!
select LAST_INSERT_ID()
This is the best alternative of SCOPE_IDENTITY()
function being used in SQL Server
.
You also need to keep in mind that this will only work if Last_INSERT_ID()
is fired following by your Insert
query.
That is the query returns the id inserted in the schema. You can not get specific table's last inserted id.
For more details please go through the link The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?
The documentation for focusout says (emphasis mine):
The
focusout
event is sent to an element when it, or any element inside of it, loses focus. This is distinct from theblur
event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
The same distinction exists between the focusin and focus events.
I think amazon definition is straight and simple to understand.
"Continuous delivery is a software development methodology where the release process is automated. Every software change is automatically built, tested, and deployed to production. Before the final push to production, a person, an automated test, or a business rule decides when the final push should occur. Although every successful software change can be immediately released to production with continuous delivery, not all changes need to be released right away.
Continuous integration is a software development practice where members of a team use a version control system and integrate their work frequently to the same location, such as a master branch. Each change is built and verified by tests and other verifications in order to detect any integration errors as quickly as possible. Continuous integration is focused on automatically building and testing code, as compared to continuous delivery, which automates the entire software release process up to production."
Please check out http://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html
Simplest of all, open MYSQL >> SELECT DB whose name you want to change >> Click on "operation" then put New name in "Rename database to:" field then click "Go" button
Simple!
[Update]
I've just realized why you weren't receiving results back... you have a missing line in your Deserialize
method. You were forgetting to assign the results to your obj
:
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
Also, just for reference, here is the Serialize
method :
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
Edit
If you want to use Json.NET here are the equivalent Serialize/Deserialize methods to the code above..
Deserialize:
JsonConvert.DeserializeObject<T>(string json);
Serialize:
JsonConvert.SerializeObject(object o);
This are already part of Json.NET so you can just call them on the JsonConvert class.
Link: Serializing and Deserializing JSON with Json.NET
Now, the reason you're getting a StackOverflow is because of your Properties
.
Take for example this one :
[DataMember]
public string unescapedUrl
{
get { return unescapedUrl; } // <= this line is causing a Stack Overflow
set { this.unescapedUrl = value; }
}
Notice that in the getter
, you are returning the actual property (ie the property's getter is calling itself over and over again), and thus you are creating an infinite recursion.
Properties (in 2.0) should be defined like such :
string _unescapedUrl; // <= private field
[DataMember]
public string unescapedUrl
{
get { return _unescapedUrl; }
set { _unescapedUrl = value; }
}
You have a private field and then you return the value of that field in the getter, and set the value of that field in the setter.
Btw, if you're using the 3.5 Framework, you can just do this and avoid the backing fields, and let the compiler take care of that :
public string unescapedUrl { get; set;}
On a generic note, you can use a combination of ng-if
and ng-style
incorporate conditional changes with change in background image.
<span ng-if="selectedItem==item.id"
ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_active.png)','background-size':'52px 57px','padding-top':'70px','background-repeat':'no-repeat','background-position': 'center'}"></span>
<span ng-if="selectedItem!=item.id"
ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_deactivated.png)','background-size':'52px 57px','padding-top':'70px','background-repeat':'no-repeat','background-position': 'center'}"></span>
I agree with @Jakub Arnold's answer. The problem should be somewhere else. I could not figure out the problem but found a work around.
Wrap your concerned element with a parent element and cause its html to create a new element with the id you are concerned with. See below
<div id="theParent">
<div id="vinanghinguyen_images_bbocde"></div>
</div>
'onSelect' : function(event,ID,fileObj) {
$("#theParent").html("<div id='vinanghinguyen_images_bbocde'></div>");
$("#vinanghinguyen_result").hide();
$(".uploadifyQueue").height(315);
}
A number of years ago (in the IE only days) I was using the <col align="right">
tag, but I just tested it and and it seems to be an IE only feature:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
</head>
<body>
<table width="100%" border="1">
<col align="left" />
<col align="left" />
<col align="right" />
<tr>
<th>ISBN</th>
<th>Title</th>
<th>Price</th>
</tr>
<tr>
<td>3476896</td>
<td>My first HTML</td>
<td>$53</td>
</tr>
</table>
</body>
</html>
The snippet is taken from www.w3schools.com. Of course, it should not be used (unless for some reason you really target the IE rendering engine only), but I thought it would be interesting to mention it.
Edit:
Overall, I don't understand the reasoning behing abandoning this tag. It would appear to be very useful (at least for manual HTML publishing).
You want to rely on commas because if you rely on the multiple assignment construct, you'll shoot yourself in the foot at one point or another.
An example would be:
>>> var a = b = c = [];
>>> c.push(1)
[1]
>>> a
[1]
They all refer to the same object in memory, they are not "unique" since anytime you make a reference to an object ( array, object literal, function ) it's passed by reference and not value. So if you change just one of those variables, and wanted them to act individually you will not get what you want because they are not individual objects.
There is also a downside in multiple assignment, in that the secondary variables become globals, and you don't want to leak into the global namespace.
(function() { var a = global = 5 })();
alert(window.global) // 5
It's best to just use commas and preferably with lots of whitespace so it's readable:
var a = 5
, b = 2
, c = 3
, d = {}
, e = [];
@GianCarlo: You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;
// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);
A solution with numpy for quick access to all indexes:
string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')
Try this it works for me:
/^(http[s]?:\/\/){0,1}(w{3,3}\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/;
You can use this method to pick image from gallery. Only images will be displayed.
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
}
and override onActivityResult as
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 1) {
final Bundle extras = data.getExtras();
if (extras != null) {
//Get image
Bitmap newProfilePic = extras.getParcelable("data");
}
}
}
You want the CASE statement
WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber)=1 THEN @OrderNumber ELSE '%' + @OrderNumber END
In C#, unlike java we do not have to use any method. TextBox property Text
is used to get or set its text.
Get
string username = txtusername.Text;
string password = txtpassword.Text;
Set
txtusername.Text = "my_username";
txtpassword.Text = "12345";
Try this:
@echo off
set yyyy=%date:~6,4%
set mm=%date:~3,2%
set dd=%date:~0,2%
set /p temp= "Enter the name of text file: "
FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%temp%.txt
This code ask you to set the name of the file after "day_" where you can input the date. If you want to name your file like the actual date you can do this:
FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%yyyy%-%mm%-%dd%.txt
It appears that although colons (:) and periods (.) are valid in the HTML spec, they are invalid as id selectors in CSS so probably best avoided if you intend to use them for that purpose.
None of the answers here were quite what I wanted. Here's what I came up with:
# Recursively revert any locally-changed files
svn revert -R .
# Delete any other files in the sandbox (including ignored files),
# being careful to handle files with spaces in the name
svn status --no-ignore | grep '^\?' | \
perl -ne 'print "$1\n" if $_ =~ /^\S+\s+(.*)$/' | \
tr '\n' '\0' | xargs -0 rm -rf
Tested on Linux; may work in Cygwin, but relies on (I believe) a GNU-specific extension which allows xargs to split based on '\0'
instead of whitespace.
The advantage to the above command is that it does not require any network activity to reset the sandbox. You get exactly what you had before, and you lose all your changes. (disclaimer before someone blames me for this code destroying their work) ;-)
I use this script on a continuous integration system where I want to make sure a clean build is performed after running some tests.
Edit: I'm not sure this works with all versions of Subversion. It's not clear if the svn status
command is always formatted consistently. Use at your own risk, as with any command that uses such a blanket rm
command.
I would like to share my implementation as well. It does require some JavaScript code though.
<form action="./index.php" id="homePage" method="post" style="display: none;">
<input type="hidden" name="action" value="homePage" />
</form>
<a href="javascript:;" onclick="javascript:
document.getElementById('homePage').submit()">Home</a>
The nice thing about this is that, contrary to GET requests, it doesn't show the parameters in the URL, which is safer.
Problem statement – Getting java.awt.HeadlessException while trying to initialize java.awt.Component from the application as the tomcat environment does not have any head(terminal).
Issue – The linux virtual environment was setup without a virtual display terminal. Tried to install virtual display – Xvfb, but Xvfb has been taken off by the redhat community.
Solution – Installed ‘xorg-x11-drv-vmware.x86_64’ using yum install xorg-x11-drv-vmware.x86_64 and executed startx. Finally set the display to :0.0 using export DISPLAY=:0.0 and then executed xhost +
You can make an empty commit with git commit --allow-empty
, but that will not allow you to commit an empty folder structure as git does not know or care about folders as objects themselves -- just the files they contain.
I would not advise a regex answer from Bart, I find parsing solution better in this particular case (as Fabian proposed). I've tried regex solution and own parsing implementation I have found that:
My solution and test below.
String tested = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\",";
long start = System.nanoTime();
String[] tokens = tested.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
long timeWithSplitting = System.nanoTime() - start;
start = System.nanoTime();
List<String> tokensList = new ArrayList<String>();
boolean inQuotes = false;
StringBuilder b = new StringBuilder();
for (char c : tested.toCharArray()) {
switch (c) {
case ',':
if (inQuotes) {
b.append(c);
} else {
tokensList.add(b.toString());
b = new StringBuilder();
}
break;
case '\"':
inQuotes = !inQuotes;
default:
b.append(c);
break;
}
}
tokensList.add(b.toString());
long timeWithParsing = System.nanoTime() - start;
System.out.println(Arrays.toString(tokens));
System.out.println(tokensList.toString());
System.out.printf("Time with splitting:\t%10d\n",timeWithSplitting);
System.out.printf("Time with parsing:\t%10d\n",timeWithParsing);
Of course you are free to change switch to else-ifs in this snippet if you feel uncomfortable with its ugliness. Note then lack of break after switch with separator. StringBuilder was chosen instead to StringBuffer by design to increase speed, where thread safety is irrelevant.
You can't upload nested structures like that through the online tool. I'd recommend using something like Bucket Explorer for more complicated uploads.
cleaner way to do this is using foreach
foreach(var item in li.Where(w => w.name =="di"))
{
item.age=10;
}
In modern JS, this is simplified, and you can write something like this:
const firstWords = str =>_x000D_
str .split (/\|/) .map (s => s .split (/\s+/) [0])_x000D_
_x000D_
const str = "Hello m|sss sss|mmm ss"_x000D_
_x000D_
console .log (firstWords (str))
_x000D_
We first split the string on the |
and then split each string in the resulting array on any white space, keeping only the first one.
The static keyword can be used in several different ways in Java and in almost all cases it is a modifier which means the thing it is modifying is usable without an enclosing object instance.
Java is an object oriented language and by default most code that you write requires an instance of the object to be used.
public class SomeObject {
public int someField;
public void someMethod() { };
public Class SomeInnerClass { };
}
In order to use someField, someMethod, or SomeInnerClass I have to first create an instance of SomeObject.
public class SomeOtherObject {
public void doSomeStuff() {
SomeObject anInstance = new SomeObject();
anInstance.someField = 7;
anInstance.someMethod();
//Non-static inner classes are usually not created outside of the
//class instance so you don't normally see this syntax
SomeInnerClass blah = anInstance.new SomeInnerClass();
}
}
If I declare those things static then they do not require an enclosing instance.
public class SomeObjectWithStaticStuff {
public static int someField;
public static void someMethod() { };
public static Class SomeInnerClass { };
}
public class SomeOtherObject {
public void doSomeStuff() {
SomeObjectWithStaticStuff.someField = 7;
SomeObjectWithStaticStuff.someMethod();
SomeObjectWithStaticStuff.SomeInnerClass blah = new SomeObjectWithStaticStuff.SomeInnerClass();
//Or you can also do this if your imports are correct
SomeInnerClass blah2 = new SomeInnerClass();
}
}
Declaring something static has several implications.
First, there can only ever one value of a static field throughout your entire application.
public class SomeOtherObject {
public void doSomeStuff() {
//Two objects, two different values
SomeObject instanceOne = new SomeObject();
SomeObject instanceTwo = new SomeObject();
instanceOne.someField = 7;
instanceTwo.someField = 10;
//Static object, only ever one value
SomeObjectWithStaticStuff.someField = 7;
SomeObjectWithStaticStuff.someField = 10; //Redefines the above set
}
}
The second issue is that static methods and inner classes cannot access fields in the enclosing object (since there isn't one).
public class SomeObjectWithStaticStuff {
private int nonStaticField;
private void nonStaticMethod() { };
public static void someStaticMethod() {
nonStaticField = 7; //Not allowed
this.nonStaticField = 7; //Not allowed, can never use *this* in static
nonStaticMethod(); //Not allowed
super.someSuperMethod(); //Not allowed, can never use *super* in static
}
public static class SomeStaticInnerClass {
public void doStuff() {
someStaticField = 7; //Not allowed
nonStaticMethod(); //Not allowed
someStaticMethod(); //This is ok
}
}
}
The static keyword can also be applied to inner interfaces, annotations, and enums.
public class SomeObject {
public static interface SomeInterface { };
public static @interface SomeAnnotation { };
public static enum SomeEnum { };
}
In all of these cases the keyword is redundant and has no effect. Interfaces, annotations, and enums are static by default because they never have a relationship to an inner class.
This just describes what they keyword does. It does not describe whether the use of the keyword is a bad idea or not. That can be covered in more detail in other questions such as Is using a lot of static methods a bad thing?
There are also a few less common uses of the keyword static. There are static imports which allow you to use static types (including interfaces, annotations, and enums not redundantly marked static) unqualified.
//SomeStaticThing.java
public class SomeStaticThing {
public static int StaticCounterOne = 0;
}
//SomeOtherStaticThing.java
public class SomeOtherStaticThing {
public static int StaticCounterTwo = 0;
}
//SomeOtherClass.java
import static some.package.SomeStaticThing.*;
import some.package.SomeOtherStaticThing.*;
public class SomeOtherClass {
public void doStuff() {
StaticCounterOne++; //Ok
StaticCounterTwo++; //Not ok
SomeOtherStaticThing.StaticCounterTwo++; //Ok
}
}
Lastly, there are static initializers which are blocks of code that are run when the class is first loaded (which is usually just before a class is instantiated for the first time in an application) and (like static methods) cannot access non-static fields or methods.
public class SomeObject {
private static int x;
static {
x = 7;
}
}
from PIL import Image
image = Image.open('File.jpg')
image.show()
What about uname -a
?
Just use the following methods to create a 2-D vector.
int rows, columns;
// . . .
vector < vector < int > > Matrix(rows, vector< int >(columns,0));
OR
vector < vector < int > > Matrix;
Matrix.assign(rows, vector < int >(columns, 0));
//Do your stuff here...
This will create a Matrix of size rows * columns and initializes it with zeros because we are passing a zero(0) as a second argument in the constructor i.e vector < int > (columns, 0).
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]
## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]
<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>
This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.
This may also add to understanding of the difference between those two operators:
df <- data.frame(
a = rnorm(10),
b <- rnorm(10)
)
For the first element R has assigned values and proper name, while the name of the second element looks a bit strange.
str(df)
# 'data.frame': 10 obs. of 2 variables:
# $ a : num 0.6393 1.125 -1.2514 0.0729 -1.3292 ...
# $ b....rnorm.10.: num 0.2485 0.0391 -1.6532 -0.3366 1.1951 ...
R version 3.3.2 (2016-10-31); macOS Sierra 10.12.1
If you get this error with Firebase Cloud Functions, this is due to the limitations of the free tier (outbound networking only allowed to Google services).
Upgrade to the Flame or Blaze plans for it to work.
delete: delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:
splice: actually removes the element, reindexes the array, and changes its length.
Delete element from last
arrName.pop();
Delete element from first
arrName.shift();
Delete from middle
arrName.splice(starting index,number of element you wnt to delete);
Ex: arrName.splice(1,1);
Delete one element from last
arrName.splice(-1);
Delete by using array index number
delete arrName[1];
You can make a function to do it:
drop function if exists getIdade;
delimiter |
create function getIdade( data_nascimento datetime )
returns int
begin
declare idade int;
declare ano_atual int;
declare mes_atual int;
declare dia_atual int;
declare ano int;
declare mes int;
declare dia int;
set ano_atual = year(curdate());
set mes_atual = month( curdate());
set dia_atual = day( curdate());
set ano = year( data_nascimento );
set mes = month( data_nascimento );
set dia = day( data_nascimento );
set idade = ano_atual - ano;
if( mes > mes_atual ) then
set idade = idade - 1;
end if;
if( mes = mes_atual and dia > dia_atual ) then
set idade = idade - 1;
end if;
return idade;
end|
delimiter ;
Now, you can get the age from a date:
select getIdade('1983-09-16');
If you date is in format Y-m-d H:i:s, you can do this:
select getIdade(substring_index('1983-09-16 23:43:01', ' ', 1));
You can reuse this function anywhere ;)
The font used in menus, dialogs and tool windows can be changed in Settings > Appearance & Behavior > Use custom font.
First things first, you need to loop to < a.length
rather than a.length - 1
. As this is strictly less than you need to include the upper bound.
So, to check all pairs of elements you can do:
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
But this will compare, for example a[2]
to a[3]
and then a[3]
to a[2]
. Given that you are checking !=
this seems wasteful.
A better approach would be to compare each element i
to the rest of the array:
for (int i = 0; i < a.length; i++) {
for (int k = i + 1; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
So if you have the indices [1...5] the comparison would go
1 -> 2
1 -> 3
1 -> 4
1 -> 5
2 -> 3
2 -> 4
2 -> 5
3 -> 4
3 -> 5
4 -> 5
So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.
mappedby
speaks for itself, it tells hibernate not to map this field. it's already mapped by this field [name="field"].
field is in the other entity (name of the variable in the class not the table in the database)
..
If you don't do that, hibernate will map this two relation as it's not the same relation
so we need to tell hibernate to do the mapping in one side only and co-ordinate between them.
Create a new package And then move the classes of default package in new package and use those classes
My code is amazing it just took 00:00:00.0007143 less than milisecond with 34 file in folder
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
bool IsEmptyDirectory = (Directory.GetFiles("d:\\pdf").Length == 0);
sw.Stop();
Console.WriteLine(sw.Elapsed);
Another option:
UPDATE `table` SET the_col = current_timestamp
Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now()
.
You can't use a foreach statement for that. The foreach is using internally an iterator:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
(From ArrayList javadoc)
In the foreach statement you don't have access to the iterator's add method and in any case that's still not the type of add that you want because it does not append at the end. You'll need to traverse the list manually:
int listSize = list.size();
for(int i = 0; i < listSize; ++i)
list.add("whatever");
Note that this is only efficient for Lists that allow random access. You can check for this feature by checking whether the list implements the RandomAccess marker interface. An ArrayList has random access. A linked list does not.
<html>
<body>
<p>Enter some text in the fields below, and then press the "Submit form" button to submit the form.</p>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit form">
</form>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
</script>
</body>
</html>
You have to add the reference of the namespace : System.Windows.Forms to your project, because for some reason it is not already added, so you can add New Reference from Visual Studio menu.
Right click on "Reference" ? "Add New Reference" ? "System.Windows.Forms"
In our case it always works the first time but rerunning the function more than 3-4 times, it fails.
Simple workaround: Store it's value in LocalStorage.
Before:
navigator.geolocation.getCurrentPosition((position) => {
let val = results[0].address_components[2].long_name;
doSthWithVal(val);
}, (error) => { });
After:
if(localStorage.getItem('getCurrentPosition') !== null) {
doSthWithVal(localStorage.getItem('getCurrentPosition'));
}
else {
navigator.geolocation.getCurrentPosition((position) => {
let val = results[0].address_components[2].long_name;
localStorage.setItem('getCurrentPosition',val);
doSthWithVal(val);
}, (error) => { });
}
html, body {
min-height: 100%;
}
Will do the trick.
By default, even html and body are only as big as the content they hold, but never more than the width/height of the windows. This can often lead to quite strange results.
You might also want to read http://css-tricks.com/perfect-full-page-background-image/
There are some great ways do achieve a very good and scalable full background image.
I have got that error after update to JDK 1.8. But the JAVA_HOME
variable was hard coded furthermore to JDK 1.7. Thew modification solved the problem:
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_241
(since I ran into this today)
Be careful when using ES2015 fat arrow syntax:
This will fail :
it('accesses the network', done => {
this.timeout(500); // will not work
// *this* binding refers to parent function scope in fat arrow functions!
// i.e. the *this* object of the describe function
done();
});
EDIT: Why it fails:
As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.
Bottom line: Don't use arrow functions for functions that need an increased timeout.
Google recommend that you don't use any of them, source.
There is no need to use entity references like
&mdash
,&rdquo
, or☺
, assuming the same encoding (UTF-8) is used for files and editors as well as among teams.
Is there a reason you can't simply use "
?
A good practice is write text inside String.xml
example:
String.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="yellow">Yellow</string>
</resources>
and inside layout:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/yellow" />
For me the app.php was here /vendor/laravel/lumen-framework/config/app.php
but I also could change it from the .env
file where it can be set to any of the values listed here (PHP original documentation here).
this.Text = "Your Text Here"
Place this under Initialize Component and it should change on form load.
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.
The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin
and xmax
are in the range [0,1].
On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin
and xmax
are the in the range of data limit of x axis.
Let's take a concrete example,
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')
plt.show()
It will produce the following plot:
The value for xmin
and xmax
are the same for the axhline
and hlines
method. But the length of produced line is different.
I just benchmarked a file transfer over both FTP and HTTP :
The result:
fdm
): 1 minuteSo, basically under a "real life" situation:
1) HTTP is faster than FTP when downloading one big file.
2) HTTP can use parallel chunk download which makes it 6x times faster than FTP depending on the network conditions.
I built a general method for that with following features:
Here the code:
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
@GET
@Path("16x16")
@Produces("image/png")
public Response get16x16PNG(@HeaderParam("If-Modified-Since") String modified) {
File repositoryFile = new File("c:/temp/myfile.png");
return returnFile(repositoryFile, modified);
}
/**
*
* Sends the file if modified and "not modified" if not modified
* future work may put each file with a unique id in a separate folder in tomcat
* * use that static URL for each file
* * if file is modified, URL of file changes
* * -> client always fetches correct file
*
* method header for calling method public Response getXY(@HeaderParam("If-Modified-Since") String modified) {
*
* @param file to send
* @param modified - HeaderField "If-Modified-Since" - may be "null"
* @return Response to be sent to the client
*/
public static Response returnFile(File file, String modified) {
if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}
// do we really need to send the file or can send "not modified"?
if (modified != null) {
Date modifiedDate = null;
// we have to switch the locale to ENGLISH as parseDate parses in the default locale
Locale old = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
try {
modifiedDate = DateUtils.parseDate(modified, org.apache.http.impl.cookie.DateUtils.DEFAULT_PATTERNS);
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
Locale.setDefault(old);
if (modifiedDate != null) {
// modifiedDate does not carry milliseconds, but fileDate does
// therefore we have to do a range-based comparison
// 1000 milliseconds = 1 second
if (file.lastModified()-modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
return Response.status(Status.NOT_MODIFIED).build();
}
}
}
// we really need to send the file
try {
Date fileDate = new Date(file.lastModified());
return Response.ok(new FileInputStream(file)).lastModified(fileDate).build();
} catch (FileNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
}
/*** copied from org.apache.http.impl.cookie.DateUtils, Apache 2.0 License ***/
/**
* Date format pattern used to parse HTTP date headers in RFC 1123 format.
*/
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in RFC 1036 format.
*/
public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in ANSI C
* <code>asctime()</code> format.
*/
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
public static final String[] DEFAULT_PATTERNS = new String[] {
PATTERN_RFC1036,
PATTERN_RFC1123,
PATTERN_ASCTIME
};
Note that the Locale switching does not seem to be thread-safe. I think, it's better to switch the locale globally. I am not sure about the side-effects though...
The answer is in this line of the output of readelf -a
in the original question
[Requesting program interpreter: /lib/ld-linux.so.2]
I was missing the /lib/ld-linux.so.2 file, which is needed to run 32-bit apps. The Ubuntu package that has this file is libc6-i386.
You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value="">
to the beginning.
You can use relative path to mount the volume to container:
docker run -v `pwd`/certs:/container/path/to/certs ...
Note the back tick on the pwd
which give you the present working directory. It assumes you have the certs
folder in current directory that the docker run
is executed. Kinda great for local development and keep the certs folder visible to your project.
If the child is always going to be a specific tag then you could do it like this
function test(el)
{
var children = el.getElementsByTagName('div');// any tag could be used here..
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child') // any attribute could be used here
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}
}
You can get its shape
with:
print((df.count(), len(df.columns)))
jQuery('.validatedForm').validate({
rules : {
password : {
minlength : 5
},
password_confirm : {
minlength : 5,
equalTo : '[name="password"]'
}
}
In general, you will not use id="password"
like this.
So, you can use [name="password"]
instead of "#password"
Another suitable way:
$ mysql -u you -p
<enter password>
>>> DROP DATABASE foo;
Kinda late, but you need to access the original event, not the jQuery massaged one. Also, since these are multi-touch events, other changes need to be made:
$('#box').live('touchstart', function(e) {
var xPos = e.originalEvent.touches[0].pageX;
});
If you want other fingers, you can find them in other indices of the touches list.
UPDATE FOR NEWER JQUERY:
$(document).on('touchstart', '#box', function(e) {
var xPos = e.originalEvent.touches[0].pageX;
});
sed would be a better choice (stream editor)
tail -n0 -f <file> | sed -n '/search string/p'
and then if you wanted the tail command to exit once you found a particular string:
tail --pid=$(($BASHPID+1)) -n0 -f <file> | sed -n '/search string/{p; q}'
Obviously a bashism: $BASHPID will be the process id of the tail command. The sed command is next after tail in the pipe, so the sed process id will be $BASHPID+1.
Use CONCAT_WS instead:
CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.
SELECT CONCAT_WS('-',`affiliate_name`,`model`,`ip`,`os_type`,`os_version`) AS device_name FROM devices
Here is the end-to-end workflow showing the various commands and their associated inputs and outputs. That should clarify the relationship between an image and a container.
+------------+ docker build +--------------+ docker run -dt +-----------+ docker exec -it +------+
| Dockerfile | --------------> | Image | ---------------> | Container | -----------------> | Bash |
+------------+ +--------------+ +-----------+ +------+
^
| docker pull
|
+--------------+
| Registry |
+--------------+
To list the images you could run, execute:
docker image ls
To list the containers you could execute commands on:
docker ps
Simple answer by program:
public class StringCamelCase {
public static void main(String[] args) {
String[] articles = {"the ", "a ", "one ", "some ", "any "};
String[] result = new String[articles.length];
int i = 0;
for (String string : articles) {
result[i++] = toUpercaseForstChar(string);
}
for (String string : result) {
System.out.println(string);
}
}
public static String toUpercaseForstChar(String string){
return new String(new char[]{string.charAt(0)}).toUpperCase() + string.substring(1,string.length());
}
}
I think in this case you want something like this:
$(window).resize(resize=function resize(){ some code...}
Now u can call resize() within some other nested functions:
$(window).scroll(function(){ resize();}
I would suggest to watch model value and update it upon chage: http://plnkr.co/edit/Mb0uRyIIv1eK8nTg3Qng?p=preview
The only interesting issue is with spaces: In AngularJS 1.0.3 ng-model on input automatically trims string, so it does not detect that model was changed if you add spaces at the end or at start (so spaces are not automatically removed by my code). But in 1.1.1 there is 'ng-trim' directive that allows to disable this functionality (commit). So I've decided to use 1.1.1 to achieve exact functionality you described in your question.
I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:
div {
width: 100%;
height: 0;
padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
position: relative;
}
div iframe {
width: 100%;
height: 100%;
position: absolute;
display: block;
top: 0;
left: 0;
}
Just did it now for a client, and it seems to be working: http://themilkrunsa.co.za/
You can also write this in mysql -
SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date < DATE_ADD(NOW(), INTERVAL -1 MONTH);
FIXED
The most efficient one is Ctrl + ..
It helps to automate insertions of using
directives. It works if the focus is on a new identifier, e.g. class name.
1) How do I check if it's even or odd? I tried "if number/2 == int" in the hope that it might do something, and the internet tells me to do "if number%2==0", but that doesn't work.
def isEven(number):
return number % 2 == 0
for iterating through JSON you can use this:
json_object = json.loads(json_file)
for element in json_object:
for value in json_object['Name_OF_YOUR_KEY/ELEMENT']:
print(json_object['Name_OF_YOUR_KEY/ELEMENT']['INDEX_OF_VALUE']['VALUE'])
This is how I do it:
with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
stripped = (line.strip() for line in infile)
lines = (line.split(",") for line in stripped if line)
writer = csv.writer(outfile)
writer.writerows(lines)
Hope it helps!
using include 'page1.php'
in second page is one option but it can generate warnings and errors of undefined variables.
Three methods by which you can use variables of one php file in another php file:
use session to pass variable from one page to another
method:
first you have to start the session in both the files using php command
sesssion_start();
then in first file consider you have one variable
$x='var1';now assign value of $x to a session variable using this:
$_SESSION['var']=$x;
now getting value in any another php file:
$y=$_SESSION['var'];//$y is any declared variable
using get method and getting variables on clicking a link
method
<a href="page2.php?variable1=value1&variable2=value2">clickme</a>
getting values in page2.php file by $_GET function:$x=$_GET['variable1'];//value1 be stored in $x
$y=$_GET['variable2'];//vale2 be stored in $y
if you want to pass variable value using button then u can use it by following method:
$x='value1'
<input type="submit" name='btn1' value='.$x.'/>
in second php$var=$_POST['btn1'];
this JavaScript give you the browser name and the version,
var browser = '';
var browserVersion = 0;
if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
browser = 'Opera';
} else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
browser = 'MSIE';
} else if (/Navigator[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
browser = 'Netscape';
} else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
browser = 'Chrome';
} else if (/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
browser = 'Safari';
/Version[\/\s](\d+\.\d+)/.test(navigator.userAgent);
browserVersion = new Number(RegExp.$1);
} else if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
browser = 'Firefox';
}
if(browserVersion === 0){
browserVersion = parseFloat(new Number(RegExp.$1));
}
alert(browser + "*" + browserVersion);
No one mentioned how to make proper checks when using Substring()
, so I wanted to contribute about that.
If you don't want to use Linq
and go with Substring()
, you have to make sure that your string is bigger than the second parameter (length) of Substring()
function.
Let's say you need the first 5 characters. You should get them with proper check, like this:
string title = "love" // 15 characters
var firstFiveChars = title.Length <= 5 ? title : title.Substring(0, 5);
// firstFiveChars: "love" (4 characters)
Without this check, Substring()
function would throw an exception because it'd iterate through letters that aren't there.
I think you get the idea...
For a similar problem, (my problem was to show UTF-8 characters from MySQL on a command prompt),
I solved it like this:
I changed the font of command prompt to Lucida Console. (This step must be irrelevant for your situation. It has to do only with what you see on the screen and not with what is really the character).
I changed the codepage to Windows-1253. You do this on the command prompt by "chcp 1253". It worked for my case where I wanted to see UTF-8.
Put the loops in a subroutine and call return
Seems like a lazy way to always know that your WHERE clause is already defined and allow you to keep adding conditions without having to check if it is the first one.