The password that you use to login to github.com portal does not work in VS Code CLI/Shell. You should copy PAT Token from URL https://github.com/settings/tokens by generating new token and paste that string in CLI as password.
EDIT :
http://codepen.io/gcyrillus/pen/daCyu
So for a popup, you have to use position:fixed , display:table property and max-width with em or rem values :)
with this CSS basis :
#popup {
position:fixed;
width:100%;
height:100%;
display:table;
pointer-events:none;
}
#popup > div {
display:table-cell;
vertical-align:middle;
}
#popup p {
width:80%;
max-width:20em;
margin:auto;
pointer-events:auto;
}
The reason why your image is resizing which is because it is fluid. You have two ways to do it:
Either give a fixed dimension to your image using CSS like:
.carousel-inner > .item > img { width:640px; height:360px; }
A second way to can do this:
.carousel { width:640px; height:360px; }
This is what I use to make the text appear on hover:
* {_x000D_
box-sizing: border-box_x000D_
}_x000D_
_x000D_
div {_x000D_
position: relative;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
border-radius: 50%;_x000D_
overflow: hidden;_x000D_
text-align: center_x000D_
}_x000D_
_x000D_
img {_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
position: absolute;_x000D_
border-radius: 50%_x000D_
}_x000D_
_x000D_
img:hover {_x000D_
opacity: 0;_x000D_
transition:opacity 2s;_x000D_
}_x000D_
_x000D_
heading {_x000D_
line-height: 40px;_x000D_
font-weight: bold;_x000D_
font-family: "Trebuchet MS";_x000D_
text-align: center;_x000D_
position: absolute;_x000D_
display: block_x000D_
}_x000D_
_x000D_
div p {_x000D_
z-index: -1;_x000D_
width: 420px;_x000D_
line-height: 20px;_x000D_
display: inline-block;_x000D_
padding: 200px 0px;_x000D_
vertical-align: middle;_x000D_
font-family: "Trebuchet MS";_x000D_
height: 450px_x000D_
}
_x000D_
<div>_x000D_
<img src="https://68.media.tumblr.com/20b34e8d12d4230f9b362d7feb148c57/tumblr_oiwytz4dh41tf8vylo1_1280.png">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing <br>elit. Reiciendis temporibus iure dolores aspernatur excepturi <br> corporis nihil in suscipit, repudiandae. Totam._x000D_
</p>_x000D_
</div>
_x000D_
Create and save a java.awt.image.bufferedImage to file:
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
public static void main(String args[]){
try{
BufferedImage img = new BufferedImage(
500, 500, BufferedImage.TYPE_INT_RGB );
File f = new File("MyFile.png");
int r = 5;
int g = 25;
int b = 255;
int col = (r << 16) | (g << 8) | b;
for(int x = 0; x < 500; x++){
for(int y = 20; y < 300; y++){
img.setRGB(x, y, col);
}
}
ImageIO.write(img, "PNG", f);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Notes:
If you're using a shell, the filepath to the Download (no "s") folder is
/storage/emulated/0/Download
Well from its description it appears it tries to make the user agent's default style consistent across all browsers rather than stripping away all the default styling as a reset would.
Preserves useful defaults, unlike many CSS resets.
Virtualenv is a tool to create isolated Python environments.
Let's say you're working in 2 different projects, A and B. Project A is a web project and the team is using the following packages:
The project B is also a web project but your team is using:
The machine that you're working doesn't have any version of django, what should you do? Install django 1.4? django 1.6? If you install django 1.4 globally would be easy to point to django 1.6 to work in project A?
Virtualenv is your solution! You can create 2 different virtualenv's, one for project A and another for project B. Now, when you need to work in project A, just activate the virtualenv for project A, and vice-versa.
A better tip when using virtualenv is to install virtualenvwrapper to manage all the virtualenv's that you have, easily. It's a wrapper for creating, working, removing virtualenv's.
create a new page php and add this code:
<?php_x000D_
function ch_title($title){_x000D_
$output = ob_get_contents();_x000D_
if ( ob_get_length() > 0) { ob_end_clean(); }_x000D_
$patterns = array("/<title>(.*?)<\/title>/");_x000D_
$replacements = array("<title>$title</title>");_x000D_
$output = preg_replace($patterns, $replacements,$output);_x000D_
echo $output;_x000D_
}_x000D_
?>
_x000D_
in <head>
add code: <?php require 'page.php' ?>
and on each page you call the function ch_title('my title');
Using basename
assumes that you know what the file extension is, doesn't it?
And I believe that the various regular expression suggestions don't cope with a filename containing more than one "."
The following seems to cope with double dots. Oh, and filenames that contain a "/" themselves (just for kicks)
To paraphrase Pascal, "Sorry this script is so long. I didn't have time to make it shorter"
#!/usr/bin/perl
$fullname = $ARGV[0];
($path,$name) = $fullname =~ /^(.*[^\\]\/)*(.*)$/;
($basename,$extension) = $name =~ /^(.*)(\.[^.]*)$/;
print $basename . "\n";
You should use
inputvalue=Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
Math.Round rounds a double-precision floating-point value to a specified number of fractional digits.
Specifies how mathematical rounding methods should process a number that is midway between two numbers.
Basically the function above will take your inputvalue and round it to 2 (or whichever number you specify) decimal places. With MidpointRounding.AwayFromZero
when a number is halfway between two others, it is rounded toward the nearest number that is away from zero. There is also another option you can use that rounds towards the nearest even number.
EventHandler handler = (s, e) => MessageBox.Show("Woho");
button.Click += handler;
button.Click -= handler;
How about:
public String UrlEncode(String in_) {
String retVal = "";
try {
retVal = URLEncoder.encode(in_, "UTF8");
} catch (UnsupportedEncodingException ex) {
Log.get().exception(Log.Level.Error, "urlEncode ", ex);
}
return retVal;
}
This worked for me endDate: "today"
$('#datepicker').datepicker({
format: "dd/mm/yyyy",
autoclose: true,
orientation: "top",
endDate: "today"
});
I made a thing that doesn't break the existing Storage objects, but creates a wrapper so you can do what you want. The result is a normal object, no methods, with access like any object.
If you want 1 localStorage
property to be magic:
var prop = ObjectStorage(localStorage, 'prop');
If you need several:
var storage = ObjectStorage(localStorage, ['prop', 'more', 'props']);
Everything you do to prop
, or the objects inside storage
will be automatically saved into localStorage
. You're always playing with a real object, so you can do stuff like this:
storage.data.list.push('more data');
storage.another.list.splice(1, 2, {another: 'object'});
And every new object inside a tracked object will be automatically tracked.
The very big downside: it depends on Object.observe()
so it has very limited browser support. And it doesn't look like it'll be coming for Firefox or Edge anytime soon.
You can use axis
:
> axis(side=1, at=c(0:23))
That is, something like this:
plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()
This problem is solved in bootstrap-4-alpha-2.
Here is the link: http://blog.getbootstrap.com/2015/12/08/bootstrap-4-alpha-2/
Clone it on github: https://github.com/twbs/bootstrap/tree/v4.0.0-alpha.2
Did you try:
$(this).is(':focus');
Take a look at Using jQuery to test if an input has focus it features some more examples
There is no built in construct in C#/.NET, but you can easily add your own extension method for this:
public static class ExtensionsForInt32
{
public static bool IsBetween (this int val, int low, int high)
{
return val > low && val < high;
}
}
Which can be used like:
if (5.IsBetween (0, 10)) { /* Do something */ }
SELECT NAME FROM v$database;
shows the database name in oracle
Go for line-height
.
The vertical-align
tag works fine for the submit button but not for the text in the input field.
Setting line-height
to the height of the input field works on all browsers. Incl IE7.
Here you can resolve this issue, you need to add flavorDimension with productFlavors's name and need to define dimension as well, see below example and for more information see here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html
flavorDimensions 'yourAppName' //here defined dimensions
productFlavors {
production {
dimension 'yourAppName' //you just need to add this line
//here you no need to write applicationIdSuffix because by default it will point to your app package which is also available inside manifest.xml file.
}
staging {
dimension 'yourAppName' //added here also
applicationIdSuffix ".staging"//(.staging) will be added after your default package name.
//or you can also use applicationId="your_package_name.staging" instead of applicationIdSuffix but remember if you are using applicationId then You have to mention full package name.
//versionNameSuffix "-staging"
}
develop {
dimension 'yourAppName' //add here too
applicationIdSuffix ".develop"
//versionNameSuffix "-develop"
}
Issue: It's because either you are not stopping your application or the application is already somehow running on the same port somehow.
Solution, Before starting it another time, the earlier application needs to be killed and the port needs to be freed up.
Depending on your platform you can run the below commands to stop the application,
on windows
netstat -anp | find "your application port number"` --> find PID
taskkill /F /PID
on Linux,
netstat -ntpl | grep "your application port number"
kill pid // pid you will get from previous command
on Mac OS
lsof -n -iTCP:"port number"
kill pid //pid you will get from previous command
Take a look at the Java guide on varargs.
You can create a method as shown below. Simply call System.out.printf
instead of System.out.println(String.format(...
.
public static void print(String format, Object... args) {
System.out.printf(format, args);
}
Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:
import static java.lang.System.out;
out.printf("Numer of apples: %d", 10);
.headerDivider {
border-left:1px solid #38546d;
border-right:1px solid #16222c;
height:80px;
position:absolute;
right:249px;
top:10px;
}
<div class="headerDivider"></div>
IF EXISTS
will basically do a SELECT - the same one that UPDATE would.
As such, it will decrease performance - if there's nothing to update, you did the same amount of work (UPDATE would have queried same lack of rows as your select) and if there's something to update, you juet did an un-needed select.
"Thousands" is not a large number. A few thousand paragraph-length strings are on the order of a couple of megabytes in size. If all you want to do is access these serially, use an immutable singly-linked List.
This is a nice way of sorting a table:
$(document).ready(function () {_x000D_
$('th').each(function (col) {_x000D_
$(this).hover(_x000D_
function () {_x000D_
$(this).addClass('focus');_x000D_
},_x000D_
function () {_x000D_
$(this).removeClass('focus');_x000D_
}_x000D_
);_x000D_
$(this).click(function () {_x000D_
if ($(this).is('.asc')) {_x000D_
$(this).removeClass('asc');_x000D_
$(this).addClass('desc selected');_x000D_
sortOrder = -1;_x000D_
} else {_x000D_
$(this).addClass('asc selected');_x000D_
$(this).removeClass('desc');_x000D_
sortOrder = 1;_x000D_
}_x000D_
$(this).siblings().removeClass('asc selected');_x000D_
$(this).siblings().removeClass('desc selected');_x000D_
var arrData = $('table').find('tbody >tr:has(td)').get();_x000D_
arrData.sort(function (a, b) {_x000D_
var val1 = $(a).children('td').eq(col).text().toUpperCase();_x000D_
var val2 = $(b).children('td').eq(col).text().toUpperCase();_x000D_
if ($.isNumeric(val1) && $.isNumeric(val2))_x000D_
return sortOrder == 1 ? val1 - val2 : val2 - val1;_x000D_
else_x000D_
return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;_x000D_
});_x000D_
$.each(arrData, function (index, row) {_x000D_
$('tbody').append(row);_x000D_
});_x000D_
});_x000D_
});_x000D_
});
_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
th {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr><th>id</th><th>name</th><th>age</th></tr>_x000D_
<tr><td>1</td><td>Julian</td><td>31</td></tr>_x000D_
<tr><td>2</td><td>Bert</td><td>12</td></tr>_x000D_
<tr><td>3</td><td>Xavier</td><td>25</td></tr>_x000D_
<tr><td>4</td><td>Mindy</td><td>32</td></tr>_x000D_
<tr><td>5</td><td>David</td><td>40</td></tr>_x000D_
</table>
_x000D_
The fiddle can be found here:
https://jsfiddle.net/e3s84Luw/
The explanation can be found here: https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code
Both tools are meant to work with text and there are tasks both tools can be used for.
For me the rule to separate them is: Use sed
to automate tasks you would do otherwise in a text editor manually. That's why it is called stream editor. (You can use the same commands to edit text in vim). Use awk
if you want to analyze text, meaning counting fields, calculate totals, extract and reorganize structures etc.
Also you should not forget about grep
. Use grep
if you only want to search/extract something in a text (file)
Couldn't you just do something simple like this?
For i = LBound(Schedule, 1) To UBound(Schedule, 1)
If (Schedule(i, 1) < ReferenceDate) Then
PrevCouponIndex = i
Else
DF = Application.Run("SomeFunction"....)
PV = PV + (DF * Coupon / CouponFrequency)
End If
Next
I had exactly the same issue, after moving from old go version (installed from old PPA) to newer (1.2.1) default packages in ubuntu 14.04.
The first step was to purge existing go:
sudo apt-get purge golang*
Which outputs following warnings:
dpkg: warning: while removing golang-go, directory '/usr/lib/go/src' not empty so not removed
dpkg: warning: while removing golang-go.tools, directory '/usr/lib/go' not empty so not removed
It looks like removing go leaves some files behind, which in turn can confuse newer install. More precisely, installation itself will complete fine, but afterwards any go command, like "go get something" gives those "unrecognized import path" errors.
All I had to do was to remove those dirs first, reinstall golang, and all works like a charm (assuming you also set GOPATH)
# careful!
sudo rm -rf /usr/lib/go /usr/lib/go/src
sudo apt-get install golang-go golang-go.tools
I use these easy functions, it work like jquery slideUp slideDown, use it in an helper class, just pass your view :
public static void expand(final View v) {
v.measure(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
final int targetHeight = v.getMeasuredHeight();
// Older versions of android (pre API 21) cancel animations for views with a height of 0.
v.getLayoutParams().height = 1;
v.setVisibility(View.VISIBLE);
Animation a = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? WindowManager.LayoutParams.WRAP_CONTENT
: (int)(targetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation()
{
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if(interpolatedTime == 1){
v.setVisibility(View.GONE);
}else{
v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
If you are an iPhone Developer don't just add your picture (by right clicking then add file...like we do in iPhone). You have to copy and paste the picture in your drawable folder.
More easy and without addition modules
Math.random().toString(26).slice(2)
Paths specified with a .
are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js
but not if you run node folder/app.js
. The only exception to this is require('./file')
and that is only possible because require
exists per-module and thus knows what module it is being called from.
To make a path relative to the script, you must use the __dirname
variable.
var path = require('path');
path.join(__dirname, 'path/to/file')
or potentially
path.join(__dirname, 'path', 'to', 'file')
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
If you use the following CSS
<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />
just change it into the following style by adding media="screen"
<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />
I think it will work.
the former answers like
@media print {
a[href]:after {
content: none !important;
}
}
were not worked well in the chrome browse.
C has always been very specific about the initial values of objects. If global or static
, they will be zeroed. If auto
, the value is indeterminate.
This was the case in pre-C89 compilers and was so specified by K&R and in DMR's original C report.
This was the case in C89, see section 6.5.7 Initialization.
If an object that has automatic storage duration is not initialized explicitely, its value is indeterminate. If an object that has static storage duration is not initialized explicitely, it is initialized implicitely as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
This was the case in C99, see section 6.7.8 Initialization.
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.
As to what exactly indeterminate means, I'm not sure for C89, C99 says:
3.17.2
indeterminate value
either an unspecified value or a trap representation
But regardless of what standards say, in real life, each stack page actually does start off as zero, but when your program looks at any auto
storage class values, it sees whatever was left behind by your own program when it last used those stack addresses. If you allocate a lot of auto
arrays you will see them eventually start neatly with zeroes.
You might wonder, why is it this way? A different SO answer deals with that question, see: https://stackoverflow.com/a/2091505/140740
If you don't want to use a library, this should cover most/all of the same form element types.
function serialize(form) {
if (!form || !form.elements) return;
var serial = [], i, j, first;
var add = function (name, value) {
serial.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
}
var elems = form.elements;
for (i = 0; i < elems.length; i += 1, first = false) {
if (elems[i].name.length > 0) { /* don't include unnamed elements */
switch (elems[i].type) {
case 'select-one': first = true;
case 'select-multiple':
for (j = 0; j < elems[i].options.length; j += 1)
if (elems[i].options[j].selected) {
add(elems[i].name, elems[i].options[j].value);
if (first) break; /* stop searching for select-one */
}
break;
case 'checkbox':
case 'radio': if (!elems[i].checked) break; /* else continue */
default: add(elems[i].name, elems[i].value); break;
}
}
}
return serial.join('&');
}
This extension makes it faster : Quick Javascript Switcher
Sometimes a website doesn't work on my PC and I want to know if it's the website or a problem local to me(e.g. my ISP, my router, etc).
The simplest way to check a website and avoid using your local network resources(and thus avoid any problems caused by them) is using a web proxy such as Proxy.org.
ps -eo pid,etime,cmd|sort -n -k2
Beginners needs practical examples. so try the following code.
public class Not_a_Number {
public static void main(String[] args) {
// TODO Auto-generated method stub
String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";
String dottedLine = "------------------------------------------------";
Double numerator = -2.0;
Double denominator = -2.0;
while (denominator <= 1) {
Double x = numerator/denominator;
Double y = new Double (x);
boolean z = y.isNaN();
System.out.println("y = " + y);
System.out.println("z = " + z);
if (z == true){
System.out.println(message);
}
else {
System.out.println("Hi, everyone");
}
numerator = numerator + 1;
denominator = denominator +1;
System.out.println(dottedLine);
} // end of while
} // end of main
} // end of class
To follow @modocache's recommendation to avoid calling view.endEditing()
, you could keep track of the text field that became first responder, but that is messy and error-prone.
An alternative is to call resignFirstResponder()
on all text fields in the viewcontroller. Here's an example of creating a collection of all text fields (which in my case was needed for validation code anyway):
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var email: UITextField!
var allTextFields: Array<UITextField>! // Forced unwrapping so it must be initialized in viewDidLoad
override func viewDidLoad()
{
super.viewDidLoad()
self.allTextFields = [self.firstName, self.lastName, self.email]
}
With the collection available, it's a simple matter to iterate through all of them:
private func dismissKeyboard()
{
for textField in allTextFields
{
textField.resignFirstResponder()
}
}
So now you can call dismissKeyboard()
in your gesture recognizer (or wherever is appropriate for you). Drawback is that you must maintain the list of UITextField
s when you add or remove fields.
Comments welcome. If there is a problem with calling resignFirstResponder()
on controls that aren't first responder, or if there's an easy and guaranteed non-buggy way to track the current first responder, I'd love to hear about it!
But if one has to substitute, then the following thing works:
:%s/\n/\r\|\-\r/g
In the above, every next line is substituted with next line, and then |-
and again a new line. This is used in wiki tables.
If the text is as follows:
line1
line2
line3
It is changed to
line1
|-
line2
|-
line3
To the parent div add a height say 50px. In the child span, add the line-height: 50px; Now the text in the span will be vertically center. This worked for me.
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.
Let's try to take an example and understand:
I have a branch, say master, pointing to X <commit-id>, and I have a new branch pointing to Y <sha1>.
Where Y <commit-id> = <master> branch commits - few commits
Now say for Y branch I have to gap-close the commits between the master branch and the new branch. Below is the procedure we can follow:
Step 1:
git checkout -b local origin/new
where local is the branch name. Any name can be given.
Step 2:
git merge origin/master --no-ff --stat -v --log=300
Merge the commits from master branch to new branch and also create a merge commit of log message with one-line descriptions from at most <n> actual commits that are being merged.
For more information and parameters about Git merge, please refer to:
git merge --help
Also if you need to merge a specific commit, then you can use:
git cherry-pick <commit-id>
Replace with
imageWidth = 1 * Convert.ToInt32(Label1.Text);
Simply mutiply the bottom of the division by 1.0 (or as many decimal places as you want)
PRINT @set1
PRINT @set2
SET @weight= @set1 / @set2 *1.00000;
PRINT @weight
$("#expires1").click(function(){
if (this.checked)
alert("testing....");
});
this.replace( new RegExp( replaceThis, 'g' ), withThis );
To customize tool bar style, first create tool bar custom style inheriting Widget.AppCompat.Toolbar, override properties and then add it to custom app theme as shown below, see http://www.zoftino.com/android-toolbar-tutorial for more information tool bar and styles.
<style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="toolbarStyle">@style/MyToolBarStyle</item>
</style>
<style name="MyToolBarStyle" parent="Widget.AppCompat.Toolbar">
<item name="android:background">#80deea</item>
<item name="titleTextAppearance">@style/MyTitleTextAppearance</item>
<item name="subtitleTextAppearance">@style/MySubTitleTextAppearance</item>
</style>
<style name="MyTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textSize">35dp</item>
<item name="android:textColor">#ff3d00</item>
</style>
<style name="MySubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
<item name="android:textSize">30dp</item>
<item name="android:textColor">#1976d2</item>
</style>
Try this.
namespace EraseJunkFiles
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\");
foreach (DirectoryInfo dir in yourRootDir.GetDirectories())
DeleteDirectory(dir.FullName, true);
}
public static void DeleteDirectory(string directoryName, bool checkDirectiryExist)
{
if (Directory.Exists(directoryName))
Directory.Delete(directoryName, true);
else if (checkDirectiryExist)
throw new SystemException("Directory you want to delete is not exist");
}
}
}
To Solve this Error just initialize that variable above that loop or statement. For Example var a =""
I think you've got your understanding of the two properties off a little. Border affects the outside edge of the element, making the element different in size. Outline will not change the size or position of the element (takes up no space) and goes outside the border. From your description you want to use the border property.
Look at the simple example below in your browser:
<div style="height: 100px; width: 100px; background: black; color: white; outline: thick solid #00ff00">SOME TEXT HERE</div>_x000D_
_x000D_
<div style="height: 100px; width: 100px; background: black; color: white; border-left: thick solid #00ff00">SOME TEXT HERE</div>
_x000D_
Notice how the border pushes the bottom div over, but the outline doesn't move the top div and the outline actually overlaps the bottom div.
private
doesn't seem to work if you are defining a method on an explicit object (in your case self
). You can use private_class_method
to define class methods as private (or like you described).
class Person
def self.get_name
persons_name
end
def self.persons_name
"Sam"
end
private_class_method :persons_name
end
puts "Hey, " + Person.get_name
puts "Hey, " + Person.persons_name
Alternatively (in ruby 2.1+), since a method definition returns a symbol of the method name, you can also use this as follows:
class Person
def self.get_name
persons_name
end
private_class_method def self.persons_name
"Sam"
end
end
puts "Hey, " + Person.get_name
puts "Hey, " + Person.persons_name
You'd use font-weight: bold
.
Do you want to make the entire document bold? Or just parts of it?
My site configuration file is example.conf in sites-available folder So you can create a symbolic link as
ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/
You need to go one level deeper in what you are retrieving.
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("MyTable")
MsgBox tbl.Range.Rows.Count
MsgBox tbl.HeaderRowRange.Rows.Count
MsgBox tbl.DataBodyRange.Rows.Count
Set tbl = Nothing
More information at:
ListObject Interface
ListObject.Range Property
ListObject.DataBodyRange Property
ListObject.HeaderRowRange Property
Check also that you don't have this turned on: Configuration Properties -> C/C++ -> Preprocessor -> Preprocess to a File.
As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.
Place your config file into src/main/resources/app-context.xml and use code
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}
or you can make yout test context with different configuration of beans.
Place your config file into src/test/resources/test-app-context.xml and use code
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}
First, install QEMU. On Debian-based distributions like Ubuntu, run:
$ apt-get install qemu
Then run the following command:
$ qemu-img convert -O vmdk imagefile.dd vmdkname.vmdk
I’m assuming a flat disk image is a dd
-style image. The convert operation also handles numerous other formats.
For more information about the qemu-img
command, see the output of
$ qemu-img -h
Perhaps use plt.annotate:
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show()
You can just do this:
git remote add origin ssh://user@host:1234/srv/git/example
1234
is the ssh port being used
> var x = 0.1
> var y = 0.2
> var cf = 10
> x * y
0.020000000000000004
> (x * cf) * (y * cf) / (cf * cf)
0.02
Quick solution:
var _cf = (function() {
function _shift(x) {
var parts = x.toString().split('.');
return (parts.length < 2) ? 1 : Math.pow(10, parts[1].length);
}
return function() {
return Array.prototype.reduce.call(arguments, function (prev, next) { return prev === undefined || next === undefined ? undefined : Math.max(prev, _shift (next)); }, -Infinity);
};
})();
Math.a = function () {
var f = _cf.apply(null, arguments); if(f === undefined) return undefined;
function cb(x, y, i, o) { return x + f * y; }
return Array.prototype.reduce.call(arguments, cb, 0) / f;
};
Math.s = function (l,r) { var f = _cf(l,r); return (l * f - r * f) / f; };
Math.m = function () {
var f = _cf.apply(null, arguments);
function cb(x, y, i, o) { return (x*f) * (y*f) / (f * f); }
return Array.prototype.reduce.call(arguments, cb, 1);
};
Math.d = function (l,r) { var f = _cf(l,r); return (l * f) / (r * f); };
> Math.m(0.1, 0.2)
0.02
You can check the full explanation here.
Try this:
using System.ComponentModel;
youtItemsControl.Items.SortDescriptions.Add(new SortDescription("yourFavoritePropertyFromItem",ListSortDirection.Ascending);
If you're okay with ES2017, await
is good:
const DEF_DELAY = 1000;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}
await sleep(100);
Note that the await
part needs to be in an async function:
//IIAFE (immediately invoked async function expression)
(async()=>{
//Do some stuff
await sleep(100);
//Do some more stuff
})()
You can call setScale(newScale, roundingMode)
method three times with changing the newScale value from 4 to 3 to 2 like
First case
BigDecimal a = new BigDecimal("10.12345");
a = a.setScale(4, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.1235
a = a.setScale(3, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.124
a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.12
Second case
BigDecimal a = new BigDecimal("10.12556");
a = a.setScale(4, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.1256
a = a.setScale(3, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.126
a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.13
Just to add to the others, you can pass a function name:
function someFunc($a)
{
echo $a;
}
function callFunc($name)
{
$name('funky!');
}
callFunc('someFunc');
This will work in PHP4.
the selected answer above is not working if you run your jar by click on it from Gnome desktop environment (not from any script or terminal).
Instead, I have fond that the following solution is working everywhere:
try {
return URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(), "UTF-8");
} catch (UnsupportedEncodingException e) {
return "";
}
Make sure Your TableView Delegate are working as well. if not then in your story board or in .xib press and hold Control + right click on tableView drag and Drop to your Current ViewController. swift 2.0
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60.0;
}
In my case I need to clear just the view and restart the controller. I could get my intention with this snippet:
$ionicHistory.clearCache([$state.current.name]).then(function() {
$state.reload();
}
The cache still working and seems that just the view is cleared.
ionic --version
says 1.7.5.
You can use PdfBox from Apache which is simple to use and has good performance.
Here is an example of extracting text from a PDF file (you can read more here) :
import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;
public class PDFTest {
public static void main(String[] args){
PDDocument pd;
BufferedWriter wr;
try {
File input = new File("C:\\Invoice.pdf"); // The PDF file from where you would like to extract
File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
pd = PDDocument.load(input);
System.out.println(pd.getNumberOfPages());
System.out.println(pd.isEncrypted());
pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
PDFTextStripper stripper = new PDFTextStripper();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
stripper.writeText(pd, wr);
if (pd != null) {
pd.close();
}
// I use close() to flush the stream.
wr.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
UPDATE:
You can get the text using PDFTextStripper:
PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created
SQL Server
does not support CREATE TABLE AS SELECT
.
Use this:
SELECT *
INTO A
FROM myview
or
SELECT TOP 10
*
INTO A
FROM myview
ORDER BY
id
Yes:
#include <iostream>
#include <functional>
struct null_ref_t {
template <typename T>
operator T&() {
union TypeSafetyBreaker {
T *ptr;
// see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
std::reference_wrapper<T> ref;
};
TypeSafetyBreaker ptr = {.ptr = nullptr};
// unwrap the reference
return ptr.ref.get();
}
};
null_ref_t nullref;
int main() {
int &a = nullref;
// Segmentation fault
a = 4;
return 0;
}
onPause()
method works in activity class you can use:
public void onDestroyView(){
super.onDestroyView
}
for same purpose..
If you want to check if your -vm eclipse.ini
option worked correctly you can use this to see under what JVM the IDE itself runs: menu Help > About Eclipse > Installation Details > Configuration tab. Locate the line that says: java.runtime.version=...
.
Okay, so here we have two things that are being mixed. First thing, is when you need to mark something to be used only on test, which I agree with @JB Nizet, using the guava annotation would be good.
A different thing, is to test private methods. Why should you test private methods from the outside? I mean.. You should be able to test the object by their public methods, and at the end that its behavior. At least, that we are doing and trying to teach to junior developers, that always try to test private methods (as a good practice).
To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.
The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.
You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.
event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.
$("p").click(function(event)
{ event.stopImmediatePropagation();
});
$("p").click(function(event)
{ // This function won't be executed
$(this).css("color", "#fff7e3");
});
If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.
In case of Windows(in my case XP):-
database_password: password
would between quotes: " or '.
like so:
database_password: "password"
Swift version
Only trims spaces at the end of the String:
private func removingSpacesAtTheEndOfAString(var str: String) -> String {
var i: Int = countElements(str) - 1, j: Int = i
while(i >= 0 && str[advance(str.startIndex, i)] == " ") {
--i
}
return str.substringWithRange(Range<String.Index>(start: str.startIndex, end: advance(str.endIndex, -(j - i))))
}
Trims spaces on both sides of the String:
var str: String = " Yolo "
var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
The post is old but I found a perfect CSS for the purpose and I want to share it.
A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).
div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
}
@param
won't affect the number. It's just for making javadocs.
More on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html
Try
UPDATE products SET former_date=20111218131717 WHERE id=1
Alternatively, you might want to look at using the STR_TO_DATE (see STR_TO_DATE(str,format)) function.
doReturn( value1, value2, value3 ).when( method-call )
A simple program's compilation workflow is simple, I can draw it as a small graph: source -> [compilation] -> object [linking] -> executable. There are files (source, object, executable) in this graph, and rules (make's terminology). That graph is definied in the Makefile.
When you launch make, it reads Makefile, and checks for changed files. If there's any, it triggers the rule, which depends on it. The rule may produce/update further files, which may trigger other rules and so on. If you create a good makefile, only the necessary rules (compiler/link commands) will run, which stands "to next" from the modified file in the dependency path.
Pick an example Makefile, read the manual for syntax (anyway, it's clear for first sight, w/o manual), and draw the graph. You have to understand compiler options in order to find out the names of the result files.
The make graph should be as complex just as you want. You can even do infinite loops (don't do)! You can tell make, which rule is your target, so only the left-standing files will be used as triggers.
Again: draw the graph!.
cd /
sudo chown -R $(whoami):$(whoami) /var
Note: I tested it using ubuntu os
I've installed and use VB6 for legacy projects many times on Windows 7.
What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.
Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721
Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm
Or this:
f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}
A solution without Regex, a little bit easier on the eye, one I was looking for
This supports ports, hash parameters etc.
Uses browsers attribute element as a parser.
function setUrlParameters(url, parameters) {
var parser = document.createElement('a');
parser.href = url;
url = "";
if (parser.protocol) {
url += parser.protocol + "//";
}
if (parser.host) {
url += parser.host;
}
if (parser.pathname) {
url += parser.pathname;
}
var queryParts = {};
if (parser.search) {
var search = parser.search.substring(1);
var searchParts = search.split("&");
for (var i = 0; i < searchParts.length; i++) {
var searchPart = searchParts[i];
var whitespaceIndex = searchPart.indexOf("=");
if (whitespaceIndex !== -1) {
var key = searchPart.substring(0, whitespaceIndex);
var value = searchPart.substring(whitespaceIndex + 1);
queryParts[key] = value;
} else {
queryParts[searchPart] = false;
}
}
}
var parameterKeys = Object.keys(parameters);
for (var i = 0; i < parameterKeys.length; i++) {
var parameterKey = parameterKeys[i];
queryParts[parameterKey] = parameters[parameterKey];
}
var queryPartKeys = Object.keys(queryParts);
var query = "";
for (var i = 0; i < queryPartKeys.length; i++) {
if (query.length === 0) {
query += "?";
}
if (query.length > 1) {
query += "&";
}
var queryPartKey = queryPartKeys[i];
query += queryPartKey;
if (queryParts[queryPartKey]) {
query += "=";
query += queryParts[queryPartKey];
}
}
url += query;
if (parser.hash) {
url += parser.hash;
}
return url;
}
I found that "@RequestMapping produces=" and other configuration changes didn't help me. By the time you do resp.getWriter(), it is also too late to set the encoding on the writer.
Adding a header to the HttpServletResponse works.
@RequestMapping(value="/test", method=RequestMethod.POST)
public void test(HttpServletResponse resp) {
try {
resp.addHeader("content-type", "application/json; charset=utf-8");
PrintWriter w = resp.getWriter();
w.write("{\"name\" : \"µr µicron\"}");
w.flush();
w.close();
} catch (Exception e) {
e.printStackTrace();
}
}
If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.
Check out SSMS Tool Pack. It works in Management Studio 2005 and 2008. There is an option to generate insert statements which I've found helpful moving small amounts of data from one system to another.
With this option you will have to script out the DDL separately.
First of all, IPAs usually only have ARM slices because the App Store does not currently accept Simulator slices in uploads.
Secondly, as of Xcode 8.3 you can drag & drop a .app
bundle into the Simulator window and it will be installed. You can find the app in your build products directory ~/Library/Developer/Xcode/DerivedData/projectname-xyzzyabcdefg/Build/Products/Debug-iphonesimulator
if you want to save it or distribute it to other people.
To install from the command line use xcrun simctl install <device> <path>
.
device
can be the device UUID, its name, or booted
which means the currently booted device.
Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.
This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).
To delete single columns, I'll just use dat$x <- NULL
.
To delete multiple columns, but less than about 3-4, I'll use dat$x <- dat$y <- dat$z <- NULL
.
For more than that, I'll use subset
, with negative names (!):
subset(mtcars, , -c(mpg, cyl, disp, hp))
JD-GUI is a very handy tool for browsing and decompiling JARs
Use a generic Last<T>
. That will work with ANY IEnumerable
, including string.
public static IEnumerable<T> Last<T>(this IEnumerable<T> enumerable, int nLastElements)
{
int count = Math.Min(enumerable.Count(), nLastElements);
for (int i = enumerable.Count() - count; i < enumerable.Count(); i++)
{
yield return enumerable.ElementAt(i);
}
}
And a specific one for string:
public static string Right(this string str, int nLastElements)
{
return new string(str.Last(nLastElements).ToArray());
}
SELECT * FROM Header WHERE userID LIKE '%' + CHAR(39) + '%'
Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed()
function:
var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?
//%%%%%%%%%%%%%%%%%%%%%% HEX to ASCII %%%%%%%%%%%%%%%%%%%%%%
public String convertHexToString(String hex){
String ascii="";
String str;
// Convert hex string to "even" length
int rmd,length;
length=hex.length();
rmd =length % 2;
if(rmd==1)
hex = "0"+hex;
// split into two characters
for( int i=0; i<hex.length()-1; i+=2 ){
//split the hex into pairs
String pair = hex.substring(i, (i + 2));
//convert hex to decimal
int dec = Integer.parseInt(pair, 16);
str=CheckCode(dec);
ascii=ascii+" "+str;
}
return ascii;
}
public String CheckCode(int dec){
String str;
//convert the decimal to character
str = Character.toString((char) dec);
if(dec<32 || dec>126 && dec<161)
str="n/a";
return str;
}
Starting in version 0.7.9 you can use the filter operator .isnot
instead of comparing constraints, like this:
query.filter(User.name.isnot(None))
This method is only necessary if pep8 is a concern.
source: sqlalchemy documentation
One way to order by positive integers, when they are stored as varchar
, is to order by the length first and then the value:
order by len(registration_no), registration_no
This is particularly useful when the column might contain non-numeric values.
Note: in some databases, the function to get the length of a string might be called length()
instead of len()
.
Here's a good article covering three algorithms for finding all permutations, including one to find the next permutation.
http://www.cut-the-knot.org/do_you_know/AllPerm.shtml
C++ and Python have built-in next_permutation and itertools.permutations functions respectively.
This function will return you image with black border try this.. hope this will help you
- (UIImage *)addBorderToImage:(UIImage *)image frameImage:(UIImage *)blackBorderImage
{
CGSize size = CGSizeMake(image.size.width,image.size.height);
UIGraphicsBeginImageContext(size);
CGPoint thumbPoint = CGPointMake(0,0);
[image drawAtPoint:thumbPoint];
UIGraphicsBeginImageContext(size);
CGImageRef imgRef = blackBorderImage.CGImage;
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width,size.height), imgRef);
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGPoint starredPoint = CGPointMake(0, 0);
[imageCopy drawAtPoint:starredPoint];
UIImage *imageC = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageC;
}
The best solution that worked great for me.
You have to: Copy this code to your main CSS file,
.responsive-video {
position: relative;
padding-bottom: 56.25%;
padding-top: 60px; overflow: hidden;
}
.responsive-video iframe,
.responsive-video object,
.responsive-video embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
and then put your embeded video to
<div class="responsive-video">
<iframe ></iframe>
</div>
That’s it! Now you can use responsive videos on your site.
The HTML tabindex atribute is responsible for indicating if an element is reachable by keyboard navigation. When the user presses the Tab key the focus is shifted from one element to another. By using the tabindex atribute, the tab order flow is shifted.
I answered a similar question here
As @Syden said, the mixins will work. Another option is using SASS map-get
like this..
@media (min-width: map-get($grid-breakpoints, sm)){
.something {
padding: 10px;
}
}
@media (min-width: map-get($grid-breakpoints, md)){
.something {
padding: 20px;
}
}
http://www.codeply.com/go/0TU586QNlV
Disclosure: I wrote FieldVal.
Here is a solution using FieldVal. By using FieldVal UI to build a form and then FieldVal to validate the input, you can pass the error straight back into the form.
You can even run the validation code on the backend (if you're using Node.js) and show the error in the form without wiring all of the fields up manually.
Live demo: http://codepen.io/MarcusLongmuir/pen/WbOydx
function validate_form(data) {
// This would work on the back end too (if you're using Node)
// Validate the provided data
var validator = new FieldVal(data);
validator.get("email", BasicVal.email(true));
validator.get("title", BasicVal.string(true));
validator.get("url", BasicVal.url(true));
return validator.end();
}
$(document).ready(function(){
// Create a form and add some fields
var form = new FVForm()
.add_field("email", new FVTextField("Email"))
.add_field("title", new FVTextField("Title"))
.add_field("url", new FVTextField("URL"))
.on_submit(function(value){
// Clear the existing errors
form.clear_errors();
// Use the function above to validate the input
var error = validate_form(value);
if (error) {
// Pass the error into the form
form.error(error);
} else {
// Use the data here
alert(JSON.stringify(value));
}
})
form.element.append(
$("<button/>").text("Submit")
).appendTo("body");
//Pre-populate the form
form.val({
"email": "[email protected]",
"title": "Your Title",
"url": "http://www.example.com"
})
});
It can be done much easier:
\S
which equals [^ \t\r\n\v\f]
If the file you are working on is not so big, and temporarily storing it in a variable is no problem, then you can use Bash string substitution on the whole file at once - there's no need to go over it line by line:
file_contents=$(</tmp/file.txt)
echo "${file_contents//abc/XYZ}" > /tmp/file.txt
The whole file contents will be treated as one long string, including linebreaks.
XYZ can be a variable eg $replacement
, and one advantage of not using sed here is that you need not be concerned that the search or replace string might contain the sed pattern delimiter character (usually, but not necessarily, /). A disadvantage is not being able to use regular expressions or any of sed's more sophisticated operations.
We can easily place the background image in PercentFrameLayout using the ImageView. We have to set the scaleType attribute value="fitXY" and in the foreground we can also display other view's like textview or button.
<android.support.percent.PercentFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<ImageView
android:src="@drawable/logo"
android:id="@+id/im1"
android:scaleType="fitXY"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
<EditText android:layout_gravity="center_horizontal"
android:hint="Enter Username"
android:id="@+id/et1"
android:layout_height="wrap_content"
app:layout_widthPercent="50%"
app:layout_marginTopPercent="30%"
/>
<Button
android:layout_gravity="center_horizontal"
android:text="Login"
android:id="@+id/b1"
android:layout_height="wrap_content"
app:layout_widthPercent="50%"
app:layout_marginTopPercent="40%"/>
</android.support.percent.PercentFrameLayout>
According to the documentation, 'RefererNotAllowedMapError' means
The current URL loading the Google Maps JavaScript API has not been added to the list of allowed referrers. Please check the referrer settings of your API key on the Google Developers Console.
I have the Google Maps Embed API set up for my own personal/work use and thus far have not specified any HTTP referrers. I register no errors. Your settings must be making Google think the URL you're visiting is not registered or allowed.
Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.
To store bitmap in a file myImage in internal storage:
public String createImageFromBitmap(Bitmap bitmap) {
String fileName = "myImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
Then in the next activity you can decode this file myImage to a bitmap using following code:
//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));
Note A lot of checking for null and scaling bitmap's is ommited.
For some further information on how to determine the processing time, and a comparison of a few methods (some mentioned already in the answers of this post) - specifically, the difference between:
start = time.time()
versus the now obsolete (as of 3.3, time.clock() is deprecated)
start = time.clock()
see this other article on Stackoverflow here:
Python - time.clock() vs. time.time() - accuracy?
If nothing else, this will work good:
start = time.time()
... do something
elapsed = (time.time() - start)
I know of enabling or disabling wifi:
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);
where status may be true
or false
as per requirement.
Edit:
You also need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
For some programs setting the super secret __COMPAT_LAYER
environment variable to RunAsInvoker
will work.Check this :
set "__COMPAT_LAYER=RunAsInvoker"
start regedit.exe
Though like this there will be no UAC prompting the user will continue without admin permissions.
This should do the trick:
$('#thisElement').find('.classToSelect')
To add to the other answers:
Make sure you call setActionBar()
or setSupportActionBar()
in your onCreate()
method before calling the getActionBar()
:
Define some Toolbar in your activity.xml, then in the onCreate():
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
// Now you can use the get methods:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
numpy.random.randint
accepts a third argument (size
) , in which you can specify the size of the output array. You can use this to create your DataFrame
-
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
Here - np.random.randint(0,100,size=(100, 4))
- creates an output array of size (100,4)
with random integer elements between [0,100)
.
Demo -
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
which produces:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
4 90 38 34 93
5 0 94 45 10
6 58 23 23 60
.. .. .. .. ..
See this.
In [14]: re.match("mandy", "MaNdY", re.IGNORECASE)
Out[14]: <_sre.SRE_Match object at 0x23a08b8>
Try doing like this: array1.compare(array2)=true
Array.prototype.compare = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].compare(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
//finding a particular word any where inthe string and printing its index and occurence
class IndOc
{
public static void main(String[] args)
{
String s="this is hyderabad city and this is";
System.out.println("the given string is ");
System.out.println("----------"+s);
char ch[]=s.toCharArray();
System.out.println(" ----word is found at ");
int j=0,noc=0;
for(int i=0;i<ch.length;i++)
{
j=i;
if(ch[i]=='i' && ch[j+1]=='s')
{
System.out.println(" index "+i);
noc++;
}
}
System.out.println("----- no of occurences are "+noc);
}
}
Use match
to return your desired vector, then cbind
it to your matrix
cbind(t, z[, "symbol"][match(rownames(t), rownames(z))])
[,1] [,2] [,3] [,4]
GO.ID "GO:0002009" "GO:0030334" "GO:0015674" NA
LEVEL "8" "6" "7" NA
Annotated "342" "343" "350" NA
Significant "1" "1" "1" NA
Expected "0.07" "0.07" "0.07" NA
resultFisher "0.679" "0.065" "0.065" NA
ILMN_1652464 "0" "0" "1" "PLAC8"
ILMN_1651838 "0" "0" "0" "RND1"
ILMN_1711311 "1" "1" "0" NA
ILMN_1653026 "0" "0" "0" "GRA"
PS. Be warned that t
is base R function that is used to transpose matrices. By creating a variable called t, it can lead to confusion in your downstream code.
Good day,
I know I am late to this party, but let me show you my answer.
const [windowSize, setWindowSize] = useState(null)
useEffect(() => {
const handleResize = () => {
setWindowSize(window.innerWidth)
}
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [])
for future details visit https://usehooks.com/useWindowSize/
That would be the modulo operator, which produces the remainder of the division of two numbers.
UPDATED - January 2021
It's possible to store in a profile.ps1
file any PowerShell code to be executed each time PowerShell starts. There are at least 6 different paths where to store the code depending on which user has to execute it. We will consider only 2 of them: the "all users" and the "only your user" paths (follow the previous link for further options).
To answer your question, you only have to create a profile.ps1
file containing the code you want to be executed, that is:
New-Alias Goto Set-Location
and save it in the proper path:
"$Home\Documents"
(usually C:\Users<yourname>\Documents): Only your user will execute the code. This is the reccomanded place.echo $profile
in PowerShell$PsHome
(C:\Windows\System32\WindowsPowerShell\v1.0): Every user will execute the code.IMPORTANT: Remember you need to restart your PowerShell instances to apply the changes.
TIPS
If both paths contain a profile.ps1
file, the all-users one is executed first, then the user-specific one. This means the user-specific commands will overwrite variables in case of duplicates or conflicts.
Always put the code in the user-specific profile if there is no need to extend its execution to every user. This is safer because you don't pollute other users' space (usually, you don't want to do that).
Another advantage is that you don't need administrator rights to add the file to your user-space (you do for anything in C:\Windows\System32).
If you really need to execute the profile code for every user, mind that the $PsHome
path is different for 32bit and 64bit instances of PowerShell. You should consider both environments if you want to always execute the profile code.
The paths are:
C:\Windows\System32\WindowsPowerShell\v1.0
for the 64bit environmentC:\Windows\SysWow64\WindowsPowerShell\v1.0
for the 32bit one (Yeah I know, the folder naming is counterintuitive, but it's correct).@Jon: Jon, are you saying using multiple where clauses e.g.
var query = from r in tempData.AsEnumerable()
where r.Field<string>("UserName") != "XXXX"
where r.Field<string>("UserName") != "YYYY"
select r;
is more restictive than using
var query = from r in tempData.AsEnumerable()
where r.Field<string>("UserName") != "XXXX" && r.Field<string>("UserName") != "YYYY"
select r;
I think they are equivalent as far as the result goes.
However, I haven't tested, if using multiple where in the first example cause in 2 subqueries, i.e. .Where(r=>r.UserName!="XXXX").Where(r=>r.UserName!="YYYY)
or the LINQ translator is smart enought to execute .Where(r=>r.UserName!="XXXX" && r.UsernName!="YYYY")
Why dont you just do it in SQL?
DELETE FROM SomeTable
attr_accessor
is (as @pst stated) just a method. What it does is create more methods for you.
So this code here:
class Foo
attr_accessor :bar
end
is equivalent to this code:
class Foo
def bar
@bar
end
def bar=( new_value )
@bar = new_value
end
end
You can write this sort of method yourself in Ruby:
class Module
def var( method_name )
inst_variable_name = "@#{method_name}".to_sym
define_method method_name do
instance_variable_get inst_variable_name
end
define_method "#{method_name}=" do |new_value|
instance_variable_set inst_variable_name, new_value
end
end
end
class Foo
var :bar
end
f = Foo.new
p f.bar #=> nil
f.bar = 42
p f.bar #=> 42
For this purpose you need to match the location in your apache or any other service you are using
If you are using apache then in httpd.conf file.
<LocationMatch "/your_relative_path">
ProxyPass absolute_path_of_your_application/your_relative_path
ProxyPassReverse absolute_path_of_your_application/your_relative_path
</LocationMatch>
Double click and install the production certificate in your key chain. This might resolve the issue.
try this following snippet, its working fine.
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openfile1 = new OpenFileDialog();
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openfile1.FileName;
}
{
string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
OleDbConnection conn = new OleDbConnection(pathconn);
OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
DataTable dt = new DataTable();
MyDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch { }
}
To handle HTTP POST
request in Express.js version 4 and above, you need to install middleware module called body-parser
.
body-parser
extract the entire body portion of an incoming request stream and exposes it on req.body
.
The middleware was a part of Express.js earlier but now you have to install it separately.
This body-parser
module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST
request. Install body-parser
using NPM as shown below.
npm install body-parser --save
edit in 2019-april-2: in [email protected] the body-parser middleware bundled with express. for more details see this
const something = { bar: "Foobar!" };
const foo = 'bar';
something[\`${foo}\`];
you can return all rows and than use php datediff function inside an if statement, although that will put extra load on the server.
if(dateDiff(date("Y/m/d"), $row['date']) <=0 ){
}else{
echo " info here";
}
Here's a little function that will do "NATO encoding" for you:
CREATE FUNCTION dbo.NATOEncode (
@String varchar(max)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
WITH L1 (N) AS (SELECT 1 UNION ALL SELECT 1),
L2 (N) AS (SELECT 1 FROM L1, L1 B),
L3 (N) AS (SELECT 1 FROM L2, L2 B),
L4 (N) AS (SELECT 1 FROM L3, L3 B),
L5 (N) AS (SELECT 1 FROM L4, L4 C),
L6 (N) AS (SELECT 1 FROM L5, L5 C),
Nums (Num) AS (SELECT Row_Number() OVER (ORDER BY (SELECT 1)) FROM L6)
SELECT
NATOString = Substring((
SELECT
Convert(varchar(max), ' ' + D.Word)
FROM
Nums N
INNER JOIN (VALUES
('A', 'Alpha'),
('B', 'Beta'),
('C', 'Charlie'),
('D', 'Delta'),
('E', 'Echo'),
('F', 'Foxtrot'),
('G', 'Golf'),
('H', 'Hotel'),
('I', 'India'),
('J', 'Juliet'),
('K', 'Kilo'),
('L', 'Lima'),
('M', 'Mike'),
('N', 'November'),
('O', 'Oscar'),
('P', 'Papa'),
('Q', 'Quebec'),
('R', 'Romeo'),
('S', 'Sierra'),
('T', 'Tango'),
('U', 'Uniform'),
('V', 'Victor'),
('W', 'Whiskey'),
('X', 'X-Ray'),
('Y', 'Yankee'),
('Z', 'Zulu'),
('0', 'Zero'),
('1', 'One'),
('2', 'Two'),
('3', 'Three'),
('4', 'Four'),
('5', 'Five'),
('6', 'Six'),
('7', 'Seven'),
('8', 'Eight'),
('9', 'Niner')
) D (Digit, Word)
ON Substring(@String, N.Num, 1) = D.Digit
WHERE
N.Num <= Len(@String)
FOR XML PATH(''), TYPE
).value('.[1]', 'varchar(max)'), 2, 2147483647)
);
This function will work on even very long strings, and performs pretty well (I ran it against a 100,000-character string and it returned in 589 ms). Here's an example of how to use it:
SELECT NATOString FROM dbo.NATOEncode('LD-23DSP-1430');
-- Output: Lima Delta Two Three Delta Sierra Papa One Four Three Zero
I intentionally made it a table-valued function so it could be inlined into a query if you run it against many rows at once, just use CROSS APPLY
or wrap the above example in parentheses to use it as a value in the SELECT
clause (you can put a column name in the function parameter position).
Try this:
$("#test-element").on("click" ,function() {
alert("click");
});
The document way of doing it is weird too. That would make sense to me if used for a class selector, but in the case of an id you probably just have useless DOM traversing there. In the case of the id selector, you get that element instantly.
Well there are lot of answeres already provided and lot are making sense too.
Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.
I came across similar situation today and here is very simple query I came up with...
declare
begin
execute immediate '
create table "TBL" ("ID" number not null)';
exception when others then
if SQLCODE = -955 then null; else raise; end if;
end;
/
955 is failure code.
This is simple, if exception come while running query it will be suppressed. and you can use same for SQL
or Oracle
.
Adding this piece of code after the val() seems to work:
$(":input#single").trigger('change');
The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.
CONTIGUOUS NON-PRINTING Ruby Code
This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml
, etc.
This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>
DETAILS:
Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:
<%# if flash[:myErrors] %>
<%# if flash[:myErrors].any? %>
<%# if @post.id.nil? %>
<%# if @myPost!=-1 %>
<%# @post = @myPost %>
<%# else %>
<%# @post = Post.new %>
<%# end %>
<%# end %>
<%# end %>
<%# end %>
YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:
<%#
if flash[:myErrors] then
if flash[:myErrors].any? then
if @post.id.nil? then
if @myPost!=-1 then
@post = @myPost
else
@post = Post.new
end
end
end
end
%>
Just use this this decrypter to decrypt your locally cached username & password.
By default, TortoiseSVN stores your cached credentials inside files in the %APPDATA%\Subversion\auth\svn.simple directory. The passwords are encrypted using the Windows Data Protection API, with a key tied to your user account. This tool reads the files and uses the API to decrypt your passwords
You'll need to use a static
readonly
list instead. And if you want the list to be immutable then you might want to consider using ReadOnlyCollection<T>
rather than List<T>
.
private static readonly ReadOnlyCollection<string> _metrics =
new ReadOnlyCollection<string>(new[]
{
SourceFile.LOC,
SourceFile.MCCABE,
SourceFile.NOM,
SourceFile.NOA,
SourceFile.FANOUT,
SourceFile.FANIN,
SourceFile.NOPAR,
SourceFile.NDC,
SourceFile.CALLS
});
public static ReadOnlyCollection<string> Metrics
{
get { return _metrics; }
}
On Windows 10 Add this to your Path:
%APPDATA%\npm
This references the folder ~/AppData/Roaming/npm
[Assumes that you have already run npm install -g grunt-cli
]
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("parameter", "value").build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(url).client(httpClient.build()).build();
Check your ".env" file in the root folder. is it correct?
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
It's the other way round:
Vehicle[] car = new Vehicle[N];
This makes more sense, as the number of elements in the array isn't part of the type of car
, but it is part of the initialization of the array whose reference you're initially assigning to car
. You can then reassign it in another statement:
car = new Vehicle[10]; // Creates a new array
(Note that I've changed the type name to match Java naming conventions.)
For further information about arrays, see section 10 of the Java Language Specification.
First you need to define a LocationListener
to handle location changes.
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
}
};
Then get the LocationManager
and ask for location updates
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
And finally make sure that you have added the permission on the Manifest,
For using only network based location use this one
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
For GPS based location, this one
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
You can use the data attribute:
<div class="datepicker" data-date-start-date="+1d"></div>
It depends on your mark-up, but it can certainly be made to work, I used the following:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).siblings('p').slideToggle();
}
);
}
);
<table>
<thead>
<tr>
<th>Actor</th>
<th>Which Doctor</th>
<th>Significant companion</th>
</tr>
</thead>
<tbody>
<tr>
<td><h2>William Hartnell</h2></td>
<td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Patrick Troughton</h2></td>
<td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Jon Pertwee</h2></td>
<td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
</tbody>
</table>
The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp()
as the paragraphs were hidden, and still leave an element, h2
to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.
As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p
elements this would work:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).closest('tr').find('p').slideToggle();
}
);
}
);
If you're looking for the equivalent to background-size: cover
for video
.
video {
object-fit: cover;
}
This will fill the container without distorting the video.
PS: I'm extending on Leo Yu's answer here.
If your context is android application , then make sure your android device time is set to current date and time. The underlying exception is "The SSL certificates was not getting authenticated."
I'm not sure what you're trying to achieve, but you may want to consider using jQuery, which allows you to put your code in the head tag or a separate script file and still have the code executed after the DOM has loaded.
You can then do something like:
$(document).ready(function() {
$(document).remove();
});
as well as selectively removing elements (all DIVs, only DIVs with certain classes, etc.)
ONE OF THE approaches for compilers is to allocate a little more memory and store count of elements in the head element.
Example how it could be done: Here
int* i = new int[4];
compiler will allocate sizeof(int)*5 bytes.
int *temp = malloc(sizeof(int)*5)
Will store 4
in first sizeof(int)
bytes
*temp = 4;
and set i
i = temp + 1;
So i
points to array of 4 elements, not 5.
And
delete[] i;
will be processed following way
int *temp = i - 1;
int numbers_of_element = *temp; // = 4
... call destructor for numbers_of_element elements if needed
... that are stored in temp + 1, temp + 2, ... temp + 4
free (temp)
public class MyMap {
public static void main(String[] args) {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
map1.put("key2", "value2");
map1.put("key3", "value3");
map1.put(null, null);
Map<String, String> map2 = new HashMap<String, String>();
map2.put("key4", "value4");
map2.put("key5", "value5");
map2.put("key6", "value6");
map2.put("key3", "replaced-value-of-key3-in-map2");
// used only if map1 can be changes/updates with the same keys present in map2.
map1.putAll(map2);
// use below if you are not supposed to modify the map1.
for (Map.Entry e : map2.entrySet())
if (!map1.containsKey(e.getKey()))
map1.put(e.getKey().toString(), e.getValue().toString());
System.out.println(map1);
}}
As @Nils mentionned, you can use the update_fields
keyword argument of the save()
method to manually specify the fields to update.
obj_instance = Model.objects.get(field=value)
obj_instance.field = new_value
obj_instance.field2 = new_value2
obj_instance.save(update_fields=['field', 'field2'])
The update_fields
value should be a list of the fields to update as strings.
See https://docs.djangoproject.com/en/2.1/ref/models/instances/#specifying-which-fields-to-save
The closest thing to "for each" is probably MySQL Procedure using Cursor and LOOP.
key
is a function that will be called to transform the collection's items before they are compared. The parameter passed to key
must be something that is callable.
The use of lambda
creates an anonymous function (which is callable). In the case of sorted
the callable only takes one parameters. Python's lambda
is pretty simple. It can only do and return one thing really.
The syntax of lambda
is the word lambda
followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while
, for
, if
and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.
We can compare the use of lambda with that of def to create a function.
adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2
lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.
variable
is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.
Similar to Julien's answer above, I had success with the following:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
This solution might be more relevant if you want more control in matlab.
Solution inspired by: https://stackoverflow.com/a/52526454/10521959
yes please download curl-devel as instructed above. also don't forget to link to lib curl:
-L/path/of/curl/lib/libcurl.a (g++)
cheers
Although this is the accepted answer, toto_tico's answer below is better :)
Try making the onclick js use 'return' to ensure the desired return value gets used...
<button type="button" value="click me" onclick="return check_me();" />
Using your example, you could do:
public void doit(A a) {
if(a instanceof B) {
// needs to cast to B to access draw2 which isn't present in A
// note that this is probably not a good OO-design, but that would
// be out-of-scope for this discussion :)
((B)a).draw2();
}
a.draw();
}
Another great Treeview jquery plugin is http://www.jstree.com/
For an advance view you should check jquery-treetable
http://ludo.cubicphuse.nl/jquery-plugins/treeTable/doc/
Use the following command
remove(list=c("data_1", "data_2", "data_3"))
Change %
to %%
for use in batch file, for %~ta
syntax enter call /?
for %a in (MyFile.txt) do set FileDate=%~ta
Sample output:
for %a in (MyFile.txt) do set FileDate=%~ta
set FileDate=05/05/2020 09:47 AM
for %a in (file_not_exist_file.txt) do set FileDate=%~ta
set FileDate=
As Sven mentioned, x[[[0],[2]],[1,3]]
will give back the 0 and 2 rows that match with the 1 and 3 columns while x[[0,2],[1,3]]
will return the values x[0,1] and x[2,3] in an array.
There is a helpful function for doing the first example I gave, numpy.ix_
. You can do the same thing as my first example with x[numpy.ix_([0,2],[1,3])]
. This can save you from having to enter in all of those extra brackets.
startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');
In this case no conditionals are needed to set the variable.
This one-liner XPath expression:
boolean(joined-subclass)
is true()
only when the child of the current node, named joined-subclass
exists and it is false()
otherwise.
The complete stylesheet is:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="class">
<xsl:variable name="subexists"
select="boolean(joined-subclass)"
/>
subexists: <xsl:text/>
<xsl:value-of select="$subexists" />
</xsl:template>
</xsl:stylesheet>
Do note, that the use of the XPath function boolean()
in this expression is to convert a node (or its absense) to one of the boolean values true()
or false()
.
While iterating over a list or array with this method:
ar = [10, 11, 12]
for i in ar:
theSum = theSum + ar[i]
You are actually getting the values of list or array sequentially in i
variable.
If you print the variable i
inside the for loop
. You will get following output:
10
11
12
However, in your code you are confusing i
variable with index value of array. Therefore, while doing ar[i]
will mean ar[10]
for the first iteration. Which is of course index out of range throwing IndexError
Edit You can read this for better understanding of different methods of iterating over array or list in Python
If you want to clear all item you stored in localStorage then
localStorage.clear();
Use this for clear all stored key.
If you want to clear/remove only specific key/value then you can use removeItem(key).
localStorage.removeItem('yourKey');
Nested classes are cool for hiding implementation details.
List:
class List
{
public:
List(): head(nullptr), tail(nullptr) {}
private:
class Node
{
public:
int data;
Node* next;
Node* prev;
};
private:
Node* head;
Node* tail;
};
Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.
Look at std::list
or std::map
they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list
.
you can Use Window Or Linux Os
import os
os.system('cls')
os.system('clear')
you can use subprocess module
import subprocess as sp
x=sp.call('cls',shell=True)
You can use a std::map
to map the input to your enum
:
#include <iostream>
#include <string>
#include <map>
using namespace std;
enum level {easy, medium, hard};
map<string, level> levels;
void register_levels()
{
levels["easy"] = easy;
levels["medium"] = medium;
levels["hard"] = hard;
}
int main()
{
register_levels();
string input;
cin >> input;
switch( levels[input] )
{
case easy:
cout << "easy!"; break;
case medium:
cout << "medium!"; break;
case hard:
cout << "hard!"; break;
}
}
Think of it as the VM that has siloed the process the app or service is running in. The siloed environment has access to a bunch of underlying system information and certain permitted resources. You need that context to get at those services.
I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...
For example in order to change it's background to yellow:
$("#"+String(this.id)).css("background-color","yellow");
INSERT
INTO Employee
(emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT '001', 'John Doe', '1 River Walk, Green Street', state_id, position_id, manager_id
FROM dual
JOIN state s
ON s.state_name = 'New York'
JOIN positions p
ON p.position_name = 'Sales Executive'
JOIN manager m
ON m.manager_name = 'Barry Green'
Note that but a single spelling mistake (or an extra space) will result in a non-match and nothing will be inserted.
You can also use a filler to fill the remaining space.
<div class="main">
<div class="a"><a href="#">Home</a></div>
<div class="b"><a href="#">Some title centered</a></div>
<div class="filler"></div>
<div class="c"><a href="#">Contact</a></div>
</div>
.filler{
flex-grow: 1;
}
I have updated the solution with 3 different versions. This because of the discussion of the validity of using an additional filler element. If you run the code snipped you see that all solutions do different things. For instance setting the filler class on item b will make this item fill the remaining space. This has the benefit that there is no 'dead' space that is not clickable.
<div class="mainfiller">_x000D_
<div class="a"><a href="#">Home</a></div>_x000D_
<div class="b"><a href="#">Some title centered</a></div>_x000D_
<div class="filler"></div>_x000D_
<div class="c"><a href="#">Contact</a></div>_x000D_
</div>_x000D_
_x000D_
<div class="mainfiller">_x000D_
<div class="a"><a href="#">Home</a></div>_x000D_
<div class="filler b"><a href="#">Some title centered</a></div>_x000D_
<div class="c"><a href="#">Contact</a></div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
<div class="main">_x000D_
<div class="a"><a href="#">Home</a></div>_x000D_
<div class="b"><a href="#">Some title centered</a></div>_x000D_
<div class="c"><a href="#">Contact</a></div>_x000D_
</div>_x000D_
_x000D_
<style>_x000D_
.main { display: flex; justify-content: space-between; }_x000D_
.mainfiller{display: flex;}_x000D_
.filler{flex-grow:1; text-align:center}_x000D_
.a, .b, .c { background: yellow; border: 1px solid #999; }_x000D_
</style>
_x000D_
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.
Quotation:
If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie response header, and sent in the Cookie header) as applicable.
Try this library:
https://github.com/avast/android-styled-dialogs
It's based on DialogFragments
instead of AlertDialogs
(like the one from @afollestad). The main advantage: Dialogs don't dismiss after rotation and callbacks still work.
Use a return statement!
return;
or
if (condition) return;
You don't need to (and can't) specify any values, if your method returns void
.
use "Content-type: application/x-www-form-urlencoded" instead of "application/json"
brew help
will show you the list of commands that are available.
brew list
will show you the list of installed packages. You can also append formulae, for example brew list postgres
will tell you of files installed by postgres (providing it is indeed installed).
brew search <search term>
will list the possible packages that you can install. brew search post
will return multiple packages that are available to install that have post in their name.
brew info <package name>
will display some basic information about the package in question.
You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)
This way you don't have to use any magic numbers:
os.MkdirAll(newPath, os.ModePerm)
Also, rather than using + to create paths, you can use:
import "path/filepath"
path := filepath.Join(someRootPath, someSubPath)
The above uses the correct separators automatically on each platform for you.
You can append array of Data at the end of custom state:
const [vehicleData, setVehicleData] = React.useState<any[]>([]);
setVehicleData(old => [...old, ...newArrayData]);
For example, In below, you appear an example of axios:
useEffect(() => {
const fetchData = async () => {
const result = await axios(
{
url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
method: 'get',
}
);
setVehicleData(old => [...old, ...result.data.data]);
};
fetchData();
}, [page]);
You can set this at boot by adding the "elevator" parameter to the kernel cmdline (such as in grub.cfg)
Example:
elevator=deadline
This will make "deadline" the default I/O scheduler for all block devices.
If you'd like to query or change the scheduler after the system has booted, or would like to use a different scheduler for a specific block device, I recommend installing and use the tool ioschedset to make this easy.
https://github.com/kata198/ioschedset
If you're on Archlinux it's available in aur:
https://aur.archlinux.org/packages/ioschedset
Some example usage:
# Get i/o scheduler for all block devices
[username@hostname ~]$ io-get-sched
sda: bfq
sr0: bfq
# Query available I/O schedulers
[username@hostname ~]$ io-set-sched --list
mq-deadline kyber bfq none
# Set sda to use "kyber"
[username@hostname ~]$ io-set-sched kyber /dev/sda
Must be root to set IO Scheduler. Rerunning under sudo...
[sudo] password for username:
+ Successfully set sda to 'kyber'!
# Get i/o scheduler for all block devices to assert change
[username@hostname ~]$ io-get-sched
sda: kyber
sr0: bfq
# Set all block devices to use 'deadline' i/o scheduler
[username@hostname ~]$ io-set-sched deadline
Must be root to set IO Scheduler. Rerunning under sudo...
+ Successfully set sda to 'deadline'!
+ Successfully set sr0 to 'deadline'!
# Get the current block scheduler just for sda
[username@hostname ~]$ io-get-sched sda
sda: mq-deadline
Usage should be self-explanatory. The tools are standalone and only require bash.
Hope this helps!
EDIT: Disclaimer, these are scripts I wrote.
As documented in ?legend
you do this like so:
plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)
Line breaks are achieved with the new line character \n
. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.
Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).
If by "checked out" you mean people who have cloned your project, then no it is not possible. You don't even need to be a GitHub user to clone a repository, so it would be infeasible to track this.
just give
a{
color:blue
}
even if its is visited it will always be blue
To restart a running service:
net stop "service name" && net start "service name"
However, if you don't know if the service is running in the first place and want to restart or start it, use this:
net stop "service name" & net start "service name"
This works if the service is already running or not.
For reference, here is the documentation on conditional processing symbols.
@Tim's answer only does half the work -- that gets it into a datetime.datetime object.
To get it into the string format you require, you use datetime.strftime:
print(datetime.strftime('%b %d,%Y'))
According to Javascript Date Documentation, you can easily do this way:
var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);
And don't worry about if hours you set will be out of 0..23
range.
Date() object will update the date accordingly.
Inspired by Eric's answer, here is my solution to this problem for selenium 3.7.0. Compared with the solution at http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/, the advantage is that there won't be a blank browser window each time I connect to the existing session.
import warnings
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.remote.errorhandler import ErrorHandler
from selenium.webdriver.remote.file_detector import LocalFileDetector
from selenium.webdriver.remote.mobile import Mobile
from selenium.webdriver.remote.remote_connection import RemoteConnection
from selenium.webdriver.remote.switch_to import SwitchTo
from selenium.webdriver.remote.webdriver import WebDriver
# This webdriver can directly attach to an existing session.
class AttachableWebDriver(WebDriver):
def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities=None, browser_profile=None, proxy=None,
keep_alive=False, file_detector=None, session_id=None):
"""
Create a new driver that will issue commands using the wire protocol.
:Args:
- command_executor - Either a string representing URL of the remote server or a custom
remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'.
- desired_capabilities - A dictionary of capabilities to request when
starting the browser session. Required parameter.
- browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object.
Only used if Firefox is requested. Optional.
- proxy - A selenium.webdriver.common.proxy.Proxy object. The browser session will
be started with given proxy settings, if possible. Optional.
- keep_alive - Whether to configure remote_connection.RemoteConnection to use
HTTP keep-alive. Defaults to False.
- file_detector - Pass custom file detector object during instantiation. If None,
then default LocalFileDetector() will be used.
"""
if desired_capabilities is None:
raise WebDriverException("Desired Capabilities can't be None")
if not isinstance(desired_capabilities, dict):
raise WebDriverException("Desired Capabilities must be a dictionary")
if proxy is not None:
warnings.warn("Please use FirefoxOptions to set proxy",
DeprecationWarning)
proxy.add_to_capabilities(desired_capabilities)
self.command_executor = command_executor
if type(self.command_executor) is bytes or isinstance(self.command_executor, str):
self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive)
self.command_executor._commands['GET_SESSION'] = ('GET', '/session/$sessionId') # added
self._is_remote = True
self.session_id = session_id # added
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
if browser_profile is not None:
warnings.warn("Please use FirefoxOptions to set browser profile",
DeprecationWarning)
if session_id:
self.connect_to_session(desired_capabilities) # added
else:
self.start_session(desired_capabilities, browser_profile)
self._switch_to = SwitchTo(self)
self._mobile = Mobile(self)
self.file_detector = file_detector or LocalFileDetector()
self.w3c = True # added hardcoded
def connect_to_session(self, desired_capabilities):
response = self.execute('GET_SESSION', {
'desiredCapabilities': desired_capabilities,
'sessionId': self.session_id,
})
# self.session_id = response['sessionId']
self.capabilities = response['value']
To use it:
if use_existing_session:
browser = AttachableWebDriver(command_executor=('http://%s:4444/wd/hub' % ip),
desired_capabilities=(DesiredCapabilities.INTERNETEXPLORER),
session_id=session_id)
self.logger.info("Using existing browser with session id {}".format(session_id))
else:
browser = AttachableWebDriver(command_executor=('http://%s:4444/wd/hub' % ip),
desired_capabilities=(DesiredCapabilities.INTERNETEXPLORER))
self.logger.info('New session_id : {}'.format(browser.session_id))
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
The simplest way is to use itertools.product
:
a = ["foo", "melon"]
b = [True, False]
c = list(itertools.product(a, b))
>> [("foo", True), ("foo", False), ("melon", True), ("melon", False)]
b = email.message_from_string(a)
if b.is_multipart():
for payload in b.get_payload():
# if payload.is_multipart(): ...
print payload.get_payload()
else:
print b.get_payload()
You need to manually filter input to constructors and setters. Well... you could use reflection but I wouldn't advise it. Part of the job of constructors and setters is to validate input. That can include things like:
public void setPrice(double price) {
if (price < 0.0d) {
throw new IllegalArgumentException("price cannot be negative " + price);
}
this.price = price;
}
and
public void setName(String name) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name;
}
You could use wrapper functions for the actual check and throwing the exception.
I know of two ways to do it.
Method 1
The first method (which I prefer) is to use msbuild:
msbuild project.sln /Flags...
Method 2
You can also run:
vcexpress project.sln /build /Flags...
The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.
Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).
So, the end result might be:
os.system("msbuild project.sln /p:Configuration=Debug")
You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).
Workarounds are not solutions, therefore the answer is "No".
Still looking for workarounds, here are possible solutions: http://support.code42.com/CrashPlan/Latest/Troubleshooting/Windows_File_Paths_Longer_Than_255_Characters
This is probably how you should do it:
void push(std::string&& filename)
{
{
std::lock_guard<std::mutex> lock(qMutex);
q.push(std::move(filename));
}
populatedNotifier.notify_one();
}
bool try_pop(std::string& filename, std::chrono::milliseconds timeout)
{
std::unique_lock<std::mutex> lock(qMutex);
if(!populatedNotifier.wait_for(lock, timeout, [this] { return !q.empty(); }))
return false;
filename = std::move(q.front());
q.pop();
return true;
}
Some useful bits and pieces:
Here's how to do it mostly in code:
Binding b = new Binding();
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, this.GetType(), 1);
b.Path = new PropertyPath("MyElementThatNeedsBinding");
MyLabel.SetBinding(ContentProperty, b);
I largely copied this from Binding Relative Source in code Behind.
Also, the MSDN page is pretty good as far as examples go: RelativeSource Class
call concat
and pass param axis=1
to concatenate column-wise:
In [5]:
pd.concat([df_a,df_b], axis=1)
Out[5]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
There is a useful guide to the various methods of merging, joining and concatenating online.
For example, as you have no clashing columns you can merge
and use the indices as they have the same number of rows:
In [6]:
df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
And for the same reasons as above a simple join
works too:
In [7]:
df_a.join(df_b)
Out[7]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.
Angular 5 Solution:
import {HttpClient} from '@angular/common/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = {} as any; // Set any options you like
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.httpClient.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Angular 4 Solution:
// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = new RequestOptions();
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.http.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Joins can only be used when there is an association between entities. Your Employee entity should not have a field named id_team
, of type int
, mapped to a column. It should have a ManyToOne association with the Team entity, mapped as a JoinColumn:
@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;
Then, the following query will work flawlessly:
select e from Employee e inner join e.team
Which will load all the employees, except those that aren't associated to any team.
The same goes for all the other fields which are a foreign key to some other table mapped as an entity, of course (id_boss
, id_profession
).
It's time for you to read the Hibernate documentation, because you missed an extremely important part of what it is and how it works.
in your code, at line
map.setCenter(new GLatLng(lat, lon), 5);
the setCenter method takes just one parameter, for the lat:long location. Why are you passing two parameters there ?
I suggest you should change it to,
map.setCenter(new GLatLng(lat, lon));