body{ background:#3F5261; text-align:center; font-family:Arial; } _x000D_
_x000D_
h1 {_x000D_
font-size:3em;_x000D_
background: -webkit-linear-gradient(top, gold, white);_x000D_
background: linear-gradient(top, gold, white);_x000D_
-webkit-background-clip: text;_x000D_
-webkit-text-fill-color: transparent;_x000D_
_x000D_
position:relative;_x000D_
margin:0;_x000D_
z-index:1;_x000D_
_x000D_
}_x000D_
_x000D_
div{ display:inline-block; position:relative; }_x000D_
div::before{ _x000D_
content:attr(data-title); _x000D_
font-size:3em;_x000D_
font-weight:bold;_x000D_
position:absolute;_x000D_
top:0; left:0;_x000D_
z-index:-1;_x000D_
color:black;_x000D_
z-index:1;_x000D_
filter:blur(5px);_x000D_
}
_x000D_
<div data-title='SOME TITLE'>_x000D_
<h1>SOME TITLE</h1>_x000D_
</div>
_x000D_
Thank you everyone, for all your precise replys.
Using the svg in a shadow dom, I add the 3 linear gradients I need within the svg, inside a . I place the css fill rule on the web component and the inheritance od fill does the job.
<svg viewbox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<path
d="m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z"></path>
</svg>
<svg height="0" width="0">
<defs>
<linearGradient id="lgrad-p" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#4169e1"></stop><stop offset="99%" stop-color="#c44764"></stop></linearGradient>
<linearGradient id="lgrad-s" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#ef3c3a"></stop><stop offset="99%" stop-color="#6d5eb7"></stop></linearGradient>
<linearGradient id="lgrad-g" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#585f74"></stop><stop offset="99%" stop-color="#b6bbc8"></stop></linearGradient>
</defs>
</svg>
<div></div>
<style>
:first-child {
height:150px;
width:150px;
fill:url(#lgrad-p) blue;
}
div{
position:relative;
width:150px;
height:150px;
fill:url(#lgrad-s) red;
}
</style>
<script>
const shadow = document.querySelector('div').attachShadow({mode: 'open'});
shadow.innerHTML="<svg viewbox=\"0 0 512 512\">\
<path d=\"m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z\"></path>\
</svg>\
<svg height=\"0\">\
<defs>\
<linearGradient id=\"lgrad-s\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#ef3c3a\"></stop><stop offset=\"99%\" stop-color=\"#6d5eb7\"></stop></linearGradient>\
<linearGradient id=\"lgrad-g\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#585f74\"></stop><stop offset=\"99%\" stop-color=\"#b6bbc8\"></stop></linearGradient>\
</defs>\
</svg>\
";
</script>
_x000D_
The first one is normal SVG, the second one is inside a shadow dom.
One option is to use str
, and then to_datetime
(or similar):
In [11]: str(dt64)
Out[11]: '2012-05-01T01:00:00.000000+0100'
In [12]: pd.to_datetime(str(dt64))
Out[12]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))
Note: it is not equal to dt
because it's become "offset-aware":
In [13]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
Out[13]: datetime.datetime(2012, 5, 1, 1, 0)
This seems inelegant.
.
Update: this can deal with the "nasty example":
In [21]: dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100')
In [22]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
Out[22]: datetime.datetime(2002, 6, 28, 1, 0)
I usually pass the RowIndex via CommandArgument and use it to retrieve the DataKey value I want.
On the Button:
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
On the Server Event
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];
You can't format the Date
itself. You can only get the formatted result in String
. Use SimpleDateFormat
as mentioned by others.
Moreover, most of the getter methods in Date
are deprecated.
I just spent about 1 hour to figure out possible solution for the same error.
So what I did under MS WIndows 7 is following
Uninstall all Java packages of all versions.
Download last packages Java SE or JRE for your 32 or 64 Windows and install it.
First install JRE and second is Java SE.
Open text editor and paste this code.
public class Hello {
public static void main(String[] args) {
System.out.println("test");
}
}
Save it like Hello.java
Go to Console and compile it like
javac Hello.java
java Hello
Should be no error.
Here's my version that uses FontAwesome for checkbox ticker, I think FontAwesome is used by almost everybody so it's safe to assume you have it too. Not tested in IE/Edge and I don't think anyone cares.
input[type=checkbox] {_x000D_
-moz-appearance:none;_x000D_
-webkit-appearance:none;_x000D_
-o-appearance:none;_x000D_
outline: none;_x000D_
content: none; _x000D_
}_x000D_
_x000D_
input[type=checkbox]:before {_x000D_
font-family: "FontAwesome";_x000D_
content: "\f00c";_x000D_
font-size: 15px;_x000D_
color: transparent !important;_x000D_
background: #fef2e0;_x000D_
display: block;_x000D_
width: 15px;_x000D_
height: 15px;_x000D_
border: 1px solid black;_x000D_
margin-right: 7px;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked:before {_x000D_
_x000D_
color: black !important;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>_x000D_
_x000D_
<input type="checkbox">
_x000D_
Ignore is exactly what the name implies.
It doesn't "throw away" something you don't need instead, it ignores the amount of characters you specify when you call it, up to the char you specify as a breakpoint.
It works with both input and output buffers.
Essentially, for std::cin
statements you use ignore before you do a getline
call, because when a user inputs something with std::cin
, they hit enter and a '\n'
char gets into the cin
buffer. Then if you use getline
, it gets the newline char instead of the string you want. So you do a std::cin.ignore(1000,'\n')
and that should clear the buffer up to the string that you want. (The 1000 is put there to skip over a specific amount of chars before the specified break point, in this case, the \n newline character.)
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
You can also use the "timestamp" data type where it just needs "dd-mm-yyyy"
Like:
insert into emp values('12-12-2012');
considering there is just one column in the table... You can adjust the insertion values according to your table.
For the times when some fields have a ";" and some do not you can also add a semi-colon to the field and use the same method described.
SET MyText = LEFT(MyText+';', CHARINDEX(';',MyText+';')-1)
From Wikipedia (emphasis and link added):
When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.
So, the real percent encoding uses %20
while form data in URLs is in a modified form that uses +
. So you're most likely to only see +
in URLs in the query string after an ?
.
XSD is to validate the document, and contains metadata about the XML whereas WSDL is to describe the webservice location and operations.
You can track by $index
if your data source has duplicate identifiers
e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
You can't iterate this collection while using 'id' as identifier (duplicate id:1).
WON'T WORK:
<element ng-repeat="item.id as item.name for item in dataSource">
// something with item ...
</element>
but you can, if using track by $index
:
<element ng-repeat="item in dataSource track by $index">
// something with item ...
</element>
Post this method in your base activity and use it other activities like a charm
public void openKeyboard() {
InputMethodManager imm =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
Seems there are 2 ways:
DESCRIBE `tablename`
or
SHOW COLUMNS FROM `tablename`
More on DESCRIBE
here: http://dev.mysql.com/doc/refman/5.0/en/describe.html
API stands for Application Programming Interface. It is a way for your application to interact with other applications via an endpoint. Conversely, you can build out an API for your application that is available for other developers to utilize/connect to via HTTP methods, which are RESTful. Representational State Transfer (REST):
Hopefully someone else is saved by reading this.
We encountered an issue with webkit based browsers doing:
window.open("webpage.htm", "_self");
The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:
location.href = "webpage.html";
all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.
IMPORTANT: Just to make something clear. I assume that the commands are inside a .py
script and the script is called using e.g. python script.py
from the console.
A simple way that works for me is:
Example of script.py
file:
plt.imshow(*something*)
plt.colorbar()
plt.xlabel("true ")
plt.ylabel("predicted ")
plt.title(" the matrix")
# Add block = False
plt.show(block = False)
################################
# OTHER CALCULATIONS AND CODE HERE ! ! !
################################
# the next command is the last line of my script
plt.show()
Using pieces from all of these answers and the comments, I put this together for anyone who sees this question in the future. It covers all of the situations listed in the other answers
# If using ISE
if ($psISE) {
$ScriptPath = Split-Path -Parent $psISE.CurrentFile.FullPath
# If Using PowerShell 3 or greater
} elseif($PSVersionTable.PSVersion.Major -gt 3) {
$ScriptPath = $PSScriptRoot
# If using PowerShell 2 or lower
} else {
$ScriptPath = split-path -parent $MyInvocation.MyCommand.Path
}
Change hidden field value with checkbox toggle like below...
HTML:
<input type='hidden' value='Unchecked' id="deleteAll" name='anyName'>
<input type="checkbox" onclick="toggle(this)"/> Delete All
Script:
function toggle(obj) {`var $input = $(obj);
if ($input.prop('checked')) {
$('#deleteAll').attr( 'value','Checked');
} else {
$('#deleteAll').attr( 'value','Unchecked');
}
}
Use new Date()
to generate a new Date
object containing the current date and time.
var today = new Date();_x000D_
var dd = String(today.getDate()).padStart(2, '0');_x000D_
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!_x000D_
var yyyy = today.getFullYear();_x000D_
_x000D_
today = mm + '/' + dd + '/' + yyyy;_x000D_
document.write(today);
_x000D_
This will give you today's date in the format of mm/dd/yyyy.
Simply change today = mm +'/'+ dd +'/'+ yyyy;
to whatever format you wish.
The favicon doesn't have to be 16x16 or 32x32. You can create a favicon that is 80x80 or 100x100, just make sure that both values are the same size, and obviously don't make it too large or too small, choose a reasonable size.
The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.
svn log -r {2009-09-17}:HEAD
where 2009-09-17
is the date you went on holiday. To see the changed files as well as the summary, add a -v
option:
svn log -r {2009-09-17}:HEAD -v
I haven't used WebSVN but there will be a log viewer somewhere that does the equivalent of these commands under the hood.
You're looking for the DataSource property
:
List<SomeType> someList = ...;
myListBox.DataSource = someList;
You should also set the DisplayMember
property to the name of a property in the object that you want the listbox to display. If you don't, it will call ToString()
.
LEFT ('BTA200', 3) will work for the examples you have given, as in :
SELECT LEFT(MyField, 3)
FROM MyTable
To extract the numeric part, you can use this code
SELECT RIGHT(MyField, LEN(MyField) - 3)
FROM MyTable
WHERE MyField LIKE 'BTA%'
--Only have this test if your data does not always start with BTA.
@Nishit, JSONObject does not natively understand how to parse through a StringBuilder; instead you appear to be using the JSONObject(java.lang.Object bean) constructor to create the JSONObject, however passing it a StringBuilder.
See this link for more information on that particular constructor.
http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29
When a constructor calls for a java.lang.Object class, more than likely it's really telling you that you're expected to create your own class (since all Classes ultimately extend java.lang.Object) and that it will interface with that class in a specific way, albeit normally it will call for an interface instead (hence the name) OR it can accept any class and interface with it "abstractly" such as calling .toString() on it. Bottom line, you typically can't just pass it any class and expect it to work.
At any rate, this particular constructor is explained as such:
Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".
So, what this means is that it's expecting you to create your own class that implements get or is methods (i.e.
public String getName() {...}
or
public boolean isValid() {...}
So, to solve your problem, if you really want that higher level of control and want to do some manipulation (e.g. modify some values, etc.) but still use StringBuilder to dynamically generate the code, you can create a class that extends the StringBuilder class so that you can use the append feature, but implement get/is methods to allow JSONObject to pull the data out of it, however this is likely not what you want/need and depending on the JSON, you might spend a lot of time and energy creating the private fields and get/is methods (or use an IDE to do it for you) or it might be all for naught if you don't necessarily know the breakdown of the JSON string.
So, you can very simply call toString()
on the StringBuilder which will provide a String representation of the StringBuilder instance and passing that to the JSONObject constructor, such as below:
...
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString.toString());
...
Set IIS to forward your mail to the remote server. The specifics vary greatly depending on the version of IIS. For IIS 7.5:
Here is the code that worked for me!
Assuming that you have a valid session going,
//Get the current users id
$uid = $facebook->getUser();
//create the url
$profile_pic = "http://graph.facebook.com/".$uid."/picture";
//echo the image out
echo "<img src=\"" . $profile_pic . "\" />";
Thanx goes to Raine, you da man!
Have a look at these pages. They contain many open source CSV parsers. JSaPar is one of them.
i solved by putting this one line in application tag...
tools:node="replace"
In my case below code
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="10dp" android:bottom="-10dp"
>
<shape android:shape="rectangle">
<solid android:color="@color/maincolor" />
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomLeftRadius="0dp"
android:bottomRightRadius="0dp"
/>
</shape>
</item>
</layer-list>
Check out this plunkr.
When you're binding to variables, you need to use the brackets. Also, you use the hashtag when you want to get references to elements in your html, not for declaring variables inside of templates like that.
<md-button-toggle *ngFor="let indicador of indicadores; let first = first;" [value]="indicador.id" [checked]="first">
...
Edit: Thanks to Christopher Moore: Angular exposes the following local variables:
index
first
last
even
odd
You can just add the word JOIN or add a ; after each line(as @pictchubbate said). Better this way because of readability and also you should not meddle DELETE with INSERT; it is easy to go south.
The last question is a matter of debate, but as far as I know yes you should close after a set of queries. This applies mostly to old plain mysql/php and not PDO, mysqli. Things get more complicated(and heated in debates) in these cases.
Finally, I would suggest either using PDO or some other method.
Resemblence with c# string static method isNullOrWhiteSpace.
def isNullOrWhiteSpace(str):
"""Indicates whether the specified string is null or empty string.
Returns: True if the str parameter is null, an empty string ("") or contains
whitespace. Returns false otherwise."""
if (str is None) or (str == "") or (str.isspace()):
return True
return False
isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("") -> True
isNullOrWhiteSpace(" ") -> True
I have a convention of naming xibs with views in them the same as the view. Same as one would do for a view controller. Then, I don't have to write out class names in code. I load a UIView from a nib file with the same name.
Example for a class called MyView.
In your code, create a new MyView like this:
MyView *myView = [MyView nib_viewFromNibWithOwner:owner];
Here's the category for this:
@implementation UIView (nib)
+ (id) nib_viewFromNib {
return [self nib_viewFromNibWithOwner:nil];
}
+ (id) nib_viewFromNibWithOwner:(id)owner {
NSString *className = NSStringFromClass([self class]);
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:className owner:owner options:nil];
UIView *view = nil;
for(UIView *v in nib) {
if ([v isKindOfClass:[self class]]) {
view = v;
break;
}
}
assert(view != nil && "View for class not found in nib file");
[view nib_viewDidLoad];
return view;
}
// override this to do custom setup
-(void)nib_viewDidLoad {
}
I'd then wire up buttons with actions from the controller I am using, and set things on labels using the outlets in my custom view subclass.
Here's a solution using xml_grep (because xpath wasn't part of our distributable and I didn't want to add it to all production machines)...
If you are looking for a specific setting in an XML file, and if all elements at a given tree level are unique, and there are no attributes, then you can use this handy function:
# File to be parsed
xmlFile="xxxxxxx"
# use xml_grep to find settings in an XML file
# Input ($1): path to setting
function getXmlSetting() {
# Filter out the element name for parsing
local element=`echo $1 | sed 's/^.*\///'`
# Verify the element is not empty
local check=${element:?getXmlSetting invalid input: $1}
# Parse out the CDATA from the XML element
# 1) Find the element (xml_grep)
# 2) Remove newlines (tr -d \n)
# 3) Extract CDATA by looking for *element> CDATA <element*
# 4) Remove leading and trailing spaces
local getXmlSettingResult=`xml_grep --cond $1 $xmlFile 2>/dev/null | tr -d '\n' | sed -n -e "s/.*$element>[[:space:]]*\([^[:space:]].*[^[:space:]]\)[[:space:]]*<\/$element.*/\1/p"`
# Return the result
echo $getXmlSettingResult
}
#EXAMPLE
logPath=`getXmlSetting //config/logs/path`
check=${logPath:?"XML file missing //config/logs/path"}
This will work with this structure:
<config>
<logs>
<path>/path/to/logs</path>
<logs>
</config>
It will also work with this (but it won't keep the newlines):
<config>
<logs>
<path>
/path/to/logs
</path>
<logs>
</config>
If you have duplicate <config> or <logs> or <path>, then it will only return the last one. You can probably modify the function to return an array if it finds multiple matches.
FYI: This code works on RedHat 6.3 with GNU BASH 4.1.2, but I don't think I'm doing anything particular to that, so should work everywhere.
NOTE: For anybody new to scripting, make sure you use the right types of quotes, all three are used in this code (normal single quote '=literal, backward single quote `=execute, and double quote "=group).
If by saying without destroying it, you mean to a keep a reference to the children, you can do:
var oldChildren = [];
while(element.hasChildNodes()) {
oldChildren.push(element.removeChild(element.firstChild));
}
Regarding the original tagging (html css
) of your question:
You cannot remove content with CSS. You could only hide it. E.g. you can hide all children of a certain node with:
#someID > * {
display: none;
}
This doesn't work in IE6 though (but you could use #someID *
).
Yes, this is possible. You don't have to be the current process owning the socket to close it. Consider for a moment that the remote machine, the network card, the network cable, and your OS can all cause the socket to close.
Consider also that Fiddler and Desktop VPN software can insert themselves into the network stack and show you all your traffic or reroute all your traffic.
So all you really need is either for Windows to provide an API that allows this directly, or for someone to have written a program that operates somewhat like a VPN or Fiddler and gives you a way to close sockets that pass through it.
There is at least one program (CurrPorts) that does exactly this and I used it today for the purpose of closing specific sockets on a process that was started before CurrPorts was started. To do this you must run it as administrator, of course.
Note that it is probably not easily possible to cause a program to not listen on a port (well, it is possible but that capability is referred to as a firewall...), but I don't think that was being asked here. I believe the question is "how do I selectively close one active connection (socket) to the port my program is listening on?". The wording of the question is a bit off because a port number for the undesired inbound client connection is given and it was referred to as "port" but it's pretty clear that it was a reference to that one socket and not the listening port.
Set self.title = ""
before self.navigationController?.pushViewController(vc, animated: true)
.
You can create your specific function like the below, then use that everywhere you need.
var each = (arr, func) =>
Array.from(
(function* (){
var i = 0;
for(var item of arr)
yield func(item, i++);
})()
);
Enjoy..
The script package does exactly what you're looking for: https://atom.io/packages/script
The package's documentation also contains the key mappings, which you can easily customize.
First option (bad because of throw-catch, but MS will do work for you):
bool IsValidEmail(string email)
{
try {
var mail = new System.Net.Mail.MailAddress(email);
return true;
}
catch {
return false;
}
}
Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification
You can use boost::array to do that:
boost::array<char, 5> test = {'a', 'b', 'c', 'd', 'e'};
std::vector<boost::array<char, 5> > v;
v.push_back(test);
Edit:
Or you can use a vector of vectors as shown below:
char test[] = {'a', 'b', 'c', 'd', 'e'};
std::vector<std::vector<char> > v;
v.push_back(std::vector<char>(test, test + sizeof(test)/ sizeof(test[0])));
There is equally formatDate
const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
According to the API it takes as param either a date string, a Date object, or a timestamp.
Gotcha: Out of the box, only en-US
is supported.
If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:
import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");
Don't forget to add corresponding import:
import { formatDate } from "@angular/common";
use the itoa()
function included in stdlib.h
char buffer[7]; //the ASCII of the integer will be stored in this char array
itoa(-31596,buffer,10); //(integer, yourBuffer, base)
<option value="" defaultValue disabled> Something </option>
you can replace defaultValue
with selected
but that would give warning.
The arguments can never be null
. They just wont exist.
In other words, what you need to do is check the length of your arguments.
public static void main(String[] args)
{
// Check how many arguments were passed in
if(args.length == 0)
{
System.out.println("Proper Usage is: java program filename");
System.exit(0);
}
}
I would make two changes:
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
onclick
handler instead of onchange
- you're changing the "checked state" of the radio input, not the value
, so there's not a change event happening.this
as a parameter, that will make it easy to check which value is currently selected.ETA: Along with your handleClick()
function, you can track the original / old value of the radio in a page-scoped variable. That is:
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
var currentValue = 0;_x000D_
function handleClick(myRadio) {_x000D_
alert('Old value: ' + currentValue);_x000D_
alert('New value: ' + myRadio.value);_x000D_
currentValue = myRadio.value;_x000D_
}
_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
_x000D_
From SQLServer 2012 more elegant alter role:
use mydb
go
ALTER ROLE db_datareader
ADD MEMBER MYUSER
go
ALTER ROLE db_datawriter
ADD MEMBER MYUSER
go
Warning: if you need update Node from an old version (in my case v4.6.0
) it is better to re-install nodejs from scratch (download link: https://nodejs.org) otherwise npm will also update itself to a version that's not compatible with the new Node (see this discussion).
This is the error message that I got after updating Node (on Windows) with npm
$ npm install -g npm stable
[ . . .]
$ npm
C:\Users\me\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js:85
let notifier = require('update-notifier')({pkg})
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supporte
d outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
After new installation npm works again:
$ npm -v
6.5.0
$ node -v
v10.15.0
The inconvenience of typing 10 < x && x < 20
is minimal compared to the increase in language complexity if one would allow 10 < x < 20
, so the designers of the Java language decided against supporting it.
The serial port communication programs moserial
or gtkterm
provide an easy way to check connectivity and modify /dev/ttyUSB0
(or /dev/ttyUSB1
!) settings. Even though there maybe only a single USB to RS232 adapter, the n
designation /dev/ttyUSBn
can and does change periodically! Both moserial
and gtkterm
will show what port designation is relevant in their respective pull down menus when selecting an appropriate port
to use.
Check out help.ubuntu.com/community/Minicom for details on minicom
.
This will give you sequence of anonymous objects, containing date string and two properties with average price:
var query = from p in PriceLogList
group p by p.LogDateTime.ToString("MMM yyyy") into g
select new {
LogDate = g.Key,
AvgGoldPrice = (int)g.Average(x => x.GoldPrice),
AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
};
If you need to get list of PriceLog objects:
var query = from p in PriceLogList
group p by p.LogDateTime.ToString("MMM yyyy") into g
select new PriceLog {
LogDateTime = DateTime.Parse(g.Key),
GoldPrice = (int)g.Average(x => x.GoldPrice),
SilverPrice = (int)g.Average(x => x.SilverPrice)
};
To extract the year from current date
SELECT YEAR(CURRENT_DATE())
IBM Netezza
extract(year from now())
HIVE
SELECT YEAR(CURRENT_DATE())
if Your Android Studio Version Greater than 3.0
Looks like we can not directly use the apk after running on the device from the build -->output->apk folder.
After upgrading to android studio 3.0 you need to go to Build -> Build Apk(s) then copy the apk from build -> output -> apk -> debug
Add set number
to your .vimrc
file in your home directory.
If the .vimrc
file is not in your home directory create one with
vim .vimrc
and add the commands you want at open.
Here's a site that explains the vimrc and how to use it.
You can simply use ToArray()
extension method
Example:
Person p1 = new Person() { Name = "Person 1", Age = 27 };
Person p2 = new Person() { Name = "Person 2", Age = 31 };
List<Person> people = new List<Person> { p1, p2 };
var array = people.ToArray();
The elements are copied using
Array.Copy()
, which is an O(n) operation, where n is Count.
Have a better one based on @hypo 's answer
public class GrowLabel : Label {
private bool mGrowing;
public GrowLabel() {
this.AutoSize = false;
}
private void resizeLabel() {
if (mGrowing)
return;
try {
mGrowing = true;
int width = this.Parent == null ? this.Width : this.Parent.Width;
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height + Padding.Bottom + Padding.Top;
} finally {
mGrowing = false;
}
}
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
resizeLabel();
}
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
resizeLabel();
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
resizeLabel();
}
}
int width = this.Parent == null ? this.Width : this.Parent.Width;
this allows you to use auto-grow label when docked to a parent, e.g. a panel.
this.Height = sz.Height + Padding.Bottom + Padding.Top;
here we take care of padding for top and bottom.
conio.h
is a C
header file used in old MS-DOS compilers to create text user interfaces. Compilers that targeted non-DOS operating systems, such as Linux, Win32 and OS/2, provided different implementations of these functions.
The #include <curses.h>
will give you almost all the functionalities that was provided in conio.h
nucurses need to be installed at the first place
In deb based Distros use
sudo apt-get install libncurses5-dev libncursesw5-dev
And in rpm based distros use
sudo yum install ncurses-devel ncurses
For getch()
class of functions, you can try this
I would rather include the factory as dependencies on the controllers than inject them with their own line of code: http://jsfiddle.net/XqDxG/550/
myModule.factory('mySharedService', function($rootScope) {
return sharedService = {thing:"value"};
});
function ControllerZero($scope, mySharedService) {
$scope.thing = mySharedService.thing;
ControllerZero.$inject = ['$scope', 'mySharedService'];
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
You can use rows
and cols
:
cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;
or size()
:
cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;
jQuery.css()
returns sizes in pixels, even if the CSS itself specifies them in em, or as a percentage, or whatever. It appends the units ('px'), but you can nevertheless use parseInt()
to convert them to integers (or parseFloat()
, for where fractions of pixels make sense).
$(document).ready(function () {
var $h1 = $('h1');
console.log($h1);
$h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
$h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});
in School,
public void addTeacherName(classroom classroom, String teacherName) {
classroom.setTeacherName(teacherName);
}
BTW, use Pascal Case for class names. Also, I would suggest a Map<String, classroom>
to map a classroom name to a classroom.
Then, if you use my suggestion, this would work
public void addTeacherName(String className, String teacherName) {
classrooms.get(className).setTeacherName(teacherName);
}
string[0] = "";
"warning: assignment makes integer from pointer without a cast
Ok, let's dive into the expression ...
0
an int: represents the number of chars (assuming string
is (or decayed into) a char*) to advance from the beginning of the object string
string[0]
: the char
object located at the beginning of the object string
""
: string literal: an object of type char[1]
=
: assignment operator: tries to assign a value of type char[1]
to an object of type char
. char[1]
(decayed to char*
) and char
are not assignment compatible, but the compiler trusts you (the programmer) and goes ahead with the assignment anyway by casting the type char*
(what char[1]
decayed to) to an int
--- and you get the warning as a bonus. You have a really nice compiler :-)
This worked for me:
img.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
((ImageView)v).setImageAlpha(200);
break;
}
case MotionEvent.ACTION_MOVE:
{
// if inside bounds
if(event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0 && event.getY() < v.getHeight())
{
((ImageView)v).setImageAlpha(200);
}
else
{
((ImageView)v).setImageAlpha(255);
}
break;
}
case MotionEvent.ACTION_UP:
{
((ImageView)v).setImageAlpha(255);
}
}
return true;
}
});
@Edit: As Gunhan said there will be backward compatibility problem with setImageAlpha method. I used this method:
public static void setImageAlpha(ImageView img, int alpha)
{
if(Build.VERSION.SDK_INT > 15)
{
img.setImageAlpha(alpha);
}
else
{
img.setAlpha(alpha);
}
}
You can use this: if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)
Explanation:
if ( str[4] === 'r' )
Check if the 5th character is a 'r'
str.slice(0, 4)
Slice the string to get everything before the 'r'
+ str.slice(5)
Add the rest of the string.
Minified: s=s[4]=='r'?s.slice(0,4)+s.slice(5):s
[37 bytes!]
DEMO:
function remove5thR (s) {_x000D_
s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;_x000D_
console.log(s); // log output_x000D_
}_x000D_
_x000D_
remove5thR('crt/r2002_2') // > 'crt/2002_2'_x000D_
remove5thR('crt|r2002_2') // > 'crt|2002_2'_x000D_
remove5thR('rrrrr') // > 'rrrr'_x000D_
remove5thR('RRRRR') // > 'RRRRR' (no change)
_x000D_
You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json
with the dns key, as
{
"dns": ["your_dns_address", "8.8.8.8"]
}
In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.
Before proceeding, save daemon.json and restart the docker service.
sudo service docker restart
Once fixed, retry to run the build command.
For dynamic SQL use:
'IN(' ||array_to_string(some_array, ',')||')'
DO LANGUAGE PLPGSQL $$
DECLARE
some_array bigint[];
sql_statement text;
BEGIN
SELECT array[1, 2] INTO some_array;
RAISE NOTICE '%', some_array;
sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
RAISE NOTICE '%', sql_statement;
END;
$$;
Result:
NOTICE: {1,2}
NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)
int min = 65;
int max = 80;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Note that nextInt(int max)
returns an int
between 0 inclusive and max exclusive. Hence the +1
.
Here is the XSLT function which will work similar to the String.Replace() function of C#.
This template has the 3 Parameters as below
text :- your main string
replace :- the string which you want to replace
by :- the string which will reply by new string
Below are the Template
<xsl:template name="string-replace-all">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)" />
<xsl:value-of select="$by" />
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Below sample shows how to call it
<xsl:variable name="myVariable ">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="'This is a {old} text'" />
<xsl:with-param name="replace" select="'{old}'" />
<xsl:with-param name="by" select="'New'" />
</xsl:call-template>
</xsl:variable>
You can also refer the below URL for the details.
From Bootstrap's docs about the remote
option;
This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.
If a remote URL is provided, content will be loaded one time via jQuery's
load
method and injected into the.modal-content
div. If you're using the data-api, you may alternatively use thehref
attribute to specify the remote source. An example of this is shown below:<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>
That's the .modal-content
div, not .modal-body
. If you want to put content inside .modal-body
then you need to do that with custom javascript.
So I would call jQuery.load
programmatically, meaning you can keep the functionality of the dismiss and/or other buttons as required.
To do this you could use a data tag with the URL from the button that opens the modal, and use the show.bs.modal
event to load content into the .modal-body
div.
HTML Link/Button
<a href="#" data-toggle="modal" data-load-url="remote.html" data-target="#myModal">Click me</a>
jQuery
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = $(e.relatedTarget).data('load-url');
$(this).find('.modal-body').load(loadurl);
});
Got sar? Likely yes if youre using RHEL/CentOS.
No need for priv, dorky binaries, hacky scripts, libpcap, etc. Win.
$ sar -n DEV 1 3
Linux 2.6.18-194.el5 (localhost.localdomain) 10/27/2010
02:40:56 PM IFACE rxpck/s txpck/s rxbyt/s txbyt/s rxcmp/s txcmp/s rxmcst/s
02:40:57 PM lo 0.00 0.00 0.00 0.00 0.00 0.00 0.00
02:40:57 PM eth0 10700.00 1705.05 15860765.66 124250.51 0.00 0.00 0.00
02:40:57 PM eth1 0.00 0.00 0.00 0.00 0.00 0.00 0.00
02:40:57 PM IFACE rxpck/s txpck/s rxbyt/s txbyt/s rxcmp/s txcmp/s rxmcst/s
02:40:58 PM lo 0.00 0.00 0.00 0.00 0.00 0.00 0.00
02:40:58 PM eth0 8051.00 1438.00 11849206.00 105356.00 0.00 0.00 0.00
02:40:58 PM eth1 0.00 0.00 0.00 0.00 0.00 0.00 0.00
02:40:58 PM IFACE rxpck/s txpck/s rxbyt/s txbyt/s rxcmp/s txcmp/s rxmcst/s
02:40:59 PM lo 0.00 0.00 0.00 0.00 0.00 0.00 0.00
02:40:59 PM eth0 6093.00 1135.00 8970988.00 82942.00 0.00 0.00 0.00
02:40:59 PM eth1 0.00 0.00 0.00 0.00 0.00 0.00 0.00
Average: IFACE rxpck/s txpck/s rxbyt/s txbyt/s rxcmp/s txcmp/s rxmcst/s
Average: lo 0.00 0.00 0.00 0.00 0.00 0.00 0.00
Average: eth0 8273.24 1425.08 12214833.44 104115.72 0.00 0.00 0.00
Average: eth1 0.00 0.00 0.00 0.00 0.00 0.00 0.00
First go to the pip documentation if not install before: http://pip.readthedocs.org/en/stable/installing/
and follow the install pip which is first download get-pip.py from https://bootstrap.pypa.io/get-pip.py
Then run the following (which may require administrator access): python get-pip.py
In your Gemfile, add the following:
gem 'example', :git => 'git://github.com/example.git'
You can also add ref, branch and tag options,
For example if you want to download from a particular branch:
gem 'example', :git => "git://github.com/example.git", :branch => "my-branch"
Then run:
bundle install
$('input:radio[checked=false]');
this will also work
input:radio:not(:checked)
or
:radio:not(:checked)
For the record:
"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".
This will only work for windows which are opened by using window.open(); method. Try this
var tmp=window.open(params);
tmp.close();
You can also use conditional (ternary) operator inside conditional operator in case you have 2 different dependencies.
{
(launch_success)
?
<span className="bg-green-100">
Success
</span>
:
(upcoming)
?
<span className="bg-teal-100">
Upcoming
</span>
:
<span className="bg-red-100">
Failed
</span>
}
...\Program Files\Microsoft SQL Server\MSSQL 1.0\MSSQL\Backup
if you are using c++11, here is a simple wrapper (see this gist):
#include <iostream>
#include <chrono>
class Timer
{
public:
Timer() : beg_(clock_::now()) {}
void reset() { beg_ = clock_::now(); }
double elapsed() const {
return std::chrono::duration_cast<second_>
(clock_::now() - beg_).count(); }
private:
typedef std::chrono::high_resolution_clock clock_;
typedef std::chrono::duration<double, std::ratio<1> > second_;
std::chrono::time_point<clock_> beg_;
};
Or for c++03 on *nix:
#include <iostream>
#include <ctime>
class Timer
{
public:
Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }
double elapsed() {
clock_gettime(CLOCK_REALTIME, &end_);
return end_.tv_sec - beg_.tv_sec +
(end_.tv_nsec - beg_.tv_nsec) / 1000000000.;
}
void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }
private:
timespec beg_, end_;
};
Example of usage:
int main()
{
Timer tmr;
double t = tmr.elapsed();
std::cout << t << std::endl;
tmr.reset();
t = tmr.elapsed();
std::cout << t << std::endl;
return 0;
}
A better way in long run is to integrate Gradle in your project environment. Its a build tool for Java, and now being used a lot in the android development space.
You will need to make a .gradle file and list your library dependencies. Then, all you would need to do is import the project in IntelliJ using Gradle.
Cheers
One pretty important practical difference occurs when subclassing. If you don't mind, I'll hijack @unutbu's example:
class A:
def foo(self, x):
print("executing foo(%s, %s)" % (self, x))
@classmethod
def class_foo(cls, x):
print("executing class_foo(%s, %s)" % (cls, x))
@staticmethod
def static_foo(x):
print("executing static_foo(%s)" % x)
class B(A):
pass
In class_foo
, the method knows which class it is called on:
A.class_foo(1)
# => executing class_foo(<class '__main__.A'>, 1)
B.class_foo(1)
# => executing class_foo(<class '__main__.B'>, 1)
In static_foo
, there is no way to determine whether it is called on A
or B
:
A.static_foo(1)
# => executing static_foo(1)
B.static_foo(1)
# => executing static_foo(1)
Note that this doesn't mean you can't use other methods in a staticmethod
, you just have to reference the class directly, which means subclasses' staticmethods will still reference the parent class:
class A:
@classmethod
def class_qux(cls, x):
print(f"executing class_qux({cls}, {x})")
@classmethod
def class_bar(cls, x):
cls.class_qux(x)
@staticmethod
def static_bar(x):
A.class_qux(x)
class B(A):
pass
A.class_bar(1)
# => executing class_qux(<class '__main__.A'>, 1)
B.class_bar(1)
# => executing class_qux(<class '__main__.B'>, 1)
A.static_bar(1)
# => executing class_qux(<class '__main__.A'>, 1)
B.static_bar(1)
# => executing class_qux(<class '__main__.A'>, 1)
Since many people arrive here debugging their slow website I would like to inform you about my case which none of the google explanations helped to resolve. My huge stalled times (sometimes 1min) were caused by Apache running on Windows having too few worker threads to handle the connections, therefore they were being queued.
This may apply to you if you apache log has following note:
Server ran out of threads to serve requests. Consider raising the ThreadsPerChild setting
This issue is resolved in Apache httpd.conf. Uncomment : Include conf/extra/httpd-mpm.conf
And edit httpd-mpm.conf
<IfModule mpm_winnt_module>
ThreadLimit 2000
ThreadsPerChild 2000
MaxConnectionsPerChild 0
</IfModule>
Note that you may not need 2000 threads, or may need more. 2000 was OK for my case.
I got a similar error, which was resolved by installing the corresponding MySQL drivers from:
http://www.connectionstrings.com/mysql-connector-odbc-5-2/info-and-download/
and by performing the following steps:
Reference:
http://www.codeproject.com/Tips/305249/ERROR-IM-Microsoft-ODBC-Driver-Manager-Data-sou
Use export VAR=Value
Then type printenv
in terminal to validate it is set correctly.
The contexts used for HTML Canvases have a built-in method for checking the size of a font. This method returns a TextMetrics
object, which has a width property that contains the width of the text.
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.c === undefined){
getWidthOfText.c=document.createElement('canvas');
getWidthOfText.ctx=getWidthOfText.c.getContext('2d');
}
var fontspec = fontsize + ' ' + fontname;
if(getWidthOfText.ctx.font !== fontspec)
getWidthOfText.ctx.font = fontspec;
return getWidthOfText.ctx.measureText(txt).width;
}
Or, as some of the other users have suggested, you can wrap it in a span
element:
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.e === undefined){
getWidthOfText.e = document.createElement('span');
getWidthOfText.e.style.display = "none";
document.body.appendChild(getWidthOfText.e);
}
if(getWidthOfText.e.style.fontSize !== fontsize)
getWidthOfText.e.style.fontSize = fontsize;
if(getWidthOfText.e.style.fontFamily !== fontname)
getWidthOfText.e.style.fontFamily = fontname;
getWidthOfText.e.innerText = txt;
return getWidthOfText.e.offsetWidth;
}
EDIT 2020: added font name+size caching at Igor Okorokov's suggestion.
Pure CSS solution, using calc
.modal-body {
max-height: calc(100vh - 200px);
overflow-y: auto;
}
200px may be adjusted in accordance to height of header & footer
May also want to use "documentElement":
var elem = document.createElement("div");
elem.style = "width:100px;height:100px;position:relative;background:#FF0000;";
document.documentElement.appendChild(elem);
Here is an easy way with String output (I created a method to do this):
public static String (String input){
String output = "";
try {
/* From ISO-8859-1 to UTF-8 */
output = new String(input.getBytes("ISO-8859-1"), "UTF-8");
/* From UTF-8 to ISO-8859-1 */
output = new String(input.getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return output;
}
// Example
input = "Música";
output = "Música";
I fixed this by changing the ownership of /usr/local
and ~/Users/user-name
like so:
sudo chown -R my_name /usr/local
This allowed me to do everything without sudo
The following command first registers the function in the context, then calls it:
. ./myScript.sh && function_name
De-structuring Assignment in ES6 would help here.For Ex:
let [arg1, arg2] = new Promise((resolve, reject) => {
resolve([argument1, argument2]);
});
You need form validation and modern browsers offer this from scratch.
So you do not need to take care that the user can not select the field. Because when he is doing it, the browser validation will tell him, that this is a wrong selection.
The browser built in validation function checkValidity().
Bootstrap has there a nice example as well.
HTML
<form class="needs-validation">
<select required>
<option value="">Please select an option</option>
<option value="1">Foo</option>
<option value="2">Bar</option>
</select>
<form>
Javascript
form = document.getElementByClassName('needs-validation');
if(form.checkValidity() === true) {
//form validation succeeded
} else {
//form validation failed
}
You can try:
SELECT *
FROM public."my_table"
Don't forget double quotes near my_table.
we can create multiply strings using * in python but not in java you can use for loop in your case:
String sample="123";
for(int i=0;i<3;i++)
{
sample=+"0";
}
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
Another solution is to update ViewPager
height according to the current page height in its PagerAdapter
. Assuming that your are creating your ViewPager
pages this way:
@Override
public Object instantiateItem(ViewGroup container, int position) {
PageInfo item = mPages.get(position);
item.mImageView = new CustomImageView(container.getContext());
item.mImageView.setImageDrawable(item.mDrawable);
container.addView(item.mImageView, 0);
return item;
}
Where mPages
is internal list of PageInfo
structures dynamically added to the PagerAdapter
and CustomImageView
is just regular ImageView
with overriden onMeasure()
method that sets its height according to specified width and keeps image aspect ratio.
You can force ViewPager
height in setPrimaryItem()
method:
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
PageInfo item = (PageInfo) object;
ViewPager pager = (ViewPager) container;
int width = item.mImageView.getMeasuredWidth();
int height = item.mImageView.getMeasuredHeight();
pager.setLayoutParams(new FrameLayout.LayoutParams(width, Math.max(height, 1)));
}
Note the Math.max(height, 1)
. That fixes annoying bug that ViewPager
does not update displayed page (shows it blank), when previous page has zero height (i. e. null drawable in the CustomImageView
), each odd swipe back and forth between two pages.
When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.
If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.
inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.
The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like
With ThisWorkbook.Worksheets("Template")
.Range(inputTemplateHeader).Value = NO_ENTRY
.Range(inputTemplateContent).Value = NO_ENTRY
End With
Adjust the workbook and worksheet references to fit your particular situation.
svn status
will tell you which files are not in SVN, as well as what's changed.
Look at the SVN properties for the ignore property.
For all things SVN, the Red Book is required reading.
You can do:
hash=$(genhash --use-ssl -s $IP -p 443 --url $URL)
or
hash=`genhash --use-ssl -s $IP -p 443 --url $URL`
If you want to result of the entire pipe to be assigned to the variable, you can use the entire pipeline in the above assignments.
I css I got no idea but I made that just by centering the form in html something like this:
in css:
form.principal {width:12em;}
form.principal label { float:left; display:block; clear:both; padding:3px;}
form.principal input { float:left; width:8em;}
form.principal button{clear:both; width:130px; height:50px; margin-top:8px;}
then in html:
<center><form class="principal" method="POST">
<fieldset>
<p><label for="username">User</label><input id="username" type="text" name="username" />
<p><label for="password">Password</label><input id="password" type="password" name="password" /></p>
<button>Log in</button>
</fieldset>
</form></center>
This will center the form, and the content will be in the left of the centered form.
I found the solution. Actually Base64 class is not available in Android. Link is given below for more information.
byte[] byteArray;
byteArray= json.getBytes(StandardCharsets.US_ASCII);
String encoded=Base64.encodeBytes(byteArray);
userLogin(encoded);
Here is the link for Base64 class: http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html
Decision tree:
Frameworks like Qt and SWT need native DLLs. So you have to ask yourself: Are all necessary platforms supported? Can you package the native DLLs with your app?
See here, how to do this for SWT.
If you have a choice here, you should prefer Qt over SWT. Qt has been developed by people who understand UI and the desktop while SWT has been developed out of necessity to make Eclipse faster. It's more a performance patch for Java 1.4 than a UI framework. Without JFace, you're missing many major UI components or very important features of UI components (like filtering on tables).
If SWT is missing a feature that you need, the framework is somewhat hostile to extending it. For example, you can't extend any class in it (the classes aren't final, they just throw exceptions when the package of this.getClass()
isn't org.eclipse.swt
and you can't add new classes in that package because it's signed).
If you need a native, pure Java solution, that leaves you with the rest. Let's start with AWT, Swing, SwingX - the Swing way.
AWT is outdated. Swing is outdated (maybe less so but not much work has been done on Swing for the past 10 years). You could argue that Swing was good to begin with but we all know that code rots. And that's especially true for UIs today.
That leaves you with SwingX. After a longer period of slow progress, development has picked up again. The major drawback with Swing is that it hangs on to some old ideas which very kind of bleeding edge 15 years ago but which feel "clumsy" today. For example, the table views do support filtering and sorting but you still have to configure this. You'll have to write a lot of boiler plate code just to get a decent UI that feels modern.
Another weak area is theming. As of today, there are a lot of themes around. See here for a top 10. But some are slow, some are buggy, some are incomplete. I hate it when I write a UI and users complain that something doesn't work for them because they selected an odd theme.
JGoodies is another layer on top of Swing, like SwingX. It tries to make Swing more pleasant to use. The web site looks great. Let's have a look at the tutorial ... hm ... still searching ... hang on. It seems that there is no documentation on the web site at all. Google to the rescue. Nope, no useful tutorials at all.
I'm not feeling confident with a UI framework that tries so hard to hide the documentation from potential new fans. That doesn't mean JGoodies is bad; I just couldn't find anything good to say about it but that it looks nice.
JavaFX. Great, stylish. Support is there but I feel it's more of a shiny toy than a serious UI framework. This feeling roots in the lack of complex UI components like tree tables. There is a webkit-based component to display HTML.
When it was introduced, my first thought was "five years too late." If your aim is a nice app for phones or web sites, good. If your aim is professional desktop application, make sure it delivers what you need.
Pivot. First time I heard about it. It's basically a new UI framework based on Java2D. So I gave it a try yesterday. No Swing, just tiny bit of AWT (new Font(...)
).
My first impression was a nice one. There is an extensive documentation that helps you getting started. Most of the examples come with live demos (Note: You must have Java enabled in your web browser; this is a security risk) in the web page, so you can see the code and the resulting application side by side.
In my experience, more effort goes into code than into documentation. By looking at the Pivot docs, a lot of effort must have went into the code. Note that there is currently a bug which prevents some of the examples to work (PIVOT-858) in your browser.
My second impression of Pivot is that it's easy to use. When I ran into a problem, I could usually solve it quickly by looking at an example. I'm missing a reference of all the styles which each component supports, though.
As with JavaFX, it's missing some higher level components like a tree table component (PIVOT-306). I didn't try lazy loading with the table view. My impression is that if the underlying model uses lazy loading, then that's enough.
Promising. If you can, give it a try.
You can add it manually in the .gitconfig file
[alias]
cm = "commit -m"
Or using the script:
git config --global alias.cm "commit -m"
Here is a screenshot of the .gitconfig
The display:table
family of CSS properties is mostly there so that HTML tables can be defined in terms of them. Because they're so intimately linked to a specific tag structure, they don't see much use beyond that.
If you were going to use these properties in your page, you would need a tag structure that closely mimicked that of tables, even though you weren't actually using the <table>
family of tags. A minimal version would be a single container element (display:table
), with direct children that can all be represented as rows (display:table-row
), which themselves have direct children that can all be represented as cells (display:table-cell
). There are other properties that let you mimic other tags in the table
family, but they require analogous structures in the HTML. Without this, it's going to be very hard (if not impossible) to make good use of these properties.
Try this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class WriteImage
{
public static void main( String[] args )
{
BufferedImage image = null;
try {
URL url = new URL("URL_IMAGE");
image = ImageIO.read(url);
ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
ImageIO.write(image, "gif",new File("C:\\out.gif"));
ImageIO.write(image, "png",new File("C:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
Try using the REPLACE function:
mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
-> 'WwWwWw.mysql.com'
Note that it is case sensitive.
I think you want something like
var count = context.MyTable.Count(t => t.MyContainer.ID == '1');
(edited to reflect comments)
Here's a solution which requires you to provide an object with the values. If you don't provide an object as parameter, it will default to using global variables. But better stick to using the parameter, it's much cleaner.
String.prototype.interpolate = function(props) {_x000D_
return this.replace(/\{(\w+)\}/g, function(match, expr) {_x000D_
return (props || window)[expr];_x000D_
});_x000D_
};_x000D_
_x000D_
// Test:_x000D_
_x000D_
// Using the parameter (advised approach)_x000D_
document.getElementById("resultA").innerText = "Eruption 1: {eruption1}".interpolate({ eruption1: 112 });_x000D_
_x000D_
// Using the global scope_x000D_
var eruption2 = 116;_x000D_
document.getElementById("resultB").innerText = "Eruption 2: {eruption2}".interpolate();
_x000D_
<div id="resultA"></div><div id="resultB"></div>
_x000D_
A DTU is a unit of measure for the performance of a service tier and is a summary of several database characteristics. Each service tier has a certain number of DTUs assigned to it as an easy way to compare the performance level of one tier versus another.
Database Throughput Unit (DTU): DTUs provide a way to describe the relative capacity of a performance level of Basic, Standard, and Premium databases. DTUs are based on a blended measure of CPU, memory, reads, and writes. As DTUs increase, the power offered by the performance level increases. For example, a performance level with 5 DTUs has five times more power than a performance level with 1 DTU. A maximum DTU quota applies to each server.
The DTU Quota applies to the server, not the individual databases and each server has a maximum of 1600 DTUs. The DTU% is the percentage of units your particular database is using and it seems that this number can go over 100% of the DTU rating of the service tier (I assume to the limit of the server). This percentage number is designed to help you choose the appropriate service tier.
From down toward the bottom of this announcement:
For example, if your DTU consumption shows a value of 80%, it indicates it is consuming DTU at the rate of 80% of the limit an S2 database would have. If you see values greater than 100% in this view it means that you need a performance tier larger than S2.
As an example, let’s say you see a percentage value of 300%. This tells you that you are using three times more resources than would be available in an S2. To determine a reasonable starting size, compare the DTUs available in an S2 (50 DTUs) with the next higher sizes (P1 = 100 DTUs, or 200% of S2, P2 = 200 DTUs or 400% of S2). Because you are at 300% of S2 you would want to start with a P2 and re-test.
I have seen many production problems caused by code not handling quotes ("), newline characters within quotes, and quotes within the quotes; e.g.: "he said ""this""" should be parsed into: he said "this"
Like it was mentioned earlier, many CSV parsing examples out there just read a line, and then break up the line by the separator character. This is rather incomplete and problematic.
For me and probably those who prefer build verses buy (or use somebody else's code and deal with their dependencies), I got down to classic text parsing programming and that worked for me:
/**
* Parse CSV data into an array of String arrays. It handles double quoted values.
* @param is input stream
* @param separator
* @param trimValues
* @param skipEmptyLines
* @return an array of String arrays
* @throws IOException
*/
public static String[][] parseCsvData(InputStream is, char separator, boolean trimValues, boolean skipEmptyLines)
throws IOException
{
ArrayList<String[]> data = new ArrayList<String[]>();
ArrayList<String> row = new ArrayList<String>();
StringBuffer value = new StringBuffer();
int ch = -1;
int prevCh = -1;
boolean inQuotedValue = false;
boolean quoteAtStart = false;
boolean rowIsEmpty = true;
boolean isEOF = false;
while (true)
{
prevCh = ch;
ch = (isEOF) ? -1 : is.read();
// Handle carriage return line feed
if (prevCh == '\r' && ch == '\n')
{
continue;
}
if (inQuotedValue)
{
if (ch == -1)
{
inQuotedValue = false;
isEOF = true;
}
else
{
value.append((char)ch);
if (ch == '"')
{
inQuotedValue = false;
}
}
}
else if (ch == separator || ch == '\r' || ch == '\n' || ch == -1)
{
// Add the value to the row
String s = value.toString();
if (quoteAtStart && s.endsWith("\""))
{
s = s.substring(1, s.length() - 1);
}
if (trimValues)
{
s = s.trim();
}
rowIsEmpty = (s.length() > 0) ? false : rowIsEmpty;
row.add(s);
value.setLength(0);
if (ch == '\r' || ch == '\n' || ch == -1)
{
// Add the row to the result
if (!skipEmptyLines || !rowIsEmpty)
{
data.add(row.toArray(new String[0]));
}
row.clear();
rowIsEmpty = true;
if (ch == -1)
{
break;
}
}
}
else if (prevCh == '"')
{
inQuotedValue = true;
}
else
{
if (ch == '"')
{
inQuotedValue = true;
quoteAtStart = (value.length() == 0) ? true : false;
}
value.append((char)ch);
}
}
return data.toArray(new String[0][]);
}
Unit Test:
String[][] data = parseCsvData(new ByteArrayInputStream("foo,\"\",,\"bar\",\"\"\"music\"\"\",\"carriage\r\nreturn\",\"new\nline\"\r\nnext,line".getBytes()), ',', true, true);
for (int rowIdx = 0; rowIdx < data.length; rowIdx++)
{
System.out.println(Arrays.asList(data[rowIdx]));
}
generates the output:
[foo, , , bar, "music", carriage
return, new
line]
[next, line]
Here is the detailed answer to the question:
Pass data into the HTTP header from the Angular side (Please note I am using Angular4.0+ in the application).
There is more than one way we can pass data into the headers. The syntax is different but all means the same.
// Option 1
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'ID': emp.UserID,
})
};
// Option 2
let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.append('Authorization', 'my-auth-token');
httpHeaders = httpHeaders.append('ID', '001');
httpHeaders.set('Content-Type', 'application/json');
let options = {headers:httpHeaders};
// Option 1
return this.http.post(this.url + 'testMethod', body,httpOptions)
// Option 2
return this.http.post(this.url + 'testMethod', body,options)
In the call you can find the field passed as a header as shown in the image below :
Still, if you are facing the issues like.. (You may need to change the backend/WebAPI side)
Response to preflight request doesn't pass access control check: No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://localhost:4200'' is therefore not allowed access
Response for preflight does not have HTTP ok status.
Find my detailed answer at https://stackoverflow.com/a/52620468/3454221
Rather than using JavaScript perhaps try something like
<a href="#">
<input type="submit" value="save" style="background: transparent none; border: 0px none; text-decoration: inherit; color: inherit; cursor: inherit" />
</a>
You might try searching the internet for ".htaccess Options not allowed here".
A suggestion I found (using google) is:
Check to make sure that your httpd.conf file has AllowOverride All.
A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):
# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html
# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
</IfModule>
# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.
Obviously some of your lines don't have valid float data, specifically some line have text id
which can't be converted to float.
When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError,e:
print "error",e,"on line",i
result=stats.ttest_ind(list1,list2)
print result[1]
Background of the problem
First thing to understand is following: it is NOT spring which renders the jsp files. It is JspServlet (org.apache.jasper.servlet.JspServlet) which does it. This servlet comes with Tomcat (jasper compiler) not with spring. This JspServlet is aware how to compile jsp page and how to return it as html text to the client. The JspServlet in tomcat by default only handles requests matching two patterns: *.jsp and *.jspx.
Now when spring renders the view with InternalResourceView
(or JstlView
), three things really takes place:
"public ModelAndView doSomething() { return new ModelAndView("home") }"
)RequestDispatcher
knows that each *.jsp request should be forwarded to JspServlet (because this is default tomcat's configuration)When you simply change the view name to home.html tomcat will not know how to handle the request. This is because there is no servlet handling *.html requests.
Solution
How to solve this. There are three most obvious solutions:
For complete code examples how to achieve this please reffer to my answer in another post: How to map requests to HTML file in Spring MVC?
A one liner:
perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile
For Windows:
To check that the file you're trying to open actually exists, you can change directories in terminal using cd
. To change to ~/Desktop/sass/css
: cd ~/Desktop/sass/css
. To see what files are in the directory: ls
.
If you want information about either of those commands, use the man
page: man cd
or man ls
, for example.
Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.
On Mac OS X, you can also use open
to open a finder window: open .
will open the current directory in finder. (open ~/Desktop/sass/css
will open the ~/Desktop/sass/css
).
the easiest way to do that in angular or angularjs without external modules or directives is using list and datalist HTML5. You just get a json and use ng-repeat for feeding the options in datalist. The json you can fetch it from ajax.
in this example:
then you can add filters and orderby in the ng-reapet
!! list and datalist id must have the same name !!
<input type="text" list="autocompleList" ng-model="ctrl.query" placeholder={{ctrl.msg}}>
<datalist id="autocompleList">
<option ng-repeat="Ids in ctrl.dataList value={{Ids}} >
</datalist>
UPDATE : is native HTML5 but be carreful with the type browser and version. check it out : https://caniuse.com/#search=datalist.
For horizontal alignment (No CSS)
Just insert an align attribute inside the table tag
<table align="center"></table
I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.
The path to the SDK is:
C:\Users\USERNAME\AppData\Local\Android\sdk
This can be used in Eclipse after you replace USERNAME with your Windows user name.
what's to stop other languages from being able to compile down to binary that runs every bit as fast as C?
Nothing. Modern languages like Java or .NET langs are oriented more on programmer productivity rather than performance. Hardware is cheap now days. Also compilation to intermediate representation gives a lot of bonuses such as security, portability etc. .NET CLR can take advantage of different hardware - for example you don't need to manually optimize/recompile program to use SSE instructions set.
step 1. sudo mysql -u root -p
step 2. USE mysql;
step 3. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'admin';
Here 'admin' is your new password, yo can change it.
step 4. exit
Thanks. You are done.
Just tell git to not assume it is changed never matter what:
git update-index --assume-unchanged src/file/to/ignore
yes, you can remove the files from the git repository. But if your team all use the same IDE or you are by yourself, you probably don't want to do that. For yourself, you want to have an ok starting point to resume working, for your teammates as well.
You can use Timer
Timer timer = new Timer();
timer.schedule( new TimerTask() {
public void run() {
// do your work
}
}, 0, 60*1000);
When the times comes
timer.cancel();
To shut it down.
As mentioned in other posts here - setting breakpoints in your code and walking thru the code to see if it behaves as you expected is a great way to learn something like Django until you have a good sense of how it all behaves - and what your code is doing.
To do this I would recommend using WingIde. Just like other mentioned IDEs nice and easy to use, nice layout and also easy to set breakpoints evaluate / modify the stack etc. Perfect for visualizing what your code is doing as you step through it. I'm a big fan of it.
Also I use PyCharm - it has excellent static code analysis and can help sometimes spot problems before you realize they are there.
As mentioned already django-debug-toolbar is essential - https://github.com/django-debug-toolbar/django-debug-toolbar
And while not explicitly a debug or analysis tool - one of my favorites is SQL Printing Middleware available from Django Snippets at https://djangosnippets.org/snippets/290/
This will display the SQL queries that your view has generated. This will give you a good sense of what the ORM is doing and if your queries are efficient or you need to rework your code (or add caching).
I find it invaluable for keeping an eye on query performance while developing and debugging my application.
Just one other tip - I modified it slightly for my own use to only show the summary and not the SQL statement.... So I always use it while developing and testing. I also added that if the len(connection.queries) is greater than a pre-defined threshold it displays an extra warning.
Then if I spot something bad (from a performance or number of queries perspective) is happening I turn back on the full display of the SQL statements to see exactly what is going on. Very handy when you are working on a large Django project with multiple developers.
If you need permissions, you cannot use 'pip' with 'sudo'. You can do a trick, so that you can use 'sudo' and install package. Just place 'sudo python -m ...' in front of your pip command.
sudo python -m pip install --user -r package_name
If you are referring to the npm module sleep, it notes in the readme that sleep
will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:
setTimeout(function() {
console.log('hello world!');
}, 5000);
For anyone looking to do this using es7 async/await, this example should help:
const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));
const example = async () => {
console.log('About to snooze without halting the event loop...');
await snooze(1000);
console.log('done!');
};
example();
If you are running behind a proxy like NGiNX or what have you, only then you should check for 'x-forwarded-for'
:
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
If the proxy isn't 'yours', I wouldn't trust the 'x-forwarded-for'
header, because it can be spoofed.
After applying : Tools > preferences > Graphics > Backend > Automatic Just restart the kernel
And you will surely get Interactive Plot. Happy Coding!
I had this same error while trying to include a PHP file in my Wordpress theme. I was able to get around it by referencing the file name using dirname(__FILE__)
. I couldn't use relative paths since my file was going to be included in different places throughout the theme, so something like require_once '../path-to/my-file'
wouldn't work.
Replacing require_once get_template_directory_uri() . '/path-to/my-file'
with require_once dirname( __FILE__ ) . '/path-to/my-file'
did the trick.
There are three options:
results = Model.objects.exclude(a=True).filter(x=5)
Use Q()
objects and the ~
operator
from django.db.models import Q
object_list = QuerySet.filter(~Q(a=True), x=5)
Register a custom lookup function
from django.db.models import Lookup
from django.db.models import Field
@Field.register_lookup
class NotEqual(Lookup):
lookup_name = 'ne'
def as_sql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
return '%s <> %s' % (lhs, rhs), params
Which can the be used as usual:
results = Model.objects.exclude(a=True, x__ne=5)
While quicksort is often a better choice than merge sort, there are definitely times when merge sort is thereotically a better choice. The most obvious time is when it's extremely important that your algorithm run faster than O(n^2). Quicksort is usually faster than this, but given the theoretical worst possible input, it could run in O(n^2), which is worse than the worst possible merge sort.
Quicksort is also more complicated than mergesort, especially if you want to write a really solid implementation, and so if you're aiming for simplicity and maintainability, merge sort becomes a promising alternative with very little performance loss.
If you want to change the size of plot the use arg figsize
df.groupby(['NFF', 'ABUSE']).size().unstack()
.plot(kind='bar', stacked=True, figsize=(15, 5))
The Proxy pattern might help you:
(function() {
// log all calls to setArray
var proxied = jQuery.fn.setArray;
jQuery.fn.setArray = function() {
console.log( this, arguments );
return proxied.apply( this, arguments );
};
})();
The above wraps its code in a function to hide the "proxied"-variable. It saves jQuery's setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.
You can do this using jQuery's .scrollTop()
and .offset()
method
Check out my sample and this jsFiddle Demonstration
$(function() {
$(document).scrollTop( $("#header").offset().top );
});
I had the same problem and I found this solution working with bindParam :
bindParam(':param', $myvar = NULL, PDO::PARAM_INT);
This is the intended use case for Ray, which is a library for parallel and distributed Python. Under the hood, it serializes objects using the Apache Arrow data layout (which is a zero-copy format) and stores them in a shared-memory object store so they can be accessed by multiple processes without creating copies.
The code would look like the following.
import numpy as np
import ray
ray.init()
@ray.remote
def func(array, param):
# Do stuff.
return 1
array = np.ones(10**6)
# Store the array in the shared memory object store once
# so it is not copied multiple times.
array_id = ray.put(array)
result_ids = [func.remote(array_id, i) for i in range(4)]
output = ray.get(result_ids)
If you don't call ray.put
then the array will still be stored in shared memory, but that will be done once per invocation of func
, which is not what you want.
Note that this will work not only for arrays but also for objects that contain arrays, e.g., dictionaries mapping ints to arrays as below.
You can compare the performance of serialization in Ray versus pickle by running the following in IPython.
import numpy as np
import pickle
import ray
ray.init()
x = {i: np.ones(10**7) for i in range(20)}
# Time Ray.
%time x_id = ray.put(x) # 2.4s
%time new_x = ray.get(x_id) # 0.00073s
# Time pickle.
%time serialized = pickle.dumps(x) # 2.6s
%time deserialized = pickle.loads(serialized) # 1.9s
Serialization with Ray is only slightly faster than pickle, but deserialization is 1000x faster because of the use of shared memory (this number will of course depend on the object).
See the Ray documentation. You can read more about fast serialization using Ray and Arrow. Note I'm one of the Ray developers.
You can try this:
function Get-UrlStatusCode([string] $Url)
{
try
{
(Invoke-WebRequest -Uri $Url -UseBasicParsing -DisableKeepAlive).StatusCode
}
catch [Net.WebException]
{
[int]$_.Exception.Response.StatusCode
}
}
$statusCode = Get-UrlStatusCode 'httpstat.us/500'
I had a lot of trouble with this too. Couldn't get it working using the case examples above, but this does the job for me:
Replace(rtrim(ltrim(ISNULL(Flat_no, '') +
' ' + ISNULL(House_no, '') +
' ' + ISNULL(Street, '') +
' ' + ISNULL(Town, '') +
' ' + ISNULL(City, ''))),' ',' ')
Replace corrects the double spaces caused by concatenating single spaces with nothing between them. r/ltrim gets rid of any spaces at the ends.
If you are using Google fonts I would suggest the following.
If you want the fonts to run from your localhost or server you need to download the files.
Instead of downloading the ttf packages in the download links, use the live link they provide, for example:
http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,300italic,400italic,600italic
Paste the URL in your browser and you should get a font-face declaration similar to the first answer.
Open the URLs provided, download and rename the files.
Stick the updated font-face declarations with relative paths to the woff files in your CSS, and you are done.
You can use the YouTube JavaScript player API, which has a feature on its own to set playback quality.
player.setPlaybackQuality(suggestedQuality:String):Void
This function sets the suggested video quality for the current video. The function causes the video to reload at its current position in the new quality. If the playback quality does change, it will only change for the video being played. Calling this function does not guarantee that the playback quality will actually change. However, if the playback quality does change, the onPlaybackQualityChange event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackQuality function. [source]
It's really simple. It's a new feature introduced in J2SE 5. Specifying angular brackets after the class name means you are creating a temporary data type which can hold any type of data.
Example:
class A<T>{
T obj;
void add(T obj){
this.obj=obj;
}
T get(){
return obj;
}
}
public class generics {
static<E> void print(E[] elements){
for(E element:elements){
System.out.println(element);
}
}
public static void main(String[] args) {
A<String> obj=new A<String>();
A<Integer> obj1=new A<Integer>();
obj.add("hello");
obj1.add(6);
System.out.println(obj.get());
System.out.println(obj1.get());
Integer[] arr={1,3,5,7};
print(arr);
}
}
Instead of <T>
, you can actually write anything and it will work the same way. Try writing <ABC>
in place of <T>
.
This is just for convenience:
<T>
is referred to as any type<E>
as element type<N>
as number type<V>
as value<K>
as keyBut you can name it anything you want, it doesn't really matter.
Moreover, Integer
, String
, Boolean
etc are wrapper classes of Java which help in checking of types during compilation. For example, in the above code, obj
is of type String
, so you can't add any other type to it (try obj.add(1)
, it will cast an error). Similarly, obj1
is of the Integer
type, you can't add any other type to it (try obj1.add("hello")
, error will be there).
The code snippet in the linked proposed duplicate reads user input.
ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?:
The user can type as many letters as they want, and it will go into the delBuild variable.
Seamus Campbell's answer doesnot work on python2.x.
list1 = sorted(list1, key=lambda e: int(e))
using lambda
function works well.
// This one has print statement so you can see the result at every stage if you would like. They are not needed
function crop(image, width, height)
{
image.width = width;
image.height = height;
//print ("in function", image, image.getWidth(), image.getHeight());
return image;
}
var image = new SimpleImage("name of your image here");
//print ("original", image, image.getWidth(), image.getHeight());
//crop(image,200,300);
print ("final", image, image.getWidth(), image.getHeight());
Because the statement defining obj
hasn't finished, key1
doesn't exist yet. Consider this solution:
var obj = { key1: "it" };
obj.key2 = obj.key1 + ' ' + 'works!';
// obj.key2 is now 'it works!'
You can use this class : class="sticky-top alert alert-dismissible"
Your error
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
appears because you must call setRequestHeader
after calling open
. Simply move your setRequestHeader
line below your open
line (but before send
):
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);
See this brilliant blog post about animating values in objects.. you can then use the values to animate whatever you like, 100% simultaneously!
I've used it like this to slide in/out:
slide : function(id, prop, from, to) {
if (from < to) {
// Sliding out
var fromvals = { add: from, subtract: 0 };
var tovals = { add: to, subtract: 0 };
} else {
// Sliding back in
var fromvals = { add: from, subtract: to };
var tovals = { add: from, subtract: from };
}
$(fromvals).animate(tovals, {
duration: 200,
easing: 'swing', // can be anything
step: function () { // called on every step
// Slide using the entire -ms-grid-columns setting
$(id).css(prop, (this.add - this.subtract) + 'px 1.5fr 0.3fr 8fr 3fr 5fr 0.5fr');
}
});
}
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
Use #propagate() method. Sample non-Guava implementation from Java 8 Blog by Sam Beran:
public class Throwables {
public interface ExceptionWrapper<E> {
E wrap(Exception e);
}
public static <T> T propagate(Callable<T> callable) throws RuntimeException {
return propagate(callable, RuntimeException::new);
}
public static <T, E extends Throwable> T propagate(Callable<T> callable, ExceptionWrapper<E> wrapper) throws E {
try {
return callable.call();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw wrapper.wrap(e);
}
}
}
This works, but there might be better solutions.
asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking
You can get your Button1 location and than increase the Y value every time you click on it.
Public Class Form1
Dim BtnCoordinate As Point
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim btn As Button = New Button
BtnCoordinate.Y += Button1.Location.Y + 4
With btn
.Location = New Point(BtnCoordinate)
.Text = TextBox1.Text
.ForeColor = Color.Black
End With
Me.Controls.Add(btn)
Me.StartPosition = FormStartPosition.CenterScreen
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Button1Coordinate = Button1.Location
End Sub
End Class
Use Arrays
class in Java which will return you an ArrayList
:
final List<String> characters = Arrays.asList("+","-");
You will need a bit more work if you need a List<Character>
.
For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.
To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.
Tested in Excel 2007.
Option Explicit
Private Type SmallArr
Elt() As Variant
End Type
Sub test()
Dim x As Long, max_row As Long, y As Long
'' Define big array as an array of small arrays
Dim BigArr() As SmallArr
y = 2
ReDim Preserve BigArr(0 To y)
For x = 0 To y
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Write what has been read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
'' Get the number of the last not empty row
max_row = Range("A" & Rows.Count).End(xlUp).Row
'' Change the size of the big array
ReDim Preserve BigArr(0 To max_row)
Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
'' Check haven't we lost any data
For x = 0 To y
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
For x = y To max_row
'' We have to change the size of each Elt,
'' because there are some new for,
'' which the size has not been set, yet.
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Check what we have read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
End Sub
As second says, most of the "design" decisions made for TeX documents are backed up by well researched usability studies, so changing them should be undertaken with care. It is, however, relatively common to replace Computer Modern with Times (also a serif face).
Try \usepackage{times}
.
It's because you have included a leading /
in your file path. The /
makes it start at the top of your filesystem. Note: filesystem path, not Web site path (you're not accessing it over HTTP). You can use a relative path with include_once
(one that doesn't start with a leading /
).
You can change it to this:
include_once 'headerSite.php';
That will look first in the same directory as the file that's including it (i.e. C:\xampp\htdocs\PoliticalForum\
in your example.
From http://www.regular-expressions.info/charclass.html :
Note that the only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\\), the caret (^) and the hyphen (-). The usual metacharacters are normal characters inside a character class, and do not need to be escaped by a backslash. To search for a star or plus, use [+*]. Your regex will work fine if you escape the regular metacharacters inside a character class, but doing so significantly reduces readability.
To include a backslash as a character without any special meaning inside a character class, you have to escape it with another backslash. [\\x] matches a backslash or an x. The closing bracket (]), the caret (^) and the hyphen (-) can be included by escaping them with a backslash, or by placing them in a position where they do not take on their special meaning. I recommend the latter method, since it improves readability. To include a caret, place it anywhere except right after the opening bracket. [x^] matches an x or a caret. You can put the closing bracket right after the opening bracket, or the negating caret. []x] matches a closing bracket or an x. [^]x] matches any character that is not a closing bracket or an x. The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret. Both [-x] and [x-] match an x or a hyphen.
What language are you writing the regex in?
You can use the length()
method on File
which returns the size in bytes.
OR
makes sense (from readability point of view), when there are less values to be compared.
IN
is useful esp. when you have a dynamic source, with which you want values to be compared.
Another alternative is to use a JOIN
with a temporary table.
I don't think performance should be a problem, provided you have necessary indexes.
$ git rm ./*.DS_Store
- remove all .DS_Store from git$ echo \.DS_Store >> .gitignore
- ignore .DS_Store in futurecommit & push
Update v8
Below answers work but exposes your application to XSS security risks!.
Instead of using this.sanitizer.bypassSecurityTrustResourceUrl(url)
, it is recommended to use this.sanitizer.sanitize(SecurityContext.URL, url)
Update
For RC.6^ version use DomSanitizer
And a good option is using pure pipe for that:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';
@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
remember to add your new SafePipe
to the declarations
array of the AppModule. (as seen on documentation)
@NgModule({
declarations : [
...
SafePipe
],
})
html
<iframe width="100%" height="300" [src]="url | safe"></iframe>
If you use embed
tag this might be interesting for you:
Old version RC.5
You can leverage DomSanitizationService
like this:
export class YourComponent {
url: SafeResourceUrl;
constructor(sanitizer: DomSanitizationService) {
this.url = sanitizer.bypassSecurityTrustResourceUrl('your url');
}
}
And then bind to url
in your template:
<iframe width="100%" height="300" [src]="url"></iframe>
Don't forget to add the following imports:
import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';
If it's a primitive type, you can use Arrays.fill()
:
Arrays.fill(array, -1);
[Incidentally, memset
in C or C++ is only of any real use for arrays of char
.]
Closes a socket connection and allows for re-use of the socket:
tcpClient.Client.Disconnect(false);
Depending on the purpose of setting the display property, you might want to take a look at
$("#yourElementID").show()
and
$("#yourElementID").hide()
The clean answer is to take a little bit of time correctly prepare your execution environment.
The first technique you have to prepare your execution environment is to use a matplotlibrc
file, as wisely recommended by Chris Q., setting
backend : Agg
in that file. You can even control — with no code changes — how and where matplotlib looks for and finds the matplotlibrc
file.
The second technique you have to prepare your execution environment is to use the MPLBACKEND
environment variable (and inform your users to make use of it):
export MPLBACKEND="agg"
python <program_using_matplotlib.py>
This is handy because you don't even have to provide another file on disk to make this work. I have employed this approach with, for example, testing in continuous integration, and running on remote machines that do not have displays.
Hard-coding your matplotlib backend to "Agg" in your Python code is like bashing a square peg into a round hole with a big hammer, when, instead, you could have just told matplotlib it needs to be a square hole.
In some cases, I just convert it into ENTITIES:
// i.e., $x= ABC\DEFGH'IJKL
$x = str_ireplace("'", "'", $x);
$x = str_ireplace("\\", "\", $x);
$x = str_ireplace('"', """, $x);
On the HTML page, the visual output is the same:
ABC\DEFGH'IJKL
However, it is sanitized in source.
This should work
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
verify(bar).DoStuff(any(Foo[].class));
After reinstalling Android Studio, Is working without adb kill-server
for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this
allEdges <- data.frame(c(edges$V1,edges$V2))
Another recursive solution
public static String reverse(ArrayList<Float> list) {
if (list.size() == 1) {
return " " +list.get(0);
}
else {
return " "+ list.remove(list.size() - 1) + reverse(list);
}
}
I want to return odd numbers of an array
If i read that correctly, you want something like this?
List<Integer> getOddNumbers(int[] integers) {
List<Integer> oddNumbers = new ArrayList<Integer>();
for (int i : integers)
if (i % 2 != 0)
oddNumbers.add(i);
return oddNumbers;
}
Context.getResources().getDimension(int id);
I was getting similar error and please see below how I resolved it.
My directory structure: /opt/git/project.git and git user is git
$ cd /opt/git/project.git
$ sudo chown -R git:git .
chown with -R option recursively changes the ownership and and group (since i typed git:git in above command) of the current directory. chown -R is necessary since git changes many files inside your git directory when you push to the repository.
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeOther alternative:
JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
String.class, "Your message");
Then:
System.out.println(element.getValue()); // Result: Your message
d = {}
# import list of year,value pairs
for year,value in mylist:
try:
d[year].append(value)
except KeyError:
d[year] = [value]
The Python way - it is easier to receive forgiveness than ask permission!
select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType
Cheers -
I guess it is too late to answer but my help some people.
I don't have enough reputation to post images sorry.
Hope it can help
I just had this issue, and was able to work around it.
First, connect to the MySQL database with an older client that doesn't mind old_passwords. Connect using the user that your script will be using.
Run these queries:
SET SESSION old_passwords=FALSE;
SET PASSWORD = PASSWORD('[your password]');
In your PHP script, change your mysql_connect function to include the client flag 1:
define('CLIENT_LONG_PASSWORD', 1);
mysql_connect('[your server]', '[your username]', '[your password]', false, CLIENT_LONG_PASSWORD);
This allowed me to connect successfully.
Edit: as per Garland Pope's comment, it may not be necessary to set CLIENT_LONG_PASSWORD manually any more in your PHP code as of PHP 5.4!
Edit: courtesy of Antonio Bonifati, a PHP script to run the queries for you:
<?php const DB = [ 'host' => '...', # localhost may not work on some hosting
'user' => '...',
'pwd' => '...', ];
if (!mysql_connect(DB['host'], DB['user'], DB['pwd'])) {
die(mysql_error());
} if (!mysql_query($query = 'SET SESSION old_passwords=FALSE')) {
die($query);
} if (!mysql_query($query = "SET PASSWORD = PASSWORD('" . DB['pwd'] . "')")) {
die($query);
}
echo "Excellent, mysqli will now work";
?>
Generally, labels and textboxes that appear in front of an image is best organized in a panel. When rendering, if labels need to be transparent to an image within the panel, you can switch to image as parent of labels in Form initiation like this:
var oldParent = panel1;
var newParent = pictureBox1;
foreach (var label in oldParent.Controls.OfType<Label>())
{
label.Location = newParent.PointToClient(label.Parent.PointToScreen(label.Location));
label.Parent = newParent;
label.BackColor = Color.Transparent;
}
Importing Maven dependencies may not work if you import the same path several times. This may happen automatically after importing an existing maven project. I can't figure out why this happens, so I'm inclined to think it is a bug.
For example, if my project is
hibernate
src/main
src/test
the three paths may be imported as top nodes:
hibernate
src/main
src/test
If such is the case, the dependencies appear to be right, but they won't be used until you remove the superfluous paths (in this case, src/main
and src/test
). Once you do this, refresh and click Build > Rebuild Project. IDEA will pick up the dependencies.
A symptom of this problem is that IDEA warns you of a duplicated path when you manually check a library (second screenshot in the question).
There are several ways to re-read the dependencies in case you need it. If you go to the “Maven Projects” tab, there is a “Reimport All Maven Projects” icon at the top left of the tab. If you suspect IDEA became confused you can click on File > Invalidate Caches.
It is strange how much beauty varies for different people. I find the list comprehension much clearer than filter
+lambda
, but use whichever you find easier.
There are two things that may slow down your use of filter
.
The first is the function call overhead: as soon as you use a Python function (whether created by def
or lambda
) it is likely that filter will be slower than the list comprehension. It almost certainly is not enough to matter, and you shouldn't think much about performance until you've timed your code and found it to be a bottleneck, but the difference will be there.
The other overhead that might apply is that the lambda is being forced to access a scoped variable (value
). That is slower than accessing a local variable and in Python 2.x the list comprehension only accesses local variables. If you are using Python 3.x the list comprehension runs in a separate function so it will also be accessing value
through a closure and this difference won't apply.
The other option to consider is to use a generator instead of a list comprehension:
def filterbyvalue(seq, value):
for el in seq:
if el.attribute==value: yield el
Then in your main code (which is where readability really matters) you've replaced both list comprehension and filter with a hopefully meaningful function name.
You could use git-svn
to import the repository into a Git repository, then use git log -p filename
. This shows each log entry for the file followed by the corresponding diff.
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for numbers in lists:
for numbers2 in numbers:
results.append(numbers2)
return results
print flatten(n)
Output: n = [1,2,3,4,5,6,7,8,9]
I think Mockito @InjectMocks
is the way to go.
Depending on your intention you can use:
More info in docs
Below is an example with field injection:
Classes:
public class Foo
{
private Bar bar = new Bar();
public void foo()
{
bar.someMethod();
}
}
public class Bar
{
public void someMethod()
{
//something
}
}
Test:
@RunWith(MockitoJUnitRunner.class)
public class FooTest
{
@Mock
Bar bar;
@InjectMocks
Foo foo;
@Test
public void FooTest()
{
doNothing().when( bar ).someMethod();
foo.foo();
verify(bar, times(1)).someMethod();
}
}
You can also fit a set of a data to whatever function you like using curve_fit
from scipy.optimize
. For example if you want to fit an exponential function (from the documentation):
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * np.exp(-b * x) + c
x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x, yn)
And then if you want to plot, you could do:
plt.figure()
plt.plot(x, yn, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()
(Note: the *
in front of popt
when you plot will expand out the terms into the a
, b
, and c
that func
is expecting.)
A TCP connection is specified by the tuple (source IP, source port, destination IP, destination port).
The reason why there is a TIME_WAIT state following session shutdown is because there may still be live packets out in the network on their way to you (or from you which may solicit a response of some sort). If you were to re-create that same tuple and one of those packets showed up, it would be treated as a valid packet for your connection (and probably cause an error due to sequencing).
So the TIME_WAIT time is generally set to double the packets maximum age. This value is the maximum age your packets will be allowed to get to before the network discards them.
That guarantees that, before you're allowed to create a connection with the same tuple, all the packets belonging to previous incarnations of that tuple will be dead.
That generally dictates the minimum value you should use. The maximum packet age is dictated by network properties, an example being that satellite lifetimes are higher than LAN lifetimes since the packets have much further to go.
A simple alternative to using a custom UserType is to construct a new java.util.Date in the setter for the date property in your persisted bean, eg:
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Column;
@Entity
public class Purchase {
private Date date;
@Column
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
// force java.sql.Timestamp to be set as a java.util.Date
this.date = new Date(date.getTime());
}
}
There are two types of contexts we are dealing with:
1: root context (parent context. Typically include all jdbc(ORM, Hibernate) initialisation and other spring security related configuration)
2: individual servlet context (child context.Typically Dispatcher Servlet Context and initialise all beans related to spring-mvc (controllers , URL Mapping etc)).
Here is an example of web.xml which includes multiple application context file
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns="http://java.sun.com/xml/ns/javaee"_x000D_
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee_x000D_
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">_x000D_
_x000D_
<display-name>Spring Web Application example</display-name>_x000D_
_x000D_
<!-- Configurations for the root application context (parent context) -->_x000D_
<listener>_x000D_
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>_x000D_
</listener>_x000D_
<context-param>_x000D_
<param-name>contextConfigLocation</param-name>_x000D_
<param-value>_x000D_
/WEB-INF/spring/jdbc/spring-jdbc.xml <!-- JDBC related context -->_x000D_
/WEB-INF/spring/security/spring-security-context.xml <!-- Spring Security related context -->_x000D_
</param-value>_x000D_
</context-param>_x000D_
_x000D_
<!-- Configurations for the DispatcherServlet application context (child context) -->_x000D_
<servlet>_x000D_
<servlet-name>spring-mvc</servlet-name>_x000D_
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>_x000D_
<init-param>_x000D_
<param-name>contextConfigLocation</param-name>_x000D_
<param-value>_x000D_
/WEB-INF/spring/mvc/spring-mvc-servlet.xml_x000D_
</param-value>_x000D_
</init-param>_x000D_
</servlet>_x000D_
<servlet-mapping>_x000D_
<servlet-name>spring-mvc</servlet-name>_x000D_
<url-pattern>/admin/*</url-pattern>_x000D_
</servlet-mapping>_x000D_
_x000D_
</web-app>
_x000D_
This is a complete solution. I've just updated this example code with the information provided in the answer below by @mad. Also check the solution below from @Khobaib explaining how to deal with picasa images.
I've just reviewed my original answer and created a simple Android Studio project you can checkout from github and import directly on your system.
https://github.com/hanscappelle/SO-2169649
(note that the multiple file selection still needs work)
With support for images from file explorers thanks to user mad.
public class BrowsePictureActivity extends Activity {
// this is the action code we use in our intent,
// this way we know we're looking at the response from our own action
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.Button01)
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
}
}
}
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
// this is our fallback here
return uri.getPath();
}
}
Since someone requested that information in a comment and it's better to have information gathered.
Set an extra parameter EXTRA_ALLOW_MULTIPLE
on the intent:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
And in the Result handling check for that parameter:
if (Intent.ACTION_SEND_MULTIPLE.equals(data.getAction()))
&& Intent.hasExtra(Intent.EXTRA_STREAM)) {
// retrieve a collection of selected images
ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
// iterate over these images
if( list != null ) {
for (Parcelable parcel : list) {
Uri uri = (Uri) parcel;
// TODO handle the images one by one here
}
}
}
Note that this is only supported by API level 18+.
I really liked @brettdj's code, but then I found that when I added additional code to edit the copy, it overwrote my original sheet instead. I've tweaked his answer so that further code pointed at ws1
will affect the new sheet rather than the original.
Sub Test()
Dim ws1 as Worksheet
ThisWorkbook.Worksheets("Master").Copy
Set ws1 = ThisWorkbook.Worksheets("Master (2)")
End Sub
SELECT COUNT(*)
FROM table_emp
WHERE YEAR(ARR_DATE) = '2012'
GROUP BY MONTH(ARR_DATE)
FireFox have problemes for getBBox(), i need to do this in vanillaJS.
I've a better Way and is the same result as real svg.getBBox() function !
With this good post : Get the real size of a SVG/G element
var el = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle
console.log( rect.width );
console.log( rect.height);
Right click on the Spring Boot Applications main class file -> select Debug As options -> Select Java Application