Sample code:
$(document).on('hide.bs.modal', '#basicModal', function (e) {
$('#basicModal').empty();
});
As per the documentation, it says : Whether or not to fail the build if the web.xml file is missing. Set to false if you want you WAR built without a web.xml file. This may be useful if you are building an overlay that has no web.xml file. Default value is: true. User property is: failOnMissingWebXml.
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<extensions>false</extensions>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
Hope it makes more clear
If all you are trying to do is solve the content length error from amazon then you could just read the bytes from the input stream to a Long and add that to the metadata.
/*
* Obtain the Content length of the Input stream for S3 header
*/
try {
InputStream is = event.getFile().getInputstream();
contentBytes = IOUtils.toByteArray(is);
} catch (IOException e) {
System.err.printf("Failed while reading bytes from %s", e.getMessage());
}
Long contentLength = Long.valueOf(contentBytes.length);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(contentLength);
/*
* Reobtain the tmp uploaded file as input stream
*/
InputStream inputStream = event.getFile().getInputstream();
/*
* Put the object in S3
*/
try {
s3client.putObject(new PutObjectRequest(bucketName, keyName, inputStream, metadata));
} catch (AmazonServiceException ase) {
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Error Message: " + ace.getMessage());
} finally {
if (inputStream != null) {
inputStream.close();
}
}
You'll need to read the input stream twice using this exact method so if you are uploading a very large file you might need to look at reading it once into an array and then reading it from there.
You should consider using an angular plug-in to handle the heavy lifting for you, unless you particularly enjoy typing hundreds of lines of knarly error prone ion-grid code. Simon Grimm has a cracking step by step tutorial that anyone can follow: https://devdactic.com/ionic-datatable-ngx-datatable/. This shows how to use ngx-datatable. But there are many other options (ng2-table is good).
The dead simple example goes like this:
<ion-content>
<ngx-datatable class="fullscreen" [ngClass]="tablestyle" [rows]="rows" [columnMode]="'force'" [sortType]="'multi'" [reorderable]="false">
<ngx-datatable-column name="Name"></ngx-datatable-column>
<ngx-datatable-column name="Gender"></ngx-datatable-column>
<ngx-datatable-column name="Age"></ngx-datatable-column>
</ngx-datatable>
</ion-content>
And the ts:
rows = [
{
"name": "Ethel Price",
"gender": "female",
"age": 22
},
{
"name": "Claudine Neal",
"gender": "female",
"age": 55
},
{
"name": "Beryl Rice",
"gender": "female",
"age": 67
},
{
"name": "Simon Grimm",
"gender": "male",
"age": 28
}
];
Since the original poster expressed their frustration of how difficult it is to achieve this with ion-grid, I think the correct answer should not be constrained by this as a prerequisite. You would be nuts to roll your own, given how good this is!
#button {
line-height: 12px;
width: 18px;
font-size: 8pt;
font-family: tahoma;
margin-top: 1px;
margin-right: 2px;
position: absolute;
top: 0;
right: 0;
}
This is the only command that worked for me. (I got it from M 8.0 documentation)
ALTER USER 'root'@'*' IDENTIFIED WITH mysql_native_password BY 'YOURPASSWORD';
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YOURPASSWORD';
In bash, an alternative to shopt -s extglob
is the GLOBIGNORE
variable. It's not really better, but I find it easier to remember.
An example that may be what the original poster wanted:
GLOBIGNORE="*techno*"; cp *Music* /only_good_music/
When done, unset GLOBIGNORE
to be able to rm *techno*
in the source directory.
When I look at this description, I have a feeling, that this xdr integer is just a big-endian "standard" integer, but it's expressed in the most obfuscated way. Two's complement notation is better know as U2, and it's what we are using on today's processors. The byte order indicates that it's a big-endian notation.
So, answering your question, you should inverse elements in your array (0 <--> 3, 1 <-->2), as they are encoded in little-endian. Just to make sure, you should first check BitConverter.IsLittleEndian
to see on what machine you are running.
A callback URL will be invoked by the API method you're calling after it's done. So if you call
POST /api.example.com/foo?callbackURL=http://my.server.com/bar
Then when /foo
is finished, it sends a request to http://my.server.com/bar
. The contents and method of that request are going to vary - check the documentation for the API you're accessing.
Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:
just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens
that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)
an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants
Realizing that this is a rather old post, I'll provide an answer anyway as I was struggling with the same problem.
You should use the "input"
event instead, and register with the .on
method. This is fast - without the lag of keyup
and solves the missing latest keypress problem you describe.
$('#dSuggest').on("input", function() {
var dInput = this.value;
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
I created an Interface and a <options>
tag helper for this. So I didn't have to convert the IEnumerable<T>
items into IEnumerable<SelectListItem>
every time I have to populate the <select>
control.
And I think it works beautifully...
The usage is something like:
<select asp-for="EmployeeId">
<option value="">Please select...</option>
<options asp-items="@Model.EmployeesList" />
</select>
And to make it work with the tag helper you have to implement that interface in your class:
public class Employee : IIntegerListItem
{
public int Id { get; set; }
public string FullName { get; set; }
public int Value { return Id; }
public string Text{ return FullName ; }
}
These are the needed codes:
The interface:
public interface IIntegerListItem
{
int Value { get; }
string Text { get; }
}
The <options>
tag helper:
[HtmlTargetElement("options", Attributes = "asp-items")]
public class OptionsTagHelper : TagHelper
{
public OptionsTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}
[HtmlAttributeNotBound]
public IHtmlGenerator Generator { get; set; }
[HtmlAttributeName("asp-items")]
public object Items { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.SuppressOutput();
// Is this <options /> element a child of a <select/> element the SelectTagHelper targeted?
object formDataEntry;
context.Items.TryGetValue(typeof(SelectTagHelper), out formDataEntry);
var selectedValues = formDataEntry as ICollection<string>;
var encodedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (selectedValues != null && selectedValues.Count != 0)
{
foreach (var selectedValue in selectedValues)
{
encodedValues.Add(Generator.Encode(selectedValue));
}
}
IEnumerable<SelectListItem> items = null;
if (Items != null)
{
if (Items is IEnumerable)
{
var enumerable = Items as IEnumerable;
if (Items is IEnumerable<SelectListItem>)
items = Items as IEnumerable<SelectListItem>;
else if (Items is IEnumerable<IIntegerListItem>)
items = ((IEnumerable<IIntegerListItem>)Items).Select(x => new SelectListItem() { Selected = false, Value = ((IIntegerListItem)x).Value.ToString(), Text = ((IIntegerListItem)x).Text });
else
throw new InvalidOperationException(string.Format("The {2} was unable to provide metadata about '{1}' expression value '{3}' for <options>.",
"<options>",
"ForAttributeName",
nameof(IModelMetadataProvider),
"For.Name"));
}
else
{
throw new InvalidOperationException("Invalid items for <options>");
}
foreach (var item in items)
{
bool selected = (selectedValues != null && selectedValues.Contains(item.Value)) || encodedValues.Contains(item.Value);
var selectedAttr = selected ? "selected='selected'" : "";
if (item.Value != null)
output.Content.AppendHtml($"<option value='{item.Value}' {selectedAttr}>{item.Text}</option>");
else
output.Content.AppendHtml($"<option>{item.Text}</option>");
}
}
}
}
There may be some typo but the aim is clear I think. I had to edit a little bit.
I guess its enough to return absolute path..
Path.GetFileName( Request.Url.AbsolutePath )
using System.IO;
You're returning the address of a local variable allocated on the stack. When your function returns, the storage for all local variables (such as wc
) is deallocated and is subject to being immediately overwritten by something else.
To fix this, you can pass the size of the buffer to GetWC
, but then you've got pretty much the same interface as mbstowcs
itself. Or, you could allocate a new buffer inside GetWC
and return a pointer to that, leaving it up to the caller to deallocate the buffer.
Import this in to app.module.ts
import {HttpClientModule} from '@angular/common/http';
and add this one in imports
HttpClientModule
I had the same problem but none of the solutions worked for me. The problem was that I had no . separators in my package name.
i.e. if your package name is my.packagename its fine but it can't be just mypackagename
Got the hint from this bug report.
Yes. They are different file formats (and their file extensions).
Wikipedia entries for each of the formats will give you quite a bit of information:
Image formats can be separated into three broad categories:
Uncompressed formats take up the most amount of data, but they are exact representations of the image. Bitmap formats such as BMP generally are uncompressed, although there also are compressed BMP files as well.
Lossy compression formats are generally suited for photographs. It is not suited for illustrations, drawings and text, as compression artifacts from compressing the image will standout. Lossy compression, as its name implies, does not encode all the information of the file, so when it is recovered into an image, it will not be an exact representation of the original. However, it is able to compress images very effectively compared to lossless formats, as it discards certain information. A prime example of a lossy compression format is JPEG.
Lossless compression formats are suited for illustrations, drawings, text and other material that would not look good when compressed with lossy compression. As the name implies, lossless compression will encode all the information from the original, so when the image is decompressed, it will be an exact representation of the original. As there is no loss of information in lossless compression, it is not able to achieve as high a compression as lossy compression, in most cases. Examples of lossless image compression is PNG and GIF. (GIF only allows 8-bit images.)
TIFF and BMP are both "wrapper" formats, as the data inside can depend upon the compression technique that is used. It can contain both compressed and uncompressed images.
When to use a certain image compression format really depends on what is being compressed.
Related question: Ruthlessly compressing large images for the web
Map default.aspx as HttpHandler route and redirect to CreateThings.aspx from within the HttpHandler.
<add verb="GET" path="default.aspx" type="RedirectHandler"/>
Make sure Default.aspx does not exists physically at your application root. If it exists physically the HttpHandler will not be given any chance to execute. Physical file overrides HttpHandler mapping.
Moreover you can re-use this for pages other than default.aspx.
<add verb="GET" path="index.aspx" type="RedirectHandler"/>
//RedirectHandler.cs in your App_Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for RedirectHandler
/// </summary>
public class RedirectHandler : IHttpHandler
{
public RedirectHandler()
{
//
// TODO: Add constructor logic here
//
}
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Redirect("CreateThings.aspx");
context.Response.End();
}
#endregion
}
Try this:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";
To put a variable in a string enclose the variable in quotes and addition signs like this:
var myname = "BOB";
var mystring = "Hi there "+myname+"!";
Just remember that one rule!
I agree with Mike's answer but there's an implicit 3 second wait if no elements are found which can be switched on/off which is useful if you're performing this action a lot:
driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
boolean exists = driver.findElements( By.id("...") ).size() != 0
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
Putting that into a utility method should improve performance if you're running a lot of tests
Since seotweaks
was originally created as a branch from master
, merging it back in is a good idea. However if you are in a situation where one of your branches is not really a branch from master
or your history is so different that you just want to obliterate the master
branch in favor of the new branch that you've been doing the work on you can do this:
git push [-f] origin seotweaks:master
This is especially helpful if you are getting this error:
! [remote rejected] master (deletion of the current branch prohibited)
And you are not using GitHub and don't have access to the "Administration" tab to change the default branch for your remote repository. Furthermore, this won't cause down time or race conditions as you may encounter by deleting master:
git push origin :master
Do not simplify the code to avoid "linq translation error": The test consist between a date with time at 0:0:0 and the same date with time at 23:59:59
iFilter.MyDate1 = DateTime.Today; // or DateTime.MinValue
// GET
var tempQuery = ctx.MyTable.AsQueryable();
if (iFilter.MyDate1 != DateTime.MinValue)
{
TimeSpan temp24h = new TimeSpan(23,59,59);
DateTime tempEndMyDate1 = iFilter.MyDate1.Add(temp24h);
// DO not change the code below, you need 2 date variables...
tempQuery = tempQuery.Where(w => w.MyDate2 >= iFilter.MyDate1
&& w.MyDate2 <= tempEndMyDate1);
}
List<MyTable> returnObject = tempQuery.ToList();
A very simple way is to use Formatter
(see date time conversions) or more directly String.format
as in
String.format("%tR", new Date())
for log file you may date to enter into text data. following code may help
# declaring variables
Logfile="logfile.txt"
MAIL_LOG="Message to print in log file"
Location="were is u want to store log file"
cd $Location
if [ -f $Logfile ]
then
echo "$MAIL_LOG " >> $Logfile
else
touch $Logfile
echo "$MAIL_LOG" >> $Logfile
fi
ouput: 2. Log file will be created in first run and keep on updating from next runs. In case log file missing in future run , script will create new log file.
$("#id").change(function(){
//does some stuff;
});
How about this, using an overlay?
.image:hover > .overlay {
width:100%;
height:100%;
position:absolute;
background-color:#000;
opacity:0.5;
border-radius:30px;
}
In my case, I achieved this with:
ALTER SEQUENCE table_tabl_id_seq RESTART WITH 6;
Where my table is named table
You can try: ng serve --configuration=dev/prod
To build use: ng build --prod --configuration=dev
Hope you are using a different kind of environment.
This is the version that works in IE 9.
<div style="display:table; table-layout: fixed; width:100%; " >
<div style="display:table-row;">
<div style="display:table-cell;">
<table style="width: 100%; table-layout: fixed;">
<div style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">First row. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</table>
</div>
<div style="display:table-cell;">
Top right Cell.
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<table style="width: 100%; table-layout: fixed;">
<div style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">Second row - Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</table>
</div>
<div style="display:table-cell;">
Bottom right cell.
</div>
</div>
</div>
starting from the chad's answer, here is the COMPLETE working solution to parse UML, with propper handling of comments, with just 2 little functions (more than 2 bu you can mix them all). I don't say chad's one didn't work at all, but it had too much issues with badly formated XML files: So you have to be a bit more tricky to handle comments and misplaced spaces/CR/TAB/etc.
The purpose of this answer is to give ready-2-use, out of the box bash functions to anyone needing parsing UML without complex tools using perl, python or anything else. As for me, I cannot install cpan, nor perl modules for the old production OS i'm working on, and python isn't available.
First, a definition of the UML words used in this post:
<!-- comment... -->
<tag attribute="value">content...</tag>
EDIT: updated functions, with handle of:
xml_read_dom() {
# https://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash
local ENTITY IFS=\>
if $ITSACOMMENT; then
read -d \< COMMENTS
COMMENTS="$(rtrim "${COMMENTS}")"
return 0
else
read -d \< ENTITY CONTENT
CR=$?
[ "x${ENTITY:0:1}x" == "x/x" ] && return 0
TAG_NAME=${ENTITY%%[[:space:]]*}
[ "x${TAG_NAME}x" == "x?xmlx" ] && TAG_NAME=xml
TAG_NAME=${TAG_NAME%%:*}
ATTRIBUTES=${ENTITY#*[[:space:]]}
ATTRIBUTES="${ATTRIBUTES//xmi:/}"
ATTRIBUTES="${ATTRIBUTES//xmlns:/}"
fi
# when comments sticks to !-- :
[ "x${TAG_NAME:0:3}x" == "x!--x" ] && COMMENTS="${TAG_NAME:3} ${ATTRIBUTES}" && ITSACOMMENT=true && return 0
# http://tldp.org/LDP/abs/html/string-manipulation.html
# INFO: oh wait it doesn't work on IBM AIX bash 3.2.16(1):
# [ "x${ATTRIBUTES:(-1):1}x" == "x/x" -o "x${ATTRIBUTES:(-1):1}x" == "x?x" ] && ATTRIBUTES="${ATTRIBUTES:0:(-1)}"
[ "x${ATTRIBUTES:${#ATTRIBUTES} -1:1}x" == "x/x" -o "x${ATTRIBUTES:${#ATTRIBUTES} -1:1}x" == "x?x" ] && ATTRIBUTES="${ATTRIBUTES:0:${#ATTRIBUTES} -1}"
return $CR
}
and the second one :
xml_read() {
# https://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash
ITSACOMMENT=false
local MULTIPLE_ATTR LIGHT FORCE_PRINT XAPPLY XCOMMAND XATTRIBUTE GETCONTENT fileXml tag attributes attribute tag2print TAGPRINTED attribute2print XAPPLIED_COLOR PROSTPROCESS USAGE
local TMP LOG LOGG
LIGHT=false
FORCE_PRINT=false
XAPPLY=false
MULTIPLE_ATTR=false
XAPPLIED_COLOR=g
TAGPRINTED=false
GETCONTENT=false
PROSTPROCESS=cat
Debug=${Debug:-false}
TMP=/tmp/xml_read.$RANDOM
USAGE="${C}${FUNCNAME}${c} [-cdlp] [-x command <-a attribute>] <file.xml> [tag | \"any\"] [attributes .. | \"content\"]
${nn[2]} -c = NOCOLOR${END}
${nn[2]} -d = Debug${END}
${nn[2]} -l = LIGHT (no \"attribute=\" printed)${END}
${nn[2]} -p = FORCE PRINT (when no attributes given)${END}
${nn[2]} -x = apply a command on an attribute and print the result instead of the former value, in green color${END}
${nn[1]} (no attribute given will load their values into your shell; use '-p' to print them as well)${END}"
! (($#)) && echo2 "$USAGE" && return 99
(( $# < 2 )) && ERROR nbaram 2 0 && return 99
# getopts:
while getopts :cdlpx:a: _OPT 2>/dev/null
do
{
case ${_OPT} in
c) PROSTPROCESS="${DECOLORIZE}" ;;
d) local Debug=true ;;
l) LIGHT=true; XAPPLIED_COLOR=END ;;
p) FORCE_PRINT=true ;;
x) XAPPLY=true; XCOMMAND="${OPTARG}" ;;
a) XATTRIBUTE="${OPTARG}" ;;
*) _NOARGS="${_NOARGS}${_NOARGS+, }-${OPTARG}" ;;
esac
}
done
shift $((OPTIND - 1))
unset _OPT OPTARG OPTIND
[ "X${_NOARGS}" != "X" ] && ERROR param "${_NOARGS}" 0
fileXml=$1
tag=$2
(( $# > 2 )) && shift 2 && attributes=$*
(( $# > 1 )) && MULTIPLE_ATTR=true
[ -d "${fileXml}" -o ! -s "${fileXml}" ] && ERROR empty "${fileXml}" 0 && return 1
$XAPPLY && $MULTIPLE_ATTR && [ -z "${XATTRIBUTE}" ] && ERROR param "-x command " 0 && return 2
# nb attributes == 1 because $MULTIPLE_ATTR is false
[ "${attributes}" == "content" ] && GETCONTENT=true
while xml_read_dom; do
# (( CR != 0 )) && break
(( PIPESTATUS[1] != 0 )) && break
if $ITSACOMMENT; then
# oh wait it doesn't work on IBM AIX bash 3.2.16(1):
# if [ "x${COMMENTS:(-2):2}x" == "x--x" ]; then COMMENTS="${COMMENTS:0:(-2)}" && ITSACOMMENT=false
# elif [ "x${COMMENTS:(-3):3}x" == "x-->x" ]; then COMMENTS="${COMMENTS:0:(-3)}" && ITSACOMMENT=false
if [ "x${COMMENTS:${#COMMENTS} - 2:2}x" == "x--x" ]; then COMMENTS="${COMMENTS:0:${#COMMENTS} - 2}" && ITSACOMMENT=false
elif [ "x${COMMENTS:${#COMMENTS} - 3:3}x" == "x-->x" ]; then COMMENTS="${COMMENTS:0:${#COMMENTS} - 3}" && ITSACOMMENT=false
fi
$Debug && echo2 "${N}${COMMENTS}${END}"
elif test "${TAG_NAME}"; then
if [ "x${TAG_NAME}x" == "x${tag}x" -o "x${tag}x" == "xanyx" ]; then
if $GETCONTENT; then
CONTENT="$(trim "${CONTENT}")"
test ${CONTENT} && echo "${CONTENT}"
else
# eval local $ATTRIBUTES => eval test "\"\$${attribute}\"" will be true for matching attributes
eval local $ATTRIBUTES
$Debug && (echo2 "${m}${TAG_NAME}: ${M}$ATTRIBUTES${END}"; test ${CONTENT} && echo2 "${m}CONTENT=${M}$CONTENT${END}")
if test "${attributes}"; then
if $MULTIPLE_ATTR; then
# we don't print "tag: attr=x ..." for a tag passed as argument: it's usefull only for "any" tags so then we print the matching tags found
! $LIGHT && [ "x${tag}x" == "xanyx" ] && tag2print="${g6}${TAG_NAME}: "
for attribute in ${attributes}; do
! $LIGHT && attribute2print="${g10}${attribute}${g6}=${g14}"
if eval test "\"\$${attribute}\""; then
test "${tag2print}" && ${print} "${tag2print}"
TAGPRINTED=true; unset tag2print
if [ "$XAPPLY" == "true" -a "${attribute}" == "${XATTRIBUTE}" ]; then
eval ${print} "%s%s\ " "\${attribute2print}" "\${${XAPPLIED_COLOR}}\"\$(\$XCOMMAND \$${attribute})\"\${END}" && eval unset ${attribute}
else
eval ${print} "%s%s\ " "\${attribute2print}" "\"\$${attribute}\"" && eval unset ${attribute}
fi
fi
done
# this trick prints a CR only if attributes have been printed durint the loop:
$TAGPRINTED && ${print} "\n" && TAGPRINTED=false
else
if eval test "\"\$${attributes}\""; then
if $XAPPLY; then
eval echo "\${g}\$(\$XCOMMAND \$${attributes})" && eval unset ${attributes}
else
eval echo "\$${attributes}" && eval unset ${attributes}
fi
fi
fi
else
echo eval $ATTRIBUTES >>$TMP
fi
fi
fi
fi
unset CR TAG_NAME ATTRIBUTES CONTENT COMMENTS
done < "${fileXml}" | ${PROSTPROCESS}
# http://mywiki.wooledge.org/BashFAQ/024
# INFO: I set variables in a "while loop" that's in a pipeline. Why do they disappear? workaround:
if [ -s "$TMP" ]; then
$FORCE_PRINT && ! $LIGHT && cat $TMP
# $FORCE_PRINT && $LIGHT && perl -pe 's/[[:space:]].*?=/ /g' $TMP
$FORCE_PRINT && $LIGHT && sed -r 's/[^\"]*([\"][^\"]*[\"][,]?)[^\"]*/\1 /g' $TMP
. $TMP
rm -f $TMP
fi
unset ITSACOMMENT
}
and lastly, the rtrim, trim and echo2 (to stderr) functions:
rtrim() {
local var=$@
var="${var%"${var##*[![:space:]]}"}" # remove trailing whitespace characters
echo -n "$var"
}
trim() {
local var=$@
var="${var#"${var%%[![:space:]]*}"}" # remove leading whitespace characters
var="${var%"${var##*[![:space:]]}"}" # remove trailing whitespace characters
echo -n "$var"
}
echo2() { echo -e "$@" 1>&2; }
oh and you will need some neat colorizing dynamic variables to be defined at first, and exported, too:
set -a
TERM=xterm-256color
case ${UNAME} in
AIX|SunOS)
M=$(${print} '\033[1;35m')
m=$(${print} '\033[0;35m')
END=$(${print} '\033[0m')
;;
*)
m=$(tput setaf 5)
M=$(tput setaf 13)
# END=$(tput sgr0) # issue on Linux: it can produces ^[(B instead of ^[[0m, more likely when using screenrc
END=$(${print} '\033[0m')
;;
esac
# 24 shades of grey:
for i in $(seq 0 23); do eval g$i="$(${print} \"\\033\[38\;5\;$((232 + i))m\")" ; done
# another way of having an array of 5 shades of grey:
declare -a colorNums=(238 240 243 248 254)
for num in 0 1 2 3 4; do nn[$num]=$(${print} "\033[38;5;${colorNums[$num]}m"); NN[$num]=$(${print} "\033[48;5;${colorNums[$num]}m"); done
# piped decolorization:
DECOLORIZE='eval sed "s,${END}\[[0-9;]*[m|K],,g"'
Either you know how to create functions and load them via FPATH (ksh) or an emulation of FPATH (bash)
If not, just copy/paste everything on the command line.
xml_read [-cdlp] [-x command <-a attribute>] <file.xml> [tag | "any"] [attributes .. | "content"]
-c = NOCOLOR
-d = Debug
-l = LIGHT (no \"attribute=\" printed)
-p = FORCE PRINT (when no attributes given)
-x = apply a command on an attribute and print the result instead of the former value, in green color
(no attribute given will load their values into your shell as $ATTRIBUTE=value; use '-p' to print them as well)
xml_read server.xml title content # print content between <title></title>
xml_read server.xml Connector port # print all port values from Connector tags
xml_read server.xml any port # print all port values from any tags
With Debug mode (-d) comments and parsed attributes are printed to stderr
On Windows machine you can temporarily set Java version.
For example, to change the version to Java 8, run this command on cmd
:
set JAVA_HOME=C:\\...\jdk1.8.0_65
There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:
@media only screen
and (min-width : 415px){
/* Styles */
}
@media only screen
and (min-width : 769px){
/* Styles */
}
@media only screen
and (min-width : 992px){
/* Styles */
}
But if you are writing media queries for smaller device first, then it would be something like:
@media only screen
and (max-width : 991px){
/* Styles */
}
@media only screen
and (max-width : 768px){
/* Styles */
}
@media only screen
and (max-width : 414px){
/* Styles */
}
With me I have a UIViewcontroller
, and into it I have a tableview with a custom cell on it. I map my outlet of UILabel into UItableviewcell
to the UIViewController
then got the error.
Very simple:
function myfunction($products, $field, $value)
{
foreach($products as $key => $product)
{
if ( $product[$field] === $value )
return $key;
}
return false;
}
Previous answers have defined a loop invariant in a very good way.
Following is how authors of CLRS used loop invariant to prove correctness of Insertion Sort.
Insertion Sort algorithm(as given in Book):
INSERTION-SORT(A)
for j ? 2 to length[A]
do key ? A[j]
// Insert A[j] into the sorted sequence A[1..j-1].
i ? j - 1
while i > 0 and A[i] > key
do A[i + 1] ? A[i]
i ? i - 1
A[i + 1] ? key
Loop Invariant in this case: Sub-array[1 to j-1] is always sorted.
Now let us check this and prove that algorithm is correct.
Initialization: Before the first iteration j=2. So sub-array [1:1] is the array to be tested. As it has only one element so it is sorted. Thus invariant is satisfied.
Maintenance: This can be easily verified by checking the invariant after each iteration. In this case it is satisfied.
Termination: This is the step where we will prove the correctness of the algorithm.
When the loop terminates then value of j=n+1. Again loop invariant is satisfied. This means that Sub-array[1 to n] should be sorted.
This is what we want to do with our algorithm. Thus our algorithm is correct.
ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.
BASE stands for -
Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.
Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.
for switch to another page, try with this code:
viewPager.postDelayed(new Runnable()
{
@Override
public void run()
{
viewPager.setCurrentItem(num, true);
}
}, 100);
You can use the Chakra engine in C#. Here is an article on msdn showing how:
http://code.msdn.microsoft.com/windowsdesktop/JavaScript-Runtime-Hosting-d3a13880
The following code gives you the answer. It essentially implements MAX(COUNT(*)) by using ALL. It has the advantage that it uses very basic commands and operations.
SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr HAVING COUNT(title) >= ALL
(SELECT COUNT(title)
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr)
Quite a busy one-liner, but here it is:
myarray
, is normalised with the max value at 1.0
.myarray
.0-255
range.np.uint8()
.Image.fromarray()
.And you're done:
from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))
with plt.savefig()
:
with im.save()
:
If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.
Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/
You can change order while edit design for table.
Try something like this:
@players.include?(p.name) ? false : true
#decorator.py
def makeHtmlTag(tag, *args, **kwds):
def real_decorator(fn):
css_class = " class='{0}'".format(kwds["css_class"]) \
if "css_class" in kwds else ""
def wrapped(*args, **kwds):
return "<"+tag+css_class+">" + fn(*args, **kwds) + "</"+tag+">"
return wrapped
# return decorator dont call it
return real_decorator
@makeHtmlTag(tag="b", css_class="bold_css")
@makeHtmlTag(tag="i", css_class="italic_css")
def hello():
return "hello world"
print hello()
You can also write decorator in Class
#class.py
class makeHtmlTagClass(object):
def __init__(self, tag, css_class=""):
self._tag = tag
self._css_class = " class='{0}'".format(css_class) \
if css_class != "" else ""
def __call__(self, fn):
def wrapped(*args, **kwargs):
return "<" + self._tag + self._css_class+">" \
+ fn(*args, **kwargs) + "</" + self._tag + ">"
return wrapped
@makeHtmlTagClass(tag="b", css_class="bold_css")
@makeHtmlTagClass(tag="i", css_class="italic_css")
def hello(name):
return "Hello, {}".format(name)
print hello("Your name")
I have a single form and display where I "add / delete / edit / insert / move" data records using one form and one submit button. What I do first is to check to see if the $_post is set, if not, set it to nothing. then I run through the rest of the code,
then on the actual $_post's I use switches and if / else's based on the data entered and with error checking for each data part required for which function is being used.
After it does whatever to the data, I run a function to clear all the $_post data for each section. you can hit refresh till your blue in the face it won't do anything but refresh the page and display.
So you just need to think logically and make it idiot proof for your users...
The accepted answer seems like it will search through the entire response message. This could give you false matches for cookie headers if the word "Set-Cookie" is at the beginning of a line. While it should be fine in most cases. The safer way might be to read through the message from the beginning until the first empty line which indicates the end of the message headers. This is just an alternate solution that should look for the first blank line and then use preg_grep on those lines only to find "Set-Cookie".
curl_setopt($ch, CURLOPT_HEADER, 1);
//Return everything
$res = curl_exec($ch);
//Split into lines
$lines = explode("\n", $res);
$headers = array();
$body = "";
foreach($lines as $num => $line){
$l = str_replace("\r", "", $line);
//Empty line indicates the start of the message body and end of headers
if(trim($l) == ""){
$headers = array_slice($lines, 0, $num);
$body = $lines[$num + 1];
//Pull only cookies out of the headers
$cookies = preg_grep('/^Set-Cookie:/', $headers);
break;
}
}
Here is a highly simplified but hopefully relevant view of what happens when you build your code in C++.
C++ splits the load of generating machine executable code in following different phases -
Preprocessing - This is where any macros - #define
s etc you might be using get expanded.
Compiling - Each cpp file along with all the #include
d files in that file directly or indirectly (together called a compilation unit) is converted into machine readable object code.
This is where C++ also checks that all functions defined (i.e. containing a body in {
}
e.g.
void Foo( int x){ return Boo(x); })
are referring to other functions in a valid manner.
The way it does that is by insisting that you provide at least a declaration of these other functions (e.g. void Boo(int);
) before you call it so it can check that you are calling it properly among other things. This can be done either directly in the cpp file where it is called or usually in an included header file.
Note that only the machine code that corresponds to functions defined in this cpp and included files gets built as the object (binary) version of this compilation unit (e.g. Foo) and not the ones that are merely declared (e.g. Boo).
Linking - This is the stage where C++ goes hunting for stuff declared and called in each compilation unit and links it to the places where it is getting called. Now if there was no definition found of this function the linker gives up and errors out. Similarly if it finds multiple definitions of the same function signature (essentially the name and parameter types it takes) it also errors out as it considers it ambiguous and doesn't want to pick one arbitrarily.
The latter is what is happening in your case. By doing a #include
of the fun.cpp
file, both fun.cpp
and mainfile.cpp
have a definition of funct()
and the linker doesn't know which one to use in your program and is complaining about it.
The fix as Vaughn mentioned above is to not include the cpp file with the definition of funct()
in mainfile.cpp
and instead move the declaration of funct()
in a separate header file and include that in mainline.cpp
. This way the compiler will get the declaration of funct()
to work with and the linker would get just one definition of funct()
from fun.cpp
and will use it with confidence.
BrowserStack.com
On this site, you can emulate a lot of iOS's devices online.
It is possible to have private methods in classes using WeakMap
.
The WeakMap object is a collection of key/value pairs in which the keys are objects only and the values can be arbitrary values.
The object references in the keys are held weakly, meaning that they are a target of garbage collection (GC) if there is no other reference to the object anymore.
And this is an example of creating Queue
data structure with a private member _items
which holds an array.
const _items = new WeakMap();
class Queue {
constructor() {
_items.set(this, []);
}
enqueue( item) {
_items.get(this).push(item);
}
get count() {
return _items.get(this).length;
}
peek() {
const anArray = _items.get(this);
if( anArray.length == 0)
throw new Error('There are no items in array!');
if( anArray.length > 0)
return anArray[0];
}
dequeue() {
const anArray = _items.get(this);
if( anArray.length == 0)
throw new Error('There are no items in array!');
if( anArray.length > 0)
return anArray.splice(0, 1)[0];
}
}
An example of using:
const c = new Queue();
c.enqueue("one");
c.enqueue("two");
c.enqueue("three");
c.enqueue("four");
c.enqueue("five");
console.log(c);
Private member _items
is hided and cannot be seen in properties or methods of an Queue
object:
However, private member _items
in the Queue
object can be reached using this way:
const anArray = _items.get(this);
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
I came across this error while attempting to pass an un-encrypted file path to the Decrypt method.The solution was to check if the passed file is encrypted first before attempting to decrypt
if (Sec.IsFileEncrypted(e.File.FullName))
{
var stream = Sec.Decrypt(e.File.FullName);
}
else
{
// non-encrypted scenario
}
When you make the call to gcc it should say
g++ -Wall -I/home/alwin/Development/Calculator/ -L/opt/lib main.cpp -lcalc -o calculator
not -libcalc.so
I have a similar problem with auto-generated makes.
You can create a soft link from your compile directory to the library directory. Then the library becomes "local".
cd /compile/directory
ln -s /path/to/libcalc.so libcalc.so
The best way I know to sort HTML table with javascript is with the following function.
Just pass to it the id of the table you'd like to sort and the column number on the row. it assumes that the column you are sorting is numeric or has numbers in it and will do regex replace to get the number itself (great for currencies and other numbers with symbols in it).
function sortTable(table_id, sortColumn){
var tableData = document.getElementById(table_id).getElementsByTagName('tbody').item(0);
var rowData = tableData.getElementsByTagName('tr');
for(var i = 0; i < rowData.length - 1; i++){
for(var j = 0; j < rowData.length - (i + 1); j++){
if(Number(rowData.item(j).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, "")) < Number(rowData.item(j+1).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, ""))){
tableData.insertBefore(rowData.item(j+1),rowData.item(j));
}
}
}
}
Using example:
$(function(){
// pass the id and the <td> place you want to sort by (td counts from 0)
sortTable('table_id', 3);
});
For Windows - Should work for other OS as well
Netbeans is just like any other java application which requires tuning for its JVM.
Please read the following link to have some benchmark results for netbeans
https://performance.netbeans.org/reports/gc/
The following settings works fine in my Windows 7 PC with 4GB RAM and I5 Quad core processor.
(Check for the line netbeans_default_options in the netbeans config file inside bin folder and replace the config line as follows)
netbeans_default_options="-XX:TargetSurvivorRatio=1 -Xverify:none -XX:PermSize=100M -Xmx500m -Xms500m -XX+UseParallelGC ${netbeans_default_options}"
Small Suggestion: Garbage collection plays a vital part in JVM heap size and since I had a quad core processor, I used Parallel GC. If you have single thread processor, please use UseSerialGC. From my experience, if Xmx Xms values are same, there is no performance overhead for JVM to switch between min and max values. In my case, whenever my app size tries to exceed 500MB, the parallel GC comes in handy to cleanup unwanted garbage so my app never exceed 500MB in my PC.
In my case, I just wanted the text from a specific area of the PDF document so I used a rectangle around the area and extracted the text from it. In the sample below the coordinates are for the entire page. I don't have PDF authoring tools so when it came time to narrow down the rectangle to the specific location I took a few guesses at the coordinates until the area was found.
Rectangle _pdfRect = new Rectangle(0f, 0f, 612f, 792f); // Entire page - PDF coordinate system 0,0 is bottom left corner. 72 points / inch
RenderFilter _renderfilter = new RegionTextRenderFilter(_pdfRect);
ITextExtractionStrategy _strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), _filter);
string _text = PdfTextExtractor.GetTextFromPage(_pdfReader, 1, _strategy);
As noted by the above comments the resulting text doesn't maintain any of the formatting found in the PDF document, however, I was happy that it did preserve the carriage returns. In my case, there were enough constants in the text that I was able to extract the values that I required.
<script>
var url= "http://www.google.com";
window.location = url;
</script>
This also happens when using empty on a function return:
!empty(trim($someText)) and doSomething()
because empty is not a function but a language construct (not sure), and it only takes variables:
Right:
empty($someVar)
Wrong:
empty(someFunc())
Since PHP 5.5, it supports more than variables. But if you need it before 5.5, use trim($name) == false
. From empty documentation.
Why cant I do this:
List<Object> object = new List<Object>();
You can't do this because List
is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List
include ArrayList
, LinkedList
etc.
Here is how one would create an instance of ArrayList
:
List<Object> object = new ArrayList<Object>();
I have a method that returns a
List<?>
, how would I turn that into aList<Object>
Show us the relevant code and I'll update the answer.
If this is nullable int field then yes.
update TableName
set FiledName = null
where Id = SomeId
If you have a github account and don't want to download software, you can export to github, then download a zip from github.
The approach is to use geometry with animations applied. Add the required geometry to the Path and animate its RotateTransform from 0-360°.
My spinner support two types of spinners:
And the central logic looks like:
if(spinner.SpinnerType == SpinnerType.Ring)
{
double innerRad = spinner.Radius - spinner.ItemRadius;
Point center = new Point(0, 0);
grp.Children.Add(new EllipseGeometry( center, spinner.Radius, spinner.Radius));
grp.Children.Add(new EllipseGeometry(center, innerRad, innerRad));
return;
}
var points = GetPointsOnCircle( spinner.Diameter/ 2);
double r = spinner.ItemRadius;
foreach (var point in points)
{
grp.Children.Add(new EllipseGeometry(point, r, r));
r -= spinner.ContinuousSizeReduction;
}
Usage is as simple as follows:
<local:SpinnerControl Diameter="60" Fill="#FFE8B311"/>
Here is the source code!
Use transform: rotate(90deg)
:
#container_2 {_x000D_
border: 1px solid;_x000D_
padding: .5em;_x000D_
width: 5em;_x000D_
height: 5em;_x000D_
transition: .3s all; /* rotate gradually instead of instantly */_x000D_
}_x000D_
_x000D_
#container_2:hover {_x000D_
-webkit-transform: rotate(90deg); /* to support Safari and Android browser */_x000D_
-ms-transform: rotate(90deg); /* to support IE 9 */_x000D_
transform: rotate(90deg);_x000D_
}
_x000D_
<div id="container_2">This box should be rotated 90° on hover.</div>
_x000D_
Click "Run code snippet", then hover over the box to see the effect of the transform.
Realistically, no other prefixed entries are needed. See Can I use CSS3 Transforms?
There's a good discussion of this issue here.
I ran into the same architectural problem: wanting a way of giving my application more organization and internal namespaces, without:
In the end, I decided to organize my code using file naming conventions rather than directories. A structure would look something like:
Then in code:
var app_config = require('./app.config');
var app_models_foo = require('./app.models.foo');
or just
var config = require('./app.config');
var foo = require('./app.models.foo');
and external dependencies are available from node_modules as usual:
var express = require('express');
In this way, all application code is hierarchically organized into modules and available to all other code relative to the application root.
The main disadvantage is of course that in a file browser, you can't expand/collapse the tree as though it was actually organized into directories. But I like that it's very explicit about where all code is coming from, and it doesn't use any 'magic'.
sorry to dig this up, I just want to share my idea, the easy way for me is to rename composer.phar to composer.bat and put it into my PATH.
Found amazing simple solution - working for Chrome (Windows, not tested on Mac)
Zebra ZP 450
Important Edit: This answer is outdated. Since writing it, the Visibility API (mdn, example, spec) has been introduced. It is the better way to solve this problem.
var focused = true;
window.onfocus = function() {
focused = true;
};
window.onblur = function() {
focused = false;
};
AFAIK, focus
and blur
are all supported on...everything. (see http://www.quirksmode.org/dom/events/index.html )
By default, Valgrind writes its output to stderr. So you need to do something like:
valgrind a.out > log.txt 2>&1
Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).
I have made a PHP script which is designed to import large database dumps which have been generated by phpmyadmin or mysql dump (from cpanel) . It's called PETMI and you can download it here [project page] [gitlab page].
It works by splitting an. sql file into smaller files called a split and processing each split one at a time. Splits which fail to process can be processed manually by the user in phpmyadmin. This can be easily programmed as in sql dumps, each command is on a new line. Some things in sql dumps work in phpmyadmin imports but not in mysqli_query so those lines have been stripped from the splits.
It has been tested with a 1GB database. It has to be uploaded to an existing website. PETMI is open source and the sample code can be seen on Gitlab.
A moderator asked me to provide some sample code. I'm on a phone so excuse the formatting.
Here is the code that creates the splits.
//gets the config page
if (isset($_POST['register']) && $_POST['register'])
{
echo " <img src=\"loading.gif\">";
$folder = "split/";
include ("config.php");
$fh = fopen("importme.sql", 'a') or die("can't open file");
$stringData = "-- --------------------------------------------------------";
fwrite($fh, $stringData);
fclose($fh);
$file2 = fopen("importme.sql","r");
//echo "<br><textarea class=\"mediumtext\" style=\"width: 500px; height: 200px;\">";
$danumber = "1";
while(! feof($file2)){
//echo fgets($file2)."<!-- <br /><hr color=\"red\" size=\"15\"> -->";
$oneline = fgets($file2); //this is fgets($file2) but formatted nicely
//echo "<br>$oneline";
$findme1 = '-- --------------------------------------------------------';
$pos1 = strpos($oneline, $findme1);
$findme2 = '-- Table structure for';
$pos2 = strpos($oneline, $findme2);
$findme3 = '-- Dumping data for';
$pos3 = strpos($oneline, $findme3);
$findme4 = '-- Indexes for dumped tables';
$pos4 = strpos($oneline, $findme4);
$findme5 = '-- AUTO_INCREMENT for dumped tables';
$pos5 = strpos($oneline, $findme5);
if ($pos1 === false && $pos2 === false && $pos3 === false && $pos4 === false && $pos5 === false) {
// setcookie("filenumber",$i);
// if ($danumber2 == ""){$danumber2 = "0";} else { $danumber2 = $danumber2 +1;}
$ourFileName = "split/sql-split-$danumber.sql";
// echo "writing danumber is $danumber";
$ourFileHandle = fopen($ourFileName, 'a') or die("can't edit file. chmod directory to 777");
$stringData = $oneline;
$stringData = preg_replace("/\/[*][!\d\sA-Za-z@_='+:,]*[*][\/][;]/", "", $stringData);
$stringData = preg_replace("/\/[*][!]*[\d A-Za-z`]*[*]\/[;]/", "", $stringData);
$stringData = preg_replace("/DROP TABLE IF EXISTS `[a-zA-Z]*`;/", "", $stringData);
$stringData = preg_replace("/LOCK TABLES `[a-zA-Z` ;]*/", "", $stringData);
$stringData = preg_replace("/UNLOCK TABLES;/", "", $stringData);
fwrite($ourFileHandle, $stringData);
fclose($ourFileHandle);
} else {
//write new file;
if ($danumber == ""){$danumber = "1";} else { $danumber = $danumber +1;}
$ourFileName = "split/sql-split-$danumber.sql";
//echo "$ourFileName has been written with the contents above.\n";
$ourFileName = "split/sql-split-$danumber.sql";
$ourFileHandle = fopen($ourFileName, 'a') or die("can't edit file. chmod directory to 777");
$stringData = "$oneline";
fwrite($ourFileHandle, $stringData);
fclose($ourFileHandle);
}
}
//echo "</textarea>";
fclose($file2);
Here is the code that imports the split
<?php
ob_start();
// allows you to use cookies
include ("config.php");
//gets the config page
if (isset($_POST['register']))
{
echo "<div id**strong text**=\"sel1\"><img src=\"loading.gif\"></div>";
// the above line checks to see if the html form has been submitted
$dbname = $accesshost;
$dbhost = $username;
$dbuser = $password;
$dbpasswd = $database;
$table_prefix = $dbprefix;
//the above lines set variables with the user submitted information
//none were left blank! We continue...
//echo "$importme";
echo "<hr>";
$importme = "$_GET[file]";
$importme = file_get_contents($importme);
//echo "<b>$importme</b><br><br>";
$sql = $importme;
$findme1 = '-- Indexes for dumped tables';
$pos1 = strpos($importme, $findme1);
$findme2 = '-- AUTO_INCREMENT for dumped tables';
$pos2 = strpos($importme, $findme2);
$dbhost = '';
@set_time_limit(0);
if($pos1 !== false){
$splitted = explode("-- Indexes for table", $importme);
// print_r($splitted);
for($i=0;$i<count($splitted);$i++){
$sql = $splitted[$i];
$sql = preg_replace("/[`][a-z`\s]*[-]{2}/", "", $sql);
// echo "<b>$sql</b><hr>";
if($table_prefix !== 'phpbb_') $sql = preg_replace('/phpbb_/', $table_prefix, $sql);
$res = mysql_query($sql);
}
if(!$res) { echo '<b>error in query </b>', mysql_error(), '<br /><br>Try importing the split .sql file in phpmyadmin under the SQL tab.'; /* $i = $i +1; */ } else {
echo ("<meta http-equiv=\"Refresh\" content=\"0; URL=restore.php?page=done&file=$filename\"/>Thank You! You will be redirected");
}
} elseif($pos2 !== false){
$splitted = explode("-- AUTO_INCREMENT for table", $importme);
// print_r($splitted);
for($i=0;$i<count($splitted);$i++){
$sql = $splitted[$i];
$sql = preg_replace("/[`][a-z`\s]*[-]{2}/", "", $sql);
// echo "<b>$sql</b><hr>";
if($table_prefix !== 'phpbb_') $sql = preg_replace('/phpbb_/', $table_prefix, $sql);
$res = mysql_query($sql);
}
if(!$res) { echo '<b>error in query </b>', mysql_error(), '<br /><br>Try importing the split .sql file in phpmyadmin under the SQL tab.'; /* $i = $i +1; */ } else {
echo ("<meta http-equiv=\"Refresh\" content=\"0; URL=restore.php?page=done&file=$filename\"/>Thank You! You will be redirected");
}
} else {
if($table_prefix !== 'phpbb_') $sql = preg_replace('/phpbb_/', $table_prefix, $sql);
$res = mysql_query($sql);
if(!$res) { echo '<b>error in query </b>', mysql_error(), '<br /><br>Try importing the split .sql file in phpmyadmin under the SQL tab.'; /* $i = $i +1; */ } else {
echo ("<meta http-equiv=\"Refresh\" content=\"0; URL=restore.php?page=done&file=$filename\"/>Thank You! You will be redirected");
}
}
//echo 'done (', count($sql), ' queries).';
}
The accepted answer is good, but it can be greatly improved by additionally backing up on every save and backing up versioned files.
First, basic settings as described in the accepted answer:
(setq version-control t ;; Use version numbers for backups.
kept-new-versions 10 ;; Number of newest versions to keep.
kept-old-versions 0 ;; Number of oldest versions to keep.
delete-old-versions t ;; Don't ask to delete excess backup versions.
backup-by-copying t) ;; Copy all files, don't rename them.
Next, also backup versioned files, which Emacs does not do by default (you don't commit on every save, right?):
(setq vc-make-backup-files t)
Finally, make a backup on each save, not just the first. We make two kinds of backups:
per-session backups: once on the first save of the buffer in each Emacs session. These simulate Emac's default backup behavior.
per-save backups: once on every save. Emacs does not do this by default, but it's very useful if you leave Emacs running for a long time.
The backups go in different places and Emacs creates the backup dirs automatically if they don't exist:
;; Default and per-save backups go here:
(setq backup-directory-alist '(("" . "~/.emacs.d/backup/per-save")))
(defun force-backup-of-buffer ()
;; Make a special "per session" backup at the first save of each
;; emacs session.
(when (not buffer-backed-up)
;; Override the default parameters for per-session backups.
(let ((backup-directory-alist '(("" . "~/.emacs.d/backup/per-session")))
(kept-new-versions 3))
(backup-buffer)))
;; Make a "per save" backup on each save. The first save results in
;; both a per-session and a per-save backup, to keep the numbering
;; of per-save backups consistent.
(let ((buffer-backed-up nil))
(backup-buffer)))
(add-hook 'before-save-hook 'force-backup-of-buffer)
I became very interested in this topic after I wrote $<
instead of
$@
in my Makefile
, about three hours after my previous commit :P
The above is based on an Emacs Wiki page I heavily edited.
For me the laziest way to allow inline inizialization is use this macro.
#define METHOD_MEMBER(TYPE, NAME, CLASS) \
CLASS &set_ ## NAME(const TYPE &_val) { NAME = _val; return *this; } \
TYPE NAME;
struct foo {
METHOD_MEMBER(string, attr1, foo)
METHOD_MEMBER(int, attr2, foo)
METHOD_MEMBER(double, attr3, foo)
};
// inline usage
foo test = foo().set_attr1("hi").set_attr2(22).set_attr3(3.14);
That macro create attribute and self reference method.
I don't know if this will work for your case, but I am running an Express.js server with this:
nodemon --inspect ./index.js --exec babel-node --presets es2015,stage-2
This gives me the ability to import and use spread operator even though I'm only using Node.js version 8.
You'll need to install babel-cli, babel-preset-es2015, and babel-preset-stage-2 to do what I'm doing.
I'd use something like:
dim customer = (from c in xmldoc...<Customer>
where c.<ID>.Value=22
select c).SingleOrDefault
Edit:
missed the c# tag, sorry......the example is in VB.NET
I had a user control which sat on page in a free form way, not constrained by another container, and the contents within the user control would not auto size but expand to the full size of what the user control was handed.
To get the user control to simply size to its content, for height only, I placed it into a grid with on row set to auto size such as this:
<Grid Margin="0,60,10,200">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<controls1:HelpPanel x:Name="HelpInfoPanel"
Visibility="Visible"
Width="570"
HorizontalAlignment="Right"
ItemsSource="{Binding HelpItems}"
Background="#FF313131" />
</Grid>
At least with Miniconda (I assume it's the same for Anaconda), within the environment folder, the packages are installed in a folder called \conda-meta.
i.e.
C:\Users\username\Miniconda3\envs\environmentname\conda-meta
If you install on the base environment, the location is:
C:\Users\username\Miniconda3\pkgs
If you don't want to alter the list:
List<Integer> list = Arrays.asList(array)
But if you want to modify it then you can use this:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(ints));
Or just use java8 like the following:
List<Integer> list = Arrays.stream(ints).collect(Collectors.toList());
Java9 has introduced this method:
List<Integer> list = List.of(ints);
However, this will return an immutable list that you can't add to.
You need to do the following to make it mutable:
List<Integer> list = new ArrayList<Integer>(List.of(ints));
Try this formula (it will return value from A1
as is if it's not a date):
=TEXT(A1,"mm-yyyy")
Or this formula (it's more strict, it will return #VALUE
error if A1
is not date):
=TEXT(MONTH(A1),"00")&"-"&YEAR(A1)
def count_letter(string):
count = 0
for i in range(len(string)):
if string[i].isalpha():
count += 1
return count
print(count_letter('The grey old fox is an idiot.'))
I'm quite a beginner in Python and I found the answer of Anand was very good but quite complicated to me, so I try to reformulate :
1) insert
and append
methods are not specific to sys.path
and as in other languages they add an item into a list or array and :
* append(item)
add item
to the end of the list,
* insert(n, item)
inserts the item
at the nth position in the list (0
at the beginning, 1
after the first element, etc ...).
2) As Anand said, python search the import files in each directory of the path in the order of the path, so :
* If you have no file name collisions, the order of the path has no impact,
* If you look after a function already defined in the path and you use append
to add your path, you will not get your function but the predefined one.
But I think that it is better to use append
and not insert
to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.
By default the database in a project in the Firebase Console is only readable/writeable by administrative users (e.g. in Cloud Functions, or processes that use an Admin SDK). Users of the regular client-side SDKs can't access the database, unless you change the server-side security rules.
You can change the rules so that the database is only readable/writeable by authenticated users:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
See the quickstart for the Firebase Database security rules.
But since you're not signing the user in from your code, the database denies you access to the data. To solve that you will either need to allow unauthenticated access to your database, or sign in the user before accessing the database.
The simplest workaround for the moment (until the tutorial gets updated) is to go into the Database panel in the console for you project, select the Rules tab and replace the contents with these rules:
{
"rules": {
".read": true,
".write": true
}
}
This makes your new database readable and writeable by anyone who knows the database's URL. Be sure to secure your database again before you go into production, otherwise somebody is likely to start abusing it.
For a (slightly) more time-consuming, but more secure, solution, call one of the signIn...
methods of Firebase Authentication to ensure the user is signed in before accessing the database. The simplest way to do this is using anonymous authentication:
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
And then attach your listeners when the sign-in is detected
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var userRef = app.dataInfo.child(app.users);
var useridRef = userRef.child(app.userid);
useridRef.set({
locations: "",
theme: "",
colorScheme: "",
food: ""
});
} else {
// User is signed out.
// ...
}
// ...
});
I believe this is the NSDate's selector you're looking for:
- (NSTimeInterval)timeIntervalSince1970
May be this could help
<script type="text/javascript" language="javascript">
function AddDays(toAdd) {
if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
var d = new Date();
d.setDate(d.getDate() + parseInt(toAdd));
document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
}
function SubtractDays(toAdd) {
if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
var d = new Date();
d.setDate(d.getDate() - parseInt(toAdd));
document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
}
</script>
---------------------- UI ---------------
<div id="result">
</div>
<input type="text" value="0" onkeyup="AddDays(this.value);" />
<input type="text" value="0" onkeyup="SubtractDays(this.value);" />
I'm using windows OS, I tried all solutions above and none of them work.
Finally, I install Tesseract-OCR on D drive(Where I run my python script from) instead of C drive and it works.
So, if you are using windows, run your python script in the same drive as your Tesseract-OCR.
My solution to avoid the infinite loop was to create another state which have made the redirection:
$stateProvider.state('app.admin.main', {
url: '/admin/main',
authenticate: 'admin',
controller: ($state, $window) => {
$state.go('app.admin.overview').then(() => {
$window.location.reload();
});
}
});
In Unity 4.3 you also had to enable External option from preferences, but since Unity 4.5 they dropped option for that, so full setup process looks like:
Visible Meta Files
in Editor ? Project Settings ? Editor ? Version Control Mode
Force Text
in Editor ? Project Settings ? Editor ? Asset Serialization Mode
File
menuAlso our team is using a bit more extended .gitignore
file:
# =============== #
# Unity generated #
# =============== #
Temp/
Library/
# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
obj/
*.svd
*.userprefs
/*.csproj
*.pidb
*.suo
/*.sln
*.user
*.unityproj
*.booproj
# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
Note that the only folders you need to keep under source control are Assets
and ProjectSettings
.
More information about keeping Unity Project under source control you can find in this post.
The difference between an operating system and a kernel:
The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:
Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.
It supports box-shadow
(except for the inset
keyword).
this
is a HTML element.
$(this)
is a jQuery object that encapsulates the HTML element.
Use $(this).text()
to retrieve the element's inner text.
I suggest you refer to the jQuery API documentation for further information.
Edit: Sorry, this won't work for you. I just remembered the line color thing is in 4.2. I ran into this problem in the past and my fix was to upgrade gnuplot.
You can control the color with set style line as well. "lt 3" will give you a dashed line while "lt 1" will give you a solid line. To add color, you can use "lc rgb 'color'". This should do what you need:
set style line 1 lt 1 lw 3 pt 3 lc rgb "red"
set style line 2 lt 3 lw 3 pt 3 lc rgb "red"
set style line 3 lt 1 lw 3 pt 3 lc rgb "blue"
set style line 4 lt 3 lw 3 pt 3 lc rgb "blue"
For simulating keyboard events in Chrome:
There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735
A working solution for it is posted in this SO answer.
First install "Microsoft ASP.NET Web API Client" nuget package:
PM > Install-Package Microsoft.AspNet.WebApi.Client
Then use the following function to post your data:
public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
using (var httpClient = new HttpClient())
{
using (var content = new FormUrlEncodedContent(postData))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
return await response.Content.ReadAsAsync<TResult>();
}
}
}
And this is how to use it:
TokenResponse tokenResponse =
await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);
or
TokenResponse tokenResponse =
(Task.Run(async ()
=> await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
.Result
or (not recommended)
TokenResponse tokenResponse =
PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;
Logical Vs Physical Address space
An address generated by the CPU is commonly refereed as Logical Address,whereas the address seen by the memory unit,that is one loaded into the memory address register of the memory is commonly refereed as the Physical Address.The compile time and load time address binding generates the identical logical and physical addresses.However, the execution time address binding scheme results in differing logical and physical addresses.
The set of all logical addresses generated by a program is known as Logical Address Space,whereas the set of all physical addresses corresponding to these logical addresses is Physical Address Space.Now, the run time mapping from virtual address to physical address is done by a hardware device known as Memory Management Unit.Here in the case of mapping the base register is known as relocation register.The value in the relocation register is added to the address generated by a user process at the time it is sent to memory.Let's understand this situation with the help of example:If the base register contains the value 1000,then an attempt by the user to address location 0 is dynamically relocated to location 1000,an access to location 346 is mapped to location 1346.
The user program never sees the real physical address space,it always deals with the Logical addresses.As we have two different type of addresses Logical address in the range (0 to max) and Physical addresses in the range(R to R+max) where R is the value of relocation register.The user generates only logical addresses and thinks that the process runs in location to 0 to max.As it is clear from the above text that user program supplies only logical addresses,these logical addresses must be mapped to physical address before they are used.
=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")
For posterity, I ran into this with an azure function, using the azure durable function / durable tasks framework. It turns out I had an outdated version of the azure functions runtime installed locally. updating it fixed it.
Easy solution if you don't want to code manually using Google Sheets Power Tools:
I have now come up with an own solution to this:
1. Created a general function to extract specific attributes from arrays
The function below extract only specific attributes from an associative array, or an array of associative arrays (the last is what you get when doing $collection->toArray() in Laravel).
It can be used like this:
$data = array_extract( $collection->toArray(), ['id','url'] );
I am using the following functions:
function array_is_assoc( $array )
{
return is_array( $array ) && array_diff_key( $array, array_keys(array_keys($array)) );
}
function array_extract( $array, $attributes )
{
$data = [];
if ( array_is_assoc( $array ) )
{
foreach ( $attributes as $attribute )
{
$data[ $attribute ] = $array[ $attribute ];
}
}
else
{
foreach ( $array as $key => $values )
{
$data[ $key ] = [];
foreach ( $attributes as $attribute )
{
$data[ $key ][ $attribute ] = $values[ $attribute ];
}
}
}
return $data;
}
This solution does not focus on performance implications on looping through the collections in large datasets.
2. Implement the above via a custom collection i Laravel
Since I would like to be able to simply do $collection->extract('id','url');
on any collection object, I have implemented a custom collection class.
First I created a general Model, which extends the Eloquent model, but uses a different collection class. All you models need to extend this custom model, and not the Eloquent Model then.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Lib\Collection;
class Model extends EloquentModel
{
public function newCollection(array $models = [])
{
return new Collection( $models );
}
}
?>
Secondly I created the following custom collection class:
<?php
namespace Lib;
use Illuminate\Support\Collection as EloquentCollection;
class Collection extends EloquentCollection
{
public function extract()
{
$attributes = func_get_args();
return array_extract( $this->toArray(), $attributes );
}
}
?>
Lastly, all models should then extend your custom model instead, like such:
<?php
namespace App\Models;
class Article extends Model
{
...
Now the functions from no. 1 above are neatly used by the collection to make the $collection->extract()
method available.
In Eclipse
Right click Project --> Java Build Path --> Libraries
I guess you may have already found the answer, but if not (and for other developers), you can do it like this:
btnMybutton.getBackground().setAlpha(45);
Here I have set the opacity to 45. You can basically set it from anything between 0(fully transparent) to 255 (completely opaque)
I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\
) character:
Hello
\
\
\
World!
This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:
World!
Personally I find this cleaner for a large number of line breaks compared to using <br>
.
Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.
It could be that the resource you're trying to request is under restricted access via your web app configuration, i.e. user must be logged for the application to serve the file.
Try adding this to your Web.Config file (this is for .NET applications):
<location path="js/resourcefile.js">
<system.web>
<authorization>
<allow users="?" />
</authorization>
</system.web>
</location>
You can place it anywhere before the closing configuration tag.
This is documented on ?logical
. The pertinent section of which is:
Details:
‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
in the R language, whereas ‘T’ and ‘F’ are global variables whose
initial values set to these. All four are ‘logical(1)’ vectors.
Logical vectors are coerced to integer vectors in contexts where a
numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.
The second paragraph there explains the behaviour you are seeing, namely 5 == 1L
and 5 == 0L
respectively, which should both return FALSE
, where as 1 == 1L
and 0 == 0L
should be TRUE for 1 == TRUE
and 0 == FALSE
respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE
and FALSE
in R, i.e. what numeric values they take when coerced to numeric.
However, only TRUE
is guaranteed to the be TRUE
:
> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE
isTRUE
is a wrapper for identical(x, TRUE)
, and from ?isTRUE
we note:
Details:
....
‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
true if and only if ‘x’ is a length-one logical vector whose only
element is ‘TRUE’ and which has no attributes (not even names).
So by the same virtue, only FALSE
is guaranteed to be exactly equal to FALSE
.
> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE
If this concerns you, always use isTRUE()
or identical(x, FALSE)
to check for equivalence with TRUE
and FALSE
respectively. ==
is not doing what you think it is.
Change your return type to java.lang.Integer . This way you can safely return null
Just another clarification for those starting out. When you add C:\PythonXX
to your path, make sure there are NO SPACES between variables e.g.
This:
SomeOtherDirectory;C:\Python27
Not this:
SomeOtherDirectory; C:\Python27
That took me a good 15 minutes of headache to figure out (I'm on windows 7, might be OS dependent). Happy coding.
A pandas MultiIndex consists of a list of tuples. So the most natural approach would be to reshape your input dict so that its keys are tuples corresponding to the multi-index values you require. Then you can just construct your dataframe using pd.DataFrame.from_dict
, using the option orient='index'
:
user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},
'Category 2': {'att_1': 23, 'att_2': 'another'}},
15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},
'Category 2': {'att_1': 30, 'att_2': 'bar'}}}
pd.DataFrame.from_dict({(i,j): user_dict[i][j]
for i in user_dict.keys()
for j in user_dict[i].keys()},
orient='index')
att_1 att_2
12 Category 1 1 whatever
Category 2 23 another
15 Category 1 10 foo
Category 2 30 bar
An alternative approach would be to build your dataframe up by concatenating the component dataframes:
user_ids = []
frames = []
for user_id, d in user_dict.iteritems():
user_ids.append(user_id)
frames.append(pd.DataFrame.from_dict(d, orient='index'))
pd.concat(frames, keys=user_ids)
att_1 att_2
12 Category 1 1 whatever
Category 2 23 another
15 Category 1 10 foo
Category 2 30 bar
I already found the solution to this problem which I forgot to post here.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {
@Mock
Person person;
@Test
public void testPrintName() throws Exception {
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Test test= new Test();
test.testMethod();
}
}
Key points to this solution are:
Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)
Instruct Powermock to prepare Test.class
for manipulation of private fields: @PrepareForTest({ Test.class })
And finally mock the constructor for Person class:
PowerMockito.mockStatic(Person.class);
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
before(default)
implementation fileTree(include: ['*.jar'], dir: 'libs')
just add '*.aar'
in include
array.
implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
it works well on Android Studio 3.x.
if you want ignore some library? do like this.
implementation fileTree(include: ['*.jar', '*.aar'], exclude: 'test_aar*', dir: 'libs')
debugImplementation files('libs/test_aar-debug.aar')
releaseImplementation files('libs/test_aar-release.aar')
try this
select *
from
(
select
sal
,dense_rank() over (order by sal desc) ranking
from table
)
where ranking = 4 -- Replace 4 with any value of N
Another Solution!
If you want to set widgets in center vertical form, you can use ListView for it. for eg: I used three buttons and add them inside ListView which followed by
shrinkWrap: true -> With this ListView only occupies the space which needed.
import 'package:flutter/material.dart';
class List extends StatelessWidget {
@override
Widget build(BuildContext context) {
final button1 =
new RaisedButton(child: new Text("Button1"), onPressed: () {});
final button2 =
new RaisedButton(child: new Text("Button2"), onPressed: () {});
final button3 =
new RaisedButton(child: new Text("Button3"), onPressed: () {});
final body = new Center(
child: ListView(
shrinkWrap: true,
children: <Widget>[button1, button2, button3],
),
);
return new Scaffold(
appBar: new AppBar(
title: Text("Sample"),
),
body: body);
}
}
void main() {
runApp(new MaterialApp(
home: List(),
));
}
Include coffee-script in package.json with the specific version required in each project, typically like this:
"dependencies":{
"coffee-script": ">= 1.2.0"
Then run npm install to install dependencies in each project. This will install the specified version of coffee-script which will be accessible locally to each project.
The ApplicationPoolIdentity
is assigned membership of the Users
group as well as the IIS_IUSRS
group. On first glance this may look somewhat worrying, however the Users
group has somewhat limited NTFS rights.
For example, if you try and create a folder in the C:\Windows
folder then you'll find that you can't. The ApplicationPoolIdentity
still needs to be able to read files from the windows system folders (otherwise how else would the worker process be able to dynamically load essential DLL's).
With regard to your observations about being able to write to your c:\dump
folder. If you take a look at the permissions in the Advanced Security Settings, you'll see the following:
See that Special permission being inherited from c:\
:
That's the reason your site's ApplicationPoolIdentity
can read and write to that folder. That right is being inherited from the c:\
drive.
In a shared environment where you possibly have several hundred sites, each with their own application pool and Application Pool Identity, you would store the site folders in a folder or volume that has had the Users
group removed and the permissions set such that only Administrators and the SYSTEM account have access (with inheritance).
You would then individually assign the requisite permissions each IIS AppPool\[name]
requires on it's site root folder.
You should also ensure that any folders you create where you store potentially sensitive files or data have the Users
group removed. You should also make sure that any applications that you install don't store sensitive data in their c:\program files\[app name]
folders and that they use the user profile folders instead.
So yes, on first glance it looks like the ApplicationPoolIdentity
has more rights than it should, but it actually has no more rights than it's group membership dictates.
An ApplicationPoolIdentity
's group membership can be examined using the SysInternals Process Explorer tool. Find the worker process that is running with the Application Pool Identity you're interested in (you will have to add the User Name
column to the list of columns to display:
For example, I have a pool here named 900300
which has an Application Pool Identity of IIS APPPOOL\900300
. Right clicking on properties for the process and selecting the Security tab we see:
As we can see IIS APPPOOL\900300
is a member of the Users
group.
Maybe not the best dev-ops solution, but good for the general use of a server for a lan party or similar.
Use screen
to run your server in and then detach before logging out, this will keep the process running, you can then re-attach at any point.
Workflow:
Start a screen: screen
Start your server: java -jar minecraft-server.jar
Detach by pressing: Ctl-a
, d
Re-attach: screen -r
More info here: https://www.gnu.org/software/screen/manual/screen.html
Date.parse()
isn't a constructor, its a static method.
So, just use
var timeInMillis = Date.parse(s);
instead of
var timeInMillis = new Date.parse(s);
No, there is no chance to do that. You just learned how important a backup can be.
It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.
It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.
Query Builder:
DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();
Eloquent:
SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();
you must import the image first then use it. It worked for me.
import image from '../image.png'
const Header = () => {
return (
<img src={image} alt='image' />
)
}
As you said the event window.onbeforeunload fires when the users clicks on a link or refreshes the page, so it would not a good even to end a session.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx describes all situations where window.onbeforeonload is triggered. (IE)
However, you can place a JavaScript global variable on your pages to identify actions that should not trigger a logoff (by using an AJAX call from onbeforeonload, for example).
The script below relies on JQuery
/*
* autoLogoff.js
*
* Every valid navigation (form submit, click on links) should
* set this variable to true.
*
* If it is left to false the page will try to invalidate the
* session via an AJAX call
*/
var validNavigation = false;
/*
* Invokes the servlet /endSession to invalidate the session.
* No HTML output is returned
*/
function endSession() {
$.get("<whatever url will end your session>");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
This script may be included in all pages
<script type="text/javascript" src="js/autoLogoff.js"></script>
Let's go through this code:
var validNavigation = false;
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
A global variable is defined at page level. If this variable is not set to true then the event windows.onbeforeonload will terminate the session.
An event handler is attached to every link and form in the page to set this variable to true, thus preventing the session from being terminated if the user is just submitting a form or clicking on a link.
function endSession() {
$.get("<whatever url will end your session>");
}
The session is terminated if the user closed the browser/tab or navigated away. In this case the global variable was not set to true and the script will do an AJAX call to whichever URL you want to end the session
This solution is server-side technology agnostic. It was not exaustively tested but it seems to work fine in my tests
Adding on to @Rob Hruska's sol, this setting in server.xml inside section works:
<Context path="" docBase="gateway" reloadable="true" override="true"> </Context>
Note: override="true" might be required in some cases.
attr_accessor
is getter
, setter
method.
whereas attr_accessible
is to say that particular attribute is accessible or not. that's it.
I wish to add we should use Strong parameter instead of attr_accessible
to protect from mass asignment.
Cheers!
I tried this and it is working fine!
var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);
Index is the position where you want to insert or delete the element. 0 i.e. the second parameters defines the number of element from the index to be removed item are the new entries which you want to make in array. It can be one or more than one.
initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");
I'd like to share my experience of using Ant in building projects, *.properties files should be copied explicitly. This is because Ant will not compile *.properties files into the build working directory by default (javac just ignore *.properties). For example:
<target name="compile" depends="init">
<javac destdir="${dst}" srcdir="${src}" debug="on" encoding="utf-8" includeantruntime="false">
<include name="com/example/**" />
<classpath refid="libs" />
</javac>
<copy todir="${dst}">
<fileset dir="${src}" includes="**/*.properties" />
</copy>
</target>
<target name="jars" depends="compile">
<jar jarfile="${app_jar}" basedir="${dst}" includes="com/example/**/*.*" />
</target>
Please notice that 'copy' section under the 'compile' target, it will replicate *.properties files into the build working directory. Without the 'copy' section the jar file will not contain the properties files, then you may encounter the java.util.MissingResourceException.
Python is a pure pass-by-value language if you think about it the right way. A python variable stores the location of an object in memory. The Python variable does not store the object itself. When you pass a variable to a function, you are passing a copy of the address of the object being pointed to by the variable.
Contrasst these two functions
def foo(x):
x[0] = 5
def goo(x):
x = []
Now, when you type into the shell
>>> cow = [3,4,5]
>>> foo(cow)
>>> cow
[5,4,5]
Compare this to goo.
>>> cow = [3,4,5]
>>> goo(cow)
>>> goo
[3,4,5]
In the first case, we pass a copy the address of cow to foo and foo modified the state of the object residing there. The object gets modified.
In the second case you pass a copy of the address of cow to goo. Then goo proceeds to change that copy. Effect: none.
I call this the pink house principle. If you make a copy of your address and tell a painter to paint the house at that address pink, you will wind up with a pink house. If you give the painter a copy of your address and tell him to change it to a new address, the address of your house does not change.
The explanation eliminates a lot of confusion. Python passes the addresses variables store by value.
You didn't publish your code, and I suspect you do something wrong. it is possible to change the size by assigning width and height attributes using numbers:
canvasNode.width = 200; // in pixels
canvasNode.height = 100; // in pixels
At least it works for me. Make sure you don't assign strings (e.g., "2cm", "3in", or "2.5px"), and don't mess with styles.
Actually this is a publicly available knowledge — you can read all about it in the HTML canvas spec — it is very small and unusually informative. This is the whole DOM interface:
interface HTMLCanvasElement : HTMLElement {
attribute unsigned long width;
attribute unsigned long height;
DOMString toDataURL();
DOMString toDataURL(in DOMString type, [Variadic] in any args);
DOMObject getContext(in DOMString contextId);
};
As you can see it defines 2 attributes width
and height
, and both of them are unsigned long
.
Thank for the wonderful solution of @paulkerfeld. On top of his solution, for all those who want to have a serialized version of trees, just use tree.threshold
, tree.children_left
, tree.children_right
, tree.feature
and tree.value
. Since the leaves don't have splits and hence no feature names and children, their placeholder in tree.feature
and tree.children_***
are _tree.TREE_UNDEFINED
and _tree.TREE_LEAF
. Every split is assigned a unique index by depth first search
.
Notice that the tree.value
is of shape [n, 1, 1]
Maven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window|Preferences|Maven|User Settings
. If the file doesn't exist, create it and put on something like this:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies>
<proxy>
<id>myproxy</id>
<active>true</active>
<protocol>http</protocol>
<host>192.168.1.100</host>
<port>6666</port>
<username></username>
<password></password>
<nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
</proxy>
</proxies>
<profiles/>
<activeProfiles/>
</settings>
After editing the file, it's just a matter of clicking on Update Settings
button and it's done. I've just done it and it worked :)
If you just want to test a library from the command line, you could do:
cat somelibrary.js mytestfile.js | node
try clean Tomcat working directory,it works for me
It depends from the database you use. Here is an incomplete list:
.schema table_name
\d table_name
sp_help table_name
(or sp_columns table_name
for only columns)desc table_name
or describe table_name
describe table_name
(or show columns from table_name
for only columns)Aside from the GC questions, for performance one should consider the optimizations that the browser may be doing in the background ->
http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/
It appears it may be better to null the reference than to delete it as that may change the behind-the-scenes 'class' Chrome uses.
Simpler than the accepted answer is this:
public static Bitmap cropAtRect(this Bitmap b, Rectangle r)
{
Bitmap nb = new Bitmap(r.Width, r.Height);
using (Graphics g = Graphics.FromImage(nb))
{
g.DrawImage(b, -r.X, -r.Y);
return nb;
}
}
and it avoids the "Out of memory" exception risk of the simplest answer.
Note that Bitmap
and Graphics
are IDisposable
hence the using
clauses.
EDIT: I find this is fine with PNGs saved by Bitmap.Save
or Paint.exe, but fails with PNGs saved by e.g. Paint Shop Pro 6 - the content is displaced. Addition of GraphicsUnit.Pixel
gives a different wrong result. Perhaps just these failing PNGs are faulty.
I didn't like how I had to explicitly specify all the other column in the other solutions so this worked best for me. Though it might be slow for large dataframes...?
df = df.set_index('Mid').reset_index()
This script exports rows from specified tables to the CSV format in the output window for any tables structure. Hope, the script will be helpful for you -
DECLARE
@TableName SYSNAME
, @ObjectID INT
DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR
SELECT
'[' + s.name + '].[' + t.name + ']'
, t.[object_id]
FROM (
SELECT DISTINCT
t.[schema_id]
, t.[object_id]
, t.name
FROM sys.objects t WITH (NOWAIT)
JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
WHERE p.[rows] > 0
AND t.[type] = 'U'
) t
JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
WHERE t.name IN ('<your table name>')
OPEN [tables]
FETCH NEXT FROM [tables] INTO
@TableName
, @ObjectID
DECLARE
@SQLInsert NVARCHAR(MAX)
, @SQLColumns NVARCHAR(MAX)
, @SQLTinyColumns NVARCHAR(MAX)
WHILE @@FETCH_STATUS = 0 BEGIN
SELECT
@SQLInsert = ''
, @SQLColumns = ''
, @SQLTinyColumns = ''
;WITH cols AS
(
SELECT
c.name
, datetype = t.name
, c.column_id
FROM sys.columns c WITH (NOWAIT)
JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
WHERE c.[object_id] = @ObjectID
AND c.is_computed = 0
AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
)
SELECT
@SQLTinyColumns = STUFF((
SELECT ', [' + c.name + ']'
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
, @SQLColumns = STUFF((SELECT CHAR(13) +
CASE
WHEN c.datetype = 'uniqueidentifier'
THEN ' + '';'' + ISNULL('''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''', ''NULL'')'
WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary')
THEN ' + '';'' + ISNULL('''' + CAST(REPLACE([' + c.name + '], '''', '''''''') AS NVARCHAR(MAX)) + '''', ''NULL'')'
WHEN c.datetype = 'datetime'
THEN ' + '';'' + ISNULL('''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''', ''NULL'')'
ELSE
' + '';'' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
END
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '''' +')
DECLARE @SQL NVARCHAR(MAX) = '
SET NOCOUNT ON;
DECLARE
@SQL NVARCHAR(MAX) = ''''
, @x INT = 1
, @count INT = (SELECT COUNT(1) FROM ' + @TableName + ')
IF EXISTS(
SELECT 1
FROM tempdb.dbo.sysobjects
WHERE ID = OBJECT_ID(''tempdb..#import'')
)
DROP TABLE #import;
SELECT ' + @SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + @SQLTinyColumns + ')
INTO #import
FROM ' + @TableName + '
WHILE @x < @count BEGIN
SELECT @SQL = STUFF((
SELECT ' + @SQLColumns + ' + ''''' + '
FROM #import
WHERE RowNumber BETWEEN @x AND @x + 9
FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 1, '''')
PRINT(@SQL)
SELECT @x = @x + 10
END'
EXEC sys.sp_executesql @SQL
FETCH NEXT FROM [tables] INTO
@TableName
, @ObjectID
END
CLOSE [tables]
DEALLOCATE [tables]
In the output window you'll get something like this (AdventureWorks.Person.Person):
1;EM;0;NULL;Ken;J;Sánchez;NULL;0;92C4279F-1207-48A3-8448-4636514EB7E2;2003-02-08 00:00:00
2;EM;0;NULL;Terri;Lee;Duffy;NULL;1;D8763459-8AA8-47CC-AFF7-C9079AF79033;2002-02-24 00:00:00
3;EM;0;NULL;Roberto;NULL;Tamburello;NULL;0;E1A2555E-0828-434B-A33B-6F38136A37DE;2001-12-05 00:00:00
4;EM;0;NULL;Rob;NULL;Walters;NULL;0;F2D7CE06-38B3-4357-805B-F4B6B71C01FF;2001-12-29 00:00:00
5;EM;0;Ms.;Gail;A;Erickson;NULL;0;F3A3F6B4-AE3B-430C-A754-9F2231BA6FEF;2002-01-30 00:00:00
6;EM;0;Mr.;Jossef;H;Goldberg;NULL;0;0DEA28FD-EFFE-482A-AFD3-B7E8F199D56F;2002-02-17 00:00:00
You can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date
object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:
start = date(2012, 12, 11)
end = date(2012, 12, 18)
new_end = end + datetime.timedelta(days=1)
ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])
As discussed previously, without doing something like this, records are ignored on the last day.
Edited to avoid the use of datetime.combine
-- seems more logical to stick with date instances when comparing against a DateTimeField
, instead of messing about with throwaway (and confusing) datetime
objects. See further explanation in comments below.
The accepted answer is good and fast:
i.ToString("00")
or
i.ToString("000")
If you need more complexity, String.Format is worth a try:
var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
str1 = String.Format("{0:00}", i);
str2 = String.Format("{0:000}", i);
}
For the i = 10
case:
str1: "10"
str2: "010"
I use this, for example, to clear the text on particular Label Controls on my form by name:
private void EmptyLabelArray()
{
var fmt = "Label_Row{0:00}_Col{0:00}";
for (var rowIndex = 0; rowIndex < 100; rowIndex++)
{
for (var colIndex = 0; colIndex < 100; colIndex++)
{
var lblName = String.Format(fmt, rowIndex, colIndex);
foreach (var ctrl in this.Controls)
{
var lbl = ctrl as Label;
if ((lbl != null) && (lbl.Name == lblName))
{
lbl.Text = null;
}
}
}
}
}
In case your appserver is WebLogic (for me it was 10.3.6) then properties responsible for timeouts are:
com.sun.xml.ws.connect.timeout
com.sun.xml.ws.request.timeout
If you use Spring Framework. There is: org.springframework.util.MultiValueMap
.
To create unmodifiable multi value map:
Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);
Or use org.springframework.util.LinkedMultiValueMap
Try this. It always works for me
wget --mirror -p --convert-links -P ./LOCAL-DIR WEBSITE-URL
You cannot have two TIMESTAMP column with the same default value of CURRENT_TIMESTAMP on your table. Please refer to this link: http://www.mysqltutorial.org/mysql-timestamp.aspx
I shared two solutions depending on your needs:
<style type="text/css" ref="stylesheet">
.border-inside-box {
border: 1px solid black;
}
.border-inside-box-v1 {
outline: 1px solid black; /* 'border-radius' not available */
}
.border-outside-box-v2 {
box-shadow: 0 0 0 1px black; /* 'border-style' not available (dashed, solid, etc) */
}
</style>
That its the correct code of background size :
<div class="html-mobile-background">
</div>
<style type="text/css">
html {
/* Whatever you want */
}
.html-mobile-background {
position: fixed;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 100%; /* To compensate for mobile browser address bar space */
background: url(YOUR BACKGROUND URL HERE) no-repeat;
center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-size: 100% 100%
}
</style>
I am currently using the Google API to retrieve the location that the user enters in the form/ input. I'm also using an angular function that showing the current location and suggests a city name pin code etc...
- add google API index.html.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&libraries=geometry,places"></script>
- add id in input box to get string & charcters.
<input id="autocomplete" type="text"(keydown)="checkAddress($event.target.value)">
- and create function on your component.ts file.
import these file
import * as _ from 'lodash';
declare var google: any;
checkAddress(value) {
if (!value) {
this.model.location = _.cloneDeep(value);
this.rfpForm.controls['location'].setValue(this.model.location);
}
}
initLocationAutocomplete() {
let autocomplete, place;
const getLocation = () => {
place = autocomplete.getPlace();
if (place && (place.formatted_address || place.name)) {
// if you want set value in your form controls like this
this.model.location = _.cloneDeep(place.formatted_address || place.name);
// YourFormName.controls['location'].setValue(this.model.location);
// YourFormName.controls['location']['_touched'] = true;
}
};
autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), { types: ['geocode'] });
autocomplete.addListener('place_changed', getLocation);
}
This error could also appear if you are having network latency or internet or local network problems. Bridged connections that have a failing counterpart may be the culprit as well.
There is no WPF equivalent. System.Windows.Forms.Screen
is still part of the .NET framework and can be used from WPF though.
See this question for more details, but you can use the calls relating to screens by using the WindowInteropHelper
class to wrap your WPF control.
I found that I had to use .setAttribute('crossOrigin', '')
and had to append a timestamp to the URL's query string to avoid a 304 response lacking the Access-Control-Allow-Origin
header.
This gives me
var url = 'http://lorempixel.com/g/400/200/';
var imgObj = new Image();
imgObj.src = url + '?' + new Date().getTime();
imgObj.setAttribute('crossOrigin', '');
// NOTE: Using "this.pass" and "this.name" will create a global variable even though it is inside the function, so be weary of your naming convention
function submit()
{
var userPass = document.getElementById("pass").value;
var userName = document.getElementById("user").value;
this.pass = userPass;
this.name = userName;
alert("whatever you want to display");
}
Don't use doubles. You can lose some precision. Here's a general purpose function.
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
You can call it with
round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);
"precision" being the number of decimal points you desire.
In my case, the VS debugger was attached to the w3wp process. After detaching the debugger, I was able to restart the Application Pool
Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.
Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.
This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.
If you need to select your list item based on an expression:
foreach (ListItem listItem in list.Items)
{
listItem.Selected = listItem.Value.Contains("some value");
}
In addition to what @mgilson said, it should be noted that there's also a ArgumentParser.add_mutually_exclusive_group(required=False)
method that would make it trivial to enforce that --flag
and --no-flag
aren't used at the same time.
Maybe it's not using TCP/IP
Have a look at the SQL Server Configuration Manager to see what protocols it's using.
Object orientated programming principles say that, the internal workings of a class should be hidden from the outside world. If you expose a field you're in essence exposing the internal implementation of the class. Therefore we wrap fields with Properties (or methods in Java's case) to give us the ability to change the implementation without breaking code depending on us. Seeing as we can put logic in the Property also allows us to perform validation logic etc if we need it. C# 3 has the possibly confusing notion of autoproperties. This allows us to simply define the Property and the C#3 compiler will generate the private field for us.
public class Person
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int Age{get;set;} //AutoProperty generates private field for us
}
From the searching I've done it appears you can not declare and set variables like this in Select statements. Is this right or am I missing something?
Within Oracle PL/SQL and SQL are two separate languages with two separate engines. You can embed SQL DML within PL/SQL, and that will get you variables. Such as the following anonymous PL/SQL block. Note the /
at the end is not part of PL/SQL, but tells SQL*Plus to send the preceding block.
declare
v_Date1 date := to_date('03-AUG-2010', 'DD-Mon-YYYY');
v_Count number;
begin
select count(*) into v_Count
from Usage
where UseTime > v_Date1;
dbms_output.put_line(v_Count);
end;
/
The problem is that a block that is equivalent to your T-SQL code will not work:
SQL> declare
2 v_Date1 date := to_date('03-AUG-2010', 'DD-Mon-YYYY');
3 begin
4 select VisualId
5 from Usage
6 where UseTime > v_Date1;
7 end;
8 /
select VisualId
*
ERROR at line 4:
ORA-06550: line 4, column 5:
PLS-00428: an INTO clause is expected in this SELECT statement
To pass the results of a query out of an PL/SQL, either an anonymous block, stored procedure or stored function, a cursor must be declared, opened and then returned to the calling program. (Beyond the scope of answering this question. EDIT: see Get resultset from oracle stored procedure)
The client tool that connects to the database may have it's own bind variables. In SQL*Plus:
SQL> -- SQL*Plus does not all date type in this context
SQL> -- So using varchar2 to hold text
SQL> variable v_Date1 varchar2(20)
SQL>
SQL> -- use PL/SQL to set the value of the bind variable
SQL> exec :v_Date1 := '02-Aug-2010';
PL/SQL procedure successfully completed.
SQL> -- Converting to a date, since the variable is not yet a date.
SQL> -- Note the use of colon, this tells SQL*Plus that v_Date1
SQL> -- is a bind variable.
SQL> select VisualId
2 from Usage
3 where UseTime > to_char(:v_Date1, 'DD-Mon-YYYY');
no rows selected
Note the above is in SQLPlus, may not (probably won't) work in Toad PL/SQL developer, etc. The lines starting with variable and exec are SQLPlus commands. They are not SQL or PL/SQL commands. No rows selected because the table is empty.
You can use:
function encodeHTML(str){
var aStr = str.split(''),
i = aStr.length,
aRet = [];
while (i--) {
var iC = aStr[i].charCodeAt();
if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
aRet.push('&#'+iC+';');
} else {
aRet.push(aStr[i]);
}
}
return aRet.reverse().join('');
}
This function HTMLEncodes everything that is not a-z/A-Z.
[Edit] A rather old answer. Let's add a simpler String extension to encode all extended characters:
String.prototype.encodeHTML = function () {
return this.replace(/[\u0080-\u024F]/g,
function (v) {return '&#'+v.charCodeAt()+';';}
);
}
// usage
log('Übergroße Äpfel mit Würmern'.encodeHTML());
//=> 'Übergroße Äpfel mit Würmern'
For further reference, a one liner that can be applied in, for example, !#/bin/sh
scripts.
EPOCH="`perl -e 'use Time::Local; print timelocal('${SEC}','${MIN}','${HOUR}','${DAY}','${MONTH}','${YEAR}'),\"\n\";'`"
Just remember to avoid octal values!
According to the definition of getchar()
, it reads a character from the standard input. Unfortunately stdin
is mistaken for keyboard which might not be the case for getchar
. getchar
uses a buffer as stdin
and reads a single character at a time. In your case since there is no EOF
, the getchar
and putchar
are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:
putchar(c);
printf("\n");
c = getchar();
Now look at the output compared to the original code.
Another example that will explain you the concept of getchar
and buffered stdin
:
void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}
Enter two characters in the first case. The second time when getchar
is running are you entering any character? NO but still putchar
works.
This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar
uses this buffer as stdin
.
Give Mobiscroll a try. The scroller style date and time picker was especially created for interaction on touch devices. It is pretty flexible, and easily customizable. It comes with iOS/Android themes.
If you just do eval $cmd
when we do cmd="ls -l"
(interactively and in a script) we get the desired result. In your case, you have a pipe with a grep without a pattern, so the grep part will fail with an error message. Just $cmd
will generate a "command not found" (or some such) message.
So try use eval and use a finished command, not one that generates an error message.
Try this code if state object has sub objects like this.state.class.fee
. We can pass values using following code:
this.setState({ class: Object.assign({}, this.state.class, { [element]: value }) }
For attributes whose type is an immutable value class that conforms to the NSCopying
protocol, you almost always should specify copy
in your @property
declaration. Specifying retain
is something you almost never want in such a situation.
Here's why you want to do that:
NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];
Person *p = [[[Person alloc] init] autorelease];
p.name = someName;
[someName setString:@"Debajit"];
The current value of the Person.name
property will be different depending on whether the property is declared retain
or copy
— it will be @"Debajit"
if the property is marked retain
, but @"Chris"
if the property is marked copy
.
Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy
. (And if you write the setter yourself instead of using @synthesize
you should remember to actually use copy
instead of retain
in it.)
$info = pathinfo($pathtofile);
if ($info["extension"] == "jpg") { .... }
Just for completeness: So long as the set of values is not too large, you could also simply string-construct a statement like
... WHERE tab.col = ? OR tab.col = ? OR tab.col = ?
which you could then pass to prepare(), and then use setXXX() in a loop to set all the values. This looks yucky, but many "big" commercial systems routinely do this kind of thing until they hit DB-specific limits, such as 32 KB (I think it is) for statements in Oracle.
Of course you need to ensure that the set will never be unreasonably large, or do error trapping in the event that it is.
I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.
Function:
function ifViewLoadContent(elem, LoadContent)
{
var top_of_element = $(elem).offset().top;
var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
var top_of_screen = $(window).scrollTop();
if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
if(!$(elem).hasClass("ImLoaded")) {
$(elem).load(LoadContent).addClass("ImLoaded");
}
}
else {
return false;
}
}
You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):
To use:
$(window).scroll(function (event) {
ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html");
ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html");
});
This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.
I used this approach to reduce the overhead on https://www.taxformcalculator.com. It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).
With LD_PRELOAD
you can give libraries precedence.
For example you can write a library which implement malloc
and free
. And by loading these with LD_PRELOAD
your malloc
and free
will be executed rather than the standard ones.
I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.
I'd declared a string and was formatting it for use with JQTree which requires curly braces ({}). You have to use doubled curly braces for it to be accepted as a properly formatted string:
string measurements = string.empty;
measurements += string.Format(@"
{{label: 'Measurement Name: {0}',
children: [
{{label: 'Measured Value: {1}'}},
{{label: 'Min: {2}'}},
{{label: 'Max: {3}'}},
{{label: 'Measured String: {4}'}},
{{label: 'Expected String: {5}'}},
]
}},",
drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
drv["Min"] == null ? "NULL" : drv["Min"],
drv["Max"] == null ? "NULL" : drv["Max"],
drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);
Hopefully this will help other folks who find this question but aren't parsing numerical data.
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
If you only need string values in the array, the following will work:
function hasDuplicates(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
We use a "hash table" valuesSoFar
whose keys are the values we've seen in the array so far. We do a lookup using in
to see if that value has been spotted already; if so, we bail out of the loop and return true
.
If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).
function hasDuplicates(array) {
var valuesSoFar = [];
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (valuesSoFar.indexOf(value) !== -1) {
return true;
}
valuesSoFar.push(value);
}
return false;
}
The difference is simply that we use an array instead of a hash table for valuesSoFar
, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in
, instead getting an O(n) lookup time of indexOf
.
//pull the last two digits of the year_x000D_
//logs to console_x000D_
//creates a new date object (has the current date and time by default)_x000D_
//gets the full year from the date object (currently 2017)_x000D_
//converts the variable to a string_x000D_
//gets the substring backwards by 2 characters (last two characters) _x000D_
console.log(new Date().getFullYear().toString().substr(-2));
_x000D_
JavaScript:
//A function for formatting a date to MMddyy_x000D_
function formatDate(d)_x000D_
{_x000D_
//get the month_x000D_
var month = d.getMonth();_x000D_
//get the day_x000D_
//convert day to string_x000D_
var day = d.getDate().toString();_x000D_
//get the year_x000D_
var year = d.getFullYear();_x000D_
_x000D_
//pull the last two digits of the year_x000D_
year = year.toString().substr(-2);_x000D_
_x000D_
//increment month by 1 since it is 0 indexed_x000D_
//converts month to a string_x000D_
month = (month + 1).toString();_x000D_
_x000D_
//if month is 1-9 pad right with a 0 for two digits_x000D_
if (month.length === 1)_x000D_
{_x000D_
month = "0" + month;_x000D_
}_x000D_
_x000D_
//if day is between 1-9 pad right with a 0 for two digits_x000D_
if (day.length === 1)_x000D_
{_x000D_
day = "0" + day;_x000D_
}_x000D_
_x000D_
//return the string "MMddyy"_x000D_
return month + day + year;_x000D_
}_x000D_
_x000D_
var d = new Date();_x000D_
console.log(formatDate(d));
_x000D_
A more recent way to do this is to use the .to_numpy() function.
If I have a dataframe with a column 'price', I can convert it as follows:
priceArray = df['price'].to_numpy()
You can also pass the data type, such as float or object, as an argument of the function
Check if tensorflow is activated in your terminal
first deactivate it using
conda deactivate
then use the command
conda install python-graphviz
and then install
conda install graphviz
this is solution for UBUNTU USERS :) CHEERS :)
This might depend on how much you want to engineer the solution - if the array is never going to be that big and you don't care about sorting the list you might want to try something similar to the following:
public string[] RemoveDuplicates(string[] myList) {
System.Collections.ArrayList newList = new System.Collections.ArrayList();
foreach (string str in myList)
if (!newList.Contains(str))
newList.Add(str);
return (string[])newList.ToArray(typeof(string));
}
$('[class*="tag"]').live('click', function() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
});
LPCWSTR
is equivalent to wchar_t const *
. It's a pointer to a wide character string that won't be modified by the function call.
You can assign to LPCWSTR
s by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";
LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE
is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx
is defined as FindWindowExA
or FindWindowExW
depending on this definition.
Check if the jQuery object contains any element before you try to get its offset:
var nav = $('.content-nav');
if (nav.length) {
var contentNav = nav.offset().top;
...continue to set up the menu
}
For those finding this via Google;
I was getting this error because, as suggested by the error, I failed to close a SqlDataReader prior to creating another on the same SqlCommand, mistakenly assuming that it would be garbage collected when leaving the method it was created in.
I solved the issue by calling sqlDataReader.Close();
before creating the second reader.
Player.cpp
require the definition of Ball
class. So simply add #include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
The one way is by using webservice, simply write a webservice method in PHP or any other language . And From your android app by using http client request and response , you can hit the web service method which will return whatever you want.
For PHP You can create a webservice like this. Assuming below we have a php file in the server. And the route of the file is yourdomain.com/api.php
if(isset($_GET['api_call'])){
switch($_GET['api_call']){
case 'userlogin':
//perform your userlogin task here
break;
}
}
Now you can use Volley or Retrofit to send a network request to the above PHP Script and then, actually the php script will handle the database operation.
In this case the PHP script is called a RESTful API.
You can learn all the operation at MySQL from this tutorial. Android MySQL Tutorial to Perform CRUD.
While invoking the mysql
CLI, you can specify the database name through the -D
option. From mysql --help
:
-D, --database=name Database to use.
I use this command:
mysql -h <db_host> -u <user> -D <db_name> -p
You could do it like this:
.switch {
position: relative;
display: inline-block;
width: 90px;
height: 34px;
}
.switch input {display:none;}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ca2222;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2ab934;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(55px);
-ms-transform: translateX(55px);
transform: translateX(55px);
}
/*------ ADDED CSS ---------*/
.on
{
display: none;
}
.on, .off
{
color: white;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 50%;
font-size: 10px;
font-family: Verdana, sans-serif;
}
input:checked+ .slider .on
{display: block;}
input:checked + .slider .off
{display: none;}
/*--------- END --------*/
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;}
_x000D_
<label class="switch">
<input type="checkbox" id="togBtn">
<div class="slider round">
<!--ADDED HTML -->
<span class="on">ON</span>
<span class="off">OFF</span>
<!--END-->
</div>
</label>
_x000D_
Or pure CSS:
.switch {
position: relative;
display: inline-block;
width: 90px;
height: 34px;
}
.switch input {display:none;}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ca2222;
-webkit-transition: .4s;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2ab934;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(55px);
}
/*------ ADDED CSS ---------*/
.slider:after
{
content:'OFF';
color: white;
display: block;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 50%;
font-size: 10px;
font-family: Verdana, sans-serif;
}
input:checked + .slider:after
{
content:'ON';
}
/*--------- END --------*/
_x000D_
<label class="switch">
<input type="checkbox" id="togBtn">
<div class="slider round"></div>
</label>
_x000D_
@DanielChapman gives a good explanation of serialVersionUID, but no solution. the solution is this: run the serialver
program on all your old classes. put these serialVersionUID
values in your current versions of the classes. as long as the current classes are serial compatible with the old versions, you should be fine. (note for future code: you should always have a serialVersionUID
on all Serializable
classes)
if the new versions are not serial compatible, then you need to do some magic with a custom readObject
implementation (you would only need a custom writeObject
if you were trying to write new class data which would be compatible with old code). generally speaking adding or removing class fields does not make a class serial incompatible. changing the type of existing fields usually will.
Of course, even if the new class is serial compatible, you may still want a custom readObject
implementation. you may want this if you want to fill in any new fields which are missing from data saved from old versions of the class (e.g. you have a new List field which you want to initialize to an empty list when loading old class data).
Since the question was asked/answered long time ago, those top answers do not work for me. Here's my solution, in 2020.
Background: Fresh mysql/mariadb installed by homebrew.
Problem: The password for root is not empty and unknown.
The fix:
The reason:
The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it.
However, there are other considerations at play here too.
Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads.
Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership).
If you refer to classic VxWorks RTOS kernel, they define three mechanisms:
Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.
the simplest:
dots = dots*1+5;
the dots will be converted to number.
In python "else if" is spelled "elif".
Also, you need a colon after the elif
and the else
.
Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).
So your code should read:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
function(input('input:'))
Update:
Since git rm .
deletes all files in this and child directories in the working checkout as well as in the index, you need to undo each of these changes:
git reset HEAD . # This undoes the index changes
git checkout . # This checks out files in this and child directories from the HEAD
This should do what you want. It does not affect parent folders of your checked-out code or index.
Old answer that wasn't:
reset HEAD
will do the trick, and will not erase any uncommitted changes you have made to your files.
after that you need to repeat any git add
commands you had queued up.
Best way to solve this as per my opinion is Using "ignoreReadonly".
First make the input field readonly then add ignoreReadonly:true. This will make sure that even if the text field is readonly , popup will show.
$('#txtStartDate').datetimepicker({
locale: "da",
format: "DD/MM/YYYY",
ignoreReadonly: true
});
$('#txtEndDate').datetimepicker({
locale: "da",
useCurrent: false,
format: "DD/MM/YYYY",
ignoreReadonly: true
});
});
The best way I found is to use another class. You can create an object and then use it on other objects.
class staticFlag:
def __init__(self):
self.__success = False
def isSuccess(self):
return self.__success
def succeed(self):
self.__success = True
class tryIt:
def __init__(self, staticFlag):
self.isSuccess = staticFlag.isSuccess
self.succeed = staticFlag.succeed
tryArr = []
flag = staticFlag()
for i in range(10):
tryArr.append(tryIt(flag))
if i == 5:
tryArr[i].succeed()
print tryArr[i].isSuccess()
With the example above, I made a class named staticFlag
.
This class should present the static var __success
(Private Static Var).
tryIt
class represented the regular class we need to use.
Now I made an object for one flag (staticFlag
). This flag will be sent as reference to all the regular objects.
All these objects are being added to the list tryArr
.
This Script Results:
False
False
False
False
False
True
True
True
True
True
Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':
pd.read_csv('sample.csv',dtype={'ID':'string'})
As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').
IN HTML 5 action=""
IS NOT SUPPORTED SO DON'T DO THIS. BAD PRACTICE.
If instead you completely negate action altogether it will submit to the same page by default, I believe this is the best practice:
<form>This will submit to the current page</form>
If you are sumbitting the form using php you may want to consider the following. read more about it here.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Alternatively you could use #
bear in mind though that this will act like an anchor and scroll to the top of the page.
<form action="#">
If your requirements are to have no duplicates, you should be using a HashSet.
HashSet.Add will return false when the item already exists (if that even matters to you).
You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice
(GetHashCode
& Equals
).
You can turn autocommit ON by setting implicit_transactions OFF:
SET IMPLICIT_TRANSACTIONS OFF
When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.
Maybe an example is clearer. This will write a change to the database:
SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION
This will not write a change to the database:
SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION
The following example will update a row, and then complain that there's no transaction to commit:
SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION
Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.
Easy and best solution is the following.
index.html
<form action="submit.php" method="POST">
<input type="text" name="name" value="" />
<input type="text" name="email" value="" />
<textarea type="text" name="message"></textarea>
<div class="g-recaptcha" data-sitekey="Insert Your Site Key"></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
submit.php
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])){
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
//your site secret key
$secret = 'InsertSiteSecretKey';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success){
//contact form submission code goes here
$succMsg = 'Your contact request have submitted successfully.';
}else{
$errMsg = 'Robot verification failed, please try again.';
}
}else{
$errMsg = 'Please click on the reCAPTCHA box.';
}
}
?>
I have found this reference and full tutorial from here - Using new Google reCAPTCHA with PHP
In case you're inside a Sub of Function and you want to exit it, you can use :
Exit Sub
or
Exit Function
Another Solution in Case You Don't Have Control Over Dynamic Content
This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).
Wrap up Your Content
Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.
<div class="selector">
<grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>
Use Angular Injector
You can use the following code to get a reference to $compile if you don't have one.
$(".selector").each(function () {
var content = $(this);
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
});
});
Summary
The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.
One Caveat of the previous code
If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.
Here is the way to remedy it:
Replace the prevous code snippet with the following overload.
...
angular.element(document).injector().invoke(
[
"$compile", function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
}
]);
...
This caused a lot of grief for me before I pieced it together.
Instead of passing variable to template globally, you can define a base template and render the 'global part' in it. The base template can be inherited.
Example of rendering template From the symfony Documentation:
<div id="sidebar">
{% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %}
</div>
Abdullah's answer is great. But i want to add some more details to it with my answer.
Implementing a Splash Screen
Implementing a splash screen the right way is a little different than you might imagine. The splash view that you see has to be ready immediately, even before you can inflate a layout file in your splash activity.
So you will not use a layout file. Instead, specify your splash screen’s background as the activity’s theme background. To do this, first create an XML drawable in res/drawable.
background_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@color/gray"/>
<item>
<bitmap
android:gravity="center"
android:src="@mipmap/ic_launcher"/>
</item>
</layer-list>
It just a layerlist with logo in center background color with it.
Now open styles.xml and add this style
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/background_splash</item>
</style>
This theme will have to actionbar and with background that we just created above.
And in manifest you need to set SplashTheme to activity that you want to use as splash.
<activity
android:name=".SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Then inside your activity code navigate user to the specific screen after splash using intent.
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
That's the right way to do. I used these references for answer.
The /240
error is due to illegal spaces before every code of line.
eg.
Do
printf("Anything");
instead of
printf("Anything");
This error is common when you copied and pasted the code in the IDE.
Your hostname is missing. JBoss uses this environment variable ($HOSTNAME) when it connects to the server.
[root@xyz ~]# echo $HOSTNAME
xyz
[root@xyz ~]# ping $HOSTNAME
ping: unknown host xyz
[root@xyz ~]# hostname -f
hostname: Unknown host
There are dozens of things that can cause this. Please comment if you discover a new reason.
For a hack until you can permanently resolve this issue on your server, you can add a line to the end of your /etc/hosts file:
127.0.0.1 xyz.xxx.xxx.edu xyz
This seems a relict from the old days of simple linkers. You can use static variables in static methods as workaround:
// header.hxx
#include <vector>
class Class {
public:
static std::vector<int> & replacement_for_initialized_static_non_const_variable() {
static std::vector<int> Static {42, 0, 1900, 1998};
return Static;
}
};
int compilation_unit_a();
and
// compilation_unit_a.cxx
#include "header.hxx"
int compilation_unit_a() {
return Class::replacement_for_initialized_static_non_const_variable()[1]++;
}
and
// main.cxx
#include "header.hxx"
#include <iostream>
int main() {
std::cout
<< compilation_unit_a()
<< Class::replacement_for_initialized_static_non_const_variable()[1]++
<< compilation_unit_a()
<< Class::replacement_for_initialized_static_non_const_variable()[1]++
<< std::endl;
}
build:
g++ -std=gnu++0x -save-temps=obj -c compilation_unit_a.cxx
g++ -std=gnu++0x -o main main.cxx compilation_unit_a.o
run:
./main
The fact that this works (consistently, even if the class definition is included in different compilation units), shows that the linker today (gcc 4.9.2) is actually smart enough.
Funny: Prints 0123
on arm and 3210
on x86.
Your code is almost right! You are right, you are just missing one step. When you read in the file, you are reading it as a string; but you want to turn the string back into a dictionary.
The error message you saw was because self.whip
was a string, not a dictionary.
I first wrote that you could just feed the string into dict()
but that doesn't work! You need to do something else.
Here is the simplest way: feed the string into eval()
. Like so:
def reading(self):
s = open('deed.txt', 'r').read()
self.whip = eval(s)
You can do it in one line, but I think it looks messy this way:
def reading(self):
self.whip = eval(open('deed.txt', 'r').read())
But eval()
is sometimes not recommended. The problem is that eval()
will evaluate any string, and if someone tricked you into running a really tricky string, something bad might happen. In this case, you are just running eval()
on your own file, so it should be okay.
But because eval()
is useful, someone made an alternative to it that is safer. This is called literal_eval
and you get it from a Python module called ast
.
import ast
def reading(self):
s = open('deed.txt', 'r').read()
self.whip = ast.literal_eval(s)
ast.literal_eval()
will only evaluate strings that turn into the basic Python types, so there is no way that a tricky string can do something bad on your computer.
Actually, best practice in Python is to use a with
statement to make sure the file gets properly closed. Rewriting the above to use a with
statement:
import ast
def reading(self):
with open('deed.txt', 'r') as f:
s = f.read()
self.whip = ast.literal_eval(s)
In the most popular Python, known as "CPython", you usually don't need the with
statement as the built-in "garbage collection" features will figure out that you are done with the file and will close it for you. But other Python implementations, like "Jython" (Python for the Java VM) or "PyPy" (a really cool experimental system with just-in-time code optimization) might not figure out to close the file for you. It's good to get in the habit of using with
, and I think it makes the code pretty easy to understand.