Basically you have two ways to iterate over all elements:
1. Using recursion (the most common way I think):
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("document.xml"));
doSomething(document.getDocumentElement());
}
public static void doSomething(Node node) {
// do something with the current node instead of System.out
System.out.println(node.getNodeName());
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
//calls this method for all the children which is Element
doSomething(currentNode);
}
}
}
2. Avoiding recursion using getElementsByTagName()
method with *
as parameter:
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("document.xml"));
NodeList nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
// do something with the current element
System.out.println(node.getNodeName());
}
}
}
I think these ways are both efficient.
Hope this helps.
My issue was that the root element actually has a xmlns="abc123"
So had to make XmlRoot("elementname",NameSpace="abc123")
I think the problem is that you are using type="text" instead of textarea. What you want is:
<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>
To clarify, a type="text" will always be one row, where-as a textarea can be multiple.
Yes, you are using encapsulation by using properties, but there are more nuances to encapsulation than just taking control over how properties are read and written. Denying a property to be set from outside the class can be useful both for robustness and performance.
An immutable class is a class that doesn't change once it's created, so private setters (or no setters at all) is needed to protect the properties.
Private setters came into more frequent use with the property shorthand that was instroduced in C# 3. In C# 2 the setter was often just omitted, and the private data accessed directly when set.
This property:
public int Size { get; private set; }
is the same as:
private int _size;
public int Size {
get { return _size; }
private set { _size = value; }
}
except, the name of the backing variable is internally created by the compiler, so you can't access it directly.
With the shorthand property the private setter is needed to create a read-only property, as you can't access the backing variable directly.
To hide errors only from users but displaying logs errors in apache log
error_reporting(E_ALL);
ini_set('display_errors', 0);
1 - Displaying error only in log
2 - hide from users
There is at least one situation where using single quotes will not work and that is if you are creating the markup "on the fly" from JavaScript. You use single quotes to contain the string and then any property in the markup can have double quotes for its value.
It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").
This is not a very nice fix but it works:
CSS:
.new-tab-opener
{
display: none;
}
HTML:
<a data-href="http://www.google.com/" href="javascript:">Click here</a>
<form class="new-tab-opener" method="get" target="_blank"></form>
Javascript:
$('a').on('click', function (e) {
var f = $('.new-tab-opener');
f.attr('action', $(this).attr('data-href'));
f.submit();
});
Live example: http://jsfiddle.net/7eRLb/
Although the other answers posted here work, I find the following approach more natural:
$obj = (object) [
'aString' => 'some string',
'anArray' => [ 1, 2, 3 ]
];
echo json_encode($obj);
In Python, you can copy the files using
shutil
moduleos
modulesubprocess
moduleimport os
import shutil
import subprocess
shutil
moduleshutil.copyfile
signature
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copyfile('source.txt', 'destination.txt')
shutil.copy
signature
shutil.copy(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy('source.txt', 'destination.txt')
shutil.copy2
signature
shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy2('source.txt', 'destination.txt')
shutil.copyfileobj
signature
shutil.copyfileobj(src_file_object, dest_file_object[, length])
# example
file_src = 'source.txt'
f_src = open(file_src, 'rb')
file_dest = 'destination.txt'
f_dest = open(file_dest, 'wb')
shutil.copyfileobj(f_src, f_dest)
os
moduleos.popen
signature
os.popen(cmd[, mode[, bufsize]])
# example
# In Unix/Linux
os.popen('cp source.txt destination.txt')
# In Windows
os.popen('copy source.txt destination.txt')
os.system
signature
os.system(command)
# In Linux/Unix
os.system('cp source.txt destination.txt')
# In Windows
os.system('copy source.txt destination.txt')
subprocess
modulesubprocess.call
signature
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)
subprocess.check_output
signature
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)
What does your text file look like?? Each line a record?
You'll have to check out the BULK INSERT statement - that should look something like:
BULK INSERT dbo.YourTableName
FROM 'D:\directory\YourFileName.csv'
WITH
(
CODEPAGE = '1252',
FIELDTERMINATOR = ';',
CHECK_CONSTRAINTS
)
Here, in my case, I'm importing a CSV file - but you should be able to import a text file just as well.
From the MSDN docs - here's a sample that hopefully works for a text file with one field per row:
BULK INSERT dbo.temp
FROM 'c:\temp\file.txt'
WITH
(
ROWTERMINATOR ='\n'
)
Seems to work just fine in my test environment :-)
Try this:
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
MessageBox.Show(printer);
}
#include<stdio.h>
#include<string.h>
main()
{
int i=0,n;
int j=0;
char str[]=" Nar ayan singh ";
char *ptr,*ptr1;
printf("sizeof str:%ld\n",strlen(str));
while(str[i]==' ')
{
memcpy (str,str+1,strlen(str)+1);
}
printf("sizeof str:%ld\n",strlen(str));
n=strlen(str);
while(str[n]==' ' || str[n]=='\0')
n--;
str[n+1]='\0';
printf("str:%s ",str);
printf("sizeof str:%ld\n",strlen(str));
}
Try to resolve the conflict using
svn resolve --accept=working PATH
-(Bool)checkIf:(String)parentString containsSubstring:(String)checkString {
NSRange textRange =[parentString rangeOfString:checkString];
return textRange.location != NSNotFound // returns true if parent string contains substring else returns false
}
I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
In order to add an EventListener to an element in angular 2+, we can use the method listen of the Renderer2 service (Renderer is deprecated, so use Renderer2):
listen(target: 'window'|'document'|'body'|any, eventName: string, callback: (event: any) => boolean | void): () => void
Example:
export class ListenDemo implements AfterViewInit {
@ViewChild('testElement')
private testElement: ElementRef;
globalInstance: any;
constructor(private renderer: Renderer2) {
}
ngAfterViewInit() {
this.globalInstance = this.renderer.listen(this.testElement.nativeElement, 'click', () => {
this.renderer.setStyle(this.testElement.nativeElement, 'color', 'green');
});
}
}
Note:
When you use this method to add an event listener to an element in the dom, you should remove this event listener when the component is destroyed
You can do that this way:
ngOnDestroy() {
this.globalInstance();
}
The way of use of ElementRef
in this method should not expose your angular application to a security risk. for more on this referrer to ElementRef security risk angular 2
In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...
@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)
This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...
model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;
May not be the best way, but it does work.
Some of these built in functions should work:
Coalesce
Is Null
IfNull
Note that "number of cores" might not be a particularly useful number, you might have to qualify it a bit more. How do you want to count multi-threaded CPUs such as Intel HT, IBM Power5 and Power6, and most famously, Sun's Niagara/UltraSparc T1 and T2? Or even more interesting, the MIPS 1004k with its two levels of hardware threading (supervisor AND user-level)... Not to mention what happens when you move into hypervisor-supported systems where the hardware might have tens of CPUs but your particular OS only sees a few.
The best you can hope for is to tell the number of logical processing units that you have in your local OS partition. Forget about seeing the true machine unless you are a hypervisor. The only exception to this rule today is in x86 land, but the end of non-virtual machines is coming fast...
This is very simple and easily manage.
jQuery(document).ready(function(){
jQuery("#search").click(function(){
jQuery("#loader").show("slow");
jQuery("#response_result").hide("slow");
jQuery.post(siteurl+"/ajax.php?q="passyourdata, function(response){
setTimeout("finishAjax('response_result', '"+escape(response)+"')", 850);
});
});
})
function finishAjax(id,response){
jQuery("#loader").hide("slow");
jQuery('#response_result').html(unescape(response));
jQuery("#"+id).show("slow");
return true;
}
If you already have the xml, and comes more than one attribute, you can handle it as follows:
String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));
Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
.getElementsByTagName("ciudad");
for (int i = 0; i < nodes.getLength(); i++) {
Ciudad ciudad = new Ciudad();
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("idCiudad");
Element element2 = (Element) name.item(0);
ciudad.setIdCiudad(Integer
.valueOf(getCharacterDataFromElement(element2)));
NodeList title = element.getElementsByTagName("nomCiudad");
element2 = (Element) title.item(0);
ciudad.setNombre(getCharacterDataFromElement(element2));
ciudades.getPartnerAccount().add(ciudad);
}
}
for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}
the method getCharacterDataFromElement is
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
If I understand correctly that you want to play the animation on A
only once youu have to add
animation-iteration-count: 1
to the style for the a
.
STEP 1: cd /opt/google/chrome
STEP 2: edit google-chrome file. gedit google-chrome
STEP 3: find this line: exec -a "$0" "$HERE/chrome" "$@"
.
Mostly this line is in the end of google-chrome file.
Comment it out like this : #exec -a "$0" "$HERE/chrome" "$@"
STEP 4:add a new line at the same place.
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir
STEP 5: save google-chrome file and quit. And then you can use chrome as root user. Enjoy it!
I also had the same issue though am using MacOS. The issue is kind of bug. I solved this issue by repeatedly running the commands,
sudo npm cache clean --force
sudo npm uninstall
sudo npm install
One time it did not work but when I repeatedly cleaned the cache and after uninstalling npm, reinstalling npm, the error went off. I am using Angular 8 and this issue is common
Upload your favicon.ico
to the root directory of your website and that should work with Chrome. Some browsers disregard the meta tag and just use /favicon.ico
Go figure?.....
I made a function which handles arrays as well as single GET or POST values
function subVal($varName, $default=NULL,$isArray=FALSE ){ // $isArray toggles between (multi)array or single mode
$retVal = "";
$retArray = array();
if($isArray) {
if(isset($_POST[$varName])) {
foreach ( $_POST[$varName] as $var ) { // multidimensional POST array elements
$retArray[]=$var;
}
}
$retVal=$retArray;
}
elseif (isset($_POST[$varName]) ) { // simple POST array element
$retVal = $_POST[$varName];
}
else {
if (isset($_GET[$varName]) ) {
$retVal = $_GET[$varName]; // simple GET array element
}
else {
$retVal = $default;
}
}
return $retVal;
}
Examples:
$curr_topdiameter = subVal("topdiameter","",TRUE)[3];
$user_name = subVal("user_name","");
You can just use the -R (recursive) flag.
chmod -R 777 /Users/Test/Desktop/PATH
You can use python3 to run file, if you don't want to use virtualenv.python3 manage.py runserver
There is a MUCH easier solution to this than posted here, or in related threads. If you are using a webview (as I am), you can achieve this by executing a JAVASCRIPT function within it. If you are not using a webview, you might want to create a hidden one for this purpose. Here's a function that works in just about any browser (or webview) to kickoff ca installation (generally through the shared os cert repository, including on a Droid). It uses a nice trick with iFrames. Just pass the url to a .crt file to this function:
function installTrustedRootCert( rootCertUrl ){
id = "rootCertInstaller";
iframe = document.getElementById( id );
if( iframe != null ) document.body.removeChild( iframe );
iframe = document.createElement( "iframe" );
iframe.id = id;
iframe.style.display = "none";
document.body.appendChild( iframe );
iframe.src = rootCertUrl;
}
UPDATE:
The iframe trick works on Droids with API 19 and up, but older versions of the webview won't work like this. The general idea still works though - just download/open the file with a webview and then let the os take over. This may be an easier and more universal solution (in the actual java now):
public static void installTrustedRootCert( final String certAddress ){
WebView certWebView = new WebView( instance_ );
certWebView.loadUrl( certAddress );
}
Note that instance_ is a reference to the Activity. This works perfectly if you know the url to the cert. In my case, however, I resolve that dynamically with the server side software. I had to add a fair amount of additional code to intercept a redirection url and call this in a manner which did not cause a crash based on a threading complication, but I won't add all that confusion here...
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
I've made this into an Xcode 4 template, in the same vein as Karl's static framework template.
I found that building static frameworks (instead of plain static libraries) was causing random crashes with LLVM, due to an apparent linker bug - so, I guess static libraries are still useful!
JPEG can't support transparency because it uses RGB color space. If you want transparency use a format that supports alpha values. Example PNG is an image format that uses RGBA color space where (r = red, g = green, b = blue, a = alpha value). Alpha value is used as an opacity measure, 0% is fully transparent and 100% is completely opaque. pixel.
Generic Webhook Trigger Plugin can be configured with filters to achieve this.
When configured with
ref
and expression $.ref
.$ref
and filter expression like ^refs/heads/master$
.Then that job will trigger for every push to master
. No polling.
You probably want more values from the webhook to actually perform the build. Just add more variables, with JSONPath, to pick what you need.
There are some use cases here: https://github.com/jenkinsci/generic-webhook-trigger-plugin/tree/master/src/test/resources/org/jenkinsci/plugins/gwt/bdd
CASE
is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY
clause of a SELECT
statement.
It looks like you just need:
ORDER BY
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc,
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
Or possibly:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.
This may be the answer we're looking for:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN 5
WHEN TblList.HighCallAlertCount <> 0 THEN 4
WHEN TblList.HighAlertCount <> 0 THEN 3
WHEN TblList.MediumCallAlertCount <> 0 THEN 2
WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
<input type="text" maxlength="5">
the maximum amount of letters that can be in the input is 5.
While executing multiple lines of code in R, you need to first select all the lines of code and then click on "Run". This error usually comes up when we don't select our statements and click on "Run".
@Szkíta Had a great solution by creating a function that gets the address parts in a named array. Here is a compiled solution for those who want to use plain JavaScript.
Function to convert results to the named array:
function getAddressParts(obj) {
var address = [];
obj.address_components.forEach( function(el) {
address[el.types[0]] = el.short_name;
});
return address;
} //getAddressParts()
Geocode the LAT/LNG values:
geocoder.geocode( { 'location' : latlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var addressParts = getAddressParts(results[0]);
// the city
var city = addressParts.locality;
// the state
var state = addressParts.administrative_area_level_1;
}
});
Directives are not "inside the angular world" as they say. So you have to use apply to get back into it when changing stuff
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
Lot of time I got the same error when installing M2Crypto
& pygraphviz
and installed all the things mention in the approved answer. But this below line solved all my problems with the other packages in approved answer too.
sudo apt-get install libssl-dev swig
sudo apt-get install -y graphviz-dev
This swig
package saved my life as the solution for M2Crypto
and graphviz-dev
for pygraphviz
. I hope this will help someone.
Excellent answer from above turned into a simple utility method.
private Uri buildURI(String url, Map<String, String> params) {
// build url with parameters.
Uri.Builder builder = Uri.parse(url).buildUpon();
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.appendQueryParameter(entry.getKey(), entry.getValue());
}
return builder.build();
}
I liked PostMan
, it was the main reason why I kept using Chrome, now I'm good with HttpRequester
https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search
Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)
using MODI;
static void Main(string[] args)
{
DocumentClass myDoc = new DocumentClass();
myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);
foreach (Image anImage in myDoc.Images)
{
Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
}
}
A good example of using the Generic Repository pattern and implementing a generic solution for this might look something like this.
public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)
{
foreach (var include in includeProperties)
{
query = query.Include(include);
}
return query.ToList();
}
Update 2:
Xcode 9 appears to have a "feature" where it will ignore the file's current line endings, and instead just use your default line-ending setting when inserting lines into a file, resulting in files with mixed line endings.
I'm pretty sure this bug didn't exist in Xcode 7; not sure about Xcode 8. The good news is that it appears to be fixed in Xcode 10.
For the time it existed, this bug caused a small amount of hilarity in the codebase I refer to in the question (which to this day uses autocrlf=false
), and led to many "EOL" commit messages and eventually to my writing a git pre-commit
hook to check for/prevent introducing mixed line endings.
Update:
Note: As noted by VonC, starting from Git 2.8, merge markers will not introduce Unix-style line-endings to a Windows-style file.
Original:
One little hiccup that I've noticed with this setup is that when there are merge conflicts, the lines git adds to mark up the differences do not have Windows line-endings, even when the rest of the file does, and you can end up with a file with mixed line endings, e.g.:
// Some code<CR><LF>
<<<<<<< Updated upstream<LF>
// Change A<CR><LF>
=======<LF>
// Change B<CR><LF>
>>>>>>> Stashed changes<LF>
// More code<CR><LF>
This doesn't cause us any problems (I imagine any tool that can handle both types of line-endings will also deal sensible with mixed line-endings--certainly all the ones we use do), but it's something to be aware of.
The other thing* we've found, is that when using git diff
to view changes to a file that has Windows line-endings, lines that have been added display their carriage returns, thus:
// Not changed
+ // New line added in^M
+^M
// Not changed
// Not changed
* It doesn't really merit the term: "issue".
Completeness
You need to check both $mysqli
and $statement
. If they are false, you need to output $mysqli->error
or $statement->error
respectively.
Efficiency
For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.
Usage example 1: Simple script
# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);
Usage example 2: Application
# This is part of an application
class FuzDatabaseException extends Exception {
}
class Foo {
public $mysqli;
public function __construct(mysqli $mysqli) {
$this->mysqli = $mysqli;
}
public function updateBar() {
$q = "UPDATE foo SET bar=1";
$statement = $this->mysqli->prepare($q);
if (!$statement) {
throw new FuzDatabaseException($mysqli->error);
}
if (!$statement->execute()) {
throw new FuzDatabaseException($statement->error);
}
}
}
$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
$foo->updateBar();
} catch (FuzDatabaseException $e)
$msg = $e->getMessage();
// Now send warning emails, write log
}
Execution is not related to laravel go to the php.ini file In php.ini file set max_execution_time=360 (time may be variable depends on need) if you want to increase execution of a specific page then write ini_set('max_execution_time',360) at top of page
otherwise in htaccess php_value max_execution_time 360
I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.
<button type="button">My Button</button>
Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):
The missing value default and invalid value default are the Submit Button state.
I'm new to python too. Here is something that looks like will do what you want to
axes([0.08, 0.08, 0.94-0.08, 0.94-0.08]) #[left, bottom, width, height]
axis('scaled')`
I believe this decides the size of the canvas.
Thinking of a string as a set of characters, in mathematics the empty set is always a subset of any set.
ax.set_title()
should set the titles for separate subplots:
import matplotlib.pyplot as plt
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
fig = plt.figure()
fig.suptitle("Title for whole figure", fontsize=16)
ax = plt.subplot("211")
ax.set_title("Title for first plot")
ax.plot(data)
ax = plt.subplot("212")
ax.set_title("Title for second plot")
ax.plot(data)
plt.show()
Can you check if this code works for you? Maybe something overwrites them later?
I change your if statement slightly and works (also for inherited obj - look on snippet)
if(!("merchant_id" in thisSession)) alert("yeah");
var sessionA = {_x000D_
amt: "10.00",_x000D_
email: "[email protected]",_x000D_
merchant_id: "sam",_x000D_
mobileNo: "9874563210",_x000D_
orderID: "123456",_x000D_
passkey: "1234",_x000D_
}_x000D_
_x000D_
var sessionB = {_x000D_
amt: "10.00",_x000D_
email: "[email protected]",_x000D_
mobileNo: "9874563210",_x000D_
orderID: "123456",_x000D_
passkey: "1234",_x000D_
}_x000D_
_x000D_
_x000D_
var sessionCfromA = Object.create(sessionA); // inheritance_x000D_
sessionCfromA.name = 'john';_x000D_
_x000D_
_x000D_
if (!("merchant_id" in sessionA)) alert("merchant_id not in sessionA");_x000D_
if (!("merchant_id" in sessionB)) alert("merchant_id not in sessionB");_x000D_
if (!("merchant_id" in sessionCfromA)) alert("merchant_id not in sessionCfromA");_x000D_
_x000D_
if ("merchant_id" in sessionA) alert("merchant_id in sessionA");_x000D_
if ("merchant_id" in sessionB) alert("merchant_id in sessionB");_x000D_
if ("merchant_id" in sessionCfromA) alert("merchant_id in sessionCfromA");
_x000D_
I know of few packages that support "make uninstall" but many more that support make install DESTDIR=xxx" for staged installs.
You can use this to create a package which you install instead of installing directly from the source. I had no luck with checkinstall but fpm works very well.
This can also help you remove a package previously installed using make install. You simply force install your built package over the make installed one and then uninstall it.
For example, I used this recently to deal with protobuf-3.3.0. On RHEL7:
make install DESTDIR=dest
cd dest
fpm -f -s dir -t rpm -n protobuf -v 3.3.0 \
--vendor "You Not RedHat" \
--license "Google?" \
--description "protocol buffers" \
--rpm-dist el7 \
-m [email protected] \
--url "http:/somewhere/where/you/get/the/package/oritssource" \
--rpm-autoreqprov \
usr
sudo rpm -i -f protobuf-3.3.0-1.el7.x86_64.rpm
sudo rpm -e protobuf-3.3.0
Prefer yum to rpm if you can.
On Debian9:
make install DESTDIR=dest
cd dest
fpm -f -s dir -t deb -n protobuf -v 3.3.0 \
-C `pwd` \
--prefix / \
--vendor "You Not Debian" \
--license "$(grep Copyright ../../LICENSE)" \
--description "$(cat README.adoc)" \
--deb-upstream-changelog ../../CHANGES.txt \
--url "http:/somewhere/where/you/get/the/package/oritssource" \
usr/local/bin \
usr/local/lib \
usr/local/include
sudo apt install -f *.deb
sudo apt-get remove protobuf
Prefer apt to dpkg where you can.
I've also posted answer this here
If you check Thrown
for Common Language Runtime Exception
in the break when an exception window (Ctrl+Alt+E in Visual Studio), then the execution should break while you are debugging when the exception is thrown.
This will probably give you some insight into what is going on.
You can use an anonymous function, too:
$indexOfLastElement = count($array) - 1;
array_walk($array, function($element, $index) use ($indexOfLastElement) {
// do something
if (0 === $index) {
// first element‘s treatment
}
if ($indexOfLastElement === $index) {
// last not least
}
});
Three more things should be mentioned:
array_values
first.$element
you have to pass it by reference (&$element
).$indexOfLastElement
inside the use
construct, again by reference if needed.Write the src tag for calling the js file as
<script type='text/javascript' src='../Users/myUserName/Desktop/myPage.js'></script>
This should work.
Here's an approach using the URL() interface:
new URL(location.pathname, location.href).href
All the languages you've mentioned are Turing Complete, so in theory there is nothing one can do and another can't. In practice of course, there are differences, especially in productivity and efficiency. Compared to C, C++ and Java, which are static typed, Python is a dynamic language and can help you write the same code in significantly fewer lines. Python has a moto "batteries included", which means that the standard library offers all the things needed to build a complex application. Other languages would need external libraries for this. On top of this, since Python is an old and mature language (older than Java), many external libraries (for game development and scientific calculations just to mention a few) have been evolved. So Python can be used to program desktop applications and in fact in some cases more efficiently than other traditional languages.
Python is also a scripting language. This means that you can easily and quickly write scripts and simple tests with it.
More recently python is also used for web frameworks. Since there is a big code base and many python programmers, this was a logical thing to do. These web frameworks follow the practice mainly introduced by Ruby on Rails.
Here is an example of concatenation operator:
architecture EXAMPLE of CONCATENATION is
signal Z_BUS : bit_vector (3 downto 0);
signal A_BIT, B_BIT, C_BIT, D_BIT : bit;
begin
Z_BUS <= A_BIT & B_BIT & C_BIT & D_BIT;
end EXAMPLE;
You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.
Try using the exact, or absolute, path.
After having this problem myself, I found a solution that works for me:
Error message:
ssh -v [email protected]
OpenSSH_5.8p1, OpenSSL 1.0.0d 8 Feb 2011
debug1: Connecting to github.com [207.97.227.239] port 22.
debug1: connect to address 207.97.227.239 port 22: Connection timed out
ssh: connect to host github.com port 22: Connection timed out
ssh: connect to host github.com port 22: Bad file number
You will only see the bad file number message when on windows using the MINGGW shell. Linux users will just get Timed out.
Problem:
SSH is probably blocked on port 22. You can see this by typing
$nmap -sS github.com -p 22
Starting Nmap 5.35DC1 ( http://nmap.org ) at 2011-11-05 10:53 CET
Nmap scan report for github.com (207.97.227.239)
Host is up (0.10s latency).
PORT STATE SERVICE
22/tcp ***filtered*** ssh
Nmap done: 1 IP address (1 host up) scanned in 2.63 seconds
As you can see the state is Filtered, which means something is blocking it. You can solve this by performing an SSH to port 443 (your firewall / isp will not block this). It is also important that you need to ssh to "ssh.github.com" instead of github.com. Otherwise, you will report to the webserver instead of the ssh server. Below are all the steps needed to solve this problem.
Solution:
(First of all make sure you generated your keys like explained on http://help.github.com/win-set-up-git/)
create file ~/.ssh/config (ssh config file located in your user directory.
On windows probably %USERPROFILE%\.ssh\config
Paste the following code in it:
Host github.com
User git
Hostname ssh.github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
Port 443
Save the file.
Perform ssh like usual:
$ssh -T github.com
$Enter passphrase for key '.......... (you can smile now :))
Note that I do not have to supply the username or port number.
public static Bitmap resizeAndCropCenter(Bitmap bitmap, int size, boolean recycle) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
if (w == size && h == size) return bitmap;
// scale the image so that the shorter side equals to the target;
// the longer side will be center-cropped.
float scale = (float) size / Math.min(w, h);
Bitmap target = Bitmap.createBitmap(size, size, getConfig(bitmap));
int width = Math.round(scale * bitmap.getWidth());
int height = Math.round(scale * bitmap.getHeight());
Canvas canvas = new Canvas(target);
canvas.translate((size - width) / 2f, (size - height) / 2f);
canvas.scale(scale, scale);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
canvas.drawBitmap(bitmap, 0, 0, paint);
if (recycle) bitmap.recycle();
return target;
}
private static Bitmap.Config getConfig(Bitmap bitmap) {
Bitmap.Config config = bitmap.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
return config;
}
Extend LinearLayout/RelativeLayout and use it straight on the XML
package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
Paint paint;
public LinearLayoutOutlined(Context context) {
super(context);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
public LinearLayoutOutlined(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
/*
Paint fillPaint = paint;
fillPaint.setARGB(255, 0, 255, 0);
fillPaint.setStyle(Paint.Style.FILL);
canvas.drawPaint(fillPaint) ;
*/
Paint strokePaint = paint;
strokePaint.setARGB(255, 255, 0, 0);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Rect r = canvas.getClipBounds() ;
Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
canvas.drawRect(outline, strokePaint) ;
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.pkg_name.LinearLayoutOutlined
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=...
android:layout_height=...
>
... your widgets here ...
</com.pkg_name.LinearLayoutOutlined>
As far as I know there is no mechanism for doing this in JUnit, however you could try subclassing Suite and overriding the run() method with a version that does provide hooks.
You only need <script></script>
Tag that's it. <script type="text/javascript"></script>
is not a valid HTML tag, so for best SEO practice use <script></script>
{/*_x000D_
<Header />_x000D_
<Content />_x000D_
<MapList />_x000D_
<HelloWorld />_x000D_
*/}
_x000D_
I wrote a plugin that does this. Ive been working on it for about a year now and I think it handles all the corner cases pretty well:
Here are some demos/docs:
http://mkoryak.github.io/floatThead/
If you have lombok, you can annotate your method with @SneakyThrows
SneakyThrow does not silently swallow, wrap into RuntimeException, or otherwise modify any exceptions of the listed checked exception types. The JVM does not check for the consistency of the checked exception system; javac does, and this annotation lets you opt out of its mechanism.
The overload that you're using sets the enumeration of serialization formatters. You need to specify the content type explicitly like:
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
Instead of $(element).hasClass('example')
in jQuery, you can use element.matches('.example')
in plain JavaScript:
if (element.matches('.example')) {
// Element has example class ...
}
i'm using arrayadpter ,using this follwed code i'm able to get items
String value = (String)adapter.getItemAtPosition(position);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String string=adapter.getItem(position);
Log.d("**********", string);
}
});
I'll assume you meant more or less what you said, and you want to find keywords in your table that "contain the letter 'a' and the letter 'b'." Some of the solutions here give the answer to a different question.
To get keywords that contain both the letters 'a' and 'b' in them (as opposed to those that contain either letter), you can use 'ab' as the in the query below:
select
keyword
from myTable
where not exists (
select Nums26.i from Nums26
where Nums26.i <= len(<matchsetstring>) -- or your dialect's equivalent for LEN()
and keyword not like '%'+substring(<matchsetstring>,Nums26.i,1)+'%' -- adapt SUBSTRING to your dialect
);
The table named "Nums26" should contain a column "i" (indexed for efficiency) that contains each of the values 1 through 26 (or more if you might try to match more than letters). See below. Advice given by others applies with regard to upper/lower case. If your collation is case-sensitive, however, you can't simply specify 'aAbB' here as your , because that would request keywords that contain each of the four characters a, A, b, and B. You might use UPPER and match 'AB', perhaps.
create table nums26 (
i int primary key
);
insert into nums26 values (1);
insert into nums26 select 1+i from nums26;
insert into nums26 select 2+i from nums26;
insert into nums26 select 4+i from nums26;
insert into nums26 select 8+i from nums26;
insert into nums26 select 16+i from nums26;
Datetime is a datatype.
Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.
For more information:
http://www.sqlteam.com/article/timestamps-vs-datetime-data-types
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
For gcc you want to omit any -O1 -O2 or -O3 options passed to the compiler or if you already have them you can append the -O0 option to turn it off again. It might also help you to add -g for debug so that you can see the c source and disassembled machine code in your debugger.
See also: http://sourceware.org/gdb/onlinedocs/gdb/Optimized-Code.html
I think I figured out the problem, this input field is part of a reactive form (?), since you have included formControlName
. This means that what you are trying to do by disabling the input field with is_edit
is not working, e.g your attempt [disabled]="is_edit"
, which would in other cases work. With your form you need to do something like this:
toggle() {
let control = this.myForm.get('name')
control.disabled ? control.enable() : control.disable();
}
and lose the is_edit
altogether.
if you want the input field to be disabled as default, you need to set the form control as:
name: [{value: '', disabled:true}]
Here's a plunker
In this example, the line do_something_else()
will not be executed if do_not_continue
is True
. Control will return, instead, to whichever function called some_function
.
def some_function():
if do_not_continue:
return # implicitly, this is the same as saying `return None`
do_something_else()
For those of you that are looking for a way to install Maven in 2018:
$ sudo yum install maven
is supported these days.
<html>
<head>
<script>
function putText() {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
}
</script>
</head>
<body onLoad = putText()>
<a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html
You can, but be aware of the return types with jQuery functions. jQuery won't always use the exact same JavaScript object type, although generally they will return subclasses of what you would expect to be returned from a similar JavaScript function.
This code I programmed is much faster for very large files:
public String readDoc(File f) {
String text = "";
int read, N = 1024 * 1024;
char[] buffer = new char[N];
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while(true) {
read = br.read(buffer, 0, N);
text += new String(buffer, 0, read);
if(read < N) {
break;
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
return text;
}
It will be fixed 64 chars, so use char(64)
Step 1: Freeze requirement & take a back-up of existing env
pip freeze > requirements.txt
deactivate
mv env env_old
Step 2: Install Python 3.7 & activate virutal environment
sudo apt-get install python3.7-venv
python3.7 -m venv env
source env/bin/activate
python --version
Step 3: Install requirements
sudo apt-get install python3.7-dev
pip3 install -r requirements.txt
Use set or select
SET @counter := 100;
SELECT @variable_name := value;
example :
SELECT @price := MAX(product.price)
FROM product
In my case the validation itself was working (I could validate an element and retrieve a correct boolean value), but there was no visual output.
My fault was that I forgot this line @Html.ValidationMessageFor(m => ...)
The TS has this in his code and got me on the right track, but I put it in here as reference for others.
This error occurs because VMware has a bug that uses the absolute path of the disk file in certain situations.
If you look at the top of that small *.vmdk file you'll likely see an incorrect absolute path to the original VMDK file that needs to be corrected.
This error happens when you have a ViewBag Non-Existent in your razor code calling a method.
Controller
public ActionResult Accept(int id)
{
return View();
}
razor:
<div class="form-group">
@Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Flag(Model.from)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@
</div>
</div>
For some reason, the .net aren't able to show the error in the correct line.
Normally this causes a lot of wasted time.
If you have already run your original migration (before editing it), then you need to generate a new migration (rails generate migration add_email_to_users email:string
will do the trick).
It will create a migration file containing line:
add_column :users, email, string
Then do a rake db:migrate
and it'll run the new migration, creating the new column.
If you have not yet run the original migration you can just edit it, like you're trying to do. Your migration code is almost perfect: you just need to remove the add_column
line completely (that code is trying to add a column to a table, before the table has been created, and your table creation code has already been updated to include a t.string :email
anyway).
I think they updated the html5 video and deprecated some codecs. It worked for me after removing the codecs.
In the below example:
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4; codecs='avc1.42E01E, mp4a.40.2'">_x000D_
<source src="sample-clip.webm" type="video/webm; codecs='vp8, vorbis'"> _x000D_
</video>_x000D_
_x000D_
must be changed to_x000D_
_x000D_
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4">_x000D_
<source src="sample-clip.webm" type="video/webm">_x000D_
</video>
_x000D_
I'm using Windows 10, Python 3.6 on Anaconda 3 and have faced the same issue.
I've had it work by doing the following in sequence:
worked fine after that.
I made this work in this way:
<button class="btn" ng-click='toggleClass($event)'>button one</button>
<button class="btn" ng-click='toggleClass($event)'>button two</button>
in your controller:
$scope.toggleClass = function (event) {
$(event.target).toggleClass('active');
}
Typescript fails in your case because it expects all the fields to be present. Use Record and Partial utility types to solve it.
Record<string, Partial<IPerson>>
interface IPerson {
firstName: string;
lastName: string;
}
var persons: Record<string, Partial<IPerson>> = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
Explanation.
Alternate.
If you wish to make last name optional you can append a ? Typescript will know that it's optional.
lastName?: string;
https://www.typescriptlang.org/docs/handbook/utility-types.html
The answer by Craig Ringer is correct. Here's a little more info for Postgres 9.1 and later…
You can only install an extension if it has already been built for your Postgres installation (your cluster in Postgres lingo). For example, I found the uuid-ossp extension included as part of the installer for Mac OS X kindly provided by EnterpriseDB.com. Any of a few dozen extensions may be available.
To see if the uuid-ossp extension is available in your Postgres cluster, run this SQL to query the pg_available_extensions
system catalog:
SELECT * FROM pg_available_extensions;
To install that UUID-related extension, use the CREATE EXTENSION command as seen in this this SQL:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
Beware: I found the QUOTATION MARK characters around extension name to be required, despite documentation to the contrary.
The SQL standards committee or Postgres team chose an odd name for that command. To my mind, they should have chosen something like "INSTALL EXTENSION" or "USE EXTENSION".
You can verify the extension was successfully installed in the desired database by running this SQL to query the pg_extension
system catalog:
SELECT * FROM pg_extension;
For more info, see the Question: Default value for UUID column in Postgres
The information above uses the new Extensions feature added to Postgres 9.1. In previous versions, we had to find and run a script in a .sql file. The Extensions feature was added to make installation easier, trading a bit more work for the creator of an extension for less work on the part of the user/consumer of the extension. See my blog post for more discussion.
By the way, the code in the Question calls the function uuid_generate_v4()
. This generates a type known as Version 4 where nearly all of the 128 bits are randomly generated. While this is fine for limited use on smaller set of rows, if you want to virtually eliminate any possibility of collision, use another "version" of UUID.
For example, the original Version 1 combines the MAC address of the host computer with the current date-time and an arbitrary number, the chance of collisions is practically nil.
For more discussion, see my Answer on related Question.
\renewcommand{\@listI}{%
\leftmargin=25pt
\rightmargin=0pt
\labelsep=5pt
\labelwidth=20pt
\itemindent=0pt
\listparindent=0pt
\topsep=0pt plus 2pt minus 4pt
\partopsep=0pt plus 1pt minus 1pt
\parsep=0pt plus 1pt
\itemsep=\parsep}
It depends on what type of fading you are looking for.
But with shadow and rounded corners you can get a nice result. Rounded corners because the bigger the shadow, the weirder it will look in the edges unless you balance it out with rounded corners.
also.. http://css3pie.com/
Instead of trying to modify the $scope
within the service, you can implement a $watch
within your controller to watch a property on your service for changes and then update a property on the $scope
. Here is an example you might try in a controller:
angular.module('cfd')
.controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.students = null;
(function () {
$scope.$watch(function () {
return StudentService.students;
}, function (newVal, oldVal) {
if ( newValue !== oldValue ) {
$scope.students = newVal;
}
});
}());
}]);
One thing to note is that within your service, in order for the students
property to be visible, it needs to be on the Service object or this
like so:
this.students = $http.get(path).then(function (resp) {
return resp.data;
});
Always get a positive random number.
var nexnumber = Guid.NewGuid().GetHashCode();
if (nexnumber < 0)
{
nexnumber *= -1;
}
I will prefer to use findIndex()
method:
var index = myArray.findIndex('hello','stevie');
index
will give you the index number.
Yes, you can 'refresh' a Google Map like this:
google.maps.event.trigger(map, 'resize');
This basically sends a signal to your map to redraw it.
Hope that helps!
You can't represent most decimal fractions exactly with binary floating point types (which is what ECMAScript uses to represent floating point values). So there isn't an elegant solution unless you use arbitrary precision arithmetic types or a decimal based floating point type. For example, the Calculator app that ships with Windows now uses arbitrary precision arithmetic to solve this problem.
You can't. You can only style the visited state.
For other people who find this, make sure that you have them in the right order:
a {color:#FF0000;} /* Unvisited link */
a:visited {color:#00FF00;} /* Visited link */
a:hover {color:#FF00FF;} /* Mouse over link */
a:active {color:#0000FF;} /* Selected link */
There are several ways to do a cross join or cartesian product:
SELECT column_names FROM table1 CROSS JOIN table2;
SELECT column_names FROM table1, table2;
SELECT column_names FROM table1 JOIN table2;
Neglecting the on condition in the third case is what results in a cross join.
Check Class.java
source code for equals()
public boolean equals(Object obj) {
return this == obj;
}
Here you can add one month for the first day of current month than delete 1 day from that day.
DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
Whats you are looking for is jQuery Ajax. And then just setup a php page to process the request.
Add a level in your appsettings.json :
{
"MySettings": {
"MyArray": [
"str1",
"str2",
"str3"
]
}
}
Create a class representing your section :
public class MySettings
{
public List<string> MyArray {get; set;}
}
In your application startup class, bind your model an inject it in the DI service :
services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));
And in your controller, get your configuration data from the DI service :
public class HomeController : Controller
{
private readonly List<string> _myArray;
public HomeController(IOptions<MySettings> mySettings)
{
_myArray = mySettings.Value.MyArray;
}
public IActionResult Index()
{
return Json(_myArray);
}
}
You can also store your entire configuration model in a property in your controller, if you need all the data :
public class HomeController : Controller
{
private readonly MySettings _mySettings;
public HomeController(IOptions<MySettings> mySettings)
{
_mySettings = mySettings.Value;
}
public IActionResult Index()
{
return Json(_mySettings.MyArray);
}
}
The ASP.NET Core's dependency injection service works just like a charm :)
I think your problem is your version numbers. Try making 8.1 --> 8.01, and so forth. That should put the points in the right order.
Alternatively, you could plot using X
, where X is the column number you want, instead of using 1:X
. That will plot those values on the y axis and integers on the x axis. Try:
plot "ls.dat" using 2 title 'Removed' with lines, \
"ls.dat" using 3 title 'Added' with lines, \
"ls.dat" using 4 title 'Modified' with lines
In eclipse,
.jrxml
file and select Open with JasperReports Book Editor
Design
tab for the .jrxml
file.Compile Report
icon.Just to share, I've developed my own script to do it. Feel free to use it. It generates "SELECT" statements that you can then run on the tables to generate the "INSERT" statements.
select distinct 'SELECT ''INSERT INTO ' + schema_name(ta.schema_id) + '.' + so.name + ' (' + substring(o.list, 1, len(o.list)-1) + ') VALUES ('
+ substring(val.list, 1, len(val.list)-1) + ');'' FROM ' + schema_name(ta.schema_id) + '.' + so.name + ';'
from sys.objects so
join sys.tables ta on ta.object_id=so.object_id
cross apply
(SELECT ' ' +column_name + ', '
from information_schema.columns c
join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
cross apply
(SELECT '''+' +case
when data_type = 'uniqueidentifier' THEN 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
WHEN data_type = 'timestamp' then '''''''''+CONVERT(NVARCHAR(MAX),CONVERT(BINARY(8),[' + COLUMN_NAME + ']),1)+'''''''''
WHEN data_type = 'nvarchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'varchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'char' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'nchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
when DATA_TYPE='datetime' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='datetime2' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='geography' and column_name<>'Shape' then 'ST_GeomFromText(''POINT('+column_name+'.Lat '+column_name+'.Long)'') '
when DATA_TYPE='geography' and column_name='Shape' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
when DATA_TYPE='bit' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
when DATA_TYPE='xml' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE(CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + ']),'''''''','''''''''''')+'''''''' END '
WHEN DATA_TYPE='image' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),CONVERT(VARBINARY(MAX),[' + COLUMN_NAME + ']),1)+'''''''' END '
WHEN DATA_TYPE='varbinary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
WHEN DATA_TYPE='binary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
when DATA_TYPE='time' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
ELSE 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE CONVERT(NVARCHAR(MAX),['+column_name+']) END' end
+ '+'', '
from information_schema.columns c
join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) val (list)
where so.type = 'U'
If destination file is read only use /y/r
xcopy /y/r source.txt dest.txt
Use the command:
git rev-parse HEAD
For the short version:
git rev-parse --short HEAD
It worked after I changed the "docker login https://hub.docker.com" to "docker login docker.io" and provided username & password.
Then follow below commands:
docker tag local-image:tagname new-repo:tagname
docker push new-repo:tagname
NOTE: "new-repo" will contain "Docker ID + Repo name"
Here I have created "ubuntu" repo in the Docker Hub before running below command.
Example:
docker tag alok/ubuntu:latest aloktiwari2007/ubuntu:latest
docker push aloktiwari2007/ubuntu:latest
Methods like sleep()
and wait()
of class Thread
might throw an InterruptedException
. This will happen if some other thread
wanted to interrupt the thread
that is waiting or sleeping.
... and here is the C version:
void permute(const char *s, char *out, int *used, int len, int lev)
{
if (len == lev) {
out[lev] = '\0';
puts(out);
return;
}
int i;
for (i = 0; i < len; ++i) {
if (! used[i])
continue;
used[i] = 1;
out[lev] = s[i];
permute(s, out, used, len, lev + 1);
used[i] = 0;
}
return;
}
Had the same problem, while differently from other answers in my case I use ASP.NET to develop the WebAPI server.
I already had Corps allowed and it worked for GET requests. To make POST requests work I needed to add 'AllowAnyHeader()' and 'AllowAnyMethod()' options to the list of Corp options.
Here are essential parts of related functions in Start class look like:
ConfigureServices method:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
;
});
});
Configure method:
app.UseCors(MyAllowSpecificOrigins);
Found this from:
To answer one of the questions, it is necessary to have both a global and local install for the tools to work.
If you try to run ng serve
on an application without the local install of the CLI (global install only), you will get the following error.
You have to be inside an Angular CLI project in order to use the serve command.
It will also print this message:
Please take the following steps to avoid issues:
"npm install --save-dev @angular/cli@latest"
Run that npm
command to update the CLI locally, and avoid the warning that you are getting.
Other question: It looks like they do not have to be in sync, but it's probably best that they are in order to avoid any unusual behavior with the tool, or any inconsistencies with the code the tool generates.
Why do we need both the global install, and a local install?
The global install is needed to start a new application. The ng new <app-name>
command is run using the global installation of the CLI. In fact, if you try to run ng new
while inside the folder structure of an existing CLI application, you get this lovely error:
You cannot use the
new
command inside an Angular CLI project.
Other commands that can be run from the global install are ng help
, ng get/set
with the --global
option, ng version
, ng doc
, and ng completion
.
The local install of the CLI is used after an application has been built. This way, when new versions of the CLI are available, you can update your global install, and not affect the local install. This is good for the stability of a project. Most ng
commands only make sense with the local version, like lint
, build
and serve
, etc.
According to the CLI GitHub readme, to update the CLI you must update the global and local package. However, I have used the CLI where the global and local version vary without any trouble so far. If I ever run across an error related to having the global and local CLI versions out of sync, I will post that here.
delete sub from (select ROW_NUMBER() OVer(Partition by empid order by empid)cnt from employee)sub where sub.cnt>1
Follow these steps and your datanode will start again.
you can make a jQuery onChange event to get the text from the combobox when the user select one of them:
<script>
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$('#EvaluationName').val(str);
})
.change();
</script>
When you select an option, it will save the text in an Input hidde
<input type="hidden" id="EvaluationName" name="EvaluationName" value="<?= $Evaluation ?>" />
After that, when you submit the form, just catch up the value of the input
$Evaluation = $_REQUEST['EvaluationName'];
Then you can do wathever you want with the text, for instance save it in a session variable and send it to other page. etc.
You can use an inline if inside your ngStyle:
[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"
A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:
[style.background-color]="myColorVaraible"
So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:
If you mean to disable the code, you just have to put <h1>
in search, and replace to ####
.
But if you want to use this regex instead, you may enable it in the icon: and use the regex: <h1>(.+?)<\/h1>
and replace to: #### $1
.
And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:
Another reason not mentioned above is that many built-in functions and methods of built-in types modify an object but do not return the modified object. If those modified objects were returned, that would make functional code cleaner and more concise. For example, if some_list.append(some_object) returned some_list with some_object appended.
I try with next code and work excellent
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by jaime on 14/01/15.
*/
@Controller
public class obteinUserSession {
@RequestMapping(value = "/loginds", method = RequestMethod.GET)
public String UserSession(ModelMap modelMap) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
modelMap.addAttribute("username", name);
return "hellos " + name;
}
You can use the dynamic object ViewBag
to pass data from Controllers to Views.
Add the following to your controller:
ViewBag.MyList = myList;
Then you can acces it from your view:
@ViewBag.MyList
// e.g.
@foreach (var item in ViewBag.MyList) { ... }
Try this:
from Tkinter import *
import sys
def exitApp():
sys.exit()
root = Tk()
Button(root, text="Quit", command=exitApp).pack()
root.mainloop()
I would like to add, [ngValue]="..." support strings, but you need to add simple quotes if it represents a number, like [ngValue]="'...'". It was to complement the Günter Zöchbauer answer.
This question has been answered already, but thought I'd add to the mix what I found out when I got these messages.
I have a repo called playground
that contains a number of sandbox apps. I added two new apps from a tutorial to the playground
directory by cloning the tutorial's repo. The result was that the new apps' git stuff pointed to the tutorial's repo and not to my repo. The solution was to delete the .git
directory from each of those apps' directories, mv
the apps' directories outside the playground
directory, and then mv
them back and run git add .
. After that it worked.
100,000 should be fine.
I have (anecdotally) seen people having problems with many millions of files and I have had problems myself with Explorer just not having a clue how to count past 60-something thousand files, but NTFS should be good for the volumes you're talking.
In case you're wondering, the technical (and I hope theoretical) maximum number of files is: 4,294,967,295
If you ought to spare memory, read char by char and realloc each time. Performance will die, but you'll spare this 10 bytes.
Another good tradeoff is to read in a function (using a local variable) then copying. So the big buffer will be function scoped.
ApplicationId must be of type UniqueIdentifier
. Your code works fine if you do:
DECLARE @TTEST TABLE
(
TEST UNIQUEIDENTIFIER
)
DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();
INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);
SELECT * FROM @TTEST
Therefore I would say it is safe to assume that ApplicationId
is not the correct data type.
Although the question has been answered, let me mention some nuances.
Let's say you are interested in the first column of the array
arr = numpy.array([[1, 2],
[3, 4],
[5, 6]])
As you already know from other answers, to get it in the form of "row vector" (array of shape (3,)
), you use slicing:
arr_col1_view = arr[:, 1] # creates a view of the 1st column of the arr
arr_col1_copy = arr[:, 1].copy() # creates a copy of the 1st column of the arr
To check if an array is a view or a copy of another array you can do the following:
arr_col1_view.base is arr # True
arr_col1_copy.base is arr # False
see ndarray.base.
Besides the obvious difference between the two (modifying arr_col1_view
will affect the arr
), the number of byte-steps for traversing each of them is different:
arr_col1_view.strides[0] # 8 bytes
arr_col1_copy.strides[0] # 4 bytes
Why is this important? Imagine that you have a very big array A
instead of the arr
:
A = np.random.randint(2, size=(10000, 10000), dtype='int32')
A_col1_view = A[:, 1]
A_col1_copy = A[:, 1].copy()
and you want to compute the sum of all the elements of the first column, i.e. A_col1_view.sum()
or A_col1_copy.sum()
. Using the copied version is much faster:
%timeit A_col1_view.sum() # ~248 µs
%timeit A_col1_copy.sum() # ~12.8 µs
This is due to the different number of strides mentioned before:
A_col1_view.strides[0] # 40000 bytes
A_col1_copy.strides[0] # 4 bytes
Although it might seem that using column copies is better, it is not always true for the reason that making a copy takes time too and uses more memory (in this case it took me approx. 200 µs to create the A_col1_copy
). However if we needed the copy in the first place, or we need to do many different operations on a specific column of the array and we are ok with sacrificing memory for speed, then making a copy is the way to go.
In the case we are interested in working mostly with columns, it could be a good idea to create our array in column-major ('F') order instead of the row-major ('C') order (which is the default), and then do the slicing as before to get a column without copying it:
A = np.asfortranarray(A) # or np.array(A, order='F')
A_col1_view = A[:, 1]
A_col1_view.strides[0] # 4 bytes
%timeit A_col1_view.sum() # ~12.6 µs vs ~248 µs
Now, performing the sum operation (or any other) on a column-view is as fast as performing it on a column copy.
Finally let me note that transposing an array and using row-slicing is the same as using the column-slicing on the original array, because transposing is done by just swapping the shape and the strides of the original array.
A[:, 1].strides[0] # 40000 bytes
A.T[1, :].strides[0] # 40000 bytes
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {_x000D_
var checked = false;_x000D_
if (document.querySelector('#opt1:checked')) {_x000D_
checked = true;_x000D_
}_x000D_
document.getElementById('msg').innerText = checked;_x000D_
}
_x000D_
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
_x000D_
According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.
And too many addresses in this post.
Use the DataFrame returned by:
yourDF.orderBy(account)
There is no explicit way to use partitionBy
on a DataFrame, only on a PairRDD, but when you sort a DataFrame, it will use that in it's LogicalPlan and that will help when you need to make calculations on each Account.
I just stumbled upon the same exact issue, with a dataframe that I want to partition by account.
I assume that when you say "want to have the data partitioned so that all of the transactions for an account are in the same Spark partition", you want it for scale and performance, but your code doesn't depend on it (like using mapPartitions()
etc), right?
You can see answers at here Get Android Phone Model Programmatically
public String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
}
private String capitalize(String s) {
if (s == null || s.length() == 0) {
return "";
}
char first = s.charAt(0);
if (Character.isUpperCase(first)) {
return s;
} else {
return Character.toUpperCase(first) + s.substring(1);
}
}
One way:
SELECT DISTINCT sc.StoreId
FROM StoreClients sc
WHERE NOT EXISTS(
SELECT * FROM StoreClients sc2
WHERE sc2.StoreId = sc.StoreId AND sc2.ClientId = 5)
You can use 'category_name' in parameters. http://codex.wordpress.org/Template_Tags/get_posts
Note: The category_name parameter needs to be a string, in this case, the category name.
You could keep it simple and use the native color translator:
Color red = ColorTranslator.FromHtml("#FF0000");
string redHex = ColorTranslator.ToHtml(red);
Then break the three color pairs into integer form:
int value = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
var module = angular.module("example", []);
module.controller("orderByController", function ($scope) {
$scope.orderByValue = function (value) {
return value;
};
$scope.items = ["c", "b", "a"];
$scope.objList = [
{
"name": "c"
}, {
"name": "b"
}, {
"name": "a"
}];
$scope.item = "b";
});
It require to include Content-Type:application/json
in web api request header section when not mention any content then by default it is Content-Type:text/plain
passes to request.
Best way to test api on postman tool.
data = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
col_width = max(len(word) for row in data for word in row) + 2 # padding
for row in data:
print "".join(word.ljust(col_width) for word in row)
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
What this does is calculate the longest data entry to determine the column width, then use .ljust()
to add the necessary padding when printing out each column.
Try this:
MyContext Context = new MyContext();
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;
document.getElementById("myspan").textContent="newtext";
this will select dom-node with id myspan
and change it text content to new text
I have similar problem when I reinstall my python, by uninstalling python3.7 and installing python3.8. But I solved it by removing the previous version of python directory. For me it was located here,
C:\Users\your-username\AppData\Local\Programs\Python
I deleted the folder named Python37 (for previous version) and keep Python38 (for updated version). This worked because python itself seems having a trouble on finding the right directory for your python scripts.
Do you have access to your database, if so just open it up and look up the column and use an SQL call to retrieve the needed.
A short example on a form to retrieve data from a database table:
Form contain only a GataGridView named DataGrid
Database name: DB.mdf
Table name: DBtable
Column names in table: Name as varchar(50), Age as int, Gender as bit.
Private Sub DatabaseTest_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Public ConString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\{username}\documents\visual studio 2010\Projects\Userapplication prototype v1.0\Userapplication prototype v1.0\Database\DB.mdf;" & "Integrated Security=True;User Instance=True"
Dim conn As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand
Dim da As New SqlClient.SqlDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New SqlClient.SqlConnection(ConString)
conn.Open() 'connects to the database
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT * FROM DBtable" 'Sql to be executed
cmd.CommandText = sSQL 'makes the string a command
da.SelectCommand = cmd 'puts the command into the sqlDataAdapter
da.Fill(dt) 'populates the dataTable by performing the command above
Me.DataGrid.DataSource = dt 'Updates the grid using the populated dataTable
'the following is only if any errors happen:
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close() 'closes the connection again so it can be accessed by other users or programs
End Try
End Sub
This will fetch all the rows and columns from your database table for review.
If you want to only fetch the names just change the sql call with: "SELECT Name FROM DBtable" this way the DataGridView will only show the column names.
I'm only a rookie but i would strongly advise to get rid of theses auto generate wizards. Using SQL you have full access to your database and what happens.
Also one last thing, if your database doesn't use SQLClient just change it to OleDB.
Example: "Dim conn As New SqlClient.SqlConnection
" becomes: Dim conn As New OleDb.OleDbConnection
I find it very clean to use the internal variable "$SECONDS"
SECONDS=0 ; sleep 10 ; echo $SECONDS
Probably you are looking for something like this:
Accept "2.0 or 2.0 as an INT but reject 2.1 and "2.1"
num = 2.0
if num.is_a? String num = Float(num) rescue false end
new_num = Integer(num) rescue false
puts num
puts new_num
puts num == new_num
The cex
parameter will do that for you.
a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
col = 1:6, space = c(0, 2))
legend("topright",
legend = c("a", "b", "c", "d", "e", "f"),
fill = 1:6, ncol = 2,
cex = 0.75)
you need to add the javascript language file,after the moment library, example:
<script type="text/javascript" src="js/moment/moment.js"></script>
<script type="text/javascript" src="js/moment/es.js"></script>
now you can set a language.
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({locale:'es'});
});
</script>
Here are all language: https://github.com/moment/moment
Stashes are not meant to be permanent things like you want. You'd probably be better served using tags on commits. Construct the thing you want to stash. Make a commit out of it. Create a tag for that commit. Then roll back your branch to HEAD^
. Now when you want to reapply that stash you can use git cherry-pick -n tagname
(-n
is --no-commit
).
As I said in the comments, a <div>
element does not have a value
attribute. Although (very) bad, it can be accessed as:
console.log(document.getElementById('demo').getAttribute);
I suggest using HTML5 data-*
attributes rather. Something like this:
<div id="demo" data-myValue="1">...</div>
in which case you could access it using:
element.getAttribute('data-myValue');
//Or using jQuery:
$('#demo').data('myValue');
In React-Native we have an Option called Dimensions
Include Dimensions at the top var where you have include the Image,and Text and other components.
Then in your Stylesheets you can use as below,
ex: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
}
In this way you can get the device window and height.
```{r results='hide', message=FALSE, warning=FALSE}
library(RJSONIO)
library(AnotherPackage)
```
see Chunk Options in the Knitr docs
On top of all the other explanations, I believe you're using equal "="
sign, instead of colon ":"
:
<span style="border:1px solid red;text-align=center">
It should be:
<span style="border:1px solid red;text-align:center">
The DPI of the screen of the Nexus 10 is ±300, which is in the unofficial xhdpi
range of 280-400.
Usually, devices use resources designed for their density. But there are exceptions, and exceptions might be added in the future.
The Nexus 10 uses xxhdpi
resources when it comes to launcher icons.
The standard quantised DPI for xxhdpi is 480 (which means screens with a DPI somewhere in the range of 400-560 are probably xxhdpi).
I realize this post is a few years old, but I just wanted to extend this to anyone still struggling through this issue.
The company I work for still uses VS2015 so in turn I still use VS2015. I recently started working on a RPC application using C++ and found the need to download the Win32 Templates. Like many others I was having this "SDK 8.1 was not found" issue. i took the following corrective actions with no luck.
None of the attempts above corrected the issue for me...
I then found this article on social MSDN https://social.msdn.microsoft.com/Forums/office/en-US/5287c51b-46d0-4a79-baad-ddde36af4885/visual-studio-cant-find-windows-81-sdk-when-trying-to-build-vs2015?forum=visualstudiogeneral
Finally what resolved the issue for me was:
I hope this saves anyone else from almost 3 full days of frustration and loss of productivity.
If the indexes are continuous:
foreach ($arr as $key => $val) {
if (isset($arr[$key+1])) {
echo $arr[$key+1]; // next element
} else {
// end of array reached
}
}
To retrieve data from form which send post request you can do it like this
def login_view(request):
if(request.POST):
login_data = request.POST.dict()
username = login_data.get("username")
password = login_data.get("password")
user_type = login_data.get("user_type")
print(user_type, username, password)
return HttpResponse("This is a post request")
else:
return render(request, "base.html")
def doubleChar(str):
result = ''
for char in str:
result += char * 2
return result
print(doubleChar("amar"))
output:
aammaarr
You can handle custom cell in uicollection view see below code.
- (void)viewDidLoad
{
UINib *nib2 = [UINib nibWithNibName:@"YourCustomCell" bundle:nil];
[CollectionVW registerNib:nib2 forCellWithReuseIdentifier:@"YourCustomCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(200, 230)];
flowLayout.minimumInteritemSpacing = 0;
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[CollectionVW setCollectionViewLayout:flowLayout];
[CollectionVW reloadData];
}
#pragma mark - COLLECTIONVIEW
#pragma mark Collection View CODE
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return Array.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"YourCustomCell";
YourCustomCell *cell = (YourCustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.MainIMG.image=[UIImage imageNamed:[Array objectAtIndex:indexPath.row]];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}
#pragma mark Collection view layout things
// Layout: Set cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize mElementSize;
mElementSize=CGSizeMake(kScreenWidth/3.4, 150);
return mElementSize;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 5.0;
}
// Layout: Set Edges
- (UIEdgeInsets)collectionView: (UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
if (isIphone5 || isiPhone4)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
else if (isIphone6)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
else if (isIphone6P)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
This is another alternate solution that can be implemented:
In the URL configuration:
urlpatterns = [path('runreport/<str:queryparams>', views.get)]
In the views:
list2 = queryparams.split("&")
My grep-a-like program ack
has a -1
option that stops at the first match found anywhere. It supports the -m 1
that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.
Take a look at this example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Do you mean include javascript variable values in the query string of the URL?
Yes:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;
Structure in C can be declared and initialized like this:
typedef struct book
{
char title[10];
char author[10];
float price;
} book;
int main() {
book b1={"DS", "Ajay", 250.0};
printf("%s \t %s \t %f", b1.title, b1.author, b1.price);
return 0;
}
Running 'pod update' in my project fixed my problem with the 'library not found for -lSTPopup' error.
Remarking Trevor Panhorst's answer:
"Just be careful doing pod update if you don't use explicit versions in your pod file."
As with the present java SE 8 release with it's excellent date time API with java.time
these kind of calculation can be done more easily instead of using java.util.Calendar
and java.util.Date
.
Now as a sample example for scheduling a task with your use case:
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
ZonedDateTime nextRun = now.withHour(5).withMinute(0).withSecond(0);
if(now.compareTo(nextRun) > 0)
nextRun = nextRun.plusDays(1);
Duration duration = Duration.between(now, nextRun);
long initalDelay = duration.getSeconds();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new MyRunnableTask(),
initalDelay,
TimeUnit.DAYS.toSeconds(1),
TimeUnit.SECONDS);
The initalDelay
is computed to ask the scheduler to delay the execution in TimeUnit.SECONDS
. Time difference issues with unit milliseconds and below seems to be negligible for this use case. But you can still make use of duration.toMillis()
and TimeUnit.MILLISECONDS
for handling the scheduling computaions in milliseconds.
And also TimerTask is better for this or ScheduledExecutorService?
NO: ScheduledExecutorService
seemingly better than TimerTask
. StackOverflow has already an answer for you.
From @PaddyD,
You still have the issue whereby you need to restart this twice a year if you want it to run at the right local time. scheduleAtFixedRate won't cut it unless you are happy with the same UTC time all year.
As it is true and @PaddyD already has given a workaround(+1 to him), I am providing a working example with Java8 date time API with ScheduledExecutorService
. Using daemon thread is dangerous
class MyTaskExecutor
{
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
MyTask myTask;
volatile boolean isStopIssued;
public MyTaskExecutor(MyTask myTask$)
{
myTask = myTask$;
}
public void startExecutionAt(int targetHour, int targetMin, int targetSec)
{
Runnable taskWrapper = new Runnable(){
@Override
public void run()
{
myTask.execute();
startExecutionAt(targetHour, targetMin, targetSec);
}
};
long delay = computeNextDelay(targetHour, targetMin, targetSec);
executorService.schedule(taskWrapper, delay, TimeUnit.SECONDS);
}
private long computeNextDelay(int targetHour, int targetMin, int targetSec)
{
LocalDateTime localNow = LocalDateTime.now();
ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
ZonedDateTime zonedNextTarget = zonedNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec);
if(zonedNow.compareTo(zonedNextTarget) > 0)
zonedNextTarget = zonedNextTarget.plusDays(1);
Duration duration = Duration.between(zonedNow, zonedNextTarget);
return duration.getSeconds();
}
public void stop()
{
executorService.shutdown();
try {
executorService.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException ex) {
Logger.getLogger(MyTaskExecutor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Note:
MyTask
is an interface with function execute
. ScheduledExecutorService
, Always use awaitTermination
after invoking shutdown
on it: There's always a likelihood your task is stuck / deadlocking and the user would wait forever.The previous example I gave with Calender was just an idea which I did mention, I avoided exact time calculation and Daylight saving issues. Updated the solution on per the complain of @PaddyD
Whenever I run into this issue with newer browsers, I just use AppRobotic Personal edition to click specific screen coordinates, or tab through the buttons and click.
Basically it's just using its macro functionality, but won't work on headless setups though.
If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom
.
Java 6 & 7:
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);
Java 8 (even more secure):
byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);
Use the GeoCoding API
For example, to lookup zip 77379 use a request like this:
If you have compatibility with Object.keys
, and node does have compatibility, you should use that for sure.
However, if you do not have compatibility, and for any reason using a loop function is out of the question - like me, I used the following solution:
JSON.stringify(obj) === '{}'
Consider this solution a 'last resort' use only if must.
See in the comments "there are many ways in which this solution is not ideal".
I had a last resort scenario, and it worked perfectly.
Now that “all” browsers support ES6, I’ve incorporated the various suggestions above into a JavaScript class that takes a table as an argument and makes the body scrollable. It lets the browser’s layout engine determine header and body cell widths, and then makes the column widths match each other.
The height of a table can be set explicitly, or made to fill the remaining part of the browser window, and provides callbacks for events such as viewport resizing and/or details
elements opening or closing.
Multi-row header support is available, and is especially effective if the table uses the id/headers attributes for accessibility as specified in the WCAC Guidelines, which is not as onerous a requirement as it might seem.
The code does not depend on any libraries, but plays nicely with them if they are being used. (Tested on pages that use JQuery).
The code and sample usage are available on Github.
This work for me in .NET Core 3.1.
But not in .NET 5 preview 7.
using System;
using System.Security.Cryptography;
using System.Text;
namespace PortalAplicaciones.Shared.Models
{
public class Encriptar
{
public static string EncriptaPassWord(string Password)
{
try
{
SHA256Managed hasher = new SHA256Managed();
byte[] pwdBytes = new UTF8Encoding().GetBytes(Password);
byte[] keyBytes = hasher.ComputeHash(pwdBytes);
hasher.Dispose();
return Convert.ToBase64String(keyBytes);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
}
}
You can use JavaScript CallBak like this:
var a;
function function1(callback) {
console.log("First comeplete");
a = "Some value";
callback();
}
function function2(){
console.log("Second comeplete:", a);
}
function1(function2);
Or Java Script Promise:
let promise = new Promise(function(resolve, reject) {
// do function1 job
let a = "Your assign value"
resolve(a);
});
promise.then(
function(a) {
// do function2 job with function1 return value;
console.log("Second comeplete:", a);
},
function(error) {
console.log("Error found");
});
Other way which I found useful is:
git checkout <wildcard>
Example:
git checkout *.html
More generally:
git checkout <branch> <filename/wildcard>
I had the same problem today. If after you delete all of the connections, the connection properties still live on. I clicked on properties, deleted the name by selecting the name window and deleting it.
A warning came up to verify I really wanted to do it. After selecting yes, it got rid of the connection. Save the workbook.
I am a hack at Excel but this seemed to work.
angular-cli resolves this by providing an --output-hashing
flag for the build command (versions 6/7, for later versions see here). Example usage:
ng build --output-hashing=all
Bundling & Tree-Shaking provides some details and context. Running ng help build
, documents the flag:
--output-hashing=none|all|media|bundles (String)
Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>
Although this is only applicable to users of angular-cli, it works brilliantly and doesn't require any code changes or additional tooling.
Update
A number of comments have helpfully and correctly pointed out that this answer adds a hash to the .js
files but does nothing for index.html
. It is therefore entirely possible that index.html
remains cached after ng build
cache busts the .js
files.
At this point I'll defer to How do we control web page caching, across all browsers?
Java implementations typically use a two-step compilation process. Java source code is compiled down to bytecode by the Java compiler. The bytecode is executed by a Java Virtual Machine (JVM). Modern JVMs use a technique called Just-in-Time (JIT) compilation to compile the bytecode to native instructions understood by hardware CPU on the fly at runtime.
Some implementations of JVM may choose to interpret the bytecode instead of JIT compiling it to machine code, and running it directly. While this is still considered an "interpreter," It's quite different from interpreters that read and execute the high level source code (i.e. in this case, Java source code is not interpreted directly, the bytecode, output of Java compiler, is.)
It is technically possible to compile Java down to native code ahead-of-time and run the resulting binary. It is also possible to interpret the Java code directly.
To summarize, depending on the execution environment, bytecode can be:
The AngularJS Bootstrap website hasn't been updated with the latest documentation. About 3 months ago pkozlowski-opensource authored a change to separate out $modal from $dialog commit is below:
https://github.com/angular-ui/bootstrap/commit/d7a48523e437b0a94615350a59be1588dbdd86bd
In that commit he added new documentation for $modal, which can be found below:
Hope this helps!
I know the question is old, but if someone is looking for a great new android color picker that use material design I have forked an great project from github and made a simple-to-use android color picker dialog.
This is the project: Android Color Picker
The aar artifact is available at the jcenter repository. Declare the repository and the
dependency in your build.gradle
.
(root)
repositories {
jcenter()
}
(module)
dependencies {
compile 'com.pes.materialcolorpicker:library:1.0.2'
}
Create a color picker dialog object
final ColorPicker cp = new ColorPicker(MainActivity.this, defaultColorR, defaultColorG, defaultColorB);
defaultColorR, defaultColorG, defaultColorB are 3 integer ( value 0-255) for the initialization of the color picker with your custom color value. If you don't want to start with a color set them to 0 or use only the first argument
Then show the dialog (when & where you want) and save the selected color
/* Show color picker dialog */
cp.show();
/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button)cp.findViewById(R.id.okColorButton);
okColor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* You can get single channel (value 0-255) */
selectedColorR = cp.getRed();
selectedColorG = cp.getGreen();
selectedColorB = cp.getBlue();
/* Or the android RGB Color (see the android Color class reference) */
selectedColorRGB = cp.getColor();
cp.dismiss();
}
});
That's all :)
Adding a bit to mitigate the confusion here. Even though Darren Davies' (accepted) answer is more straight forward, I think Andrei's answer is a better approach for MVC applications.
The answer from Andrei means that you can use HttpContext
just as you would use System.Web.HttpContext.Current
. For example, if you want to do this:
System.Web.HttpContext.Current.User.Identity.Name
you should instead do this:
HttpContext.User.Identity.Name
Both achieve the same result, but (again) in terms of MVC, the latter is more recommended.
Another good and also straight forward information regarding this matter can be found here: Difference between HttpContext.Current and Controller.Context in MVC ASP.NET.
Sometime limiting your data is also helpful, for example checkout the followings:
//This caused error:
print_r($request);
//This resolved issue:
print_r($request->all());
Spring-boot framework allows us to provide YAML files as a replacement for the .properties file and it is convenient.The keys in property files can be provided in YAML format in application.yml file in the resource folder and spring-boot will automatically take it up.Keep in mind that the yaml format has to keep the spaces correct for the value to be read correctly.
You can use the @Value("${property}")
to inject the values from the YAML files.
Also Spring.active.profiles can be given to differentiate between different YAML for different environments for convenient deployment.
For testing purposes, the test YAML file can be named like application-test.yml and placed in the resource folder of the test directory.
If you are specifying the application-test.yml
and provide the spring test profile in the .yml, then you can use the @ActiveProfiles('test')
annotation to direct spring to take the configurations from the application-test.yml that you have specified.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationTest.class)
@ActiveProfiles("test")
public class MyTest {
...
}
If you are using JUnit 5 then no need for other annotations as @SpringBootTest already include the springrunner annotation. Keeping a separate main ApplicationTest.class enables us to provide separate configuration classes for tests and we can prevent the default configuration beans from loading by excluding them from a component scan in the test main class. You can also provide the profile to be loaded there.
@SpringBootApplication(exclude=SecurityAutoConfiguration.class)
public class ApplicationTest {
public static void main(String[] args) {
SpringApplication.run(ApplicationTest.class, args);
}
}
Here is the link for Spring documentation regarding the use of YAML instead of .properties
file(s): https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
<div id="demo"></div>
<input type="submit" name="submit" id="submit" value="Submit" onClick="return empty()">
<script type="text/javascript">
function empty()
{
var x;
x = document.getElementById("feedbackpost").value;
if (x == "")
{
var demo = document.getElementById("demo");
demo.innerHTML =document.write='<h1>Hello member</h1>';
return false;
};
}
</script>
You can try this:
<a href="link.html">
<input type="button" value="Visit Page" />
</a>
This will create button inside a link and it works on any browser
I was pushing into the repository for the first time. So there was no HEAD
defined.
The easiest way would be to:
git push -u origin master
It will then prompt for the password, and once you enter that it will be saved automatically, and you will be able to push.
You can't add a new unique auto-generated ID to a SharePoint list, but there already is one there! If you edit the "All Items" view you will see a list of columns that do not have the display option checked.
There are quite a few of these columns that exist but that are never displayed, like "Created By" and "Created". These fields are used within SharePoint, but they are not displayed by default so as not to clutter up the display. You can't edit these fields, but you can display them to the user. if you check the "Display" box beside the ID field you will get a unique and auto-generated ID field displayed in your list.
Check out: Unique ID in SharePoint list
Here is one way (put this in Page_Load):
if (this.IsPostBack)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>var isPostBack = true;</script>");
}
Then just check that variable in the JS.
In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.
I would change to this, though. You don't need "ans" at all.
return String.format("%d:%d", mins, secs);
I ran into this recently. Our organization restricts the accounts that run application pools to a select list of servers in Active Directory. I found that I had not added one of the machines hosting the application to the "Log On To" list for the account in AD.
There is a good explanation at https://stackoverflow.com/a/33833319/903783
The values expected seem to be xlCopy and xlCut according to xlCutCopyMode enumeration (https://msdn.microsoft.com/en-us/VBA/Excel-VBA/articles/xlcutcopymode-enumeration-excel), but the 0 value (this is what False equals to in VBA) seems to be useful to clear Excel data put on the Clipboard.
According to the WWDC 713_hd_whats_new_in_ios_notifications. The previous size limit of 256 bytes for a push payload has now been increased to 2 kilobytes for iOS 8.
Source: http://asciiwwdc.com/2014/sessions/713?q=notification#1414.0
To be super clear, Collection.sort(list, compartor) does not return anything so something like this list = Collection.sort(list, compartor);
will throw an error (void cannot be converted to [list type]) and should instead be Collection.sort(list, compartor)
One way:
var1="1:2:3:4:5"
var2=${var1##*:}
Another, using an array:
var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
var2=${var2[@]: -1}
Yet another with an array:
var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
count=${#var2[@]}
var2=${var2[$count-1]}
Using Bash (version >= 3.2) regular expressions:
var1="1:2:3:4:5"
[[ $var1 =~ :([^:]*)$ ]]
var2=${BASH_REMATCH[1]}
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}