I would use itertools.chain
- this will also cater for > 1 element in each sublist:
from itertools import chain
list(chain.from_iterable([[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]))
If you just have the currency symbol and the number of decimal places, you can use the following helper function, which respects the symbol/amount order, separators etc, only changing the currency symbol itself and the number of decimal places to display to.
public static string FormatCurrency(string currencySymbol, Decimal currency, int decPlaces)
{
NumberFormatInfo localFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
localFormat.CurrencySymbol = currencySymbol;
localFormat.CurrencyDecimalDigits = decPlaces;
return currency.ToString("c", localFormat);
}
You are correct: calling finish()
will only exit the current activity, not the entire application. however, there is a workaround for this:
Every time you start an Activity, start it using startActivityForResult(...)
. When you want to close the entire app, you can do something like this:
setResult(RESULT_CLOSE_ALL);
finish();
Then define every activity's onActivityResult(...)
callback so when an activity returns with the RESULT_CLOSE_ALL
value, it also calls finish()
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(resultCode)
{
case RESULT_CLOSE_ALL:
setResult(RESULT_CLOSE_ALL);
finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
This will cause a cascade effect closing all activities.
Also, I support CommonsWare in his suggestion: store the password in a variable so that it will be destroyed when the application is closed.
There is a package random_word could implement this request very conveniently:
$ pip install random-word
from random_word import RandomWords
r = RandomWords()
# Return a single random word
r.get_random_word()
# Return list of Random words
r.get_random_words()
# Return Word of the day
r.word_of_the_day()
Here's a Lodash solution to this that works for flat key => value object, rather than a nested object. The accepted answer's suggestion to use _.findKey
works for objects with nested objects, but it doesn't work in this common circumstance.
This approach inverts the object, swapping keys for values, and then finds the key by looking up the value on the new (inverted) object. If the key isn't found then false
is returned, which I prefer over undefined
, but you could easily swap this out in the third parameter of the _.get
method in getKey()
.
// Get an object's key by value_x000D_
var getKey = function( obj, value ) {_x000D_
var inverse = _.invert( obj );_x000D_
return _.get( inverse, value, false );_x000D_
};_x000D_
_x000D_
// US states used as an example_x000D_
var states = {_x000D_
"AL": "Alabama",_x000D_
"AK": "Alaska",_x000D_
"AS": "American Samoa",_x000D_
"AZ": "Arizona",_x000D_
"AR": "Arkansas",_x000D_
"CA": "California",_x000D_
"CO": "Colorado",_x000D_
"CT": "Connecticut",_x000D_
"DE": "Delaware",_x000D_
"DC": "District Of Columbia",_x000D_
"FM": "Federated States Of Micronesia",_x000D_
"FL": "Florida",_x000D_
"GA": "Georgia",_x000D_
"GU": "Guam",_x000D_
"HI": "Hawaii",_x000D_
"ID": "Idaho",_x000D_
"IL": "Illinois",_x000D_
"IN": "Indiana",_x000D_
"IA": "Iowa",_x000D_
"KS": "Kansas",_x000D_
"KY": "Kentucky",_x000D_
"LA": "Louisiana",_x000D_
"ME": "Maine",_x000D_
"MH": "Marshall Islands",_x000D_
"MD": "Maryland",_x000D_
"MA": "Massachusetts",_x000D_
"MI": "Michigan",_x000D_
"MN": "Minnesota",_x000D_
"MS": "Mississippi",_x000D_
"MO": "Missouri",_x000D_
"MT": "Montana",_x000D_
"NE": "Nebraska",_x000D_
"NV": "Nevada",_x000D_
"NH": "New Hampshire",_x000D_
"NJ": "New Jersey",_x000D_
"NM": "New Mexico",_x000D_
"NY": "New York",_x000D_
"NC": "North Carolina",_x000D_
"ND": "North Dakota",_x000D_
"MP": "Northern Mariana Islands",_x000D_
"OH": "Ohio",_x000D_
"OK": "Oklahoma",_x000D_
"OR": "Oregon",_x000D_
"PW": "Palau",_x000D_
"PA": "Pennsylvania",_x000D_
"PR": "Puerto Rico",_x000D_
"RI": "Rhode Island",_x000D_
"SC": "South Carolina",_x000D_
"SD": "South Dakota",_x000D_
"TN": "Tennessee",_x000D_
"TX": "Texas",_x000D_
"UT": "Utah",_x000D_
"VT": "Vermont",_x000D_
"VI": "Virgin Islands",_x000D_
"VA": "Virginia",_x000D_
"WA": "Washington",_x000D_
"WV": "West Virginia",_x000D_
"WI": "Wisconsin",_x000D_
"WY": "Wyoming"_x000D_
};_x000D_
_x000D_
console.log( 'The key for "Massachusetts" is "' + getKey( states, 'Massachusetts' ) + '"' );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_x000D_
Here seems to be an even better answer with 'in' clause that allows for multiple keys for the join:
update fp_active set STATE='E',
LAST_DATE_MAJ = sysdate where (client,code) in (select (client,code) from fp_detail
where valid = 1) ...
The full example is here: http://forums.devshed.com/oracle-development-96/how-to-update-from-two-tables-195893.html - from web archive since link was dead.
The beef is in having the columns that you want to use as the key in parentheses in the where clause before 'in' and have the select statement with the same column names in parentheses. where (column1,column2) in ( select (column1,column2) from table where "the set I want" );
How to differentiate between single clicks and double clicks on one and the same element?
If you don't need to mix them, you can rely on click
and dblclick
and each will do the job just fine.
A problem arises when trying to mix them: a dblclick
event will actually trigger a click
event as well, so you need to determine whether a single click is a "stand-alone" single click, or part of a double click.
In addition: you shouldn't use both click
and dblclick
on one and the same element:
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
Source: https://api.jquery.com/dblclick/
Now on to the good news:
You can use the event's detail
property to detect the number of clicks related to the event. This makes double clicks inside of click
fairly easy to detect.
The problem remains of detecting single clicks and whether or not they're part of a double click. For that, we're back to using a timer and setTimeout
.
Wrapping it all together, with use of a data attribute (to avoid a global variable) and without the need to count clicks ourselves, we get:
<div class="clickit" style="font-size: 200%; margin: 2em; padding: 0.25em; background: orange;">Double click me</div>
<div id="log" style="background: #efefef;"></div>
<script>
var clickTimeoutID;
$( document ).ready(function() {
$( '.clickit' ).click( function( event ) {
if ( event.originalEvent.detail === 1 ) {
$( '#log' ).append( '(Event:) Single click event received.<br>' );
/** Is this a true single click or it it a single click that's part of a double click?
* The only way to find out is to wait it for either a specific amount of time or the `dblclick` event.
**/
clickTimeoutID = window.setTimeout(
function() {
$( '#log' ).append( 'USER BEHAVIOR: Single click detected.<br><br>' );
},
500 // how much time users have to perform the second click in a double click -- see accessibility note below.
);
} else if ( event.originalEvent.detail === 2 ) {
$( '#log' ).append( '(Event:) Double click event received.<br>' );
$( '#log' ).append( 'USER BEHAVIOR: Double click detected.<br>' );
window.clearTimeout( clickTimeoutID ); // it's a dblclick, so cancel the single click behavior.
} // triple, quadruple, etc. clicks are ignored.
});
});
</script>
It took a while to find a satisfying solution, I hope this helps!
Execution Timeout is 90 seconds for .NET
Framework 1.0 and 1.1, 110 seconds otherwise.
If you need to change defult settings you need to do it in your web.config
under <httpRuntime>
<httpRuntime executionTimeout = "number(in seconds)"/>
But Remember:
This time-out applies only if the debug attribute in the compilation element is False.
Have look at in detail about compilation Element
Have look at this document about httpRuntime Element
If you have multiple ports to allow in Centos 7 FIrewalld then we can use the following command.
#firewall-cmd --add-port={port number/tcp,port number/tcp} --permanent
#firewall-cmd --reload
And check the Port opened or not after reloading the firewall.
#firewall-cmd --list-port
For other configuration [Linuxwindo.com][1]
One of the best explanations I have read comes from the great book Code Complete, which I now quote:
A heuristic is a technique that helps you look for an answer. Its results are subject to chance because a heuristic tells you only how to look, not what to find. It doesn’t tell you how to get directly from point A to point B; it might not even know where point A and point B are. In effect, a heuristic is an algorithm in a clown suit. It’s less predict- able, it’s more fun, and it comes without a 30-day, money-back guarantee.
Here is an algorithm for driving to someone’s house: Take Highway 167 south to Puy-allup. Take the South Hill Mall exit and drive 4.5 miles up the hill. Turn right at the light by the grocery store, and then take the first left. Turn into the driveway of the large tan house on the left, at 714 North Cedar.
Here’s a heuristic for getting to someone’s house: Find the last letter we mailed you. Drive to the town in the return address. When you get to town, ask someone where our house is. Everyone knows us—someone will be glad to help you. If you can’t find anyone, call us from a public phone, and we’ll come get you.
The difference between an algorithm and a heuristic is subtle, and the two terms over-lap somewhat. For the purposes of this book, the main difference between the two is the level of indirection from the solution. An algorithm gives you the instructions directly. A heuristic tells you how to discover the instructions for yourself, or at least where to look for them.
To do it exactly your way? You could use the for...else structure
for url in list_of_urls:
for url_dict in urls:
if url_dict['url'] == url:
url_dict['nbr'] += 1
break
else:
urls.append(dict(url=url, nbr=1))
But it is quite inelegant. Do you really have to store the visited urls as a LIST? If you sort it as a dict, indexed by url string, for example, it would be way cleaner:
urls = {'http://www.google.fr/': dict(url='http://www.google.fr/', nbr=1)}
for url in list_of_urls:
if url in urls:
urls[url]['nbr'] += 1
else:
urls[url] = dict(url=url, nbr=1)
A few things to note in that second example:
urls
removes the need for going through the whole urls
list when testing for one single url
. This approach will be faster.dict( )
instead of braces makes your code shorterlist_of_urls
, urls
and url
as variable names make the code quite hard to parse. It's better to find something clearer, such as urls_to_visit
, urls_already_visited
and current_url
. I know, it's longer. But it's clearer.And of course I'm assuming that dict(url='http://www.google.fr', nbr=1)
is a simplification of your own data structure, because otherwise, urls
could simply be:
urls = {'http://www.google.fr':1}
for url in list_of_urls:
if url in urls:
urls[url] += 1
else:
urls[url] = 1
Which can get very elegant with the defaultdict stance:
urls = collections.defaultdict(int)
for url in list_of_urls:
urls[url] += 1
it's so easy...converting a date to calendar like this:
Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();
Declare a Flask endpoint to accept POST input type and then do necessary steps. Use jQuery to post the data.
from flask import request
@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data(data):
if request.method == "POST":
#perform action here
var value = $('.textbox').val();
$.ajax({
type: 'POST',
url: "{{ url_for('parse_data') }}",
data: JSON.stringify(value),
contentType: 'application/json',
success: function(data){
// do something with the received data
}
});
The Array.prototype.join() method:
var arr = ["Zero", "One", "Two"];_x000D_
_x000D_
document.write(arr.join(", "));
_x000D_
Well, the solution depends on the type of problem, I use the javascript animate method for the button click. and I use codes from bellow links for the navbar
https://css-tricks.com/snippets/jquery/smooth-scrolling/
$(document).ready(function () {
$(".js--scroll-to-plans").click(function () {
$("body,html").animate(
{
scrollTop: $(".js--section-plans").offset().top,
},
1000
);
return false;
});
$(".js--scroll-to-start").click(function () {
$("body,html").animate(
{
scrollTop: $(".js--section-features").offset().top,
},
1000
);
return false;
});
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
});
If you are reading unicode escaped chars from a file, then you will have a tough time doing that because the string will be read literally along with an escape for the back slash:
my_file.txt
Blah blah...
Column delimiter=;
Word delimiter=\u0020 #This is just unicode for whitespace
.. more stuff
Here, when you read line 3 from the file the string/line will have:
"Word delimiter=\u0020 #This is just unicode for whitespace"
and the char[] in the string will show:
{...., '=', '\\', 'u', '0', '0', '2', '0', ' ', '#', 't', 'h', ...}
Commons StringUnescape will not unescape this for you (I tried unescapeXml()). You'll have to do it manually as described here.
So, the sub-string "\u0020" should become 1 single char '\u0020'
But if you are using this "\u0020" to do String.split("... ..... ..", columnDelimiterReadFromFile)
which is really using regex internally, it will work directly because the string read from file was escaped and is perfect to use in the regex pattern!! (Confused?)
That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?
Also, have you perhaps changed the file's properties' Build Action
to something other than Compile
?
With Mercurial you do a
$ hg grep "search for this" [file...]
There are other options that narrow down the range of revisions that are searched.
You can do it like this
[btnTwo setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
In brief, $@
expands to the positional arguments passed from the caller to either a function or a script. Its meaning is context-dependent: Inside a function, it expands to the arguments passed to such function. If used in a script (not inside the scope a function), it expands to the arguments passed to such script.
$ cat my-sh
#! /bin/sh
echo "$@"
$ ./my-sh "Hi!"
Hi!
$ put () ( echo "$@" )
$ put "Hi!"
Hi!
Now, another topic that is of paramount importance when understanding how $@
behaves in the shell is word splitting. The shell splits tokens based on the contents of the IFS
variable. Its default value is \t\n
; i.e., whitespace, tab, and newline.
Expanding "$@"
gives you a pristine copy of the arguments passed. However, expanding $@
will not always. More specifically, if the arguments contain characters from IFS
, they will split.
Most of the time what you will want to use is "$@"
, not $@
.
All logging output is handled by the handlers; just add a logging.StreamHandler()
to the root logger.
Here's an example configuring a stream handler (using stdout
instead of the default stderr
) and adding it to the root logger:
import logging
import sys
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)
I'm a little confused about custom made completion handlers. In your example:
Say you have a download function to download a file from network,and want to be notified when download task has finished.
typealias CompletionHandler = (success:Bool) -> Void
func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {
// download code.
let flag = true // true if download succeed,false otherwise
completionHandler(success: flag)
}
Your // download code
will still be ran asynchronously. Why wouldn't the code go straight to your let flag = true
and completion Handler(success: flag)
without waiting for your download code to be finished?
I found that selecting a clob
column in CTE caused this explosion. ie
with cte as (
select
mytable1.myIntCol,
mytable2.myClobCol
from mytable1
join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...
presumably because oracle can't handle a clob in a temporary table.
Because my values were longer than 4K, I couldn't use to_char()
.
My work around was to select it from the final select
, ie
with cte as (
select
mytable1.myIntCol
from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...
Too bad if this causes a performance problem.
You can also use day names like Mon
for Monday, Tue
for Tuesday, etc. It's more human friendly.
Implemented in a category as below:
UIButton+Border.h:
@interface UIButton (Border)
- (void)addBottomBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
- (void)addLeftBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
- (void)addRightBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
- (void)addTopBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
@end
UIButton+Border.m:
@implementation UIButton (Border)
- (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
[self.layer addSublayer:border];
}
- (void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
[self.layer addSublayer:border];
}
- (void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
[self.layer addSublayer:border];
}
- (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
[self.layer addSublayer:border];
}
@end
do setup by following bellow link and domain name you need to mention as like wht you have mentioned in facebook app domain name.
Go to https://developers.facebook.com/
Click on the Apps menu on the top bar.
@NgModule({
declarations: [
SearchComponent
],
exports: [
CommonModule,
MatInputModule,
MatButtonModule,
MatCardModule,
MatFormFieldModule,
MatDialogModule,
]
})
export class MaterialModule { }
Also, do not forget to import the MaterialModule
in the imports array of AppModule
.
I had the same problem, ruby-1.8.7-p357, and tried loads of things in vain...
I finally realised that it happens only on multiple calls using the same XMLRPC::Client instance!
So now I'm re-instantiating my client at each call and it just works:|
if you are using tomcat you may try this
<servlet-mapping>
<http-method>POST</http-method>
</servlet-mapping>
in addition to <servlet-name>
and <url-mapping>
I tested the accepted answer AND @thewolf's fastest solution against a very basic loop and the loop was faster than both:
import time
import operator
d = {"a"+str(i): i for i in range(1000000)}
def t1(dct):
mx = float("-inf")
key = None
for k,v in dct.items():
if v > mx:
mx = v
key = k
return key
def t2(dct):
v=list(dct.values())
k=list(dct.keys())
return k[v.index(max(v))]
def t3(dct):
return max(dct.items(),key=operator.itemgetter(1))[0]
start = time.time()
for i in range(25):
m = t1(d)
end = time.time()
print ("Iterating: "+str(end-start))
start = time.time()
for i in range(25):
m = t2(d)
end = time.time()
print ("List creating: "+str(end-start))
start = time.time()
for i in range(25):
m = t3(d)
end = time.time()
print ("Accepted answer: "+str(end-start))
results:
Iterating: 3.8201940059661865
List creating: 6.928712844848633
Accepted answer: 5.464320182800293
public int GetNthOccurrenceOfChar(string s, char c, int occ)
{
return String.Join(c.ToString(), s.Split(new char[] { c }, StringSplitOptions.None).Take(occ)).Length;
}
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
Set the text of the button by setting the innerHTML
var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.innerHTML = 'test value';
var wrapper = document.getElementById('divWrapper');
wrapper.appendChild(b);
Can't you style the forms themselves? Then, style the divs accordingly.
form
{
/* styles */
}
You can always overrule inherited styles by making it important:
form
{
/* styles */ !important
}
Disable time in boostrap datetime picker...
$(document).ready(function () {
$('.timepicker').datetimepicker({
format: "dd-mm-yy",
});
});
Disable date in boostrap datetime picker...
$(document).ready(function () {
$('.timepicker').datetimepicker({
format: "HH:mm A",
});
});
Try the following:
INSERT INTO table1
SELECT 'A string', 5, idTable2 idTable2 FROM table2 WHERE ...
The answer by @Andreas Krey is actually good. Anything Java makes difficult, you probably shouldn't be doing.
The most common uses of Pair's in my experience have been multiple return values from a method and as VALUES in a hashmap (often indexed by strings).
In the latter case, I recently used a data structure, something like this:
class SumHolder{MyObject trackedObject, double sum};
There is your entire "Pair" class, pretty much the same amount of code as a generic "Pair" but with the advantage of descriptive names. It can be defined in-line right in the method it's used which will eliminate typical problems with public variables and the like. In other words, it's absolutely better than a pair for this usage (due to the named members) and no worse.
If you actually want a "Pair" for the key of a hashmap you are essentially creating a double-key index. I think this may be the one case where a "Pair" is significantly less code. It's not really easier because you could have eclipse generate equals/hash on your little data class, but it would be a good deal more code. Here a Pair would be a quick fix, but if you need a double-indexed hash who's to say you don't need an n-indexed hash? The data class solution will scale up, the Pair will not unless you nest them!
So the second case, returning from a method, is a bit harder. Your class needs more visibility (the caller needs to see it too). You can define it outside the method but inside the class exactly as above. At that point your method should be able to return a MyClass.SumHolder object. The caller gets to see the names of the returned objects, not just a "Pair". Note again that the "Default" security of package level is pretty good--it's restrictive enough that you shouldn't get yourself into too much trouble. Better than a "Pair" object anyway.
The other case I can see a use for Pairs is a public api with return values for callers outside your current package. For this I'd just create a true object--preferably immutable. Eventually a caller will share this return value and having it mutable could be problematic. This is another case of the Pair object being worse--most pairs cannot be made immutable.
Another advantage to all these cases--the java class expands, my sum class needed a second sum and a "Created" flag by the time I was done, I would have had to throw away the Pair and gone with something else, but if the pair made sense, my class with 4 values still makes at least as much sense.
Two main purposes for error handling:
So, how would you do this?
First of all, create an error form to display when an unexpected error occurs.
It could look something like this (FYI: Mine is called frmErrors):
Notice the following labels:
Also, the standard command buttons:
There's nothing spectacular in the code for this form:
Option Explicit
Private Sub cmdCancel_Click()
Me.Tag = CMD_CANCEL
Me.Hide
End Sub
Private Sub cmdIgnore_Click()
Me.Tag = CMD_IGNORE
Me.Hide
End Sub
Private Sub cmdRetry_Click()
Me.Tag = CMD_RETRY
Me.Hide
End Sub
Private Sub UserForm_Initialize()
Me.lblErrorTitle.Caption = "Custom Error Title Caption String"
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
'Prevent user from closing with the Close box in the title bar.
If CloseMode <> 1 Then
cmdCancel_Click
End If
End Sub
Basically, you want to know which button the user pressed when the form closes.
Next, create an Error Handler Module that will be used throughout your VBA app:
'****************************************************************
' MODULE: ErrorHandler
'
' PURPOSE: A VBA Error Handling routine to handle
' any unexpected errors
'
' Date: Name: Description:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'03/22/2010 Ray Initial Creation
'****************************************************************
Option Explicit
Global Const CMD_RETRY = 0
Global Const CMD_IGNORE = 1
Global Const CMD_CANCEL = 2
Global Const CMD_CONTINUE = 3
Type ErrorType
iErrNum As Long
sHeadline As String
sProblemMsg As String
sResponseMsg As String
sErrorSource As String
sErrorDescription As String
iBtnCap(3) As Integer
iBitmap As Integer
End Type
Global gEStruc As ErrorType
Sub EmptyErrStruc_S(utEStruc As ErrorType)
Dim i As Integer
utEStruc.iErrNum = 0
utEStruc.sHeadline = ""
utEStruc.sProblemMsg = ""
utEStruc.sResponseMsg = ""
utEStruc.sErrorSource = ""
For i = 0 To 2
utEStruc.iBtnCap(i) = -1
Next
utEStruc.iBitmap = 1
End Sub
Function FillErrorStruct_F(EStruc As ErrorType) As Boolean
'Must save error text before starting new error handler
'in case we need it later
EStruc.sProblemMsg = Error(EStruc.iErrNum)
On Error GoTo vbDefaultFill
EStruc.sHeadline = "Error " & Format$(EStruc.iErrNum)
EStruc.sProblemMsg = EStruc.sErrorDescription
EStruc.sErrorSource = EStruc.sErrorSource
EStruc.sResponseMsg = "Contact the Company and tell them you received Error # " & Str$(EStruc.iErrNum) & ". You should write down the program function you were using, the record you were working with, and what you were doing."
Select Case EStruc.iErrNum
'Case Error number here
'not sure what numeric errors user will ecounter, but can be implemented here
'e.g.
'EStruc.sHeadline = "Error 3265"
'EStruc.sResponseMsg = "Contact tech support. Tell them what you were doing in the program."
Case Else
EStruc.sHeadline = "Error " & Format$(EStruc.iErrNum) & ": " & EStruc.sErrorDescription
EStruc.sProblemMsg = EStruc.sErrorDescription
End Select
GoTo FillStrucEnd
vbDefaultFill:
'Error Not on file
EStruc.sHeadline = "Error " & Format$(EStruc.iErrNum) & ": Contact Tech Support"
EStruc.sResponseMsg = "Contact the Company and tell them you received Error # " & Str$(EStruc.iErrNum)
FillStrucEnd:
Exit Function
End Function
Function iErrorHandler_F(utEStruc As ErrorType) As Integer
Static sCaption(3) As String
Dim i As Integer
Dim iMCursor As Integer
Beep
'Setup static array
If Len(sCaption(0)) < 1 Then
sCaption(CMD_IGNORE) = "&Ignore"
sCaption(CMD_RETRY) = "&Retry"
sCaption(CMD_CANCEL) = "&Cancel"
sCaption(CMD_CONTINUE) = "Continue"
End If
Load frmErrors
'Did caller pass error info? If not fill struc with the needed info
If Len(utEStruc.sHeadline) < 1 Then
i = FillErrorStruct_F(utEStruc)
End If
frmErrors!lblHeadline.Caption = utEStruc.sHeadline
frmErrors!lblProblem.Caption = utEStruc.sProblemMsg
frmErrors!lblSource.Caption = utEStruc.sErrorSource
frmErrors!lblResponse.Caption = utEStruc.sResponseMsg
frmErrors.Show
iErrorHandler_F = frmErrors.Tag ' Save user response
Unload frmErrors ' Unload and release form
EmptyErrStruc_S utEStruc ' Release memory
End Function
You may have errors that will be custom only to your application. This would typically be a short list of errors specifically only to your application. If you don't already have a constants module, create one that will contain an ENUM of your custom errors. (NOTE: Office '97 does NOT support ENUMS.). The ENUM should look something like this:
Public Enum CustomErrorName
MaskedFilterNotSupported
InvalidMonthNumber
End Enum
Create a module that will throw your custom errors.
'********************************************************************************************************************************
' MODULE: CustomErrorList
'
' PURPOSE: For trapping custom errors applicable to this application
'
'INSTRUCTIONS: To use this module to create your own custom error:
' 1. Add the Name of the Error to the CustomErrorName Enum
' 2. Add a Case Statement to the raiseCustomError Sub
' 3. Call the raiseCustomError Sub in the routine you may see the custom error
' 4. Make sure the routine you call the raiseCustomError has error handling in it
'
'
' Date: Name: Description:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'03/26/2010 Ray Initial Creation
'********************************************************************************************************************************
Option Explicit
Const MICROSOFT_OFFSET = 512 'Microsoft reserves error values between vbObjectError and vbObjectError + 512
'************************************************************************************************
' FUNCTION: raiseCustomError
'
' PURPOSE: Raises a custom error based on the information passed
'
'PARAMETERS: customError - An integer of type CustomErrorName Enum that defines the custom error
' errorSource - The place the error came from
'
' Returns: The ASCII vaule that should be used for the Keypress
'
' Date: Name: Description:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'03/26/2010 Ray Initial Creation
'************************************************************************************************
Public Sub raiseCustomError(customError As Integer, Optional errorSource As String = "")
Dim errorLong As Long
Dim errorDescription As String
errorLong = vbObjectError + MICROSOFT_OFFSET + customError
Select Case customError
Case CustomErrorName.MaskedFilterNotSupported
errorDescription = "The mask filter passed is not supported"
Case CustomErrorName.InvalidMonthNumber
errorDescription = "Invalid Month Number Passed"
Case Else
errorDescription = "The custom error raised is unknown."
End Select
Err.Raise errorLong, errorSource, errorDescription
End Sub
You are now well equipped to trap errors in your program. You sub (or function), should look something like this:
Public Sub MySub(monthNumber as Integer)
On Error GoTo eh
Dim sheetWorkSheet As Worksheet
'Run Some code here
'************************************************
'* OPTIONAL BLOCK 1: Look for a specific error
'************************************************
'Temporarily Turn off Error Handling so that you can check for specific error
On Error Resume Next
'Do some code where you might expect an error. Example below:
Const ERR_SHEET_NOT_FOUND = 9 'This error number is actually subscript out of range, but for this example means the worksheet was not found
Set sheetWorkSheet = Sheets("January")
'Now see if the expected error exists
If Err.Number = ERR_SHEET_NOT_FOUND Then
MsgBox "Hey! The January worksheet is missing. You need to recreate it."
Exit Sub
ElseIf Err.Number <> 0 Then
'Uh oh...there was an error we did not expect so just run basic error handling
GoTo eh
End If
'Finished with predictable errors, turn basic error handling back on:
On Error GoTo eh
'**********************************************************************************
'* End of OPTIONAL BLOCK 1
'**********************************************************************************
'**********************************************************************************
'* OPTIONAL BLOCK 2: Raise (a.k.a. "Throw") a Custom Error if applicable
'**********************************************************************************
If not (monthNumber >=1 and monthnumber <=12) then
raiseCustomError CustomErrorName.InvalidMonthNumber, "My Sub"
end if
'**********************************************************************************
'* End of OPTIONAL BLOCK 2
'**********************************************************************************
'Rest of code in your sub
goto sub_exit
eh:
gEStruc.iErrNum = Err.Number
gEStruc.sErrorDescription = Err.Description
gEStruc.sErrorSource = Err.Source
m_rc = iErrorHandler_F(gEStruc)
If m_rc = CMD_RETRY Then
Resume
End If
sub_exit:
'Any final processing you want to do.
'Be careful with what you put here because if it errors out, the error rolls up. This can be difficult to debug; especially if calling routine has no error handling.
Exit Sub 'I was told a long time ago (10+ years) that exit sub was better than end sub...I can't tell you why, so you may not want to put in this line of code. It's habit I can't break :P
End Sub
A copy/paste of the code above may not work right out of the gate, but should definitely give you the gist.
BTW, if you ever need me to do your company logo, look me up at http://www.MySuperCrappyLogoLabels99.com
In Python mutable objects are passed as reference, so you can pass a reference of the outer class to the inner class.
class OuterClass:
def __init__(self):
self.outer_var = 1
self.inner_class = OuterClass.InnerClass(self)
print('Inner variable in OuterClass = %d' % self.inner_class.inner_var)
class InnerClass:
def __init__(self, outer_class):
self.outer_class = outer_class
self.inner_var = 2
print('Outer variable in InnerClass = %d' % self.outer_class.outer_var)
You can replace
document.getElementById(this.state.baction).addPrecent(10);
with
this.refs[this.state.baction].addPrecent(10);
<Progressbar completed={25} ref="Progress1" id="Progress1"/>
Cygwin can give you this functionality.
if you are on Linux (Ubuntu)... the go to File-> Settings-> Plugin and select plugin from respective location.
If you are on Mac OS... the go to File-> Preferences-> Plugin and select plugin from respective location.
For those using asyncio, an easy way is to use asyncio.wait_for()
:
async def my_loop():
res = False
while not res:
res = await do_something()
await asyncio.wait_for(my_loop(), 10)
The images c, d, e , and f in the following show colorspace conversion they also happen to be numpy arrays <type 'numpy.ndarray'>
:
import numpy, cv2
def show_pic(p):
''' use esc to see the results'''
print(type(p))
cv2.imshow('Color image', p)
while True:
k = cv2.waitKey(0) & 0xFF
if k == 27: break
return
cv2.destroyAllWindows()
b = numpy.zeros([200,200,3])
b[:,:,0] = numpy.ones([200,200])*255
b[:,:,1] = numpy.ones([200,200])*255
b[:,:,2] = numpy.ones([200,200])*0
cv2.imwrite('color_img.jpg', b)
c = cv2.imread('color_img.jpg', 1)
c = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)
d = cv2.imread('color_img.jpg', 1)
d = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)
e = cv2.imread('color_img.jpg', -1)
e = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)
f = cv2.imread('color_img.jpg', -1)
f = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)
pictures = [d, c, f, e]
for p in pictures:
show_pic(p)
# show the matrix
print(c)
print(c.shape)
See here for more info: http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor
OR you could:
img = numpy.zeros([200,200,3])
img[:,:,0] = numpy.ones([200,200])*255
img[:,:,1] = numpy.ones([200,200])*255
img[:,:,2] = numpy.ones([200,200])*0
r,g,b = cv2.split(img)
img_bgr = cv2.merge([b,g,r])
Try this code
private void clearAppData() {
try {
if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData();
} else {
Runtime.getRuntime().exec("pm clear " + getApplicationContext().getPackageName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Wow, even 3 comments are pretty correct!
Empty input is not a reason to skip function call, e.g. I remove waste parameter from url before redirect
.on ('input', function() { ... });
should be used to trigger keyup
, paste
and change
events
definitely .val()
or .value
must be used
You can use $(this)
inside event function instead of #id
to work with multiple inputs
(my decision) I use anonymous function instead of doneTyping
in setTimeout
to easily access $(this)
from n.4, but you need to save it first like var $currentInput = $(this);
EDIT I see that some people don't understand directions without the possibility to copy-paste ready code. Here you're
var typingTimer;
// 2
$("#myinput").on('input', function () {
// 4 3
var input = $(this).val();
clearTimeout(typingTimer);
// 5
typingTimer = setTimeout(function() {
// do something with input
alert(input);
}, 5000);
});
Ensures that the object is displayed (or should be) only to readers and similar devices. It give more sense in context with other element with attribute aria-hidden="true".
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
Enter a valid email address
</div>
Glyphicon will be displayed on all other devices, word Error: on text readers.
set global max_allowed_packet=10000000000;
You can use this to get a name of any provided member:
public static class MemberInfoGetting
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}
To get name of a variable:
string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);
To get name of a parameter:
public class TestClass
{
public void TestMethod(string param1, string param2)
{
string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
}
}
You can use the nameof operator for parameters, variables and properties alike:
string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);
Both answers given are correct, but I do mine a little different. You might want to consider a couple things...
Start the batch with:
SetLocal
and end it with
EndLocal
This will keep all your 'SETs" to be only valid during the current session, and will not leave vars left around named like "FileName1" or any other variables you set during the run, that could interfere with the next run of the batch file. So, you can do something like:
IF "%1"=="" SET FileName1=c:\file1.txt
The other trick is if you only provide 1, or 2 parameters, use the SHIFT command to move them, so the one you are looking for is ALWAYS at %1...
For example, process the first parameter, shift them, and then do it again. This way, you are not hard-coding %1, %2, %3, etc...
The Windows batch processor is much more powerful than people give it credit for.. I've done some crazy stuff with it, including calculating yesterday's date, even across month and year boundaries including Leap Year, and localization, etc.
If you really want to get creative, you can call functions in the batch processor... But that's really for a different discussion... :)
Oh, and don't name your batch files .bat either.. They are .cmd's now.. heh..
Hope this helps.
@qbzenker provided the most idiomatic method IMO
Here are a few alternatives:
In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
Col1 Col2 Col3
1 0 NaN 0.0
In [29]: df[np.isnan(df.Col2)]
Out[29]:
Col1 Col2 Col3
1 0 NaN 0.0
There is a property of the built-in window.location
object that will provide that for the current window.
// If URL is http://www.somedomain.com/account/search?filter=a#top
window.location.pathname // /account/search
// For reference:
window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a
It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location
object and anchor elements implement the interface.
So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:
var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";
el.host // www.somedomain.com (includes port if there is one[1])
el.hostname // www.somedomain.com
el.hash // #top
el.href // http://www.somedomain.com/account/search?filter=a#top
el.pathname // /account/search
el.port // (port if there is one[1])
el.protocol // http:
el.search // ?filter=a
[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right
This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.
There's also a coming URL
object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.
Try this console app:
static void Main(string[] args)
{
//Encoding _UTF8 = Encoding.UTF8;
string[] _mainString = { "Héllo World" };
Console.WriteLine("Main String: " + _mainString);
//Convert a string to utf-8 bytes.
byte[] _utf8Bytes = Encoding.UTF8.GetBytes(_mainString[0]);
//Convert utf-8 bytes to a string.
string _stringuUnicode = Encoding.UTF8.GetString(_utf8Bytes);
Console.WriteLine("String Unicode: " + _stringuUnicode);
}
If you change your property to use a backing field (instead of an automatic property), you can do the following:
public event EventHandler ImageFullPath1Changed;
private string _imageFullPath1 = string.Empty;
public string ImageFullPath1
{
get
{
return imageFullPath1 ;
}
set
{
if (_imageFullPath1 != value)
{
_imageFullPath1 = value;
EventHandler handler = ImageFullPathChanged;
if (handler != null)
handler(this, e);
}
}
}
After asking a similar question I’ve created another package which uses Pygments, and offers quite a few more options than texments
. It’s called minted
and is quite stable and usable.
Just to show it off, here’s a code highlighted with minted:
on click of Logout you may call this
private void GoToPreviousActivity() {
setResult(REQUEST_CODE_LOGOUT);
this.finish();
}
onActivityResult() of previous Activity call this above code again until you finished the all activities.
if you want as you expressed with breaks after each value;
$('#select-meal-type').change(function(){
var meals = $(this).val();
var selectedmeals = meals.join(", "); // there is a break after comma
alert (selectedmeals); // just for testing what will be printed
})
What you have is correct. Of course, you'll see that emp1 and item1 have the same pointer value.
To switch branch for a submodule (assuming you already have the submodule as part of the repository):
cd
to root of your repository containing the submodules.gitmodules
for editingpath = ...
and url = ...
that says branch = your-branch
, for each submodule; save file .gitmodules
.$ git submodule update --remote
...this should pull in the latest commits on the specified branch, for each submodule thus modified.
The (a,b,c)
list only works with in
. For like
, you have to use or
:
WHERE interests LIKE '%sports%' OR interests LIKE '%pub%'
You should try using the option -i
for in-place editing.
You can also export template and then create a new project from the exported template changing the name as you prefer
Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)
Ok, this is not a very serious review, but here is what I can say:
I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:
#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis
import sys, time
stdout = sys.stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
class Iterator(object) :
def __init__(self):
print 'Rendering...'
for y in xrange(-39, 39):
stdout.write('\n')
for x in xrange(-39, 39):
if self.mandelbrot(x/40.0, y/40.0) :
stdout.write(' ')
else:
stdout.write('*')
def mandelbrot(self, x, y):
cr = y - 0.5
ci = x
zi = 0.0
zr = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
if zi2 + zr2 > BAILOUT:
return i
return 0
t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)
As a result:
PyChecker
is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.PyFlakes
is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.PyLint
has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).Strong points of PyLint
:
Cons of Pylint:
Corrected script (with lazy doc strings and variable names):
#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""
import time
from sys import stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
def mandelbrot(dim_1, dim_2):
"""
function doc string
"""
cr1 = dim_1 - 0.5
ci1 = dim_2
zi1 = 0.0
zr1 = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr1 * zi1
zr2 = zr1 * zr1
zi2 = zi1 * zi1
zr1 = zr2 - zi2 + cr1
zi1 = temp + temp + ci1
if zi2 + zr2 > BAILOUT:
return i
return 0
def execute() :
"""
func doc string
"""
print 'Rendering...'
for dim_1 in xrange(-39, 39):
stdout.write('\n')
for dim_2 in xrange(-39, 39):
if mandelbrot(dim_1/40.0, dim_2/40.0) :
stdout.write(' ')
else:
stdout.write('*')
START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)
Thanks to Rudiger Wolf, I discovered pep8
that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.
Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.
To give you a little idea of their output:
pep8:
./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3
Pylint:
************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C: 1: Missing docstring
C: 5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
[...] and a very long report with useful stats like :
Duplication
-----------
+-------------------------+------+---------+-----------+
| |now |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines |0 |0 |= |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000 |= |
+-------------------------+------+---------+-----------+
You will need InternetExplorer driver executable on your system. So download it from the hinted source (http://www.seleniumhq.org/download/) unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe
Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:
File file = new File("C:/Selenium/iexploredriver.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();
Basically, you have to set this property before you initialize driver
For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly
and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.
This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.
To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.
cc -DDISPLAY_STRING demo.c
If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.
#define TERMINAL "/dev/ttyUSB0"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int set_interface_attribs(int fd, int speed)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error from tcgetattr: %s\n", strerror(errno));
return -1;
}
cfsetospeed(&tty, (speed_t)speed);
cfsetispeed(&tty, (speed_t)speed);
tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; /* 8-bit characters */
tty.c_cflag &= ~PARENB; /* no parity bit */
tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */
tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
/* setup for non-canonical mode */
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
/* fetch bytes as they become available */
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSANOW, &tty) != 0) {
printf("Error from tcsetattr: %s\n", strerror(errno));
return -1;
}
return 0;
}
void set_mincount(int fd, int mcount)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error tcgetattr: %s\n", strerror(errno));
return;
}
tty.c_cc[VMIN] = mcount ? 1 : 0;
tty.c_cc[VTIME] = 5; /* half second timer */
if (tcsetattr(fd, TCSANOW, &tty) < 0)
printf("Error tcsetattr: %s\n", strerror(errno));
}
int main()
{
char *portname = TERMINAL;
int fd;
int wlen;
char *xstr = "Hello!\n";
int xlen = strlen(xstr);
fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0) {
printf("Error opening %s: %s\n", portname, strerror(errno));
return -1;
}
/*baudrate 115200, 8 bits, no parity, 1 stop bit */
set_interface_attribs(fd, B115200);
//set_mincount(fd, 0); /* set to pure timed read */
/* simple output */
wlen = write(fd, xstr, xlen);
if (wlen != xlen) {
printf("Error from write: %d, %d\n", wlen, errno);
}
tcdrain(fd); /* delay for output */
/* simple noncanonical input */
do {
unsigned char buf[80];
int rdlen;
rdlen = read(fd, buf, sizeof(buf) - 1);
if (rdlen > 0) {
#ifdef DISPLAY_STRING
buf[rdlen] = 0;
printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
unsigned char *p;
printf("Read %d:", rdlen);
for (p = buf; rdlen-- > 0; p++)
printf(" 0x%x", *p);
printf("\n");
#endif
} else if (rdlen < 0) {
printf("Error from read: %d: %s\n", rdlen, strerror(errno));
} else { /* rdlen == 0 */
printf("Timeout from read\n");
}
/* repeat read to get full message */
} while (1);
}
For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.
For Unix Users
find ~/.m2 -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;
Right-click your project and choose Update Dependencies
For Windows
for /r %i in (*.lastUpdated) do del %i
I got same error before I forgot to enclose component content in template
element.
I have this initially
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './com/Home.vue';
Vue.use(VueRouter);
Vue.router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
},
]
});
Then in Home.vue I have:
<h1>Hello Vue</h1>
Hence the error:
Failed to mount component: template or render function not defined.
found in
---> <Home> at resources/js/com/Home.vue
<Root>
Enclosing in element fixed the error:
<template>
<h1>Hello Vue</h1>
</template>
$ set quick brown fox jumps
$ echo ${*: -1:1} # last argument
jumps
$ echo ${*: -1} # or simply
jumps
$ echo ${*: -2:1} # next to last
fox
The space is necessary so that it doesnt get interpreted as a default value.
Note that this is bash-only.
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
This worked for me:
$scanresults = Invoke-Expression "& 'C:\Program Files (x86)\Nmap\nmap.exe' -vv -sn 192.168.1.1-150 --open"
In this particular example, you can use:
#container:hover #cube {
background-color: yellow;
}
This example only works since cube
is a child of container
. For more complicated scenarios, you'd need to use different CSS, or use JavaScript.
I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);
If you response is like {'customer':{'first_name':'John','last_name':'Cena'}}
var d = JSON.parse(response);
alert(d.customer.first_name); // contains "John"
Thanks,
In fact, xargs
can run commands in parallel for you. There is a special -P max_procs
command-line option for that. See man xargs
.
Even your question is answered, still i want tell more entities same like this.
These are html entities
, so in android you will write them like:
Replace below with:
& with &
> with >
< with <
" with ", “ or ”
' with ', ‘ or ’
} with }
If you want the font you chose to be applied and not the one in bootstrap without modifying the original bootstrap files you can rearrange the tags in your HTML documents so your CSS files that applies the font called after the bootstrap one. In this way since the browser reads the documents line after line first it will read the bootstrap files and apply it roles then it will read your file and override the roles in the bootstrap and replace it with the ones in your file.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
public String getMacAddress(Context context) {
WifiManager wimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wimanager.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Device don't have mac address or wi-fi is disabled";
}
return macAddress;
}
have others way here
It's not immediately obvious from the documentation why the following does not work:
<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>
But when doing it entirely inline:
"em"
class
is className
The correct way looks like this:
<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>
better tr command:
tr [:blank:] \\t
This will clean up the output of say, unzip -l , for further processing with grep, cut, etc.
e.g.,
unzip -l some-jars-and-textfiles.zip | tr [:blank:] \\t | cut -f 5 | grep jar
This will help....
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return
c.substring(nameEQ.length,c.length);
}
return null;
}
Array notaion is the best way of combining styles in react native.
This shows how to combine 2 Style objects,
<Text style={[styles.base, styles.background]} >Test </Text>
this shows how to combine Style object and property,
<Text style={[styles.base, {color: 'red'}]} >Test </Text>
This will work on any react native application.
I think it will be sometime before we get to see access to the NFC as the pure security side of it like for example being able to walk past somebody brush past them and & get your phone to the zap the card details or simply Wave your phone over someone's wallet which They left on the desk.
I think the first step is for Apple to talk to banks and find more ways of securing cards and NFC before This will be allowed
You will need to assign an ID to the checkbox:
<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">
and then in JavaScript:
document.getElementById("checkboxId").checked = false;
If you're using .NET, use the DirectorySearcher class. You can pass in your domain as a string into the constructor.
// if you domain is domain.com...
string username = "user"
string domain = "LDAP://DC=domain,DC=com";
DirectorySearcher search = new DirectorySearcher(domain);
search.Filter = "(SAMAccountName=" + username + ")";
you should add plug in to your local setting of firefox in your user home
vladimir@shinsengumi ~/.mozilla/plugins $ pwd
/home/vladimir/.mozilla/plugins
vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
lrwxrwxrwx 1 vladimir vladimir 60 Jan 1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so
Here is a website that will give you what you need
As a summary, it provides links to InputMethodManager
and View
from Android Developers. It will reference to the getWindowToken
inside of View
and hideSoftInputFromWindow()
for InputMethodManager
A better answer is given in the link, hope this helps.
here is an example to consume the onTouch event:
editText_input_field.setOnTouchListener(otl);
private OnTouchListener otl = new OnTouchListener() {
public boolean onTouch (View v, MotionEvent event) {
return true; // the listener has consumed the event
}
};
Here is another example from the same website. This claims to work but seems like a bad idea since your EditBox is NULL it will be no longer an editor:
MyEditor.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
int inType = MyEditor.getInputType(); // backup the input type
MyEditor.setInputType(InputType.TYPE_NULL); // disable soft input
MyEditor.onTouchEvent(event); // call native handler
MyEditor.setInputType(inType); // restore input type
return true; // consume touch even
}
});
Hope this points you in the right direction
The official instructions seem to be here: https://docs.anaconda.com/anaconda/install/uninstall/
but if you like me that didn't work for some reason and for some reason your conda was installed somewhere else with telling you do this:
rm -rf ~/opt
I have no idea why it was saved there but that's what did it for me.
This was useful to me in fixing my conda installation (if that is the reason you are uninstalling it in the first place like me): https://stackoverflow.com/a/60902863/1601580 that ended up fixing it for me. Not sure why conda was acting weird in the first place or installing things wrongly in the first place though...
The best answer is...
The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.
Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?
For many tasks, using Beautiful Soup will be far faster and easier to use:
>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser') # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']
If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser
that does exactly what you want:
from html.parser import HTMLParser
class MyParser(HTMLParser):
def __init__(self, output_list=None):
HTMLParser.__init__(self)
if output_list is None:
self.output_list = []
else:
self.output_list = output_list
def handle_starttag(self, tag, attrs):
if tag == 'a':
self.output_list.append(dict(attrs).get('href'))
Test:
>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']
You could even create a new method that accepts a string, calls feed
, and returns output_list
. This is a vastly more powerful and extensible way than regular expressions to extract information from html.
To add to Rob's answer, since iOS 10.0, Apple has introduced an entirely new "Unified Logging" system that supersedes existing logging systems (including ASL and Syslog, NSLog), and also surpasses existing logging approaches in performance, thanks to its new techniques including log data compression and deferred data collection.
From Apple:
The unified logging system provides a single, efficient, performant API for capturing messaging across all levels of the system. This unified system centralizes the storage of log data in memory and in a data store on disk.
Apple highly recommends using os_log
going forward to log all kinds of messages, including info, debug, error messages because of its much improved performance compared to previous logging systems, and its centralized data collection allowing convenient log and activity inspection for developers. In fact, the new system is likely so low-footprint that it won't cause the "observer effect" where your bug disappears if you insert a logging command, interfering the timing of the bug to happen.
You can learn more about this in details here.
To sum it up: use print()
for your personal debugging for convenience (but the message won't be logged when deployed on user devices). Then, use Unified Logging (os_log
) as much as possible for everything else.
It works like this:
h4 {
display:inline;
}
h4:after {
content:"\a";
white-space: pre;
}
Example: http://jsfiddle.net/Bb2d7/
The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)
You also can do it with functional programming:
from functools import reduce
reduce(lambda df1, df2: df1.merge(df2, "outer"), mydfs)
Add one possible reason in practise:
In practise, Error may be thrown silently, e.g, you submit a timer task and in the timer task it throws Error, while in most cases, your program only catches Exception. Then the Timer main loop is ended without any information. A similar Error to NoClassDefFoundError is ExceptionInInitializerError, when your static initializer or the initializer for a static variable throws an exception.
@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.
From Tomcat Documentation
maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.
maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.
In Spring 4.2+ you can now simply do:
@Component
class StartupHousekeeper {
@EventListener(ContextRefreshedEvent.class)
public void contextRefreshedEvent() {
//do whatever
}
}
Epoch is the number of seconds since Jan 1, 1970..
So:
String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );
For more information: http://www.epochconverter.com/
Yet another way to get this:
class GenericFoo<T> {}
class ConcreteFoo : GenericFoo<ClassFromAnotherAssembly> {}
Code in an assembly that doesn't reference the assembly of ClassFromAnotherAssembly.
var foo = new ConcreteFoo(); //kaboom
This happened to me when ClassFromAnotherAssembly was ValueTuple.
I have thesame issue before but i solved it easily by just following this steps:
*connect your android phone in a debugging mode (to enable debugging mode goto settings scroll down About Phone scroll down tap seven times Build Number and it will automatically enable developer option turn on developer options and check USB debugging)
download Universal ADB Driver Installer
*choose Adb Driver Installer (Universal)
*install it *it will automatically detect your android device(any kind of brand) *chose the device and install
I found a very simple solution to this question which meets my needs. I add one line to the bottom of all of my macros which exports a *.txt
file with the entire macro code each time it is run. The code:
ActiveWorkbook.VBProject.VBComponents("moduleName").Export"C:\Path\To\Spreadsheet\moduleName.txt"
(Found on Tom's Tutorials, which also covers some setup you may need to get this working.)
Since I'll always run the macro whenever I'm working on the code, I'm guaranteed that git will pick up the changes. The only annoying part is that if I need to checkout an earlier version, I have to manually copy/paste from the *.txt
into the spreadsheet.
You can use pure JavaScript, using appendChild()
method...
The appendChild() method appends a node as the last child of a node.
Tip: If you want to create a new paragraph, with text, remember to create the text as a Text node which you append to the paragraph, then append the paragraph to the document.
You can also use this method to move an element from one element to another.
Tip: Use the insertBefore() method to insert a new child node before a specified, existing, child node.
So you can do that to do the job, this is what I created for you, using appendChild()
, run and see how it works for your case:
function appendIt() {_x000D_
var source = document.getElementById("source");_x000D_
document.getElementById("destination").appendChild(source);_x000D_
}
_x000D_
#source {_x000D_
color: white;_x000D_
background: green;_x000D_
padding: 4px 8px;_x000D_
}_x000D_
_x000D_
#destination {_x000D_
color: white;_x000D_
background: red;_x000D_
padding: 4px 8px;_x000D_
}_x000D_
_x000D_
button {_x000D_
margin-top: 20px;_x000D_
}
_x000D_
<div id="source">_x000D_
<p>Source</p>_x000D_
</div>_x000D_
_x000D_
<div id="destination">_x000D_
<p>Destination</p>_x000D_
</div>_x000D_
_x000D_
<button onclick="appendIt()">Move Element</button>
_x000D_
In my case, I had duplicate IDs in the source table, so none of the proposals worked. I don't care about performance, it's just done once. To solve this I took the records one by one with a cursor to ignore the duplicates.
So here's the code example:
DECLARE @c1 AS VARCHAR(12);
DECLARE @c2 AS VARCHAR(250);
DECLARE @c3 AS VARCHAR(250);
DECLARE MY_cursor CURSOR STATIC FOR
Select
c1,
c2,
c3
from T2
where ....;
OPEN MY_cursor
FETCH NEXT FROM MY_cursor INTO @c1, @c2, @c3
WHILE @@FETCH_STATUS = 0
BEGIN
if (select count(1)
from T1
where a1 = @c1
and a2 = @c2
) = 0
INSERT INTO T1
values (@c1, @c2, @c3)
FETCH NEXT FROM MY_cursor INTO @c1, @c2, @c3
END
CLOSE MY_cursor
DEALLOCATE MY_cursor
For me, the easiest solution would be keep value when count is equal to the maximum. Therefore, the following one line command is enough :
df[df['count'] == df.groupby(['Mt'])['count'].transform(max)]
You could do this pretty easily with my date-shortcode package:
const dateShortcode = require('date-shortcode')
var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'
The second snippet doesn't work either and that's why.
array_shift
is a modifier function, that changes its argument. Therefore it expects its parameter to be a reference, and you cannot reference something that is not a variable. See Rasmus' explanations here: Strict standards: Only variables should be passed by reference
I can't see anything obviously wrong, but perhaps a different approach might help you debug it?
You could try specify your datasource in the per-application-context instead of the global tomcat one.
You can do this by creating a src/main/webapp/META-INF/context.xml (I'm assuming you're using the standard maven directory structure - if not, then the META-INF folder should be a sibling of your WEB-INF directory). The contents of the META-INF/context.xml file would look something like:
<?xml version="1.0" encoding="UTF-8"?>
<Context [optional other attributes as required]>
<Resource name="jdbc/PollDatasource" auth="Container"
type="javax.sql.DataSource" driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail" maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>
Obviously the path and docBase would need to match your application's specific details.
Using this approach, you don't have to specify the datasource details in Tomcat's context.xml file. Although, if you have multiple applications talking to the same database, then your approach makes more sense.
At any rate, give this a whirl and see if it makes any difference. It might give us a clue as to what is going wrong with your approach.
This is the simplest query to retrive all Columns and Tables
SELECT * FROM information_schema.`COLUMNS` C WHERE TABLE_SCHEMA = 'YOUR_DATABASE'
All the tables or those with specific string in name could be searched via Search tab in phpMyAdmin.
Have Nice Query... \^.^/
Similarly to the approved answer. If you want to create an array from dictionary keys:
np.array( tuple(dict.keys()) )
If you want to create an array from dictionary values:
np.array( tuple(dict.values()) )
Since .NET 4.7.1, you can use the side-effect free Prepend()
and Append()
. The output is going to be an IEnumerable.
// Creating an array of numbers
var ti = new List<int> { 1, 2, 3 };
// Prepend and Append any value of the same type
var results = ti.Prepend(0).Append(4);
// output is 0, 1, 2, 3, 4
Console.WriteLine(string.Join(", ", results ));
Using pure JavaScript.It's very easy using local storage.
The first page form:
function getData()
{
//gettting the values
var email = document.getElementById("email").value;
var password= document.getElementById("password").value;
var telephone= document.getElementById("telephone").value;
var mobile= document.getElementById("mobile").value;
//saving the values in local storage
localStorage.setItem("txtValue", email);
localStorage.setItem("txtValue1", password);
localStorage.setItem("txtValue2", mobile);
localStorage.setItem("txtValue3", telephone);
}
_x000D_
input{
font-size: 25px;
}
label{
color: rgb(16, 8, 46);
font-weight: bolder;
}
#data{
}
_x000D_
<fieldset style="width: fit-content; margin: 0 auto; font-size: 30px;">
<form action="action.html">
<legend>Sign Up Form</legend>
<label>Email:<br />
<input type="text" name="email" id="email"/></label><br />
<label>Password<br />
<input type="text" name="password" id="password"/></label><br>
<label>Mobile:<br />
<input type="text" name="mobile" id="mobile"/></label><br />
<label>Telephone:<br />
<input type="text" name="telephone" id="telephone"/></label><br>
<input type="submit" value="Submit" onclick="getData()">
</form>
</fieldset>
_x000D_
This is the second page:
//displaying the value from local storage to another page by their respective Ids
document.getElementById("data").innerHTML=localStorage.getItem("txtValue");
document.getElementById("data1").innerHTML=localStorage.getItem("txtValue1");
document.getElementById("data2").innerHTML=localStorage.getItem("txtValue2");
document.getElementById("data3").innerHTML=localStorage.getItem("txtValue3");
_x000D_
<div style=" font-size: 30px; color: rgb(32, 7, 63); text-align: center;">
<div style="font-size: 40px; color: red; margin: 0 auto;">
Here's Your data
</div>
The Email is equal to: <span id="data"> Email</span><br>
The Password is equal to <span id="data1"> Password</span><br>
The Mobile is equal to <span id="data2"> Mobile</span><br>
The Telephone is equal to <span id="data3"> Telephone</span><br>
</div>
_x000D_
As of today, you can read some values from HTML5 data
attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data
properties for setting the content
.
Unfortunately it is not working for the width
and height
(tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).
But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width
and data-height
. You can find the GitHub repo to it here: cssattr.js.
You might take a look at JavaScience's source for OpenSSLKey
There's code in there that does exactly what you want to do.
In fact, they have a lot of crypto source code available here.
Source code snippet:
//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider ---
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;
// --------- Set up stream to decode the asn.1 encoded RSA private key ------
MemoryStream mem = new MemoryStream(privkey) ;
BinaryReader binr = new BinaryReader(mem) ; //wrap Memory Stream with BinaryReader for easy reading
byte bt = 0;
ushort twobytes = 0;
int elems = 0;
try {
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
return null;
bt = binr.ReadByte();
if (bt !=0x00)
return null;
//------ all private key components are Integer sequences ----
elems = GetIntegerSize(binr);
MODULUS = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
E = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
D = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
P = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
Q = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
DP = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
DQ = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
IQ = binr.ReadBytes(elems) ;
Console.WriteLine("showing components ..");
if (verbose) {
showBytes("\nModulus", MODULUS) ;
showBytes("\nExponent", E);
showBytes("\nD", D);
showBytes("\nP", P);
showBytes("\nQ", Q);
showBytes("\nDP", DP);
showBytes("\nDQ", DQ);
showBytes("\nIQ", IQ);
}
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAparams = new RSAParameters();
RSAparams.Modulus =MODULUS;
RSAparams.Exponent = E;
RSAparams.D = D;
RSAparams.P = P;
RSAparams.Q = Q;
RSAparams.DP = DP;
RSAparams.DQ = DQ;
RSAparams.InverseQ = IQ;
RSA.ImportParameters(RSAparams);
return RSA;
}
catch (Exception) {
return null;
}
finally {
binr.Close();
}
}
Now I solved this issue in this way,
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream;
// Create a trust manager that does not validate certificate chains like the default
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
//No need to implement.
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
//No need to implement.
}
}
};
// Install the all-trusting trust manager
try
{
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
catch (Exception e)
{
System.out.println(e);
}
Of course this solution should only be used in scenarios, where it is not possible to install the required certifcates using keytool
e.g. local testing with temporary certifcates.
Answered this in 'top question' about emails verification https://stackoverflow.com/a/41129750/1848217
For me the right way for checking emails is:
- Check that symbol @ exists, and before and after it there are some non-@ symbols:
/^[^@]+@[^@]+$/
- Try to send an email to this address with some "activation code".
- When the user "activated" his email address, we will see that all is right.
Of course, you can show some warning or tooltip in front-end when user typed "strange" email to help him to avoid common mistakes, like no dot in domain part or spaces in name without quoting and so on. But you must accept the address "hello@world" if user really want it.
Also, you must remember that email address standard was and can evolute, so you can't just type some "standard-valid" regexp once and for all times. And you must remember that some concrete internet servers can fail some details of common standard and in fact work with own "modified standard".
So, just check @, hint user on frontend and send verification emails on given address.
Add tomcat in Eclipse
In Eclipse, as tomcat server, double click "Tomcat v7.0 Server at Localhost", Change the properties as shown in time out settings 45 to whatever sec you like
Reference: https://metamug.com/blog/eclipse-gson-class-not-found
In the case where you have multiple extensions this one-liner using pathlib
and str.replace
works a treat:
>>> from pathlib import Path
>>> p = Path("/path/to/myfile.tar.gz")
>>> extensions = "".join(p.suffixes)
# any python version
>>> str(p).replace(extensions, "")
'/path/to/myfile'
# python>=3.9
>>> str(p).removesuffix(extensions)
'/path/to/myfile'
>>> p = Path("/path/to/myfile.tar.gz")
>>> extensions = "".join(p.suffixes)
>>> new_ext = ".jpg"
>>> str(p).replace(extensions, new_ext)
'/path/to/myfile.jpg'
If you also want a pathlib
object output then you can obviously wrap the line in Path()
>>> Path(str(p).replace("".join(p.suffixes), ""))
PosixPath('/path/to/myfile')
from pathlib import Path
from typing import Union
PathLike = Union[str, Path]
def replace_ext(path: PathLike, new_ext: str = "") -> Path:
extensions = "".join(Path(path).suffixes)
return Path(str(p).replace(extensions, new_ext))
p = Path("/path/to/myfile.tar.gz")
new_ext = ".jpg"
assert replace_ext(p, new_ext) == Path('/path/to/myfile.jpg')
assert replace_ext(str(p), new_ext) == Path('/path/to/myfile.jpg')
assert replace_ext(p) == Path('/path/to/myfile')
Try the following steps:
Make sure you have connectivity (you can browse) (This kind of error is usually due to connectivity with Internet)
Download Maven and unzip it
Create a JAVA_HOME
System Variable
Create an M2_HOME
System Variable
Add %JAVA_HOME%\bin;%M2_HOME%\bin;
to your PATH
variable
Open a command window cmd
. Check: mvn -v
If you have a proxy, you will need to configure it
http://maven.apache.org/guides/mini/guide-proxies.html
Make sure you have .m2/repository
(erase all the folders and files below)
If you are going to use Eclipse, You will need to create the settings.xml
Maven plugin in Eclipse - Settings.xml file is missing
You can see more detail in
http://maven.apache.org/ref/3.2.5/maven-settings/settings.html
Well, display: none;
will not display the table at all, try display: inline-block;
with the width and min-width declarations remaining 'auto'.
Here is a solution using functions plot()
, polygon()
and lines()
.
set.seed(1234)
df <- data.frame(x =1:10,
F =runif(10,1,2),
L =runif(10,0,1),
U =runif(10,2,3))
plot(df$x, df$F, ylim = c(0,4), type = "l")
#make polygon where coordinates start with lower limit and
# then upper limit in reverse order
polygon(c(df$x,rev(df$x)),c(df$L,rev(df$U)),col = "grey75", border = FALSE)
lines(df$x, df$F, lwd = 2)
#add red lines on borders of polygon
lines(df$x, df$U, col="red",lty=2)
lines(df$x, df$L, col="red",lty=2)
Now use example data provided by OP in another question:
Lower <- c(0.418116841, 0.391011834, 0.393297710,
0.366144073,0.569956636,0.224775521,0.599166016,0.512269587,
0.531378573, 0.311448219, 0.392045751,0.153614913, 0.366684097,
0.161100849,0.700274810,0.629714150, 0.661641288, 0.533404093,
0.412427559, 0.432905333, 0.525306427,0.224292061,
0.28893064,0.099543648, 0.342995605,0.086973739,0.289030388,
0.081230826,0.164505624, -0.031290586,0.148383474,0.070517523,0.009686605,
-0.052703529,0.475924192,0.253382210, 0.354011010,0.130295355,0.102253218,
0.446598823,0.548330752,0.393985810,0.481691632,0.111811248,0.339626541,
0.267831909,0.133460254,0.347996621,0.412472322,0.133671128,0.178969601,0.484070587,
0.335833224,0.037258467, 0.141312363,0.361392799,0.129791998,
0.283759439,0.333893418,0.569533076,0.385258093,0.356201955,0.481816148,
0.531282473,0.273126565,0.267815691,0.138127486,0.008865700,0.018118398,0.080143484,
0.117861634,0.073697418,0.230002398,0.105855042,0.262367348,0.217799352,0.289108011,
0.161271889,0.219663224,0.306117717,0.538088622,0.320711912,0.264395149,0.396061543,
0.397350946,0.151726970,0.048650180,0.131914718,0.076629840,0.425849394,
0.068692279,0.155144797,0.137939059,0.301912657,-0.071415593,-0.030141781,0.119450922,
0.312927614,0.231345972)
Upper.limit <- c(0.6446223,0.6177311, 0.6034427, 0.5726503,
0.7644718, 0.4585430, 0.8205418, 0.7154043,0.7370033,
0.5285199, 0.5973728, 0.3764209, 0.5818298,
0.3960867,0.8972357, 0.8370151, 0.8359921, 0.7449118,
0.6152879, 0.6200704, 0.7041068, 0.4541011, 0.5222653,
0.3472364, 0.5956551, 0.3068065, 0.5112895, 0.3081448,
0.3745473, 0.1931089, 0.3890704, 0.3031025, 0.2472591,
0.1976092, 0.6906118, 0.4736644, 0.5770463, 0.3528607,
0.3307651, 0.6681629, 0.7476231, 0.5959025, 0.7128883,
0.3451623, 0.5609742, 0.4739216, 0.3694883, 0.5609220,
0.6343219, 0.3647751, 0.4247147, 0.6996334, 0.5562876,
0.2586490, 0.3750040, 0.5922248, 0.3626322, 0.5243285,
0.5548211, 0.7409648, 0.5820070, 0.5530232, 0.6863703,
0.7206998, 0.4952387, 0.4993264, 0.3527727, 0.2203694,
0.2583149, 0.3035342, 0.3462009, 0.3003602, 0.4506054,
0.3359478, 0.4834151, 0.4391330, 0.5273411, 0.3947622,
0.4133769, 0.5288060, 0.7492071, 0.5381701, 0.4825456,
0.6121942, 0.6192227, 0.3784870, 0.2574025, 0.3704140,
0.2945623, 0.6532694, 0.2697202, 0.3652230, 0.3696383,
0.5268808, 0.1545602, 0.2221450, 0.3553377, 0.5204076,
0.3550094)
Fitted.values<- c(0.53136955, 0.50437146, 0.49837019,
0.46939721, 0.66721423, 0.34165926, 0.70985388, 0.61383696,
0.63419092, 0.41998407, 0.49470927, 0.26501789, 0.47425695,
0.27859380, 0.79875525, 0.73336461, 0.74881668, 0.63915795,
0.51385774, 0.52648789, 0.61470661, 0.33919656, 0.40559797,
0.22339000, 0.46932536, 0.19689011, 0.40015996, 0.19468781,
0.26952645, 0.08090917, 0.26872696, 0.18680999, 0.12847285,
0.07245286, 0.58326799, 0.36352329, 0.46552867, 0.24157804,
0.21650915, 0.55738088, 0.64797691, 0.49494416, 0.59728999,
0.22848680, 0.45030036, 0.37087676, 0.25147426, 0.45445930,
0.52339711, 0.24922310, 0.30184215, 0.59185198, 0.44606040,
0.14795374, 0.25815819, 0.47680880, 0.24621212, 0.40404398,
0.44435727, 0.65524894, 0.48363255, 0.45461258, 0.58409323,
0.62599114, 0.38418264, 0.38357103, 0.24545011, 0.11461756,
0.13821664, 0.19183886, 0.23203127, 0.18702881, 0.34030391,
0.22090140, 0.37289121, 0.32846615, 0.40822456, 0.27801706,
0.31652008, 0.41746184, 0.64364785, 0.42944100, 0.37347037,
0.50412786, 0.50828681, 0.26510696, 0.15302635, 0.25116438,
0.18559609, 0.53955941, 0.16920626, 0.26018389, 0.25378867,
0.41439675, 0.04157232, 0.09600163, 0.23739430, 0.41666762,
0.29317767)
Assemble into a data frame (no x provided, so using indices)
df2 <- data.frame(x=seq(length(Fitted.values)),
fit=Fitted.values,lwr=Lower,upr=Upper.limit)
plot(fit~x,data=df2,ylim=range(c(df2$lwr,df2$upr)))
#make polygon where coordinates start with lower limit and then upper limit in reverse order
with(df2,polygon(c(x,rev(x)),c(lwr,rev(upr)),col = "grey75", border = FALSE))
matlines(df2[,1],df2[,-1],
lwd=c(2,1,1),
lty=1,
col=c("black","red","red"))
Isn't this a much simpler solution, if I correctly understand the question, of course.
I want to load email addresses that are in a table called "spam" into a variable.
select email from spam
produces the following list, say:
.accountant
.bid
.buiilldanything.com
.club
.cn
.cricket
.date
.download
.eu
To load into the variable @list:
declare @list as varchar(8000)
set @list += @list (select email from spam)
@list may now be INSERTed into a table, etc.
I hope this helps.
To use it for a .csv file or in VB, spike the code:
declare @list as varchar(8000)
set @list += @list (select '"'+email+',"' from spam)
print @list
and it produces ready-made code to use elsewhere:
".accountant,"
".bid,"
".buiilldanything.com,"
".club,"
".cn,"
".cricket,"
".date,"
".download,"
".eu,"
One can be very creative.
Thanks
Nico
So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.
// Download button
$("#download-image").on('click', function () {
let width = __CANVAS.width;
let height = __CANVAS.height;
//set the orientation
if(width > height){
pdf = new jsPDF('l', 'px', [width, height]);
}
else{
pdf = new jsPDF('p', 'px', [height, width]);
}
//then we get the dimensions from the 'pdf' file itself
width = pdf.internal.pageSize.getWidth();
height = pdf.internal.pageSize.getHeight();
pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
pdf.save("download.pdf");
});
Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476
Data flow diagram shows the flow of data between the different entities and datastores in a system while a flow chart shows the steps involved to carried out a task. In a sense, data flow diagram provides a very high level view of the system, while a flow chart is a lower level view (basically showing the algorithm).
Whether you use data flow diagram or flow charts depends on figuring out what is it that you are trying to show.
The equivalent to WinForms' MessageBox
in WPF is called System.Windows.MessageBox
.
you can round your double and cast ist:
(int)Math.Round(myDouble);
Do not use css3 variables due to support.
I would do the following if you want a pure css solution.
Use color classes with semenatic names.
.bg-primary { background: #880000; }
.bg-secondary { background: #008800; }
.bg-accent { background: #F5F5F5; }
Separate the structure from the skin (OOCSS)
/* Instead of */
h1 {
font-size: 2rem;
line-height: 1.5rem;
color: #8000;
}
/* use this */
h1 {
font-size: 2rem;
line-height: 1.5rem;
}
.bg-primary {
background: #880000;
}
/* This will allow you to reuse colors in your design */
Put these inside a separate css file to change as needed.
You can use a trick to use scopes as you wish, just declare enum in such way:
struct Days
{
enum type
{
Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday
};
};
Days::type day = Days::Saturday;
if (day == Days::Saturday)
namespace FileUpload
{
public partial class Form1 : Form
{
string fileName = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = "";
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Attach customer proposal document";
fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
fDialog.InitialDirectory = @"C:\";
if (fDialog.ShowDialog() == DialogResult.OK)
{
fileName = System.IO.Path.GetFileName(fDialog.FileName);
path = Path.GetDirectoryName(fDialog.FileName);
textBox1.Text = path + "\\" + fileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential("erandika1986", "123");
Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\"+fileName);
client.Credentials = nc;
byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
MessageBox.Show(arrReturn.ToString());
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
}
}
Here is my code that works just fine.
public async Task<bool> UpdateDeviceShutdownAsync(Guid id, DateTime shutdownAtTime, int areaID, decimal mileage,
decimal motohours, int driverID, List<int> commission,
string shutdownPlaceDescr, int deviceShutdownTypeID, string deviceShutdownDesc,
bool isTransportation, string violationConditions, DateTime shutdownStartTime,
DateTime shutdownEndTime, string notes, List<Guid> faultIDs )
{
try
{
using (var db = new GJobEntities())
{
var isExisting = await db.DeviceShutdowns.FirstOrDefaultAsync(x => x.ID == id);
if (isExisting != null)
{
isExisting.AreaID = areaID;
isExisting.DriverID = driverID;
isExisting.IsTransportation = isTransportation;
isExisting.Mileage = mileage;
isExisting.Motohours = motohours;
isExisting.Notes = notes;
isExisting.DeviceShutdownDesc = deviceShutdownDesc;
isExisting.DeviceShutdownTypeID = deviceShutdownTypeID;
isExisting.ShutdownAtTime = shutdownAtTime;
isExisting.ShutdownEndTime = shutdownEndTime;
isExisting.ShutdownStartTime = shutdownStartTime;
isExisting.ShutdownPlaceDescr = shutdownPlaceDescr;
isExisting.ViolationConditions = violationConditions;
// Delete children
foreach (var existingChild in isExisting.DeviceShutdownFaults.ToList())
{
db.DeviceShutdownFaults.Remove(existingChild);
}
if (faultIDs != null && faultIDs.Any())
{
foreach (var faultItem in faultIDs)
{
var newChild = new DeviceShutdownFault
{
ID = Guid.NewGuid(),
DDFaultID = faultItem,
DeviceShutdownID = isExisting.ID,
};
isExisting.DeviceShutdownFaults.Add(newChild);
}
}
// Delete all children
foreach (var existingChild in isExisting.DeviceShutdownComissions.ToList())
{
db.DeviceShutdownComissions.Remove(existingChild);
}
// Add all new children
if (commission != null && commission.Any())
{
foreach (var cItem in commission)
{
var newChild = new DeviceShutdownComission
{
ID = Guid.NewGuid(),
PersonalID = cItem,
DeviceShutdownID = isExisting.ID,
};
isExisting.DeviceShutdownComissions.Add(newChild);
}
}
await db.SaveChangesAsync();
return true;
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
return false;
}
All the answers provided here uses normal function but these days most of our code uses arrow functions in ES6. I hope my answer will help readers on how to use arrow function when we do iteration over array of objects
let data = {
"messages": [{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}]
}
Do .forEach on array using arrow function
data.messages.forEach((obj, i) => {
console.log("msgFrom", obj.msgFrom);
console.log("msgBody", obj.msgBody);
});
Do .map on array using arrow function
data.messages.map((obj, i) => {
console.log("msgFrom", obj.msgFrom);
console.log("msgBody", obj.msgBody);
});
I developed a new plugin called JavaScript Enhancements, that you can find on Package Control. It uses Flow (javascript static type checker from Facebook) under the hood.
Furthermore, it offers smart javascript autocomplete (compared to my other plugin JavaScript Completions), real-time errors, code refactoring and also a lot of features about creating, developing and managing javascript projects.
See the Wiki to know all the features that it offers!
An introduction to this plugin could be found in this css-tricks.com article: Turn Sublime Text 3 into a JavaScript IDE
Just some quick screenshots:
At the time this question was asked nobody thought about Bitcoin price. In the case of BTC, it is probably insufficient to use DECIMAL(15,2)
. If the Bitcoin will rise to $100,000 or more, we will need at least DECIMAL(18,9)
to support cryptocurrencies in our apps.
DECIMAL(18,9)
takes 12 bytes of space in MySQL (4 bytes per 9 digits).
From the simulator, in iPad mode:
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-us) AppleWebKit/531.9 (KHTML, like Gecko) Version/4.0.3 Safari/531.9(this is for 3.2 beta 1)Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10 (this is for 3.2 beta 3)
and in iPhone mode:
Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.20 (KHTML, like Gecko) Mobile/7B298g
I don't know how reliable the simulator is, but it seems you can't detect whether the device is iPad just from the user-agent string.
(Note: I'm on Snow Leopard which the User Agent string for Safari is
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-us) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10
)
I had exactly this issue in a recent project which really is a pain in the rear. I finally found it's because the Python we used in Docker has encoding "ansi_x3.4-1968" instead of "utf-8". So if anyone out there using Docker and got this error, following these steps may thoroughly solve your problem.
create a file and name it default_locale in the same directory of your Dockerfile, put this line in it,
environment=LANG="es_ES.utf8", LC_ALL="es_ES.UTF-8", LC_LANG="es_ES.UTF-8"
add these to your Dockerfile,
RUN apt-get clean && apt-get update && apt-get install -y locales
RUN locale-gen en_CA.UTF-8
COPY ./default_locale /etc/default/locale
RUN chmod 0755 /etc/default/locale
ENV LC_ALL=en_CA.UTF-8
ENV LANG=en_CA.UTF-8
ENV LANGUAGE=en_CA.UTF-8
This thoroughly solved my issue when I built and run my Docker again, hopefully this solve your issue also.
You could try JarNavigator to view and search contents of a jar file.
Python is a pure pass-by-value language if you think about it the right way. A python variable stores the location of an object in memory. The Python variable does not store the object itself. When you pass a variable to a function, you are passing a copy of the address of the object being pointed to by the variable.
Contrasst these two functions
def foo(x):
x[0] = 5
def goo(x):
x = []
Now, when you type into the shell
>>> cow = [3,4,5]
>>> foo(cow)
>>> cow
[5,4,5]
Compare this to goo.
>>> cow = [3,4,5]
>>> goo(cow)
>>> goo
[3,4,5]
In the first case, we pass a copy the address of cow to foo and foo modified the state of the object residing there. The object gets modified.
In the second case you pass a copy of the address of cow to goo. Then goo proceeds to change that copy. Effect: none.
I call this the pink house principle. If you make a copy of your address and tell a painter to paint the house at that address pink, you will wind up with a pink house. If you give the painter a copy of your address and tell him to change it to a new address, the address of your house does not change.
The explanation eliminates a lot of confusion. Python passes the addresses variables store by value.
You could try this. It doesn't read all of f into memory at once (using the file object's iterator) and it closes the file when the code leaves the with block.
if data.find('!masters') != -1:
with open('masters.txt', 'r') as f:
for line in f:
print line
sck.send('PRIVMSG ' + chan + " " + line + '\r\n')
If you're using an older version of python (pre 2.6) you'll have to have
from __future__ import with_statement
It works for me, use iframe to ignore browsers show GET error message
var imgFrame = $('<iframe><img src="' + path + '" /></iframe>');
if ($(imgFrame).find('img').attr('width') > 0) {
// do something
} else {
// do something
}
try run with sudo
permission mode
example sudo kubectl....
Python
element.text
Java
element.getText()
C#
element.Text
Ruby
element.text
For those like me, only needing information on how to connect to a (DB2) WAS Data Source from Java using JNDI lookup (Used IBM Websphere 8.5.5 & DB2 Universal JDBC Driver Provider with implementation class: com.ibm.db2.jcc.DB2ConnectionPoolDataSource):
public DataSource getJndiDataSource() throws NamingException {
DataSource datasource = null;
InitialContext context = new InitialContext();
// Tomcat/Possibly others: java:comp/env/jdbc/myDatasourceJndiName
datasource = (DataSource) context.lookup("jdbc/myDatasourceJndiName");
return datasource;
}
mailx -s "subjec_of_mail" [email protected] < file_name
through mailx
utility we can send a file from unix
to mail server
.
here in above code we can see
first parameter is -s "subject of mail"
the second parameter is mail ID
and the last parameter is name of file which we want to attach
With the new ValueTuple
from C# 7 (VS 2017 and above), there is a new solution:
List<(int,string)> mylist= new List<(int,string)>();
Which creates a list of ValueTuple type. If you're targeting .Net Framework 4.7+ or .Net Core, it's native, otherwise you have to get the ValueTuple package from nuget.
It's a struct opposing to Tuple
, which is a class. It also has the advantage over the Tuple
class that you could create a named tuple, like this:
var mylist = new List<(int myInt, string myString)>();
That way you can access like mylist[0].myInt
and mylist[0].myString
What I have found is that simply wrapping code in the componentDidMount
or componentDidUpdate
with a setTimeout
with a time of 0 milliseconds ensures that the browser DOM has been updated with the React changes before executing the setTimeout
function.
Like this:
componentDidMount() {
setTimeout(() => {
$("myclass") // $ is available here
}, 0)
}
This puts the anonymous function on the JS Event Queue to run immediately after the currently running React stack frame has completed.
It depends on what you are trying to print. You need a third party pdf printer application or if you are printing data of your own you can use report viewer in visual studio. It can output reports to excel and pdf -files.
Try with regular expression and default parameters argument
public static int parseIntWithDefault(String str, int defaultInt) {
return str.matches("-?\\d+") ? Integer.parseInt(str) : defaultInt;
}
int testId = parseIntWithDefault("1001", 0);
System.out.print(testId); // 1001
int testId = parseIntWithDefault("test1001", 0);
System.out.print(testId); // 1001
int testId = parseIntWithDefault("-1001", 0);
System.out.print(testId); // -1001
int testId = parseIntWithDefault("test", 0);
System.out.print(testId); // 0
if you're using apache.commons.lang3 then by using NumberUtils:
int testId = NumberUtils.toInt("test", 0);
System.out.print(testId); // 0
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
To turn off axes for all subplots, do either:
[axi.set_axis_off() for axi in ax.ravel()]
or
map(lambda axi: axi.set_axis_off(), ax.ravel())
I had to set both HighlightBrushKey and ControlBrushKey to get it to be correctly styled. Otherwise, whilst it has focus this will correctly use the transparent HighlightBrusKey. Bt, if the control loses focus (whilst it is still highlighted) then it uses the ControlBrushKey.
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</Style.Resources>
When Using .Net 4.5 and above, use InactiveSelectionHighlightBrushKey
instead of ControlBrushKey
:
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</Style.Resources>
Hope this helps someone out.
I had issues with the IsInternetAvailable answer not testing for cellular networks, rather only if wifi was connected. This answer works for both wifi and mobile data:
How to check network connection enable or disable in WIFI and 3G(data plan) in mobile?
Simplest answer is the following.....
All members in C# always take the LEAST accessible modifier possible by default.
That is why all top level classes in an assembly are "internal" by default, which means they are public to the assembly they are in, but private or excluded from access to outside assemblies. The only other option for a top level class is public which is more accessible. For nested types its all private except for a few rare exceptions like members of enums and interfaces which can only be public. Some examples. In the case of top level classes and interfaces, the defaults are:
class Animal same as internal class Animal
interface Animal same as public interface Animal
In the case of nested classes and interfaces (inside types), the defaults are:
class Animal same as private class Animal
interface Animal same as private interface Animal
If you just assume the default is always the most private, then you do not need to use an accessors until you need to change the default. Easy.
Simple solution (ES6)
If you don't have duplicate element
Array.prototype.remove = function(elem) {
var indexElement = this.findIndex(el => el === elem);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};
just in case someone need it, in firefox for me it work like this
<iframe src="filename.pdf#zoom=FitH" style="position:absolute;right:0; top:0; bottom:0; width:100%;"></iframe>
Try going to Tools->Android->Enable ADB Integration
In my case it got automagically disabled
System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("Red");
(Use my method if you want to accept HTML-style hex colors.)
You can check your Network (console) and See the answer from the Server ... The "<" will be the first letter of your response. Something like "<"undefined index XY in line Z>"
This works in Linux. Not sure how it behaves in other *nixes.
getent passwd "${OTHER_USER}"|cut -d\: -f 6
If you are using windows, you should make sure that the certificate file csr.pem and key.pem don't have unix-style line endings. Openssl will generate the key files with unix style line endings. You can convert these files to dos format using a utility like unix2dos or a text editor like notepad++
Yes, it’s frustrating—sometimes type
and other programs
print gibberish, and sometimes they do not.
First of all, Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the default Raster Font.
But if the console font doesn’t contain the character you’re trying to display, you’ll see question marks instead of gibberish. When you get gibberish, there’s more going on than just font settings.
When programs use standard C-library I/O functions like printf
, the
program’s output encoding must match the console’s output encoding, or
you will get gibberish. chcp
shows and sets the current codepage. All
output using standard C-library I/O functions is treated as if it is in the
codepage displayed by chcp
.
Matching the program’s output encoding with the console’s output encoding can be accomplished in two different ways:
A program can get the console’s current codepage using chcp
or
GetConsoleOutputCP
, and configure itself to output in that encoding, or
You or a program can set the console’s current codepage using chcp
or
SetConsoleOutputCP
to match the default output encoding of the program.
However, programs that use Win32 APIs can write UTF-16LE strings directly
to the console with
WriteConsoleW
.
This is the only way to get correct output without setting codepages. And
even when using that function, if a string is not in the UTF-16LE encoding
to begin with, a Win32 program must pass the correct codepage to
MultiByteToWideChar
.
Also, WriteConsoleW
will not work if the program’s output is redirected;
more fiddling is needed in that case.
type
works some of the time because it checks the start of each file for
a UTF-16LE Byte Order Mark
(BOM), i.e. the bytes 0xFF 0xFE
.
If it finds such a
mark, it displays the Unicode characters in the file using WriteConsoleW
regardless of the current codepage. But when type
ing any file without a
UTF-16LE BOM, or for using non-ASCII characters with any command
that doesn’t call WriteConsoleW
—you will need to set the
console codepage and program output encoding to match each other.
How can we find this out?
Here’s a test file containing Unicode characters:
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
Here’s a Java program to print out the test file in a bunch of different
Unicode encodings. It could be in any programming language; it only prints
ASCII characters or encoded bytes to stdout
.
import java.io.*;
public class Foo {
private static final String BOM = "\ufeff";
private static final String TEST_STRING
= "ASCII abcde xyz\n"
+ "German äöü ÄÖÜ ß\n"
+ "Polish aezznl\n"
+ "Russian ??????? ???\n"
+ "CJK ??\n";
public static void main(String[] args)
throws Exception
{
String[] encodings = new String[] {
"UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" };
for (String encoding: encodings) {
System.out.println("== " + encoding);
for (boolean writeBom: new Boolean[] {false, true}) {
System.out.println(writeBom ? "= bom" : "= no bom");
String output = (writeBom ? BOM : "") + TEST_STRING;
byte[] bytes = output.getBytes(encoding);
System.out.write(bytes);
FileOutputStream out = new FileOutputStream("uc-test-"
+ encoding + (writeBom ? "-bom.txt" : "-nobom.txt"));
out.write(bytes);
out.close();
}
}
}
}
The output in the default codepage? Total garbage!
Z:\andrew\projects\sx\1259084>chcp
Active code page: 850
Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
= bom
´++ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
== UTF-16LE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
= bom
¦A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
== UTF-16BE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
= bom
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
== UTF-32LE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? z? |? D? B?
R u s s i a n 0? 1? 2? 3? 4? 5? 6? M? N
? O?
C J K `O }Y
= bom
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? z? |? D? B?
R u s s i a n 0? 1? 2? 3? 4? 5? 6? M? N
? O?
C J K `O }Y
== UTF-32BE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
= bom
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
However, what if we type
the files that got saved? They contain the exact
same bytes that were printed to the console.
Z:\andrew\projects\sx\1259084>type *.txt
uc-test-UTF-16BE-bom.txt
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
uc-test-UTF-16BE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
uc-test-UTF-16LE-bom.txt
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
uc-test-UTF-16LE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
uc-test-UTF-32BE-bom.txt
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
uc-test-UTF-32BE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
uc-test-UTF-32LE-bom.txt
A S C I I a b c d e x y z
G e r m a n ä ö ü Ä Ö Ü ß
P o l i s h a e z z n l
R u s s i a n ? ? ? ? ? ? ? ? ? ?
C J K ? ?
uc-test-UTF-32LE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? z? |? D? B?
R u s s i a n 0? 1? 2? 3? 4? 5? 6? M? N
? O?
C J K `O }Y
uc-test-UTF-8-bom.txt
´++ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
uc-test-UTF-8-nobom.txt
ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
The only thing that works is UTF-16LE file, with a BOM, printed to the
console via type
.
If we use anything other than type
to print the file, we get garbage:
Z:\andrew\projects\sx\1259084>copy uc-test-UTF-16LE-bom.txt CON
¦A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
1 file(s) copied.
From the fact that copy CON
does not display Unicode correctly, we can
conclude that the type
command has logic to detect a UTF-16LE BOM at the
start of the file, and use special Windows APIs to print it.
We can see this by opening cmd.exe
in a debugger when it goes to type
out a file:
After type
opens a file, it checks for a BOM of 0xFEFF
—i.e., the bytes
0xFF 0xFE
in little-endian—and if there is such a BOM, type
sets an
internal fOutputUnicode
flag. This flag is checked later to decide
whether to call WriteConsoleW
.
But that’s the only way to get type
to output Unicode, and only for files
that have BOMs and are in UTF-16LE. For all other files, and for programs
that don’t have special code to handle console output, your files will be
interpreted according to the current codepage, and will likely show up as
gibberish.
You can emulate how type
outputs Unicode to the console in your own programs like so:
#include <stdio.h>
#define UNICODE
#include <windows.h>
static LPCSTR lpcsTest =
"ASCII abcde xyz\n"
"German äöü ÄÖÜ ß\n"
"Polish aezznl\n"
"Russian ??????? ???\n"
"CJK ??\n";
int main() {
int n;
wchar_t buf[1024];
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
n = MultiByteToWideChar(CP_UTF8, 0,
lpcsTest, strlen(lpcsTest),
buf, sizeof(buf));
WriteConsole(hConsole, buf, n, &n, NULL);
return 0;
}
This program works for printing Unicode on the Windows console using the default codepage.
For the sample Java program, we can get a little bit of correct output by setting the codepage manually, though the output gets messed up in weird ways:
Z:\andrew\projects\sx\1259084>chcp 65001
Active code page: 65001
Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
? ???
CJK ??
??
?
?
= bom
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
?? ???
CJK ??
??
?
?
== UTF-16LE
= no bom
A S C I I a b c d e x y z
…
However, a C program that sets a Unicode UTF-8 codepage:
#include <stdio.h>
#include <windows.h>
int main() {
int c, n;
UINT oldCodePage;
char buf[1024];
oldCodePage = GetConsoleOutputCP();
if (!SetConsoleOutputCP(65001)) {
printf("error\n");
}
freopen("uc-test-UTF-8-nobom.txt", "rb", stdin);
n = fread(buf, sizeof(buf[0]), sizeof(buf), stdin);
fwrite(buf, sizeof(buf[0]), n, stdout);
SetConsoleOutputCP(oldCodePage);
return 0;
}
does have correct output:
Z:\andrew\projects\sx\1259084>.\test
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
The moral of the story?
type
can print UTF-16LE files with a BOM regardless of your current codepageWriteConsoleW
.chcp
, and will probably still get weird output.Here's a really hacky way to do it in *nix, you'll get some stuff you don't really care about (ie: warnings::register etc), but it should give you a list of every .pm file that's accessible via perl.
for my $path (@INC) {
my @list = `ls -R $path/**/*.pm`;
for (@list) {
s/$path\///g;
s/\//::/g;
s/\.pm$//g;
print;
}
}
For a list, you could use a list comp. For example, to make b
a copy of a
without the 3rd element:
a = range(10)[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
b = [x for i,x in enumerate(a) if i!=3] # [9, 8, 7, 5, 4, 3, 2, 1, 0]
This is very general, and can be used with all iterables, including numpy arrays. If you replace []
with ()
, b
will be an iterator instead of a list.
Or you could do this in-place with pop
:
a = range(10)[::-1] # a = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
a.pop(3) # a = [9, 8, 7, 5, 4, 3, 2, 1, 0]
In numpy you could do this with a boolean indexing:
a = np.arange(9, -1, -1) # a = array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
b = a[np.arange(len(a))!=3] # b = array([9, 8, 7, 5, 4, 3, 2, 1, 0])
which will, in general, be much faster than the list comprehension listed above.
This two commands work for me in my project
composer require laravel/ui --dev
Then
php artisan ui:auth
My preferred solution is:
class MyClass:
_data = []
__init__(self,data=None):
# do init stuff
if not data: return
self._data = list(data) # list() copies the list, instead of pointing to it.
Then invoke it with either MyClass()
or MyClass([1,2,3])
.
Hope that helps. Happy Coding!
; good example of unlimited num print
.model small
.stack 100h
.data
number word 6432
string db 10 dup('$')
.code
main proc
mov ax,@data
mov ds,ax
mov ax,number
mov bx ,10
mov cx,0
l1:
mov dx,0
div bx
add dx,48
push dx
inc cx
cmp ax,0
jne l1
mov bx ,offset string
l2:
pop dx
mov [bx],dx
inc bx
loop l2
mov ah,09
mov dx,offset string
int 21h
mov ax,4c00h
int 21h
main endp
end main
Modern cmake offers simpler ways to configure compilers to use a specific version of C++. The only thing anyone needs to do is set the relevant target properties. Among the properties supported by cmake, the ones that are used to determine how to configure compilers to support a specific version of C++ are the following:
CXX_STANDARD
sets the C++ standard whose features are requested to build the target. Set this as 11
to target C++11.
CXX_EXTENSIONS
, a boolean specifying whether compiler specific extensions are requested. Setting this as Off
disables support for any compiler-specific extension.
To demonstrate, here is a minimal working example of a CMakeLists.txt
.
cmake_minimum_required(VERSION 3.1)
project(testproject LANGUAGES CXX )
set(testproject_SOURCES
main.c++
)
add_executable(testproject ${testproject_SOURCES})
set_target_properties(testproject
PROPERTIES
CXX_STANDARD 11
CXX_EXTENSIONS off
)
For Rest API to upload images from host to host:
import urllib2
import requests
api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'
img_file = urllib2.urlopen(image_url)
response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)
You can use option verify set to False to omit SSL verification for HTTPS requests.
a = [0,4,8,2,5,0,2,6]
a.empty? ? nil : a.reduce(:+)/a.size.to_f
=> 3.375
Solves divide by zero, integer division and is easy to read. Can be easily modified if you choose to have an empty array return 0.
I like this variant too, but it's a little more wordy.
a = [0,4,8,2,5,0,2,6]
a.empty? ? nil : [a.reduce(:+), a.size.to_f].reduce(:/)
=> 3.375
and what if I want to extract a youtue url from a string full of other characters? like this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco https://www.youtube.com/watch?v=cPW9Y94BJI0 laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
and get https://www.youtube.com/watch?v=cPW9Y94BJI0 from that string?
In my case (using IntelliJ) I copy and pasted and renamed the workspace, and I am still using the old path to compile the new project.
In this case this particular error will happen too, if you have the same error you can check if you have done the similar things.
When uploading .mp4 file into Perl script, using CGI.pm I see it as video/mp when printing out Content-type
for the uploaded file.
I hope it will help someone.
You can generate n unique random number between 0 to n-1 in java
public static void RandomGenerate(int n)
{
Set<Integer> st=new HashSet<Integer>();
Random r=new Random();
while(st.size()<n)
{
st.add(r.nextInt(n));
}
}
Try replaceAll("\\\\", "")
or replaceAll("\\\\/", "/")
.
The problem here is that a backslash is (1) an escape chararacter in Java string literals, and (2) an escape character in regular expressions – each of this uses need doubling the character, in effect needing 4 \
in row.
Of course, as Bozho said, you need to do something with the result (assign it to some variable) and not throw it away. And in this case the non-regex variant is better.
SQL*Plus uses &1, &2... &n to access the parameters.
Suppose you have the following script test.sql
:
SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off
you could call this script like this for example:
$ sqlplus login/pw @test Hello World!
In a UNIX script you would usually call a SQL script like this:
sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF
so that your login/password won't be visible with another session's ps
No, you can unpublish but once your application has been live
on the market you cannot delete it. (Each package name is unique and Google remembers all package names anyway so you could use this a reminder)
The "Delete" button only works for unpublished version of your app. Once you published your app or a particular version of it, you cannot delete it from the Market. However, you can still "unpublish" it. The "Delete" button is only handy when you uploaded a new version, then you realized you goofed and want to remove that new version before publishing it.
Update, 2016
you can now filter out unpublished or draft apps from your listing.
Unpublish option can be found in the header area, beside PUBLISHED text.
UPDATE 2020
Due to changes in the new play console, the unpublish option was moved to a different location as follows.
Click All Apps
in the left pane. Then click the app you want to remove.
Then under the Setup
option in the left pane, Click Advanced Settings
.
Then under App Availablity
on the right, change the status to UnPublished
and click Save Changes
at the bottom.
Take a look at the image below:
If you want to know how to read a file, within a directory, and do something with it, here you go. This also shows you how to run a command through the power shell
. This is in TypeScript
! I had trouble with this, so I hope this helps someone one day. Feel free to down vote me if you think its THAT unhelpful. What this did for me was webpack
all of my .ts
files in each of my directories within a certain folder to get ready for deployment. Hope you can put it to use!
import * as fs from 'fs';
let path = require('path');
let pathDir = '/path/to/myFolder';
const execSync = require('child_process').execSync;
let readInsideSrc = (error: any, files: any, fromPath: any) => {
if (error) {
console.error('Could not list the directory.', error);
process.exit(1);
}
files.forEach((file: any, index: any) => {
if (file.endsWith('.ts')) {
//set the path and read the webpack.config.js file as text, replace path
let config = fs.readFileSync('myFile.js', 'utf8');
let fileName = file.replace('.ts', '');
let replacedConfig = config.replace(/__placeholder/g, fileName);
//write the changes to the file
fs.writeFileSync('myFile.js', replacedConfig);
//run the commands wanted
const output = execSync('npm run scriptName', { encoding: 'utf-8' });
console.log('OUTPUT:\n', output);
//rewrite the original file back
fs.writeFileSync('myFile.js', config);
}
});
};
// loop through all files in 'path'
let passToTest = (error: any, files: any) => {
if (error) {
console.error('Could not list the directory.', error);
process.exit(1);
}
files.forEach(function (file: any, index: any) {
let fromPath = path.join(pathDir, file);
fs.stat(fromPath, function (error2: any, stat: any) {
if (error2) {
console.error('Error stating file.', error2);
return;
}
if (stat.isDirectory()) {
fs.readdir(fromPath, (error3: any, files1: any) => {
readInsideSrc(error3, files1, fromPath);
});
} else if (stat.isFile()) {
//do nothing yet
}
});
});
};
//run the bootstrap
fs.readdir(pathDir, passToTest);
Im using the following code in order to access generated find methods from my custom implementation. Getting the implementation through the bean factory prevents circular bean creation problems.
public class MyRepositoryImpl implements MyRepositoryExtensions, BeanFactoryAware {
private BrandRepository myRepository;
public MyBean findOne(int first, int second) {
return myRepository.findOne(new Id(first, second));
}
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
myRepository = beanFactory.getBean(MyRepository.class);
}
}
t
refers to the text mode. There is no difference between r
and rt
or w
and wt
since text mode is the default.
Documented here:
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)
The default mode is 'r'
(open for reading text, synonym of 'rt'
).
You should be looking for the second tr that has the td that equals ' Color Digest ', then you need to look at either the following sibling of the first td in the tr, or the second td.
Try the following:
//tr[td='Color Digest'][2]/td/following-sibling::td[1]
or
//tr[td='Color Digest'][2]/td[2]
http://www.xpathtester.com/saved/76bb0bca-1896-43b7-8312-54f924a98a89
Try this:
function funcName() {
alert("test");
}
var run = setInterval(funcName, 10000)
you can use this solution:
items = { 'a', 'b' }
for k,v in pairs(items) do
if v == 'a' then
--do something
else
--do something
end
end
or
items = {'a', 'b'}
for k,v in pairs(items) do
while v do
if v == 'a' then
return found
else
break
end
end
end
return nothing
You can try to load the child component with history. to do so, pass 'history' through props. Something like that:
return (
<div>
<Login history={this.props.history} />
<br/>
<Register/>
</div>
)
The previous answers have covered the traditional menu used in android. Their is another option you can use if you are looking for an alternative
https://github.com/AnshulBansal/Android-Pulley-Menu
Pulley menu is an alternate to the traditional Menu which allows user to select any option for an activity intuitively. The menu is revealed by dragging the screen downwards and in that gesture user can also select any of the options.
app.all('*', function(req, res,next) {
/**
* Response settings
* @type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt
and python-pip
.
Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
php5-mcrypt \
python-pip
However, according to this answer you should think about installing the python3-pip
package instead of the python-pip
package when using Python 3.x.
Furthermore, to make the php5-mcrypt
package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository
command missing in the Ubuntu Docker image so I installed the package software-properties-common
at first to make the command available.
Splitting up the statements and putting apt-get update
and apt-get install
into one RUN
command is also recommended here.
Oh and by the way, you actually don't need the -y
flag at apt-get update
because there is nothing that has to be confirmed automatically.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
apache2 \
curl \
git \
libapache2-mod-php5 \
php5 \
php5-mcrypt \
php5-mysql \
python3.4 \
python3-pip
Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.
If you are not able to access tomcat from remote, there might be reason that taken port is not open in your machine. Suppose you have taken 8081 port.
On Your windows machine:
Open Control panel-> windows Firewall-> Advance setting->Inbound Rules
Create a new rule: mention Port
Configure your port and then shutdown and start your tomcat and it will be accessible from remote as well.
That port issue majorly comes in AWS machines.
If it is still not working then please check with your administrator that selected port is open for public access or not, if not then open it.
With Guava we can do a little better than Khoth's answer:
public static E random(Set<E> set) {
int index = random.nextInt(set.size();
if (set instanceof ImmutableSet) {
// ImmutableSet.asList() is O(1), as is .get() on the returned list
return set.asList().get(index);
}
return Iterables.get(set, index);
}
int *generate_randomnumbers(int start, int end){
int *res = malloc(sizeof(int)*(end-start));
srand(time(NULL));
for (int i= 0; i < (end -start)+1; i++){
int r = rand()%end + start;
int dup = 0;
for (int j = 0; j < (end -start)+1; j++){
if (res[j] == r){
i--;
dup = 1;
break;
}
}
if (!dup)
res[i] = r;
}
return res;
}
I realize this is somewhat of an older post, but for anyone that comes to this page looking for a similar solution...
http://api.jquery.com/jQuery.getScript/
jQuery.getScript( url, [ success(data, textStatus) ] )
url
- A string containing the URL to which the request is sent.
success(data, textStatus)
- A callback function that is executed if the request succeeds.$.getScript('ajax/test.js', function() { alert('Load was performed.'); });
For anyone looks for a shorthand way, to add transition for all properties except for one specific property with delay, be aware of there're differences among even modern browsers.
A simple demo below shows the difference. Check out full code
div:hover {
width: 500px;
height: 500px;
border-radius: 0;
transition: all 2s, border-radius 2s 4s;
}
Chrome will "combine" the two animation (which is like I expect), like below:
While Safari "separates" it (which may not be expected):
A more compatible way is that you assign the specific transition for specific property, if you have a delay for one of them.
There is no real solution to this - even in the links to other questions given above. In the end I have decided to use setTimeout
and call a method that checks every second! Not an ideal solution, but a solution that works and code I am calling is simple enough to not have an effect on performance by being called all the time.
function InitPageControls() {
CheckIfChanged();
}
function CheckIfChanged() {
// do logic
setTimeout(function () {
CheckIfChanged();
}, 1000);
}
Hope this helps someone in the future as it seems there is no surefire way of acheiving this using event handlers...
Try:
DateTime first;
DateTime second;
int milliSeconds = (int)((TimeSpan)(second - first)).TotalMilliseconds;
The answers here work to open the page in the same browser window/tab.
However, I wanted the page to open in a new window/tab when they click a button. (tab/window decision depends on the user's browser setting)
So here is how it worked to open the page in new tab/window:
<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>
It doesn't have to be a button, you can use anywhere. Notice the _blank that is used to open in new tab/window.
I suggest Freewall
. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.
Home page and document: also found here
.
Check that the file is called GNUMakefile, makefile or Makefile.
If it is called anything else (and you don't want to rename it) then try:
make -f othermakefilename clean
To find files accessed 1, 2, or 3 minutes ago use -3
find . -cmin -3
Please try the following code snippet,
IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value),
Format(Avg(Fields!Vision_Score.Value)),
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))
hope it will help, Thank-you.
1.Open postman app 2.Enter the URL in the URL bar in postman app along with the name of the design.Use slash(/) after URL to give the design name. 3.Select POST from the dropdown list from URL textbox. 4.Select raw from buttons available below the URL textbox. 5.Select JSON from the dropdown. 6.In the text area enter your data to be updated and enter send. 7.Select GET from dropdown list from URL textbox and enter send to see the updated result.