I had the same problem with a Repeater because I had a web-page with a Repeater control in a web-site which had EnableEventValidation switched on. It wasn't good. I was getting invalid postback related exceptions.
What worked for me was to set EnableViewState="false" for the Repeater. The advantages are that it is simpler to use, as simple as switching event validation off for the web-site or web-page, but the scope is a lot less than switching event validation off for either.
Since the fields are empty they are not valid, so the ng-invalid
and ng-invalid-required
classes are added properly.
You can use the class ng-pristine
to check out whether the fields have already been used or not.
Since strptime
returns a datetime object which has tzinfo
attribute, We can simply replace it with desired timezone.
>>> import datetime
>>> date_time_str = '2018-06-29 08:15:27.243860'
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
>>> date_time_obj.tzname()
'UTC'
$ echo "This is a sentence." | tr -s " " "\012"
This
is
a
sentence.
For checking for spaces, use grep:
$ echo "This is a sentence." | grep " " > /dev/null
$ echo $?
0
$ echo "Thisisasentence." | grep " " > /dev/null
$ echo $?
1
If all vectors have equal size, create a matrix and plot it.
Each column is plotted with a different color automatically
Then you can use legend
to indicate columns:
data = randn(100, 5);
figure;
plot(data);
legend(cellstr(num2str((1:size(data,2))')))
Or, if you have a cell with kernels names, use
legend(names)
Another way that I found useful to use a small Expect script from a Bash script is as follows.
...
Bash script start
Bash commands
...
expect - <<EOF
spawn your-command-here
expect "some-pattern"
send "some-command"
...
...
EOF
...
More Bash commands
...
This works because ...If the string "-" is supplied as a filename, standard input is read instead...
It is the difference between greedy and non-greedy quantifiers.
Consider the input 101000000000100
.
Using 1.*1
, *
is greedy - it will match all the way to the end, and then backtrack until it can match 1
, leaving you with 1010000000001
.
.*?
is non-greedy. *
will match nothing, but then will try to match extra characters until it matches 1
, eventually matching 101
.
All quantifiers have a non-greedy mode: .*?
, .+?
, .{2,6}?
, and even .??
.
In your case, a similar pattern could be <([^>]*)>
- matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than >
in-between <
and >
).
Having your packages stored on the network drive can slow down the performance of R / R Studio considerably, and you spend a lot of time waiting for the libraries to load/install, due to the bottlenecks of having to retrieve and push data over the server back to your local host. See the following for instructions on how to create an .RProfile on your local machine:
Sys.getenv("HOME")
to get your home directory (this is where your .RProfile will be stored and R will always check there for packages- and this is on the network if packages are stored there).Rprofile
and place it in :\YOUR\HOME\DIRECTORY\ON_NETWORK
(the directory you get after typing Sys.getenv("HOME")
in R Console).Rprofile
should be like this:#search 2 places for packages- install new packages to first directory- load built-in packages from the second (this is from your base R package- will be different for some)
.libPaths(c("C:\Users\xxxxxx\Documents\R\3.4", "C:/Program Files/Microsoft/R Client/R_SERVER/library"))
message("*** Setting libPath to local hard drive ***")
#insert a sleep command at line 12 of the unpackPkgZip function. So, just after the package is unzipped.
trace(utils:::unpackPkgZip, quote(Sys.sleep(2)), at=12L, print=TRUE)
message("*** Add 2 second delay when installing packages, to accommodate virus scanner for R 3.4 (fixed in R 3.5+)***")
# fix problem with tcltk for sqldf package: https://github.com/ggrothendieck/sqldf#problem-involvling-tcltk
options(gsubfn.engine = "R")
message("*** Successfully loaded .Rprofile ***")
Now you can enjoy faster performance of your application on local host, vs. storing the packages on the network and slowing everything down.
In most situations the best solution is to rely on the so-called "user site" location (see the PEP for details) by running:
pip install --user package_name
Below is a more "manual" way from my original answer, you do not need to read it if the above solution works for you.
With easy_install you can do:
easy_install --prefix=$HOME/local package_name
which will install into
$HOME/local/lib/pythonX.Y/site-packages
(the 'local' folder is a typical name many people use, but of course you may specify any folder you have permissions to write into).
You will need to manually create
$HOME/local/lib/pythonX.Y/site-packages
and add it to your PYTHONPATH
environment variable (otherwise easy_install will complain -- btw run the command above once to find the correct value for X.Y).
If you are not using easy_install
, look for a prefix option, most install scripts let you specify one.
With pip you can use:
pip install --install-option="--prefix=$HOME/local" package_name
In your Html page please add
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test the multiselect with ajax</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Bootstrap multiselect -->
<link rel="stylesheet" href="http://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<br>
<form method="post" id="myForm">
<!-- Build your select: -->
<select name="categories[]" id="example-getting-started" multiple="multiple" class="col-md-12">
<option value="A">Cheese</option>
<option value="B">Tomatoes</option>
<option value="C">Mozzarella</option>
<option value="D">Mushrooms</option>
<option value="E">Pepperoni</option>
<option value="F">Onions</option>
<option value="G">10</option>
<option value="H">11</option>
<option value="I">12</option>
</select>
<br><br>
<button type="button" class="btnSubmit"> Send </button>
</form>
<br><br>
<div id="result">result</div>
</div><!--container-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Bootstrap multiselect -->
<script src="http://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>
<!-- Bootstrap multiselect -->
<script src="ajax.js"></script>
<!-- Initialize the plugin: -->
<script type="text/javascript">
$(document).ready(function() {
$('#example-getting-started').multiselect();
});
</script>
</body>
</html>
In your ajax.js page please add
$(document).ready(function () {
$(".btnSubmit").on('click',(function(event) {
var formData = new FormData($('#myForm')[0]);
$.ajax({
url: "action.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#result").html(data);
// To clear the selected options
var select = $("#example-getting-started");
select.children().remove();
if (data.d) {
$(data.d).each(function(key,value) {
$("#example-getting-started").append($("<option></option>").val(value.State_id).html(value.State_name));
});
}
$('#example-getting-started').multiselect({includeSelectAllOption: true});
$("#example-getting-started").multiselect('refresh');
},
error: function()
{
console.log("failed to send the data");
}
});
}));
});
In your action.php page add
echo "<b>You selected :</b>";
for($i=0;$i<=count($_POST['categories']);$i++){
echo $_POST['categories'][$i]."<br>";
}
There is none. Don't forget that the value may be found on any number of keys, including 0 or more than 1.
I'm using this function
function isNull() {
for (var i = 0; i < arguments.length; i++) {
if (
typeof arguments[i] !== 'undefined'
&& arguments[i] !== undefined
&& arguments[i] != null
&& arguments[i] != NaN
&& arguments[i]
) return arguments[i];
}
}
test
console.log(isNull(null, null, undefined, 'Target'));
There is a dedicated npm
package for it. css-scrollbar-side
I ran into this problem after I forgot to install ejs before the first time I ran my app. For some reason ejs was not being seen after installing it later. I found a quick, clean, and effective solution to this problem which was to reinstall express by running npm uninstall express
then npm install express
in the local directory before restarting the server.
For future readers.
I wanted specific control over this issue, so this is what I did:
From a fragment or activity, hide your other views (that aren't needed while the keyboard is up), then restore them to solve this problem:
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
int heightDiff = rootView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
//ok now we know the keyboard is up...
view_one.setVisibility(View.GONE);
view_two.setVisibility(View.GONE);
} else {
//ok now we know the keyboard is down...
view_one.setVisibility(View.VISIBLE);
view_two.setVisibility(View.VISIBLE);
}
}
});
I see you've found your answer, however it didn't work for me. Delete kept returning false, so I tried the following and it worked (For anybody else for whom the chosen answer didn't work):
System.out.println(new File(path).getAbsoluteFile().delete());
The System out can be ignored obviously, I put it for convenience of confirming the deletion.
How is your web app configured? Does it run under Cassini (the tray web server) or IIS?
This shouldn't happen normally though. I think ProcessExplorer can tell you what files a process has locked. If not process explorer one of the other sysinternals tools.
One thing to try before even downloading one of the SI tools is to stop the Cassini web server, and seeing if that frees up the file.
I got asked a similar question in a test.
Find a number's length without converting to string
const numbers = [1, 10, 100, 12, 123, -1, -10, -100, -12, -123, 0, -0]
const numberLength = number => {
let length = 0
let n = Math.abs(number)
do {
n /= 10
length++
} while (n >= 1)
return length
}
console.log(numbers.map(numberLength)) // [ 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 1 ]
Negative numbers were added to complicate it a little more, hence the Math.abs().
First some general things to follow my argumentation:
The main challenge in designing big software systems is that they have to be flexible and uncomplicated to change. For this reason, there are some metrics like coupling and cohesion. To achieve systems that can be easily altered or extended in its functionality without the need to redesign the whole system from scratch, you can follow the design principles (like SOLID, etc.). After a while some developer recognized that if they follow those principles there are some similar solutions that worked well to similar problems. Those standard solutions turned out to be the design patterns.
So the design patterns are to support you to follow the general design principles in order to achieve loosely coupled systems with high cohesion.
Answering the question:
By asking the difference between two patterns you have to ask yourself what pattern makes your system in which way more flexible. Each pattern has its own purpose to organize dependencies between classes in your system.
The Abstract Factory Pattern: GoF: “Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”
What does this mean: By providing an interface like this the call to the constructor of each of the family’s product is encapsulated in the factory class. And because this is the only place in your whole system where those constructors are called you can alter your system by implementing a new factory class. If you exchange the representation of the factory through another, you can exchange a whole set of products without touching the majority of your code.
The Builder Pattern: GoF: “Separate the construction of a complex object from its representation so that the same construction process can create different representations.”
What does this mean: You encapsulate the process of construction in another class, called the director (GoF). This director contains the algorithm of creating new instances of the product (e.g. compose a complex product out of other parts). To create the integral parts of the whole product the director uses a builder. By exchanging the builder in the director you can use the same algorithm to create the product, but change the representations of single parts (and so the representation of the product). To extend or modify your system in the representation of the product, all you need to do is to implement a new builder class.
So in short: The Abstract Factory Pattern’s purpose is to exchange a set of products which are made to be used together. The Builder Pattern’s purpose is to encapsulate the abstract algorithm of creating a product to reuse it for different representations of the product.
In my opinion you can’t say that the Abstract Factory Pattern is the big brother of the Builder Pattern. YES, they are both creational patterns, but the main intent of the patterns is entirely different.
If you're doing some sort of math with the numbers you might also want to know the units. Given your input restrictions (that the input string contains unit and value only), this should correctly return both (you'll just need to figure out how to convert units into common units for your math).
def unit_value(str):
m = re.match(r'([^\d]*)(\d*\.?\d+)([^\d]*)', str)
if m:
g = m.groups()
return ' '.join((g[0], g[2])).strip(), float(g[1])
else:
return int(str)
If you want to remove leading and ending spaces, use str.strip()
:
sentence = ' hello apple'
sentence.strip()
>>> 'hello apple'
If you want to remove all space characters, use str.replace()
:
(NB this only removes the “normal” ASCII space character ' ' U+0020
but not any other whitespace)
sentence = ' hello apple'
sentence.replace(" ", "")
>>> 'helloapple'
If you want to remove duplicated spaces, use str.split()
:
sentence = ' hello apple'
" ".join(sentence.split())
>>> 'hello apple'
This errors TypeError: Cannot read property 'length' of undefined
usually means that jQuery DataTables cannot find the data in the response to the Ajax request.
By default jQuery DataTables expects the data to be in one of the formats shown below. Error occurs because data is returned in the format other than default.
Array of arrays
{
"data": [
[
"Tiger Nixon",
"System Architect",
"$320,800",
"2011/04/25",
"Edinburgh",
"5421"
]
]
}
Array of objects
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
}
]
}
Use default format or use ajax.dataSrc
option to define data property containing table data in Ajax response (data
by default).
See Data array location for more information.
See jQuery DataTables: Common JavaScript console errors for more details.
A more elegant way is to assign the whole array at once:
Sub PrintArray(Data, SheetName, StartRow, StartCol)
Dim Rng As Range
With Sheets(SheetName)
Set Rng = .Range(.Cells(StartRow, StartCol), _
.Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
UBound(Data, 2) - LBound(Data, 2) + StartCol))
End With
Rng.Value2 = Data
End Sub
But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.
As mentioned in this tutorial, it's as simple as:
To install
brew install gradle
To upgrade
brew upgrade gradle
(using Homebrew of course)
Also see (finally) updated docs.
Cheers :)!
You can use async/await
for this. I would explain more, but there's nothing really to it. It's just a regular for
loop but I added the await
keyword before the construction of your Promise
What I like about this is your Promise can resolve a normal value instead of having a side effect like your code (or other answers here) include. This gives you powers like in The Legend of Zelda: A Link to the Past where you can affect things in both the Light World and the Dark World – ie, you can easily work with data before/after the Promised data is available without having to resort to deeply nested functions, other unwieldy control structures, or stupid IIFEs.
// where DarkWorld is in the scary, unknown future
// where LightWorld is the world we saved from Ganondorf
LightWorld ... await DarkWorld
So here's what that will look like ...
const someProcedure = async n =>_x000D_
{_x000D_
for (let i = 0; i < n; i++) {_x000D_
const t = Math.random() * 1000_x000D_
const x = await new Promise(r => setTimeout(r, t, i))_x000D_
console.log (i, x)_x000D_
}_x000D_
return 'done'_x000D_
}_x000D_
_x000D_
someProcedure(10).then(x => console.log(x)) // => Promise_x000D_
// 0 0_x000D_
// 1 1_x000D_
// 2 2_x000D_
// 3 3_x000D_
// 4 4_x000D_
// 5 5_x000D_
// 6 6_x000D_
// 7 7_x000D_
// 8 8_x000D_
// 9 9_x000D_
// done
_x000D_
See how we don't have to deal with that bothersome .then
call within our procedure? And async
keyword will automatically ensure that a Promise
is returned, so we can chain a .then
call on the returned value. This sets us up for great success: run the sequence of n
Promises, then do something important – like display a success/error message.
create LOGIN guest WITH PASSWORD='guest@123', CHECK_POLICY = OFF;
Be sure when you want to exceute the following
DENY VIEW ANY DATABASE TO guest;
ALTER AUTHORIZATION ON DATABASE::BiddingSystemDB TO guest
Selected Database should be Master
function removeParam(parameter)
{
var url=document.location.href;
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift();
var queryString=urlparts.join("?");
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;)
if (pars[i].lastIndexOf(prefix, 0)!==-1)
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .
}
return url;
}
This will resolve your problem
This could be another answers.
let cards = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"];
let totalCards = [...cards, ...cards, ...cards, ...cards];
The simple way to avoid this is not to use the worksheet method ShowAllData
Autofilter has the same ShowAllData method which doesn't throw an error when the filter is enabled but no filter is set
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilter.ShowAllData
You guys are doing way too much for selecting. Just select by value:
$("#mySelect").val( 3 );
You can use the inline-block value for display, however in this case you will loose the block feature of h1 i.e. the siblings will be displayed inline with h1 if they are inline elements(in which case you can use a line-break
).
display:inline-block;
Unfortunately, what you're trying to do is impossible. Under the hood, the query variable is typed to be an IEnumerable
of an anonymous type. Anonymous type names cannot be represented in user code hence there is no way to make them an input parameter to a function.
Your best bet is to create a type and use that as the return from the query and then pass it into the function. For example,
struct Data {
public string ColumnName;
}
var query = (from name in some.Table
select new Data { ColumnName = name });
MethodOp(query);
...
MethodOp(IEnumerable<Data> enumerable);
In this case though, you are only selecting a single field, so it may be easier to just select the field directly. This will cause the query to be typed as an IEnumerable
of the field type. In this case, column name.
var query = (from name in some.Table select name); // IEnumerable<string>
This issue has been fixed in the regular release of MVC4. Now you can do:
public string GetFindBooks(string author="", string title="", string isbn="", string somethingelse="", DateTime? date= null)
{
// ...
}
and everything will work out of the box.
<div id="contentse "><br>
<h2>Percentage Calculator</h2>
<form action="/charactercount" class="align-items-center" style="border: 1px solid #eee;padding:15px;" method="post" enctype="multipart/form-data" name="form">
<input type="hidden" name="csrfmiddlewaretoken" value="NCBdw9beXfKV07Tc1epTBPqJ0gzfkmHNXKrAauE34n3jn4TGeL8Vv6miOShhqv6O">
<div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
<br><div class="input-float" style="float: left;"> what is <input type="text" id="aa" required=""> % of <input type="text" id="ab"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatea()"> <input type="text" id="ac" readonly=""> </div><br style="clear: both;"> </div><br>
<hr><br>
<div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
<div class="input-float" style="float: left;"><input type="text" id="ba"> is what percent of <input type="text" id="bb"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculateb()"> <input type="text" id="bc" readonly=""> % </div><br style="clear: both;"></div><br>
<hr><br>
<div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
Find percentage change(increase/decrease) <br><br>
<div class="input-float" style="float: left;">from <input type="text" id="ca"> to <input type="text" id="cb"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatec()"> <input type="text" id="cc" readonly=""> %</div><br style="clear: both;"></div>
</form>
</div>
_x000D_
Live example here: setool-percentage-calculator
System.Threading.Thread.Sleep(
(int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);
Or with using
statements:
Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);
I prefer this to 1000 * numSeconds
(or simply 3000
) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep
before. It better documents your intent.
I know this is an expansion off of @tibor-udvari's answer, but for a nicer copy and paste.
async function createFile(url, type){
if (typeof window === 'undefined') return // make sure we are in the browser
const response = await fetch(url)
const data = await response.blob()
const metadata = {
type: type || 'video/quicktime'
}
return new File([data], url, metadata)
}
If you go into Configure under Home there is a "Help" note on how to:
Home directory /var/lib/jenkins Help for feature: Home directory
By default, Jenkins stores all of its data in this directory on the file system.
There are a few ways to change the Jenkins home directory:
Edit the JENKINS_HOME variable in your Jenkins configuration file (e.g. /etc/sysconfig/jenkins on Red Hat Linux).
Use your web container's admin tool to set the JENKINS_HOME environment variable.
Set the environment variable JENKINS_HOME before launching your web container, or before launching Jenkins directly from the WAR file.
Set the JENKINS_HOME Java system property when launching your web container, or when launching Jenkins directly from the WAR file.
Modify web.xml in jenkins.war (or its expanded image in your web container). This is not recommended.
This value cannot be changed while Jenkins is running. It is shown here to help you ensure that your configuration is taking effect.
Better to just use .addClass()
and .removeClass()
even if you have 1 or more styles to change. It's more maintainable and readable.
If you really have the urge to do multiple CSS properties, then use the following:
.css({
'font-size' : '10px',
'width' : '30px',
'height' : '10px'
});
NB!
Any CSS properties with a hyphen need to be quoted.
I've placed the quotes so no one will need to clarify that, and the code will be 100% functional.
Do not simplify the code to avoid "linq translation error": The test consist between a date with time at 0:0:0 and the same date with time at 23:59:59
iFilter.MyDate1 = DateTime.Today; // or DateTime.MinValue
// GET
var tempQuery = ctx.MyTable.AsQueryable();
if (iFilter.MyDate1 != DateTime.MinValue)
{
TimeSpan temp24h = new TimeSpan(23,59,59);
DateTime tempEndMyDate1 = iFilter.MyDate1.Add(temp24h);
// DO not change the code below, you need 2 date variables...
tempQuery = tempQuery.Where(w => w.MyDate2 >= iFilter.MyDate1
&& w.MyDate2 <= tempEndMyDate1);
}
List<MyTable> returnObject = tempQuery.ToList();
The shift can be implement with data types (char, int and long int). The float and double data connot be shifted.
value= value >> steps // Right shift, signed data.
value= value << steps // Left shift, signed data.
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
Depends on what your native code does, but v7a has support for hardware floating point operations, which makes a huge difference. armeabi will work fine on all devices, but will be a lot slower, and won't take advantage of newer devices' CPU capabilities. Do take some benchmarks for your particular application, but removing the armeabi-v7a binaries is generally not a good idea. If you need to reduce size, you might want to have two separate apks for older (armeabi) and newer (armeabi-v7a) devices.
Downloading Wget is not necessary; the .NET Framework has web client classes built in.
$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")
You can use wget which is popular downloading shell tool for that. https://pypi.python.org/pypi/wget This will be the simplest method since it does not need to open up the destination file. Here is an example.
import wget
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350'
wget.download(url, '/Users/scott/Downloads/cat4.jpg')
For me, it worked like following. Please look at JAVA_HOME environment variable, whether it is pointing to JRE or JDK.? If it pointed to JRE, you will face "Perhaps you are running on a JRE rather than a JDK" issue. if so change the path to JDK.
Modifying like this, it worked for me.
JAVA_HOME C:\Program Files\Java\jdk1.8.0_31
Use two single-quotes
SQL> SELECT 'D''COSTA' name FROM DUAL;
NAME
-------
D'COSTA
Alternatively, use the new (10g+) quoting method:
SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;
NAME
-------
D'COSTA
you can use any prefix or postfix name for modal. but you need to make sure that's should use everywhere with same prefix/postfix name.
body .modal-nk {
/* new custom width */
width: 560px;
/* must be half of the width, minus scrollbar on the left (30px) */
margin-left: -280px;
}
or
body .nk-modal {
/* new custom width */
width: 560px;
/* must be half of the width, minus scrollbar on the left (30px) */
margin-left: -280px;
}
There are three reasons why you shouldn't use for..in
to iterate over array elements:
for..in
will loop over all own and inherited properties of the array object which aren't DontEnum
; that means if someone adds properties to the specific array object (there are valid reasons for this - I've done so myself) or changed Array.prototype
(which is considered bad practice in code which is supposed to work well with other scripts), these properties will be iterated over as well; inherited properties can be excluded by checking hasOwnProperty()
, but that won't help you with properties set in the array object itself
for..in
isn't guaranteed to preserve element ordering
it's slow because you have to walk all properties of the array object and its whole prototype chain and will still only get the property's name, ie to get the value, an additional lookup will be required
I tried almost all the possible suggestions mention here but for me problem got solved after changing "Access for less secure apps" to ENABLE in my Google account security settings tab. Hope this might useful for others !
Just run powershell.exe with COMPLUS_version
environment variable set to v4.0.30319
.
For example, from cmd.exe or .bat-file:
set COMPLUS_version=v4.0.30319
powershell -file c:\scripts\test.ps1
The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.
However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).
The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).
For example:
[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
protected override void OnCreate(Bundle bindle)
{
base.OnCreate(bindle);
}
}
I also had this problem. I was trying to enter data into the database without saving changes I had made in it. after i saved the changes worked
You may try this:
public static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12345");
System.out.println(toPrecision(a, 2));
}
private static BigDecimal toPrecision(BigDecimal dec, int precision) {
String plain = dec.movePointRight(precision).toPlainString();
return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}
OUTPUT:
10.12
The basic syntax for using ternary operator is like this:
(condition) ? (if_true) : (if_false)
For you case it is like this:
number < 0 ? bigInt.sign = 0 : bigInt.sign = 1;
I am beginner to iOS development so I would like to share whole info I got in this section.
First from image assets (images.xcassets) create image set .
According to Documentation here is all sizes need to create background image.
For iPhone 5:
640 x 1136
For iPhone 6:
750 x 1334 (@2x) for portrait
1334 x 750 (@2x) for landscape
For iPhone 6 Plus:
1242 x 2208 (@3x) for portrait
2208 x 1242 (@3x) for landscape
iPhone 4s (@2x)
640 x 960
iPad and iPad mini (@2x)
1536 x 2048 (portrait)
2048 x 1536 (landscape)
iPad 2 and iPad mini (@1x)
768 x 1024 (portrait)
1024 x 768 (landscape)
iPad Pro (@2x)
2048 x 2732 (portrait)
2732 x 2048 (landscape)
call the image background we can call image from image assets by using this method UIImage(named: "background")
here is full code example
override func viewDidLoad() {
super.viewDidLoad()
assignbackground()
// Do any additional setup after loading the view.
}
func assignbackground(){
let background = UIImage(named: "background")
var imageView : UIImageView!
imageView = UIImageView(frame: view.bounds)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
imageView.image = background
imageView.center = view.center
view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
}
This is quite an old question so I've updated this answer to take the HTML 5 email type into account.
You don't actually need JavaScript for this at all with HTML 5; just use the email input type:
<input type="email" />
If you want to make it mandatory, you can add the required parameter.
If you want to add additional RegEx validation (limit to @foo.com email addresses for example), you can use the pattern parameter, e.g.:
<input type="email" pattern="[email protected]" />
There's more information available on MozDev.
Original answer follows
First off - I'd recommend the email validator RegEx from Hexillion: http://hexillion.com/samples/
It's pretty comprehensive - :
^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$
I think you want a function in your JavaScript like:
function validateEmail(sEmail) {
var reEmail = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/;
if(!sEmail.match(reEmail)) {
alert("Invalid email address");
return false;
}
return true;
}
In the HTML input you need to trigger the event with an onblur - the easy way to do this is to simply add something like:
<input type="text" name="email" onblur="validateEmail(this.value);" />
Of course that's lacking some sanity checks and won't do domain verification (that has to be done server side) - but it should give you a pretty solid JS email format verifier.
Note: I tend to use the match()
string method rather than the test()
RegExp method but it shouldn't make any difference.
You can use these functions to brutally remove everything Docker related:
removecontainers() {
docker stop $(docker ps -aq)
docker rm $(docker ps -aq)
}
armageddon() {
removecontainers
docker network prune -f
docker rmi -f $(docker images --filter dangling=true -qa)
docker volume rm $(docker volume ls --filter dangling=true -q)
docker rmi -f $(docker images -qa)
}
You can add those to your ~/Xrc
file, where X is your shell interpreter (~/.bashrc
if you're using bash) file and reload them via executing source ~/Xrc
. Also, you can just copy paste them to the console and afterwards (regardless the option you took before to get the functions ready) just run:
armageddon
It's also useful for just general Docker clean up. Have in mind that this will also remove your images, not only your containers (either running or not) and your volumes of any kind.
@joe : Many thanks, this was a good heads up!
I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file
So that's how I did it (using JQuery to handle the AJAX request):
Initial post request:
var parameters = {
pid : "mypid",
"files[]": ["file1.jpg","file2.jpg","file3.jpg"]
}
var options = {
url: "request/url",//replace with your request url
type: "POST",//replace with your request type
data: parameters,//see above
context: document.body,//replace with your contex
success: function(data){
if (data) {
if (data.path) {
//Create an hidden iframe, with the 'src' attribute set to the created ZIP file.
var dlif = $('<iframe/>
',{'src':data.path}).hide();
//Append the iFrame to the context
this.append(dlif);
} else if (data.error) {
alert(data.error);
} else {
alert('Something went wrong');
}
}
}
};
$.ajax(options);
The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:
//Code to create the zip file
//......
//Id of the file
$zipid = "myzipfile.zip"
//Download Link - it can be prettier
$dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
//JSON response to be handled on the client side
$result = '{"success":1,"path":"'.$dlink.'","error":null}';
header('Content-type: application/json;');
echo $result;
The "request/download" can perform some security checks, if needed, and generate the file transfer:
$fn = $_GET['file'];
if ($fn) {
//Perform security checks
//.....check user session/role/whatever
$result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
if (file_exists($result)) {
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($result));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($result));
ob_clean();
flush();
readfile($result);
@unlink($result);
}
}
the documentation has this blurb https://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history
import requests
r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for
when you are in El Capitan, will get error: ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted
need to close the "System Integrity Protection".
first, reboot and hold on cmd + R to enter the Recovery mode, then launch the terminal and type the command: csrutil disable
, now you can reboot and try again.
If you want to want to treat 1,2 and 2,1 as the same pair, then this will give you the unique list on MS-SQL:
SELECT DISTINCT
CASE WHEN a > b THEN a ELSE b END as a,
CASE WHEN a > b THEN b ELSE a END as b
FROM pairs
Inspired by @meszias answer above
I've added the Initial Catalog to your connection string. I've also abandonded the ADODB.Command syntax in favor of simply creating my own SQL statement and open the recordset on that variable.
Hope this helps.
Sub GetDataFromADO()
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=abc;Password=abc;"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from myTable"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
End Sub
Assuming your RDBMS know window functions and CTE and USER_ID is the patient's id:
WITH TT AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY USER_ID ORDER BY DOCUMENT_DATE DESC) AS N
FROM test_table
)
SELECT *
FROM TT
WHERE N = 1;
I assumed you wanted to sort by DOCUMENT_DATE, you can easily change that if wanted. If your RDBMS doesn't know window functions, you'll have to do a join :
SELECT *
FROM test_table T1
INNER JOIN (SELECT USER_ID, MAX(DOCUMENT_DATE) AS maxDate
FROM test_table
GROUP BY USER_ID) T2
ON T1.USER_ID = T2.USER_ID
AND T1.DOCUMENT_DATE = T2.maxDate;
It would be good to tell us what your RDBMS is though. And this query selects the most recent date for every patient, you can add a condition for a given patient.
You should use the HasValue
property:
SomeProperty.HasValue
For example:
if (SomeProperty.HasValue)
{
// Do Something
}
else
{
// Do Something Else
}
FYI
public Nullable<System.Guid> SomeProperty { get; set; }
is equivalent to:
public System.Guid? SomeProperty { get; set; }
The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx
Swift 5. To see IF A DATE HAS PASSED:
let expiryDate = "2020-01-10" // Jan 10 2020
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if Date() < dateFormatter.date(from: expiryDate) ?? Date() {
print("Not Yet expiryDate")
} else {
print("expiryDate has passed")
}
The following worked just fine in all scenarios i needed :
"dependencies": {
"GitRepo": "git+https://<token-from-github>:[email protected]/<user>/<GitRepo>.git"
}
So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.
So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.
Here's how I understand it:
x
lie in a rangeLet's assume you have a range from 0
to 100
. Given an arbitrary number from that range, what "percent" from that range does it lie in? This should be pretty simple, 0
would be 0%
, 50
would be 50%
and 100
would be 100%
.
Now, what if your range was 20
to 100
? We cannot apply the same logic as above (divide by 100) because:
20 / 100
doesn't give us 0
(20
should be 0%
now). This should be simple to fix, we just need to make the numerator 0
for the case of 20
. We can do that by subtracting:
(20 - 20) / 100
However, this doesn't work for 100
anymore because:
(100 - 20) / 100
doesn't give us 100%
. Again, we can fix this by subtracting from the denominator as well:
(100 - 20) / (100 - 20)
A more generalized equation for finding out what % x
lies in a range would be:
(x - MIN) / (MAX - MIN)
Now that we know what percent a number lies in a range, we can apply it to map the number to another range. Let's go through an example.
old range = [200, 1000]
new range = [10, 20]
If we have a number in the old range, what would the number be in the new range? Let's say the number is 400
. First, figure out what percent 400
is within the old range. We can apply our equation above.
(400 - 200) / (1000 - 200) = 0.25
So, 400
lies in 25%
of the old range. We just need to figure out what number is 25%
of the new range. Think about what 50%
of [0, 20]
is. It would be 10
right? How did you arrive at that answer? Well, we can just do:
20 * 0.5 = 10
But, what about from [10, 20]
? We need to shift everything by 10
now. eg:
((20 - 10) * 0.5) + 10
a more generalized formula would be:
((MAX - MIN) * PERCENT) + MIN
To the original example of what 25%
of [10, 20]
is:
((20 - 10) * 0.25) + 10 = 12.5
So, 400
in the range [200, 1000]
would map to 12.5
in the range [10, 20]
To map x
from old range to new range:
OLD PERCENT = (x - OLD MIN) / (OLD MAX - OLD MIN)
NEW X = ((NEW MAX - NEW MIN) * OLD PERCENT) + NEW MIN
This will create a Date
exactly one year in the future with just one line. First we get the fullYear
from a new Date
, increment it, set that as the year of a new Date
. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date
object so we wrap the whole thing in a Date
constructor.
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
import os
directory = os.path.abspath('\\') # root directory
print(directory) # e.g. 'C:\'
directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:\Users\User\Desktop'
parent_directory, directory_name = os.path.split(directory)
print(directory_name) # e.g. 'Desktop'
parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
print(parent_directory_name) # e.g. 'User'
This should also do the trick.
You just need:
if (!empty($_POST['search_term']) && !empty($_POST['postcode']))
isset && !empty
is redundant.
import { Component, ElementRef, HostListener, Input } from '@angular/core';
@Component({
selector: 'selector',
template: `
<div>
{{text}}
</div>
`
})
export class AnotherComponent {
public text: String;
@HostListener('document:click', ['$event'])
clickout(event) {
if(this.eRef.nativeElement.contains(event.target)) {
this.text = "clicked inside";
} else {
this.text = "clicked outside";
}
}
constructor(private eRef: ElementRef) {
this.text = 'no clicks yet';
}
}
First of all jar
creates a jar, and does not run it. Try java -jar
instead.
Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2
) and as file (com/mycomp/myproj/dir2/MainClass2.class
)?
Edit:
It seems as if java -jar
requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ...
instead. -cp
sets the jar on the classpath and enables java to look up the main class there.
Very edge case, but I had to use a program that worked correctly only when I specified
StartInfo = {..., RedirectStandardOutput = true}
Not specifying it would result in an error. There was not even the need to read the output afterward.
Here is your code for add data into both tableView:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var table1Text: UITextField!
@IBOutlet weak var table2Text: UITextField!
@IBOutlet weak var table1: UITableView!
@IBOutlet weak var table2: UITableView!
var table1Data = ["a"]
var table2Data = ["1"]
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func addData(sender: AnyObject) {
//add your data into tables array from textField
table1Data.append(table1Text.text)
table2Data.append(table2Text.text)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//reload your tableView
self.table1.reloadData()
self.table2.reloadData()
})
table1Text.resignFirstResponder()
table2Text.resignFirstResponder()
}
//delegate methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == table1 {
return table1Data.count
}else if tableView == table2 {
return table2Data.count
}
return Int()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == table1 {
let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = table1Data[row]
return cell
}else if tableView == table2 {
let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = table2Data[row]
return cell
}
return UITableViewCell()
}
}
And your result will be:
The Equals
method does a reference comparison - if the arrays are different objects, this will indeed return false.
To check if the arrays contain identical values (and in the same order), you will need to iterate over them and test equality on each.
If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:
next(obj for obj in objs if obj.val == 5)
This is however faster than a complete list comprehension. Compare these two:
[i for i in xrange(100000) if i == 1000][0]
next(i for i in xrange(100000) if i == 1000)
The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).
To get the entire contents of a file:
$content = [IO.File]::ReadAllText(".\test.txt")
Number of lines:
([IO.File]::ReadAllLines(".\test.txt")).length
or
(gc .\test.ps1).length
Sort of hackish to include trailing empty line:
[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count
Before 7.2, the cache is at C:\Users\username\.netbeans\7.0\var\cache
. Deleting this directory should clear the cache for you.
You can find all sorts of professional code with 'break' statements in them. It perfectly make sense to use this whenever necessary. In your case this option is better than creating a separate variable just for the purpose of coming out of the loop.
Every process running under the Linux kernel receives its own, unique environment that it inherits from its parent. In this case, the parent will be either a shell itself (spawning a sub shell), or the 'login' program (on a typical system).
As each process' environment is protected, there is no way to 'inject' an environmental variable to every running process, so even if you modify the default shell .rc / profile, it won't go into effect until each process exits and reloads its start up settings.
Look in /etc/ to modify the default start up variables for any particular shell. Just realize that users can (and often do) change them in their individual settings.
Unix is designed to obey the user, within limits.
NB: Bash is not the only shell on your system. Pay careful attention to what the /bin/sh symbolic link actually points to. On many systems, this could actually be dash which is (by default, with no special invocation) POSIXLY correct. Therefore, you should take care to modify both defaults, or scripts that start with /bin/sh will not inherit your global defaults. Similarly, take care to avoid syntax that only bash understands when editing both, aka avoiding bashisms
.
from tkinter import *
def close_window():
import sys
sys.exit()
root = Tk()
frame = Frame (root)
frame.pack()
button = Button (frame, text="Good-bye", command=close_window)
button.pack()
mainloop()
Something like this would work
/^\d{2}$/
I'm too fond of <?=$whatever?>
to let it go. Never had a problem with it. I'll wait until it bites me in the ass. In all seriousness, 85% of (my) clients have access to php.ini in the rare occasion they are turned off. The other 15% use mainstream hosting providers, and virtually all of them have them enabled. I love 'em.
In my case I was seeing referrals when I was accessing AD via SSO with an account in a trusted domain. The problem went away when I connected with explicit credentials in the local domain.
i.e. I replaced
DirectoryEntry de = new DirectoryEntry("blah.com");
with
DirectoryEntry de = new DirectoryEntry("blah.com", "[email protected]", "supersecret");
and the problem went away.
About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.
The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).
Section 2 of RFC 2368 says that the body
field is supposed to be in text/plain
format, so you can't do HTML.
However even if you use plain text it's possible that some modern mail clients would render a URL as a clickable link anyway, though.
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for words in elements:
# Does this element belong in the resulting list?
if i <= len(elements):
# Add this element to the resulting list
new_list.insert(i,elements[i])
# Increment i
i += 2
return new_list
toISOString()
assumes your date is local time and converts it to UTC. You will get an incorrect date string.
The following method should return what you need.
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Answer 1 : Yes it called upcasting but the way you do it is not modern way. Upcasting can be performed implicitly you don't need any conversion. So just writing Employee emp = mgr; is enough for upcasting.
Answer 2 : If you create object of Manager class we can say that manager is an employee. Because class Manager : Employee depicts Is-A relationship between Employee Class and Manager Class. So we can say that every manager is an employee.
But if we create object of Employee class we can not say that this employee is manager because class Employee is a class which is not inheriting any other class. So you can not directly downcast that Employee Class object to Manager Class object.
So answer is, if you want to downcast from Employee Class object to Manager Class object, first you must have object of Manager Class first then you can upcast it and then you can downcast it.
Pay attention, there is a bug with Jquery 1.8.0, $(window).height() returns the all document height !
"Once upon a time there were three little pigs".Split(" ") | ForEach {
"$_ is a token"
}
The key is $_
, which stands for the current variable in the pipeline.
About the code you found online:
%
is an alias for ForEach-Object
. Anything enclosed inside the brackets is run once for each object it receives. In this case, it's only running once, because you're sending it a single string.
$_.Split(" ")
is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach
.
There is a shortcut (Ctrl+Shift+A for Windows and Linux users, Command+Shift+A for Mac users) to select the whole block within the currently selected tag.
For example, if you pressed this while your text cursor was within the outer div
tag in the code below, all the div
s with class selected
would be selected.
<div class='current_tag_block'>
<div class='selected'></div>
<div class='selected'></div>
<div class='selected'></div>
<div class='selected'></div>
</div>
Adding screen shots(examples) and some more context for the answer of @Thomas G.
import pandas as pd
is ran properly before checking below shortcut.Place the cursor in middle of parenthesis ()
before you use shortcut.
shift + tab
Display short document and few params
shift + tab + tab
Expands document with scroll bar
shift + tab + tab + tab
Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.
shift + tab + tab + tab + tab
It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.
phpMyAdmin includes a neat find-and-replace tool.
Select the table, then hit Search > Find and replace
This query took about a minute and successfully replaced several thousand instances of oldurl.ext
with the newurl.ext
within Column post_content
Best thing about this method : You get to check every match before committing.
N.B. I am using phpMyAdmin 4.9.0.1
If you can already see the SQL being printed, that means you have the code below in your hibernate.cfg.xml:
<property name="show_sql">true</property>
To print the bind parameters as well, add the following to your log4j.properties file:
log4j.logger.net.sf.hibernate.type=debug
PreparedStatements are the way to go, because they make SQL injection impossible. Here's a simple example taking the user's input as the parameters:
public insertUser(String name, String email) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = setupTheDatabaseConnectionSomehow();
stmt = conn.prepareStatement("INSERT INTO person (name, email) values (?, ?)");
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
}
finally {
try {
if (stmt != null) { stmt.close(); }
}
catch (Exception e) {
// log this error
}
try {
if (conn != null) { conn.close(); }
}
catch (Exception e) {
// log this error
}
}
}
No matter what characters are in name and email, those characters will be placed directly in the database. They won't affect the INSERT statement in any way.
There are different set methods for different data types -- which one you use depends on what your database fields are. For example, if you have an INTEGER column in the database, you should use a setInt
method. The PreparedStatement documentation lists all the different methods available for setting and getting data.
flatMap
transform the items emitted by an Observable into new Observables, then flattens the emissions from those into a single Observable.
Check out the scenario below where get("posts")
returns an Observable that is "flattened" by flatMap
.
myObservable.map(e => get("posts")).subscribe(o => console.log(o));
// this would log Observable objects to console.
myObservable.flatMap(e => get("posts")).subscribe(o => console.log(o));
// this would log posts to console.
Here is c++ solution
/**
*array sorting needed to verify if first arrays n'th element is greater than sencond arrays
*some element then all elements following n will do the same
*/
#include<stdio.h>
#include<iostream>
using namespace std;
int countInversions(int array[],int size);
int merge(int arr1[],int size1,int arr2[],int size2,int[]);
int main()
{
int array[] = {2, 4, 1, 3, 5};
int size = sizeof(array) / sizeof(array[0]);
int x = countInversions(array,size);
printf("number of inversions = %d",x);
}
int countInversions(int array[],int size)
{
if(size > 1 )
{
int mid = size / 2;
int count1 = countInversions(array,mid);
int count2 = countInversions(array+mid,size-mid);
int temp[size];
int count3 = merge(array,mid,array+mid,size-mid,temp);
for(int x =0;x<size ;x++)
{
array[x] = temp[x];
}
return count1 + count2 + count3;
}else{
return 0;
}
}
int merge(int arr1[],int size1,int arr2[],int size2,int temp[])
{
int count = 0;
int a = 0;
int b = 0;
int c = 0;
while(a < size1 && b < size2)
{
if(arr1[a] < arr2[b])
{
temp[c] = arr1[a];
c++;
a++;
}else{
temp[c] = arr2[b];
b++;
c++;
count = count + size1 -a;
}
}
while(a < size1)
{
temp[c] = arr1[a];
c++;a++;
}
while(b < size2)
{
temp[c] = arr2[b];
c++;b++;
}
return count;
}
Below is my code for fetch. Took me while researching because jQuery.active doesn't work with fetch. Here is the answer helped me proxy fetch, but its only for ajax not fetch mock for selenium
public static void customPatchXMLHttpRequest(WebDriver driver) {
try {
if (driver instanceof JavascriptExecutor) {
JavascriptExecutor jsDriver = (JavascriptExecutor) driver;
Object numberOfAjaxConnections = jsDriver.executeScript("return window.openHTTPs");
if (numberOfAjaxConnections instanceof Long) {
return;
}
String script = " (function() {" + "var oldFetch = fetch;"
+ "window.openHTTPs = 0; console.log('starting xhttps');" + "fetch = function(input,init ){ "
+ "window.openHTTPs++; "
+ "return oldFetch(input,init).then( function (response) {"
+ " if (response.status >= 200 && response.status < 300) {"
+ " window.openHTTPs--; console.log('Call completed. Remaining active calls: '+ window.openHTTPs); return response;"
+ " } else {"
+ " window.openHTTPs--; console.log('Call fails. Remaining active calls: ' + window.openHTTPs); return response;"
+ " };})" + "};" + "var oldOpen = XMLHttpRequest.prototype.open;"
+ "XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {"
+ "window.openHTTPs++; console.log('xml ajax called');"
+ "this.addEventListener('readystatechange', function() {" + "if(this.readyState == 4) {"
+ "window.openHTTPs--; console.log('xml ajax complete');" + "}" + "}, false);"
+ "oldOpen.call(this, method, url, async, user, pass);" + "}" +
"})();";
jsDriver.executeScript(script);
} else {
System.out.println("Web driver: " + driver + " cannot execute javascript");
}
} catch (Exception e) {
System.out.println(e);
}
}
Per @l3x, it depends.
There are clearly two sets of general situations where the correct answer can be different, along with a third which is not as general:
a) You are a user sending private mails:
Very few modern email systems implement case sensitivity, so you are probably fine to ignore case and choose whatever case you feel like using. There is no guarantee that all your mails will be delivered - but so few mails would be negatively affected that you should not worry about it.
b) You are developing mail software:
See RFC5321 2.4 excerpt at the bottom.
When you are developing mail software, you want to be RFC-compliant. You can make your own users' email addresses case insensitive if you want to (and you probably should). But in order to be RFC compliant, you MUST treat outside addresses as case sensitive.
c) Managing business-owned lists of email addresses as an employee:
It is possible that the same email recipient is added to a list more than once - but using different case. In this situation though the addresses are technically different, it might result in a recipient receiving duplicate emails. How you treat this situation is similar to situation a) in that you are probably fine to treat them as duplicates and to remove a duplicate entry. It is better to treat these as special cases however, by sending a "reminder" mail to both addresses to ask them if the case of the email address is accurate.
From a legal standpoint, if you remove a duplicate without acknowledgement/permission from both addresses, you can be held responsible for leaking private information/authentication to an unauthorised address simply because two actually-separate recipients have the same address with different cases.
Excerpt from RFC5321 2.4:
The local-part of a mailbox MUST BE treated as case sensitive. Therefore, SMTP implementations MUST take care to preserve the case of mailbox local-parts. In particular, for some hosts, the user "smith" is different from the user "Smith". However, exploiting the case sensitivity of mailbox local-parts impedes interoperability and is discouraged.
Use robocopy
. Robocopy is shipped by default on Windows Vista and newer, and is considered the replacement for xcopy
. (xcopy
has some significant limitations, including the fact that it can't handle paths longer than 256 characters, even if the filesystem can).
robocopy c:\ d:\ /e /zb /copyall /purge /dcopy:dat
Note that using /purge
on the root directory of the volume will cause Robocopy to apply the requested operation on files inside the System Volume Information directory. Run robocopy /?
for help. Also note that you probably want to open the command prompt as an administrator to be able to copy system files. To speed things up, use /b
instead of /zb
.
UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;
you might want to use CEIL()
if A
is always a floating point value > 0
and <= 2
For Java 12 onwards, official General-Availability (GA) and Early-Access (EA) Windows 64-bit builds of the OpenJDK (GPL2 + Classpath Exception) from Oracle are available as tar.gz/zip from the JDK website.
If you prefer an installer, there are several distributions. There is a public Google Doc and Blog post by the Java Champions community which lists the best-supported OpenJDK distributions. Currently, these are:
You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.
You also can't have such code in the class directly. It needs to be moved into a method or the constructor.
What you can do is not to subscribe()
directly but use an operator like map()
export class DataComponent{
someMethod() {
return this.http.get(path).map(res => {
return res.json();
});
}
}
In addition, you can combine multiple .map
with the same Observables as sometimes this improves code clarity and keeps things separate. Example:
validateResponse = (response) => validate(response);
parseJson = (json) => JSON.parse(json);
fetchUnits() {
return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}
This way an observable will be return the caller can subscribe to
export class DataComponent{
someMethod() {
return this.http.get(path).map(res => {
return res.json();
});
}
otherMethod() {
this.someMethod().subscribe(data => this.data = data);
}
}
The caller can also be in another class. Here it's just for brevity.
data => this.data = data
and
res => return res.json()
are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...)
or map(...)
to be called from the observable when data arrives from the response.
This is why data can't be returned directly, because when someMethod()
is completed, the data wasn't received yet.
For those who need path() change without controllers reload - Here is plugin: https://github.com/anglibs/angular-location-update
Usage:
$location.update_path('/notes/1');
Based on https://stackoverflow.com/a/24102139/1751321
P.S. This solution https://stackoverflow.com/a/24102139/1751321 contains bug after path(, false) called - it will break browser navigation back/forward until path(, true) called
Removing Language="c#" in global.asax file resolved the issue for me.
It's just how JavaScript works. You can declare a named function:
function foo(msg){
alert(msg);
}
And call it:
foo("Hi!");
Or, you can declare an anonymous function:
var foo = function (msg) {
alert(msg);
}
And call that:
foo("Hi!");
Or, you can just never bind the function to a name:
(function(msg){
alert(msg);
})("Hi!");
Functions can also return functions:
function make_foo() {
return function(msg){ alert(msg) };
}
(make_foo())("Hi!");
It's worth nothing that any variables defined with "var" in the body of make_foo
will be closed over by each function returned by make_foo
. This is a closure, and it means that the any change made to the value by one function will be visible by another.
This lets you encapsulate information, if you desire:
function make_greeter(msg){
return function() { alert(msg) };
}
var hello = make_greeter("Hello!");
hello();
It's just how nearly every programming language but Java works.
You can Zoom In and Zoom Out the entire user interface from the View menu.
Right now i'm using version 1.21.1 and there in view menu you can get the Zoom in and Zoom out option which are the 2nd and 3rd last options. You can do it by using Ctrl + + and Ctrl + -.
You can reset the zoom at any time by selecting Reset Zoom option.
Using a custom url attribute makes the HTML invalid. Although that may not be a huge problem, the given examples are neither accessible. Not for keyboard navigation and not in cases when JavaScript is turned off (or blocked by some other script). Even Google will not find the page located at the specified url, not via this route at least.
It's quite easy to make this accessible though. Just make sure there's a regular link inside the div that points to the url. Using JavaScript/jQuery you add an onclick to the div that redirects to the location specified by the link's href attribute. Now, when JavaScript doesn't work, the link still does and it can even catch the focus when using the keyboard to navigate (and you don't need custom attributes, so your HTML can be valid).
I wrote a jQuery plugin some time ago that does this. It also adds classNames to the div (or any other element you want to make clickable) and the link so you can alter their looks with CSS when the div is indeed clickable. It even adds classNames that you can use to specify hover and focus styles.
All you need to do is specify the element(s) you want to make clickable and call their clickable() method: in your case that would be $("div.clickable).clickable();
For downloading + documentation see the plugin's page: jQuery: clickable — jLix
You have to create service.That service should implement LocationListener. Then You have to use AlarmManager for calling service repeatedly with certain time limit.
I hope this one will help to you :)
I apologize for putting an answer up to this question, but I figured it would be the easiest way to view my final code. It includes fixes for nullable types and null values :-)
public static DataSet ToDataSet<T>(this IList<T> list)
{
Type elementType = typeof(T);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);
//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
t.Columns.Add(propInfo.Name, ColType);
}
//go through each property on T and add each value to the table
foreach (T item in list)
{
DataRow row = t.NewRow();
foreach (var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}
t.Rows.Add(row);
}
return ds;
}
The -jar option is mutually exclusive of -classpath. See an old description here
-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.
See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
A quick and dirty hack is to append your classpath to the bootstrap classpath:
-Xbootclasspath/a:path
Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.
However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
There is a javascript version available which manually redirects events from one div to another.
I cleaned it up and made it into a jQuery plugin.
Here's the Github repository: https://github.com/BaronVonSmeaton/jquery.forwardevents
Unfortunately, the purpose I was using it for - overlaying a mask over Google Maps did not capture click and drag events, and the mouse cursor does not change which degrades the user experience enough that I just decided to hide the mask under IE and Opera - the two browsers which dont support pointer events.
tl;dr for folks looking here for an ISO formatted date:
instead of using something like '%Y-%m-%d %H:%M:%S.%03d%z', create your own class as @unutbu indicated. Here's one for iso date format:
import logging
from time import gmtime, strftime
class ISOFormatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
t = strftime("%Y-%m-%dT%H:%M:%S", gmtime(record.created))
z = strftime("%z",gmtime(record.created))
s = "%s.%03d%s" % (t, record.msecs,z)
return s
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
logger.addHandler(console)
formatter = ISOFormatter(fmt='%(asctime)s - %(module)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
logger.debug('Jackdaws love my big sphinx of quartz.')
#2020-10-23T17:25:48.310-0800 - <stdin> - DEBUG - Jackdaws love my big sphinx of quartz.
i was trying to use airbnb deeplink dispatch and got this error. i had to also exlude the findbugs group from the annotationProcessor.
//airBnb
compile ('com.airbnb:deeplinkdispatch:3.1.1'){
exclude group:'com.google.code.findbugs'
}
annotationProcessor ('com.airbnb:deeplinkdispatch-processor:3.1.1'){
exclude group:'com.google.code.findbugs'
}
You don't have to add a .
in getElementsByClassName
, i.e.
var multibutton = angular.element(element.getElementsByClassName("multi-files"));
However, when using angular.element
, you do have to use jquery style selectors:
angular.element('.multi-files');
should do the trick.
Also, from this documentation "If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.""
Call ToString()
instead of casting the reader result.
reader[0].ToString();
reader[1].ToString();
// etc...
And if you want to fetch specific data type values (int
in your case) try the following:
reader.GetInt32(index);
It means '\0' is a NULL
character in C, don't know about Objective-C
but its probably the same.
Sets pattern validation error key if the ngModel $viewValue does not match a RegExp found by evaluating the Angular expression given in the attribute value. If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters.
It seems that a most voted answer in this question should be updated, because when i try it, it does not apply test
function and validation not working.
Example from Angular docs works good for me:
Modifying built-in validators
html
<form name="form" class="css-form" novalidate>
<div>
Overwritten Email:
<input type="email" ng-model="myEmail" overwrite-email name="overwrittenEmail" />
<span ng-show="form.overwrittenEmail.$error.email">This email format is invalid!</span><br>
Model: {{myEmail}}
</div>
</form>
js
var app = angular.module('form-example-modify-validators', []);
app.directive('overwriteEmail', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;
return {
require: 'ngModel',
restrict: '',
link: function(scope, elm, attrs, ctrl) {
// only apply the validator if ngModel is present and Angular has added the email validator
if (ctrl && ctrl.$validators.email) {
// this will overwrite the default Angular email validator
ctrl.$validators.email = function(modelValue) {
return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
};
}
}
};
});
Just use a MaterialButton and the app:backgroundTint and android:textColor attributes:
<MaterialButton
app:backgroundTint="@color/my_color"
android:textColor="@android:color/white"/>
If you join the facilities table twice you will get what you are after:
select u.*
from room u
JOIN facilities_r fu1 on fu1.id_uc = u.id_uc and fu1.id_fu = '4'
JOIN facilities_r fu2 on fu2.id_uc = u.id_uc and fu2.id_fu = '3'
where 1 and vizibility='1'
group by id_uc
order by u_premium desc, id_uc desc
The ALTER TABLE
MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.
ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.
I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.
This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.
Try something like this:
try {
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// not going to happen - value came from JDK's own StandardCharsets
}
Java 10 added direct support for Charset
to the API, meaning there's no need to catch UnsupportedEncodingException:
String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);
Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.
RegisteredClientScriptBlock
adds the script at the top of the page on the post-back with no assurance about the order, meaning that either the call is being injected after the function declaration (your js file with the function is inlined after your call) or when the script tries to execute the div is probably not there yet 'cause the page is still rendering. A good idea is probably to simulate the two scenarios I described above on firebug and see if you get similar errors.
My guess is this would work if you append the script at the bottom of the page with RegisterStartupScript
- worth a shot at least.
Anyway, as an alternative solution if you add the runat="server"
attribute to the div you will be able to access it by its id in the codebehind (without reverting to js - how cool that might be), and make it disappear like this:
data.visible = false
Assuming he opens an interactive session (that is, allocates a pseudo terminal) and you have access to stdin, you can call an ioctl on that device to get the device number (/dev/pts/4711) and try to find that one in /var/run/utmp (where there will also be the username and the IP address the connection originated from).
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
Because it has already been pushed, you shouldn't directly manipulate history. git revert
will revert specific changes from a commit using a new commit, so as to not manipulate commit history.
You can also use
HttpRuntime.AppDomainAppVirtualPath
Try making your constructor private like this:
private Foo newClass = new Foo();
I took your question as a challenge to write this in "portable" shell code, i.e.
It runs on any POSIX conformant shell (zsh, bash, ksh, ash, busybox, ...). It even contains a testsuite to verify its operation. Canonicalization of pathnames is left as an exercise. :-)
#!/bin/sh
# Find common parent directory path for a pair of paths.
# Call with two pathnames as args, e.g.
# commondirpart foo/bar foo/baz/bat -> result="foo/"
# The result is either empty or ends with "/".
commondirpart () {
result=""
while test ${#1} -gt 0 -a ${#2} -gt 0; do
if test "${1%${1#?}}" != "${2%${2#?}}"; then # First characters the same?
break # No, we're done comparing.
fi
result="$result${1%${1#?}}" # Yes, append to result.
set -- "${1#?}" "${2#?}" # Chop first char off both strings.
done
case "$result" in
(""|*/) ;;
(*) result="${result%/*}/";;
esac
}
# Turn foo/bar/baz into ../../..
#
dir2dotdot () {
OLDIFS="$IFS" IFS="/" result=""
for dir in $1; do
result="$result../"
done
result="${result%/}"
IFS="$OLDIFS"
}
# Call with FROM TO args.
relativepath () {
case "$1" in
(*//*|*/./*|*/../*|*?/|*/.|*/..)
printf '%s\n' "'$1' not canonical"; exit 1;;
(/*)
from="${1#?}";;
(*)
printf '%s\n' "'$1' not absolute"; exit 1;;
esac
case "$2" in
(*//*|*/./*|*/../*|*?/|*/.|*/..)
printf '%s\n' "'$2' not canonical"; exit 1;;
(/*)
to="${2#?}";;
(*)
printf '%s\n' "'$2' not absolute"; exit 1;;
esac
case "$to" in
("$from") # Identical directories.
result=".";;
("$from"/*) # From /x to /x/foo/bar -> foo/bar
result="${to##$from/}";;
("") # From /foo/bar to / -> ../..
dir2dotdot "$from";;
(*)
case "$from" in
("$to"/*) # From /x/foo/bar to /x -> ../..
dir2dotdot "${from##$to/}";;
(*) # Everything else.
commondirpart "$from" "$to"
common="$result"
dir2dotdot "${from#$common}"
result="$result/${to#$common}"
esac
;;
esac
}
set -f # noglob
set -x
cat <<EOF |
/ / .
/- /- .
/? /? .
/?? /?? .
/??? /??? .
/?* /?* .
/* /* .
/* /** ../**
/* /*** ../***
/*.* /*.** ../*.**
/*.??? /*.?? ../*.??
/[] /[] .
/[a-z]* /[0-9]* ../[0-9]*
/foo /foo .
/foo / ..
/foo/bar / ../..
/foo/bar /foo ..
/foo/bar /foo/baz ../baz
/foo/bar /bar/foo ../../bar/foo
/foo/bar/baz /gnarf/blurfl/blubb ../../../gnarf/blurfl/blubb
/foo/bar/baz /gnarf ../../../gnarf
/foo/bar/baz /foo/baz ../../baz
/foo. /bar. ../bar.
EOF
while read FROM TO VIA; do
relativepath "$FROM" "$TO"
printf '%s\n' "FROM: $FROM" "TO: $TO" "VIA: $result"
if test "$result" != "$VIA"; then
printf '%s\n' "OOOPS! Expected '$VIA' but got '$result'"
fi
done
# vi: set tabstop=3 shiftwidth=3 expandtab fileformat=unix :
There are already several answers however none of them mention the best (and easiest) way to do this, which is using spawn
and the { stdio: 'inherit' }
option. It seems to produce the most accurate output, for example when displaying the progress information from a git clone
.
Simply do this:
var spawn = require('child_process').spawn;
spawn('coffee', ['-cw', 'my_file.coffee'], { stdio: 'inherit' });
Credit to @MorganTouvereyQuilling for pointing this out in this comment.
There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )
The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.
To make this work, your function needs to loop through each of the Areas
in the input ranges. For example:
Function calculateIt(Sessions As Range, Customers As Range) As Single
' check we passed the same number of areas
If (Sessions.Areas.Count <> Customers.Areas.Count) Then
calculateIt = CVErr(xlErrNA)
Exit Function
End If
Dim mySession, myCustomers As Range
' run through each area and calculate
For a = 1 To Sessions.Areas.Count
Set mySession = Sessions.Areas(a)
Set myCustomers = Customers.Areas(a)
' calculate them...
Next a
End Function
The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9)
.
Hope that helps :)
As of node.js
>4.0
it gets more compatible with ES6 standard, where string manipulation greatly improved.
The answer to the original question can be as simple as:
var s = `hello ${my_name}, how are you doing`;
// note: tilt ` instead of single quote '
Where the string can spread multiple lines, it makes templates or HTML/XML processes quite easy. More details and more capabilitie about it: Template literals are string literals at mozilla.org.
Maybe not as elegant but another possibility would be to write a formula to do the check and fill it in an adjacent column. You could then filter on that column.
The following looks in cell b14 and would return true for all the file types you mention. This assumes that the file extension is by itself in the column. If it's not it would be a little more complicated but you could still do it this way.
=OR(B14=".pdf",B14=".doc",B14=".docx",B14=".xls",B14=".xlsx",B14=".rtf",B14=".txt",B14=".csv",B14=".pps")
Like I said, not as elegant as the advanced filters but options are always good.
Use the zip function to decouple elements:
>>> inpt = [(1, u'abc'), (2, u'def')]
>>> unzipped = zip(*inpt)
>>> print unzipped
[(1, 2), (u'abc', u'def')]
>>> print list(unzipped[0])
[1, 2]
Edit (@BradSolomon):
The above works for Python 2.x, where zip
returns a list.
In Python 3.x, zip
returns an iterator and the following is equivalent to the above:
>>> print(list(list(zip(*inpt))[0]))
[1, 2]
It's included because your minimum SDK version is set to 10. The ActionBar
was introduced in API 11. Eclipse adds it automatically so your app can look more consistent throughout the spectrum of all android versions you are supporting.
For Mac OS:
#ifdef __APPLE__
For MingW on Windows:
#ifdef __MINGW32__
For Linux:
#ifdef __linux__
For other Windows compilers, check this thread and this for several other compilers and architectures.
Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct. In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
for the point no 2 we have to follow below steps :
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
2) write below method, which calls doTrustToCertificates before trying to connect to URL
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to URL.
Be careful if you are working on localhost ! If you store your cookie in js like this:
document.cookie = "key=value;domain=localhost"
It might not be accessible to your subdomain, like sub.localhost
. In order to solve this issue you need to use Virtual Host. For exemple you can configure your virtual host with ServerName
localhost.com
then you will be able to store your cookie on your domain and subdomain like this:
document.cookie = "key=value;domain=localhost.com"
I would choose varchar unless the column stores fixed value like US state code -- which is always 2 chars long and the list of valid US states code doesn't change often :).
In every other case, even like storing hashed password (which is fixed length), I would choose varchar.
Why -- char type column is always fulfilled with spaces, which makes for column my_column defined as char(5) with value 'ABC' inside comparation:
my_column = 'ABC' -- my_column stores 'ABC ' value which is different then 'ABC'
false.
This feature could lead to many irritating bugs during development and makes testing harder.
Don’t use the DOM to do this. Using the DOM to decode HTML entities (as suggested in the currently accepted answer) leads to differences in cross-browser results.
For a robust & deterministic solution that decodes character references according to the algorithm in the HTML Standard, use the he library. From its README:
he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.
Here’s how you’d use it:
he.decode("We're unable to complete your request at this time.");
? "We're unable to complete your request at this time."
Disclaimer: I'm the author of the he library.
See this Stack Overflow answer for some more info.
You can even set the prof. pic size to its high resolution that is '1080x1080'
replace "150x150" with 1080x1080 and remove /vp/ from the link.
SELECT emp.LoginID, emp.JobTitle, emp.BirthDate, emp.ModifiedDate ,
CASE WHEN emp.JobTitle NOT LIKE '%Document Control%' THEN emp.JobTitle
ELSE SUBSTRING(emp.JobTitle,CHARINDEX('Document Control',emp.JobTitle),LEN('Document Control'))
END
,emp.gender,emp.MaritalStatus
FROM HumanResources.Employee [emp]
WHERE JobTitle LIKE '[C-F]%'
I don't have reputation to comment yet, but I want to add to alko answer for further reference.
From the docs:
skiprows: A collection of numbers for rows in the file to skip. Can also be an integer to skip the first n rows
I found this arrow(start, end)
function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.
Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu
Bootstrap 3
I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/
The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..
http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook
//in linux
// in your home folder .android hidden folder is there go to that there you can find the avd folder open that and check your avd name that you created open that and you can see the sdcard.img
that is your sdcard file.
//To install apk in linux
$adb install ./yourfolder/myapkfile.apk
I have spent many hours trying to build a fat static library that will work on armv7, armv7s, and the simulator. Finally found a solution.
The gist is to build the two libraries (one for the device and then one for the simulator) separately, rename them to distinguish from each other, and then lipo -create them into one library.
lipo -create libPhone.a libSimulator.a -output libUniversal.a
I tried it and it works!
Type-safe means that the set of values that may be assigned to a program variable must fit well-defined and testable criteria. Type-safe variables lead to more robust programs because the algorithms that manipulate the variables can trust that the variable will only take one of a well-defined set of values. Keeping this trust ensures the integrity and quality of the data and the program.
For many variables, the set of values that may be assigned to a variable is defined at the time the program is written. For example, a variable called "colour" may be allowed to take on the values "red", "green", or "blue" and never any other values. For other variables those criteria may change at run-time. For example, a variable called "colour" may only be allowed to take on values in the "name" column of a "Colours" table in a relational database, where "red, "green", and "blue", are three values for "name" in the "Colours" table, but some other part of the computer program may be able to add to that list while the program is running, and the variable can take on the new values after they are added to the Colours table.
Many type-safe languages give the illusion of "type-safety" by insisting on strictly defining types for variables and only allowing a variable to be assigned values of the same "type". There are a couple of problems with this approach. For example, a program may have a variable "yearOfBirth" which is the year a person was born, and it is tempting to type-cast it as a short integer. However, it is not a short integer. This year, it is a number that is less than 2009 and greater than -10000. However, this set grows by 1 every year as the program runs. Making this a "short int" is not adequate. What is needed to make this variable type-safe is a run-time validation function that ensures that the number is always greater than -10000 and less than the next calendar year. There is no compiler that can enforce such criteria because these criteria are always unique characteristics of the problem domain.
Languages that use dynamic typing (or duck-typing, or manifest typing) such as Perl, Python, Ruby, SQLite, and Lua don't have the notion of typed variables. This forces the programmer to write a run-time validation routine for every variable to ensure that it is correct, or endure the consequences of unexplained run-time exceptions. In my experience, programmers in statically typed languages such as C, C++, Java, and C# are often lulled into thinking that statically defined types is all they need to do to get the benefits of type-safety. This is simply not true for many useful computer programs, and it is hard to predict if it is true for any particular computer program.
The long & the short.... Do you want type-safety? If so, then write run-time functions to ensure that when a variable is assigned a value, it conforms to well-defined criteria. The down-side is that it makes domain analysis really difficult for most computer programs because you have to explicitly define the criteria for each program variable.
The easiest way would be to use Python's built-in threading library. They're not "real" / kernel threads They have issues (like serialization), but are good enough. You'd want a queue & thread pool. One option is here, but it's trivial to write your own. You can't parallelize all 100,000 calls, but you can fire off 100 (or so) of them at the same time.
#define roundz(x,d) ((floor(((x)*pow(10,d))+.5))/pow(10,d))
a = 8.000000
sqrt(a) = r = 2.828427
roundz(r,2) = 2.830000
roundz(r,3) = 2.828000
roundz(r,5) = 2.828430
You should make x
and y
numpy arrays, not lists:
x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
0.478,0.335,0.365,0.424,0.390,0.585,0.511])
With this change, it produces the expect plot. If they are lists, m * x
will not produce the result you expect, but an empty list. Note that m
is anumpy.float64
scalar, not a standard Python float
.
I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:
In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]
while multiplying a list with a float gives an error (as I think it should):
In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'
The weird thing is that multiplying a Python list with a Numpy scalar apparently works:
In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []
In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]
In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]
So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:
In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123, 2.123, 3.123])
OK, I found this post: http://msdn.microsoft.com/en-us/library/aa479319.aspx
with this very illustrative diagram:
(source: microsoft.com)
in essence, to get at those exception details i need to store them myself in Global.asax, for later retrieval on my custom error page.
it seems the best way is to do the bulk of the work in Global.asax, with the custom error pages handling helpful content rather than logic.
Yes, MD5 is somewhat less CPU-intensive. On my Intel x86 (Core2 Quad Q6600, 2.4 GHz, using one core), I get this in 32-bit mode:
MD5 411
SHA-1 218
SHA-256 118
SHA-512 46
and this in 64-bit mode:
MD5 407
SHA-1 312
SHA-256 148
SHA-512 189
Figures are in megabytes per second, for a "long" message (this is what you get for messages longer than 8 kB). This is with sphlib, a library of hash function implementations in C (and Java). All implementations are from the same author (me) and were made with comparable efforts at optimizations; thus the speed differences can be considered as really intrinsic to the functions.
As a point of comparison, consider that a recent hard disk will run at about 100 MB/s, and anything over USB will top below 60 MB/s. Even though SHA-256 appears "slow" here, it is fast enough for most purposes.
Note that OpenSSL includes a 32-bit implementation of SHA-512 which is quite faster than my code (but not as fast as the 64-bit SHA-512), because the OpenSSL implementation is in assembly and uses SSE2 registers, something which cannot be done in plain C. SHA-512 is the only function among those four which benefits from a SSE2 implementation.
Edit: on this page (archive), one can find a report on the speed of many hash functions (click on the "Telechargez maintenant" link). The report is in French, but it is mostly full of tables and numbers, and numbers are international. The implemented hash functions do not include the SHA-3 candidates (except SHABAL) but I am working on it.
I am currently using tmux.
Installation: sudo apt-get install tmux Run it: tmux
Ctrl + b followed by Ctr + % : it splits your terminal window in two vertical halves.
Ctrl + "arrow left | arrow right" : moves between terminals.
You can do this by creating a new image (also answered in your other posting of this question):
- (UIImage*)imageWithBorderFromImage:(UIImage*)source;
{
CGSize size = [source size];
UIGraphicsBeginImageContext(size);
CGRect rect = CGRectMake(0, 0, size.width, size.height);
[source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 0.5, 1.0, 1.0);
CGContextStrokeRect(context, rect);
UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return testImg;
}
This code will produce a pink border around the image. However if you are going to just display the border then use the layer of the UIImageView
and set its border.
Read Cookie
in Web Api
var cookie = actionContext.Request.Headers.GetCookies("newhbsslv1");
Logger.Log("Cookie " + cookie, LoggerLevel.Info);
Logger.Log("Cookie count " + cookie.Count, LoggerLevel.Info);
if (cookie != null && cookie.Count > 0)
{
Logger.Log("Befor For " , LoggerLevel.Info);
foreach (var perCookie in cookie[0].Cookies)
{
Logger.Log("perCookie " + perCookie, LoggerLevel.Info);
if (perCookie.Name == "newhbsslv1")
{
strToken = perCookie.Value;
}
}
}
Another way to send header information to JavaScript would be through cookies. The server can extract whatever data it needs from the request headers and send them back inside a Set-Cookie
response header — and cookies can be read in JavaScript. As keparo says, though, it's best to do this for just one or two headers, rather than for all of them.
First add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
using Bitmap from resources
Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
Tested via bluetooth and other messengers
Your arguments are in the wrong order. Try git commit -m 'my notes' path/to/my/file.ext
, or if you want to be more explicit, git commit -m 'my notes' -- path/to/my/file.ext
.
Incidentally, git v1.5.2.1 is 4.5 years old. You may want to update to a newer version (1.7.8.3 is the current release).
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
If a
is your array:
In [11]: a[:,:2]
Out[11]:
array([[-0.57098887, -0.4274751 ],
[-0.22279713, -0.51723555],
[ 0.67492385, -0.69294472],
[ 0.41086611, 0.26374238]])
As a recorded macro.
range("A:A, B:B, D:D, E:E, G:G, H:H").select
If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:
div#wrapper {
position: absolute;
width: 100%;
text-align: center;
}
Remember that in order to position an element absolutely, the parent element must be positioned relatively.
The properties on the style
object are only the styles applied directly to the element (e.g., via a style
attribute or in code). So .style.marginTop
will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).
To get the current calculated style of the object, you use either the currentStyle
property (Microsoft) or the getComputedStyle
function (pretty much everyone else).
Example:
var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);
display("Current marginTop: " + style.marginTop);
Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p
element in IE9, I get back "1em"
.
All these answers are explaining the scenario of your second activity needs to be finish after sending the data.
But in case if you don't want to finish the second activity and want to send the data back in to first then for that you can use BroadCastReceiver.
In Second Activity -
Intent intent = new Intent("data");
intent.putExtra("some_data", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
In First Activity-
private BroadcastReceiver tempReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// do some action
}
};
Register the receiver in onCreate()-
LocalBroadcastManager.getInstance(this).registerReceiver(tempReceiver,new IntentFilter("data"));
Unregister it in onDestroy()
To convert the object to a byte array use the concept of Serialization and De-serialization
.
The complete conversion from object to byte array explained in is tutorial.
Q. How can we convert object into byte array?
Q. How can we serialize a object?
Q. How can we De-serialize a object?
Q. What is the need of serialization and de-serialization?
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
You can set the path from the current cmd window using the PATH =
command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. (Computer > Advanced System Settings > Environment Variables)
You would goto your cmd instance, and put in PATH=C:/Python27/;%PATH%
.
If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.
Why not measure it:
class Program
{
class NameComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y, true);
}
}
class Person
{
public Person(string id, string name)
{
Id = id;
Name = name;
}
public string Id { get; set; }
public string Name { get; set; }
}
static void Main()
{
List<Person> persons = new List<Person>();
persons.Add(new Person("P005", "Janson"));
persons.Add(new Person("P002", "Aravind"));
persons.Add(new Person("P007", "Kazhal"));
Sort(persons);
OrderBy(persons);
const int COUNT = 1000000;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
}
static void Sort(List<Person> list)
{
list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
}
static void OrderBy(List<Person> list)
{
var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
}
}
On my computer when compiled in Release mode this program prints:
Sort: 1162ms
OrderBy: 1269ms
UPDATE:
As suggested by @Stefan here are the results of sorting a big list fewer times:
List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
persons.Add(new Person("P" + i.ToString(), "Janson" + i.ToString()));
}
Sort(persons);
OrderBy(persons);
const int COUNT = 30;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
Prints:
Sort: 8965ms
OrderBy: 8460ms
In this scenario it looks like OrderBy performs better.
UPDATE2:
And using random names:
List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
}
Where:
private static Random randomSeed = new Random();
public static string RandomString(int size, bool lowerCase)
{
var sb = new StringBuilder(size);
int start = (lowerCase) ? 97 : 65;
for (int i = 0; i < size; i++)
{
sb.Append((char)(26 * randomSeed.NextDouble() + start));
}
return sb.ToString();
}
Yields:
Sort: 8968ms
OrderBy: 8728ms
Still OrderBy is faster
Use SELECT SCOPE_IDENTITY() in query
In C++ the requirements imposed on default arguments with regard to their location in parameter list are as follows:
Default argument for a given parameter has to be specified no more than once. Specifying it more than once (even with the same default value) is illegal.
Parameters with default arguments have to form a contiguous group at the end of the parameter list.
Now, keeping that in mind, in C++ you are allowed to "grow" the set of parameters that have default arguments from one declaration of the function to the next, as long as the above requirements are continuously satisfied.
For example, you can declare a function with no default arguments
void foo(int a, int b);
In order to call that function after such declaration you'll have to specify both arguments explicitly.
Later (further down) in the same translation unit, you can re-declare it again, but this time with one default argument
void foo(int a, int b = 5);
and from this point on you can call it with just one explicit argument.
Further down you can re-declare it yet again adding one more default argument
void foo(int a = 1, int b);
and from this point on you can call it with no explicit arguments.
The full example might look as follows
void foo(int a, int b);
int main()
{
foo(2, 3);
void foo(int a, int b = 5); // redeclare
foo(8); // OK, calls `foo(8, 5)`
void foo(int a = 1, int b); // redeclare again
foo(); // OK, calls `foo(1, 5)`
}
void foo(int a, int b)
{
// ...
}
As for the code in your question, both variants are perfectly valid, but they mean different things. The first variant declares a default argument for the second parameter right away. The second variant initially declares your function with no default arguments and then adds one for the second parameter.
The net effect of both of your declarations (i.e. the way it is seen by the code that follows the second declaration) is exactly the same: the function has default argument for its second parameter. However, if you manage to squeeze some code between the first and the second declarations, these two variants will behave differently. In the second variant the function has no default arguments between the declarations, so you'll have to specify both arguments explicitly.
A project is not exactly the same thing as an executable jar file.
For starters, a project generally contains source code, while an executable jar file generally doesn't. Again, generally speaking, you need to export an Eclipse project to obtain a file suitable for importing.
My typical expectation is than when "subject" is used a context like this, it means the target of the certificate. If you think of a certificate as a cryptographically secured description of a thing (person, device, communication channel, etc), then the subject is the stuff related to that thing.
It's not the thing itself. For example, no one would say "the subject takes his SmartCard and authenticates his PIN". That would be the "user".
But it usually relates to the various data items related to that that thing. For example:
Usually, it's used to distinguish between the other players in the PKI world. Namely the "issuer" and the "root". The issuer is the CA that issued the cert (to the subject), and the root is the CA that is end point of all the trust in the heirarchy. The typical relationship is root--->issuer--->subject.
This should work:
SELECT * FROM Accounts WHERE Username LIKE '%$query%'
in Winforms, there is a Screen class you can use to get data about screen dimensions and color depth for all displays connected to the computer. Here's the docs page: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx
CHANGING the screen resolution is trickier. There is a Resolution third party class that wraps the native code you'd otherwise hook into. Use its CResolution nested class to set the screen resolution to a new height and width; but understand that doing this will only work for height/width combinations the display actually supports (800x600, 1024x768, etc, not 817x435).
import os
print os.path.abspath(__file__)
I think it is a simple way not do to anything more You can change border left or right according to your need
.vertical-line{
border-left:1px solid #000
}
_x000D_
<span class="vertical-line"></span
_x000D_
You have a variety of problems. First, why are you using your specific @@FETCH_STATUS values? It should just be @@FETCH_STATUS = 0.
Second, you are not selecting your inner Cursor into anything. And I cannot think of any circumstance where you would select all fields in this way - spell them out!
Here's a sample to go by. Folder has a primary key of "ClientID" that is also a foreign key for Attend. I'm just printing all of the Attend UIDs, broken down by Folder ClientID:
Declare @ClientID int;
Declare @UID int;
DECLARE Cur1 CURSOR FOR
SELECT ClientID From Folder;
OPEN Cur1
FETCH NEXT FROM Cur1 INTO @ClientID;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Processing ClientID: ' + Cast(@ClientID as Varchar);
DECLARE Cur2 CURSOR FOR
SELECT UID FROM Attend Where ClientID=@ClientID;
OPEN Cur2;
FETCH NEXT FROM Cur2 INTO @UID;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Found UID: ' + Cast(@UID as Varchar);
FETCH NEXT FROM Cur2 INTO @UID;
END;
CLOSE Cur2;
DEALLOCATE Cur2;
FETCH NEXT FROM Cur1 INTO @ClientID;
END;
PRINT 'DONE';
CLOSE Cur1;
DEALLOCATE Cur1;
Finally, are you SURE you want to be doing something like this in a stored procedure? It is very easy to abuse stored procedures and often reflects problems in characterizing your problem. The sample I gave, for example, could be far more easily accomplished using standard select calls.
Rather than using aliases, I prefer creating git-XXX scripts so I can source control them more easily (our devs all have a certain source controlled dir on their path for this type of thing).
This script (called git-setpush
) will set the config value for remote.origin.push
value to something that will only push the current branch:
#!/bin/bash -eu
CURRENT_BRANCH=$(git branch | grep '^\*' | cut -d" " -f2)
NEW_PUSH_REF=HEAD:refs/for/$CURRENT_BRANCH
echo "setting remote.origin.push to $NEW_PUSH_REF"
git config remote.origin.push $NEW_PUSH_REF
note, as we're using Gerrit
, it sets the target to refs/for/XXX
to push into a review branch. It also assumes origin is your remote name.
Invoke it after checking out a branch with
git checkout your-branch
git setpush
It could obviously be adapted to also do the checkout, but I like scripts to do one thing and do it well
I had the same problem. I realized my file was somehow encoded in UCS-2 BE BOM
. Converting my .env
file to UTF-8
fixed it (you can easily do that using Notepad++, for example).
Import paths are relative to your $GOPATH
and $GOROOT
environment variables. For example, with the following $GOPATH
:
GOPATH=/home/me/go
Packages located in /home/me/go/src/lib/common
and /home/me/go/src/lib/routers
are imported respectively as:
import (
"lib/common"
"lib/routers"
)
Since glibc version 2.17, the library linking -lrt
is no longer required.
The clock_*
are now part of the main C library. You can see the change history of glibc 2.17 where this change was done explains the reason for this change:
+* The `clock_*' suite of functions (declared in <time.h>) is now available
+ directly in the main C library. Previously it was necessary to link with
+ -lrt to use these functions. This change has the effect that a
+ single-threaded program that uses a function such as `clock_gettime' (and
+ is not linked with -lrt) will no longer implicitly load the pthreads
+ library at runtime and so will not suffer the overheads associated with
+ multi-thread support in other code such as the C++ runtime library.
If you decide to upgrade glibc, then you can check the compatibility tracker of glibc if you are concerned whether there would be any issues using the newer glibc.
To check the glibc version installed on the system, run the command:
ldd --version
(Of course, if you are using old glibc (<2.17) then you will still need -lrt
.)
this is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
A lightweight solution with Check constraint:
CREATE TABLE example (
discriminator INTEGER DEFAULT 0 NOT NULL CHECK (discriminator = 0)
);
In your Laravel deployment it would be
/vendor/laravel/framework/src/Illuminate/Foundation/Application.php
to see who changed your Laravel version look at what's defined in composer.json. If you have "laravel/framework": "5.4.*", then it will update to the latest after composer update is run. Composer.lock is the file that results from running a composer update, so really see who last one to modify the composer.json file was (hopefully you have that in version control). You can read more about it here https://getcomposer.org/doc/01-basic-usage.md
I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:
div {
width: 100%;
height: 0;
padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
position: relative;
}
div iframe {
width: 100%;
height: 100%;
position: absolute;
display: block;
top: 0;
left: 0;
}
Just did it now for a client, and it seems to be working: http://themilkrunsa.co.za/
You can use /* tslint:disable-next-line */
to locally disable tslint. However, as this is a compiler error disabling tslint might not help.
You can always temporarily cast $
to any
:
delete ($ as any).summernote.options.keyMap.pc.TAB
which will allow you to access whatever properties you want.
Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:
if (false) {
// @ts-ignore: Unreachable code error
console.log("hello");
}
Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any
instead as that better expresses intent.
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
http://servername/sites/SiteCollection/SubSite/_vti_bin/Lists.asmx
ListsWebService
Here is the code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace WebServicesConsoleApp
{
class Program
{
static void Main(string[] args)
{
try
{
ListsWebService.Lists listsWebSvc = new WebServicesConsoleApp.ListsWebService.Lists();
listsWebSvc.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
listsWebSvc.Url = "http://servername/sites/SiteCollection/SubSite/_vti_bin/Lists.asmx";
XmlNode node = listsWebSvc.GetList("Issues");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
http://servername/sites/SiteCollection/SubSite/_vti_bin/Lists.asmx
Change your app.config file from:
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
To:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm"/>
</security>
Change your program.cs file and add the following code to your Main function:
ListsSoapClient client = new ListsSoapClient();
client.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
XmlElement listCollection = client.GetListCollection();
Add the using statements:
using [your app name].ServiceReference1;
using System.Xml;
TL;DR. In Visual Studio 2019
, when you add an Icon
resource to a Win32
(desktop) application you get an auto-generated icon file that has the formats below. I assume that the #1 developer tool for Windows does this right. Thus, a Windows
compatible should have the following formats:
| Resolution | Color depth | Format |
|:-----------|------------:|:------:|
| 256x256 | 32-bit | PNG |
| 64x64 | 32-bit | BMP |
| 48x48 | 32-bit | BMP |
| 32x32 | 32-bit | BMP |
| 16x16 | 32-bit | BMP |
| 48x48 | 8-bit | BMP |
| 32x32 | 8-bit | BMP |
| 16x16 | 8-bit | BMP |
Several ways to accomplish that but be aware that your DB date_format option & date_order option settings could affect the incoming format:
Select
cast('2008-09-16' as date)
convert(date,'16/09/2008',103)
date('2008-09-16')
from dummy;
You can also hide spinner with following trick :
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
opacity:0;
pointer-events:none;
}
I would like to give you also the idea to disable an <option>
with a given defined value (not innerhtml
). I recommend to it with jQuery
to get the simplest way. See my sample below.
HTML
Status:
<div id="option">
<select class="status">
<option value="hand" selected>Hand</option>
<option value="simple">Typed</option>
<option value="printed">Printed</option>
</select>
</div>
Javascript
The idea here is how to disable Printed
option when current Status
is Hand
var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;
You may see how it works here:
Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.
To append 'api'
to my baseURL, I have my default baseURL set as,
axios.defaults.baseURL = '/api/';
Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'
axios({
method:'post',
url:'logout',
baseURL: '/',
})
.then(response => {
window.location.reload();
})
.catch(error => {
console.log(error);
});
Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).
var offset = $('#whatever').offset();
offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));