Set editable
to False
and default
to your default value.
http://docs.djangoproject.com/en/stable/ref/models/fields/#editable
b = models.CharField(max_length=7, default='0000000', editable=False)
Also, your id
field is unnecessary. Django will add it automatically.
Compatibility with older browsers can be a drag, so be adviced.
If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.
Change left and right values to meet your requirement.
Thank you.
Hope this helps.
#container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
width: 100px;_x000D_
flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
width: 100px;_x000D_
flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
flex: 1;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
background: orange;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="column left">this is left</div>_x000D_
<div class="column center">this is center</div>_x000D_
<div class="column right">this is right</div>_x000D_
</div>
_x000D_
Updating the NodeJS https://nodejs.org/en/ Fixed My Issue.
Run npm install -g npm
& npm cache clean
Thanks @Arnaud & @Conny for highlighting this answer. This really helped me.
I would like to add one more thing here is, adding this line <meta http-equiv="x-ua-compatible" content="IE=edge">
just after the title in tag prior to all meta tags is must for to work as it overrides the compatibility mode of IE.
Here is a example of embedding without an iFrame:
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
<embed
src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
wmode="transparent"
type="video/mp4"
width="100%" height="100%"
allow="autoplay; encrypted-media; picture-in-picture"
allowfullscreen
title="Keyboard Cat"
>
</div>
_x000D_
compare to regular iframe "embed" code from YouTube:
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
_x000D_
and as far as HTML5 goes, use <object>
tag like so (corrected):
<object
style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
I had the same problem. I used a trigger and in that trigger I called a procedure which computed some values into 2 OUT variables. When I tried to print the result in the trigger body, nothing showed on screen. But then I solved this problem by making 2 local variables in a function, computed what I need with them and finally, copied those variables in your OUT procedure variables. I hope it'll be useful and successful!
You can try this one:
String newFileName = "my-image";
File imageFile = new File("/users/victor/images/image.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();
You can increase client_max_body_size and upload_max_filesize + post_max_size all day long. Without adjusting HTTP timeout it will never work.
//You need to adjust this, and probably on PHP side also. client_body_timeout 2min // 1GB fileupload
Novoda also has a great lazy image loading library and many apps like Songkick, Podio, SecretDJ and ImageSearch use their library.
Their library is hosted here on Github and they have a pretty active issues tracker as well. Their project seems to be pretty active too, with over 300+ commits at the time of writing this reply.
One thing to check for...
If your class is defined as a typedef:
typedef struct myclass { };
Then you try to refer to it as struct myclass
anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from:
typedef struct mystruct {}...
struct mystruct *myvar = value;
Instead use...
mystruct *myvar = value;
Common mistake.
Try something like:
SELECT id, NewsHeadline as news_headline, NewsText as news_text, state CreatedDate as created_on
FROM News
WHERE CreatedDate >= DATEADD(day,-7, GETDATE())
For security reasons, you can't move the mouse pointer with javascript, nor simulate a click with it.
What is it that you are trying to accomplish?
1) Instead of PreparedStatement
use Statement
2) After executing query in ResultSet
, extract values with the help of rs.getString()
as :
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
rs.getString(1); //or rs.getString("column name");
}
What is the difference?
From the documentation:
- - (Boolean)
instance_of?(class)
- Returns
true
ifobj
is an instance of the given class.
and:
- - (Boolean)
is_a?(class)
- (Boolean)kind_of?(class)
- Returns
true
ifclass
is the class ofobj
, or ifclass
is one of the superclasses ofobj
or modules included inobj
.
If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.
When should I use which?
Never. Use polymorphism instead.
Why are there so many of them?
I wouldn't call two "many". There are two of them, because they do two different things.
As other posters have pointed out, there are some limitations with the AWS Transfer for SFTP service. You need to closely align requirements. For example, there are no quotas, whitelists/blacklists, file type limits, and non key based access requires external services. There is also a certain overhead relating to user management and IAM, which can get to be a pain at scale.
We have been running an SFTP S3 Proxy Gateway for about 5 years now for our customers. The core solution is wrapped in a collection of Docker services and deployed in whatever context is needed, even on-premise or local development servers. The use case for us is a little different as our solution is focused data processing and pipelines vs a file share. In a Salesforce example, a customer will use SFTP as the transport method sending email, purchase...data to an SFTP/S3 enpoint. This is mapped an object key on S3. Upon arrival, the data is picked up, processed, routed and loaded to a warehouse. We also have fairly significant auditing requirements for each transfer, something the Cloudwatch logs for AWS do not directly provide.
As other have mentioned, rolling your own is an option too. Using AWS Lightsail you can setup a cluster, say 4, of $10 2GB instances using either Route 53 or an ELB.
In general, it is great to see AWS offer this service and I expect it to mature over time. However, depending on your use case, alternative solutions may be a better fit.
I have wrote a generic function in which you can pass context, icon is id drawable/mipmap image icon and new color which you need for that icon.
This function returns a drawable.
public static Drawable changeDrawableColor(Context context,int icon, int newColor) {
Drawable mDrawable = ContextCompat.getDrawable(context, icon).mutate();
mDrawable.setColorFilter(new PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN));
return mDrawable;
}
changeDrawableColor(getContext(),R.mipmap.ic_action_tune, Color.WHITE);
A final
variable means that it can be instantiated only one time.
in Java you can't use non-final variables in lambda as well as in anonymous inner classes.
You can refactor your code with the old for-each loop:
private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
try {
for(Component component : cal.getComponents().getComponents("VTIMEZONE")) {
VTimeZone v = (VTimeZone) component;
v.getTimeZoneId();
if(calTz==null) {
calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
}
}
} catch (Exception e) {
log.warn("Unable to determine ical timezone", e);
}
return null;
}
Even if I don't get the sense of some pieces of this code:
v.getTimeZoneId();
without using its return valuecalTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
you don't modify the originally passed calTz
and you don't use it in this methodnull
, why don't you set void
as return type?Hope also these tips helps you to improve.
To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.
Below code will only print files within directory and exclude directories within given directory while traversing.
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
DIR *d;
struct dirent *dir;
char path[1000]="/home/joy/Downloads";
d = opendir(path);
char full_path[1000];
if (d)
{
while ((dir = readdir(d)) != NULL)
{
//Condition to check regular file.
if(dir->d_type==DT_REG){
full_path[0]='\0';
strcat(full_path,path);
strcat(full_path,"/");
strcat(full_path,dir->d_name);
printf("%s\n",full_path);
}
}
closedir(d);
}
return(0);
}
To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.
Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:
RGB
:
To shade:
newR = currentR * (1 - shade_factor)
newG = currentG * (1 - shade_factor)
newB = currentB * (1 - shade_factor)
To tint:
newR = currentR + (255 - currentR) * tint_factor
newG = currentG + (255 - currentG) * tint_factor
newB = currentB + (255 - currentB) * tint_factor
More generally, the color resulting in layering a color RGB(currentR,currentG,currentB)
with a color RGBA(aR,aG,aB,alpha)
is:
newR = currentR + (aR - currentR) * alpha
newG = currentG + (aG - currentG) * alpha
newB = currentB + (aB - currentB) * alpha
where (aR,aG,aB) = black = (0,0,0)
for shading, and (aR,aG,aB) = white = (255,255,255)
for tinting
HSV
or HSB
:
Value
/ Brightness
or increase the Saturation
Saturation
or increase the Value
/ Brightness
HSL
:
Lightness
Lightness
There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB
and want to use the HSV
model to shade for example, you can just convert to HSV
, do the shading and convert back to RGB
. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :
RGB
has the advantage of being really simple to implement, but:
HSV
or HSB
is kind of complex because you need to play with two parameters to get what you want (Saturation
& Value
/ Brightness
)HSL
is the best from my point of view:
50%
means an unaltered Hue>50%
means the Hue is lighter (tint)<50%
means the Hue is darker (shade)Lightness
part)The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:
CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)
If you're using Windows it will not let you create a file without a filename in Windows Explorer. It will give you the error "You must type a file name" if you try to rename a text file as .gitignore
To get around this I used the following steps
ren gitignore.txt .gitignore
Alternatively @HenningCash suggests in the comments
You can get around this Windows Explorer error by appending a dot to the filename without extension: .gitignore. will be automatically changed to .gitignore
You can to do it this way:
string Camnr = "", Klantnr = "", ... // or String.Empty
Or you could declare them all first and then in the next line use your way.
These two loops are equivalent (bar the safety railings of course):
for ($i=0; $i<count($things); $i++) { ... }
foreach ($things as $i=>$thing) { ... }
eg
for ($i=0; $i<count($things); $i++) {
echo "Thing ".$i." is ".$things[$i];
}
foreach ($things as $i=>$thing) {
echo "Thing ".$i." is ".$thing;
}
I would simply do this, which literally follows what your desired logic was:
df.groupby(['org']).mean().groupby(['cluster']).mean()
Its not that hard to replicate in javascript :-) , though it will only work for width and height the best but you can expand it as per your expectations :-)
function calcShim(element,property,expression){
var calculated = 0;
var freed_expression = expression.replace(/ /gi,'').replace("(","").replace(")","");
// Remove all the ( ) and spaces
// Now find the parts
var parts = freed_expression.split(/[\*+-\/]/gi);
var units = {
'px':function(quantity){
var part = 0;
part = parseFloat(quantity,10);
return part;
},
'%':function(quantity){
var part = 0,
parentQuantity = parseFloat(element.parent().css(property));
part = parentQuantity * ((parseFloat(quantity,10))/100);
return part;
} // you can always add more units here.
}
for( var i = 0; i < parts.length; i++ ){
for( var unit in units ){
if( parts[i].indexOf(unit) != -1 ){
// replace the expression by calculated part.
expression = expression.replace(parts[i],units[unit](parts[i]));
break;
}
}
}
// And now compute it. though eval is evil but in some cases its a good friend.
// Though i wish there was math. calc
element.css(property,eval(expression));
}
Here is yet another approach, which was more convenient in my case (I just wanted to drop root privileges and do the rest of my script from restricted user): you can make the script restart itself from correct user. Let's suppose it is run as root initially. Then it will look like this:
#!/bin/bash
if [ $UID -eq 0 ]; then
user=$1
dir=$2
shift 2 # if you need some other parameters
cd "$dir"
exec su "$user" "$0" -- "$@"
# nothing will be executed beyond that line,
# because exec replaces running process with the new one
fi
echo "This will be run from user $UID"
...
TL;DR
To store "abc"
into $foo
:
echo "abc" | read foo
But, because pipes create forks, you have to use $foo
before the pipe ends, so...
echo "abc" | ( read foo; date +"I received $foo on %D"; )
Sure, all these other answers show ways to not do what the OP asked, but that really screws up the rest of us who searched for the OP's question.
read
command.# I would usually do this on one line, but for readability...
series | of | commands \
| \
(
read string;
mystic_command --opt "$string" /path/to/file
) \
| \
handle_mystified_file
Let's pretend that the series | of | commands
is a very complicated series of piped commands.
mystic_command
can accept the content of a file as stdin in lieu of a file path, but not the --opt
arg therefore it must come in as a variable. The command outputs the modified content and would commonly be redirected into a file or piped to another command. (E.g. sed
, awk
, perl
, etc.)
read
takes stdin and places it into the variable $string
Putting the read
and the mystic_command
into a "sub shell" via parenthesis is not necessary but makes it flow like a continuous pipe as if the 2 commands where in a separate script file.
There is always an alternative, and in this case the alternative is ugly and unreadable compared to my example above.
# my example above as a oneliner
series | of | commands | (read string; mystic_command --opt "$string" /path/to/file) | handle_mystified_file
# ugly and unreadable alternative
mystic_command --opt "$(series | of | commands)" /path/to/file | handle_mystified_file
My way is entirely chronological and logical. The alternative starts with the 4th command and shoves commands 1, 2, and 3 into command substitution.
I have a real world example of this in this script but I didn't use it as the example above because it has some other crazy/confusing/distracting bash magic going on also.
Use the oncontextmenu
event.
Here's an example:
<div oncontextmenu="javascript:alert('success!');return false;">
Lorem Ipsum
</div>
And using event listeners (credit to rampion from a comment in 2011):
el.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success!');
return false;
}, false);
Don't forget to return false, otherwise the standard context menu will still pop up.
If you are going to use a function you've written rather than javascript:alert("Success!")
, remember to return false in BOTH the function AND the oncontextmenu
attribute.
Map
is an interface; HashMap
is a particular implementation of that interface.
HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.
As said, the browser doesn't let the server know when it closes.
Still, there are some ways to achieve close to this behavior. You can put a small AJAX script in place that updates the server regularly that the browser is open. You should pair this with something that fires on actions made by the user, so you can time out an idle session as well as one that has closed out.
NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
The XML declaration in the document map consists of the following:
The version number, ?xml version="1.0"?.
This is mandatory. Although the number might change for future versions of XML, 1.0 is the current version.
The encoding declaration,
encoding="UTF-8"?
This is optional. If used, the encoding declaration must appear immediately after the version information in the XML declaration, and must contain a value representing an existing character encoding.
How are you doing the compiling and linking? You'll need to specify both files, something like:
gcc testpoint.c point.c
...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main
. You'll need/want to eliminate one (undoubtedly the one in point.c).
In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make
to do the work. In this case you'd have something like this:
OBJS=testpoint.o point.o
testpoint.exe: $(OBJS)
gcc $(OJBS)
The first is just a macro for the names of the object files. You get it expanded with $(OBJS)
. The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.
Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:
.c.o:
$(CC) -c $(CFLAGS) $<
This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc
) and allows you to specify any flags you care about in a macro named CFLAGS
(e.g., CFLAGS=-O3
to turn on optimization) and $<
is a special macro that expands to the name of the source file.
You typically store this in a file named Makefile
, and to build your program, you just type make
at the command line. It implicitly looks for a file named Makefile
, and runs whatever rules it contains.
The good point of this is that make
automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).
Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.
server.close() takes a while to close the connection, thus we should make this an asynchronous call as such:
await server.close();
IMPORTANT: when using await, we must use the async keyword in our encapsulating function as such:
async () => {
await server.close();
}
Create WScript.Shell object and invoke Run() method on it.
http://msdn.microsoft.com/en-us/library/d5fk67ky(v=vs.85).aspx
First, don't do it that way. The best approach is to use find -exec
properly:
# this is safe
find test -type d -exec echo '{}' +
The other safe approach is to use NUL-terminated list, though this requires that your find support -print0
:
# this is safe
while IFS= read -r -d '' n; do
printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d -print0)
You can also populate an array from find, and pass that array later:
# this is safe
declare -a myarray
while IFS= read -r -d '' n; do
myarray+=( "$n" )
done < <(find test -mindepth 1 -type d -print0)
printf '%q\n' "${myarray[@]}" # printf is an example; use it however you want
If your find doesn't support -print0
, your result is then unsafe -- the below will not behave as desired if files exist containing newlines in their names (which, yes, is legal):
# this is unsafe
while IFS= read -r n; do
printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d)
If one isn't going to use one of the above, a third approach (less efficient in terms of both time and memory usage, as it reads the entire output of the subprocess before doing word-splitting) is to use an IFS
variable which doesn't contain the space character. Turn off globbing (set -f
) to prevent strings containing glob characters such as []
, *
or ?
from being expanded:
# this is unsafe (but less unsafe than it would be without the following precautions)
(
IFS=$'\n' # split only on newlines
set -f # disable globbing
for n in $(find test -mindepth 1 -type d); do
printf '%q\n' "$n"
done
)
Finally, for the command-line parameter case, you should be using arrays if your shell supports them (i.e. it's ksh, bash or zsh):
# this is safe
for d in "$@"; do
printf '%s\n' "$d"
done
will maintain separation. Note that the quoting (and the use of $@
rather than $*
) is important. Arrays can be populated in other ways as well, such as glob expressions:
# this is safe
entries=( test/* )
for d in "${entries[@]}"; do
printf '%s\n' "$d"
done
I was working on a JSON format for log appenders and ended up here trying to solve a similar problem. After a while, I realized I could just make Node do the work:
const util = require("util");
...
return JSON.stringify(obj, (name, value) => {
if (value instanceof Error) {
return util.format(value);
} else {
return value;
}
}
When a there are 2 columns for primary keys they make up a composite primary key therefore you have to make sure that in the table that is being referenced there are also 2 columns of the same data type.
While many of the suggestions work when converting 2 -> 4 space. I ran into some issues when converting 4 -> 2.
Here's what I ended up using:
Sublime Text 3/Packages/User/to-2.sublime-macro
[
{ "args": null, "command": "select_all" },
{ "args": { "set_translate_tabs": true }, "command": "unexpand_tabs" },
{ "args": { "setting": "tab_size", "value": 1 }, "command": "set_setting" },
{ "args": { "set_translate_tabs": true }, "command": "expand_tabs" },
{ "args": { "setting": "tab_size", "value": 2 }, "command": "set_setting" }
]
Drawing an image using a QLabel
seems like a bit of a kludge to me. With newer versions of Qt you can use a QGraphicsView
widget. In Qt Creator, drag a Graphics View
widget onto your UI and name it something (it is named mainImage
in the code below). In mainwindow.h
, add something like the following as private
variables to your MainWindow
class:
QGraphicsScene *scene;
QPixmap image;
Then just edit mainwindow.cpp
and make the constructor something like this:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
image.load("myimage.png");
scene = new QGraphicsScene(this);
scene->addPixmap(image);
scene->setSceneRect(image.rect());
ui->mainImage->setScene(scene);
}
First, launch your Safari browser from the Home screen and go to the webpage that you want to view full screen.
After locating the webpage, tap on the arrow icon at the top of your screen.
In the drop-down menu, tap on the Add to Home Screen option.
The Add to Home window should be displayed. You can customize the description that will appear as a title on the home screen of your iPad. When you are done, tap on the Add button.
A new icon should now appear on your home screen. Tapping on the icon will open the webpage in the fullscreen mode.
Note: The icon on your iPad home screen only opens the bookmarked page in the fullscreen mode. The next page you visit will be contain the Safari address and title bars. This way of playing your webpage or HTML5 presentation in the fullscreen mode works if the source code of the webpage contains the following tag:
<meta name="apple-mobile-web-app-capable" content="yes">
You can add this tag to your webpage using a third-party tool, for example iWeb SEO Tool or any other you like. Please note that you need to add the tag first, refresh the page and then add a bookmark to your home screen.
In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:
Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase
Just another approach:
SELECT col1 * 1.0 / col2 FROM tbl1
Multiplying by 1.0 turns an integer into a float numeric(13,1) and so works like a typecast, but most probably it is slower than that.
A slightly shorter variation suggested by Aleksandr Fedorenko in a comment:
SELECT col1 * 1. / col2 FROM tbl1
The effect would be basically the same. The only difference is that the multiplication result in this case would be numeric(12,0).
Principal advantage: less wordy than other approaches.
From what I've seen of this the following is true for Firefox and Chrome;
1) If you have a HTML page open from a remote host then file://
links will not work i.e. Your address bar reads http://someserver.domain
and the page contains a link such as <a href="file:///S:/sharedfile.txt">
2) If you have a HTML page open from your local host then file://
links will work i.e. your address bar reads file:///C:/mydir/index.html
and the page contains a link such as <a href="file:///S:/sharedfile.txt">
For Internet Explorer point 1) does not hold true. A file on your local host can be accessed using the file://
link syntax from a webpage on a remote host. This is considered a security flaw in IE(By who? References?) (and it's there in IE8 too) because a remote host can access files on your local computer without your knowledge .... admittedly they have to get lucky with the filename but there are plenty of commonly named files there with the potential to contain personal/private information.
For Kotlin users, I created a ImageStorageManager
class which will handle save, get and delete actions for images easily:
class ImageStorageManager {
companion object {
fun saveToInternalStorage(context: Context, bitmapImage: Bitmap, imageFileName: String): String {
context.openFileOutput(imageFileName, Context.MODE_PRIVATE).use { fos ->
bitmapImage.compress(Bitmap.CompressFormat.PNG, 25, fos)
}
return context.filesDir.absolutePath
}
fun getImageFromInternalStorage(context: Context, imageFileName: String): Bitmap? {
val directory = context.filesDir
val file = File(directory, imageFileName)
return BitmapFactory.decodeStream(FileInputStream(file))
}
fun deleteImageFromInternalStorage(context: Context, imageFileName: String): Boolean {
val dir = context.filesDir
val file = File(dir, imageFileName)
return file.delete()
}
}
}
Read more here
Strictly speaking you shouldn't need to use !important if you've structured your CSS well and don't have too many degrees of specificity.
The most appropriate time to use !important is when you have one exceptional style that you want to style outside of your site's normal cascade.
The right query:
drop table #tmp_table
select new_acc_no, count(new_acc_no) as count1
into #tmp_table
from table
where unit_id = '0007'
group by unit_id, new_acc_no
having count(new_acc_no) > 1
a += b
is in this case the same as
a = a + b
In this case cnt += 1 means that cnt is increased by one.
Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.
Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.
The windows equivalent to the diff command is the fc (File Comapre) command.
Here are the basic steps to do so:
1. Keep the two files in a folder (Example file1.html and file2.html)
2. Launch command prompt
3. Type fc file1Location file2Location
Have found a detailed tutorial on the same:
http://www.howtogeek.com/206123/how-to-use-fc-file-compare-from-the-windows-command-prompt/
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
.queue()
and .dequeue()
Queues in jQuery are used for animations. You can use them for any purpose you like. They are an array of functions stored on a per element basis, using jQuery.data()
. They are First-In-First-Out (FIFO). You can add a function to the queue by calling .queue()
, and you remove (by calling) the functions using .dequeue()
.
To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is .delay()
:
$.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
};
fx
The default queue in jQuery is fx
. The default queue has some special properties that are not shared with other queues.
$(elem).queue(function(){});
the fx
queue will automatically dequeue
the next function and run it if the queue hasn't started. dequeue()
a function from the fx
queue, it will unshift()
(push into the first location of the array) the string "inprogress"
- which flags that the queue is currently being run.fx
queue is used by .animate()
and all functions that call it by default.NOTE: If you are using a custom queue, you must manually .dequeue()
the functions, they will not auto start!
You can retrieve a reference to a jQuery queue by calling .queue()
without a function argument. You can use the method if you want to see how many items are in the queue. You can use push
, pop
, unshift
, shift
to manipulate the queue in place. You can replace the entire queue by passing an array to the .queue()
function.
Quick Examples:
// lets assume $elem is a jQuery object that points to some element we are animating.
var queue = $elem.queue();
// remove the last function from the animation queue.
var lastFunc = queue.pop();
// insert it at the beginning:
queue.unshift(lastFunc);
// replace queue with the first three items in the queue
$elem.queue(queue.slice(0,3));
fx
) queue example:$(function() {
// lets do something with google maps:
var $map = $("#map_canvas");
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map($map[0], myOptions);
var resized = function() {
// simple animation callback - let maps know we resized
google.maps.event.trigger(map, 'resize');
};
// wait 2 seconds
$map.delay(2000);
// resize the div:
$map.animate({
width: 250,
height: 250,
marginLeft: 250,
marginTop:250
}, resized);
// geocode something
$map.queue(function(next) {
// find stackoverflow's whois address:
geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);
function handleResponse(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
map.setZoom(13);
map.setCenter(location);
new google.maps.Marker({ map: map, position: location });
}
// geocoder result returned, continue with animations:
next();
}
});
// after we find stack overflow, wait 3 more seconds
$map.delay(3000);
// and resize the map again
$map.animate({
width: 500,
height: 500,
marginLeft:0,
marginTop: 0
}, resized);
});
var theQueue = $({}); // jQuery on an empty object - a perfect queue holder
$.each([1,2,3],function(i, num) {
// lets add some really simple functions to a queue:
theQueue.queue('alerts', function(next) {
// show something, and if they hit "yes", run the next function.
if (confirm('index:'+i+' = '+num+'\nRun the next function?')) {
next();
}
});
});
// create a button to run the queue:
$("<button>", {
text: 'Run Queue',
click: function() {
theQueue.dequeue('alerts');
}
}).appendTo('body');
// create a button to show the length:
$("<button>", {
text: 'Show Length',
click: function() {
alert(theQueue.queue('alerts').length);
}
}).appendTo('body');
I developed an $.ajaxQueue()
plugin that uses the $.Deferred
, .queue()
, and $.ajax()
to also pass back a promise that is resolved when the request completes. Another version of $.ajaxQueue
that still works in 1.4 is posted on my answer to Sequencing Ajax Requests
/*
* jQuery.ajaxQueue - A queue for ajax requests
*
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/
(function($) {
// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});
$.ajaxQueue = function( ajaxOpts ) {
var jqXHR,
dfd = $.Deferred(),
promise = dfd.promise();
// queue our ajax request
ajaxQueue.queue( doRequest );
// add the abort method
promise.abort = function( statusText ) {
// proxy abort to the jqXHR if it is active
if ( jqXHR ) {
return jqXHR.abort( statusText );
}
// if there wasn't already a jqXHR we need to remove from queue
var queue = ajaxQueue.queue(),
index = $.inArray( doRequest, queue );
if ( index > -1 ) {
queue.splice( index, 1 );
}
// and then reject the deferred
dfd.rejectWith( ajaxOpts.context || ajaxOpts,
[ promise, statusText, "" ] );
return promise;
};
// run the actual query
function doRequest( next ) {
jqXHR = $.ajax( ajaxOpts )
.done( dfd.resolve )
.fail( dfd.reject )
.then( next, next );
}
return promise;
};
})(jQuery);
I have now added this as an article on learn.jquery.com, there are other great articles on that site about queues, go look.
To match pattern
or an empty string, use
^$|pattern
^
and $
are the beginning and end of the string anchors respectively.|
is used to denote alternates, e.g. this|that
.\b
\b
in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.
That is, \b
is located:
\w
and \W
(either order):
^
and \w
\w
\w
and $
\w
This is not trivial depending on specification.
It's a pretty useful functionality, for example here is a Node.js code snippet to test the set up of a 3 second timing function.
const waitTime = 3000;
console.log(`setting a ${waitTime/1000} second delay`);
Explanation
This is very old thread, but I tried using the solution and could not get the information out of File::stat. (Perl 5.10.1)
I had to do the following:
my $f_stats = stat($fh);
my $timestamp_mod = localtime($f_stats->mtime);
print "MOD_TIME = $timestamp_mod \n";
Just thought I share in case anyone else had the same trouble.
I use printf, is shorter as it doesn't need flags to do the work:
printf "\rMy static $myvars composed text"
I have been using one machine to push code to two different GitHub accounts with different username. Assuming you already set up one account and want to add a new one:
ssh-keygen -t rsa -C "[email protected]"
id_rsa
. Give it a different name, e.g. id_rsa_another
Settings -> SSH and GPG keys -> New SSH key -> Give a label and paste the key -> Add SSH key
ssh-add ~/.ssh/id_rsa_another
touch ~/.ssh/config
and edit the file by providing configurations to your accounts:#first account
Host github.com-first
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
#another account
Host github.com-another
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_another
Now you should be able to push from different accounts depending on what key you add to the ssh agent, i.e. to use your first account, do
ssh-add ~/.ssh/id_rsa
.
You might also want to change your user email:
git config --global user.email "[email protected]"
or clean out ssh keys in case of permission error when pusing code to one of the accounts:
ssh-add -D
Your code is indeed using the normal way to create and delete a dynamic object. Yes, it's perfectly normal (and indeed guaranteed by the language standard!) that delete
will call the object's destructor, just like new
has to invoke the constructor.
If you weren't instantiating Object1
directly but some subclass thereof, I'd remind you that any class intended to be inherited from must have a virtual destructor (so that the correct subclass's destructor can be invoked in cases analogous to this one) -- but if your sample code is indeed representative of your actual code, this cannot be your current problem -- must be something else, maybe in the destructor code you're not showing us, or some heap-corruption in the code you're not showing within that function or the ones it calls...?
BTW, if you're always going to delete the object just before you exit the function which instantiates it, there's no point in making that object dynamic -- just declare it as a local (storage class auto
, as is the default) variable of said function!
If you want to consider null values equality too, try the following
select column1, column2,
case
when column1 is NULL and column2 is NULL then 'true'
when column1=column2 then 'true'
else 'false'
end
from table;
This is the error line:
if (called_from.equalsIgnoreCase("add")) { --->38th error line
This means that called_from
is null. Simple check if it is null above:
String called_from = getIntent().getStringExtra("called");
if(called_from == null) {
called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
// do whatever
} else {
// do whatever
}
That way, if called_from
is null, it'll execute the else
part of your if statement.
Easiest way to clear/reset the text field on click is to clear/reset the scope
<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>
In Controller
$scope.clearfunction=function(event){
event.searchAll=null;
}
SELECT
p1.Person,
p1.`GROUP`,
p1.Age
FROM
person AS p1
WHERE
(
SELECT
COUNT( DISTINCT ( p2.age ) )
FROM
person AS p2
WHERE
p2.`GROUP` = p1.`GROUP`
AND p2.Age >= p1.Age
) < 2
ORDER BY
p1.`GROUP` ASC,
p1.age DESC
Since some of the functions depend on other libraries like GEOS and proj4 you might want to get their versions too. Then use:
SELECT PostGIS_full_version();
Yes, this is a current issue in Chrome. There is an issue report here.
The fix will appear in 40.x.y.z versions.
Until then? I don't think you can resolve the issue yourself. But you can ignore it. The shown error is only related to the dev tools and does not influence the behavior of your website. If you have any other problems they are not related to this error.
If you are using TortoiseHg you have to perform these three steps shown in the attached screen shot, this would add your credentials for the specific repository you are working with.
To add global settings you can access the file C:\users\user.name\mercurial.ini and add the section
[auth]
bb.prefix=https://bitbucket.org/zambezia/packagemanager
bb.username = $username
bb.password = $password
Hope this helps.
Use apply function,
Xlower = df['x'].apply(lambda x: x.upper()).head(10)
(Update: overlooked a fault in the matter, I have corrected)
(Update2: I wrote from memory the code screwed up, repaired it)
(Update3: check on SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150)
,Questions nvarchar(100)
,Answer nvarchar(100)
)
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
inner join deleted d on i.BusinessUnit = d.BusinessUnit
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
FROM
deleted d
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
delete Derived_Values;
and then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
Record Count: 0;
BUSINESSUNIT QUESTIONS ANSWER
Updated Record -- After Update Trigger.BU1 Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1 Q11 A11
Updated Record -- After Update Trigger.BU1 Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1 Q12 A12
Updated Record -- After Update Trigger.BU2 Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2 Q21 A21
Updated Record -- After Update Trigger.BU2 Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2 Q22 A22
(Update4: If you want to sync: SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
CREATE TRIGGER trgAfterInsert ON [Derived_Values]
FOR INSERT
AS
begin
insert
[Derived_Values_Test]
(BusinessUnit,Questions,Answer)
SELECT
i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
end
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
update
[Derived_Values_Test]
set
--BusinessUnit = i.BusinessUnit
--,Questions = i.Questions
Answer = i.Answer
from
[Derived_Values]
inner join inserted i
on
[Derived_Values].BusinessUnit = i.BusinessUnit
and
[Derived_Values].Questions = i.Questions
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR DELETE
AS
begin
delete
[Derived_Values_Test]
from
[Derived_Values_Test]
inner join deleted d
on
[Derived_Values_Test].BusinessUnit = d.BusinessUnit
and
[Derived_Values_Test].Questions = d.Questions
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
--delete Derived_Values;
And then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
CSS can be applied and you will have to set transform-origin
correctly to get the applied transformation in the way you want
See the fiddle:
http://jsfiddle.net/OMS_/gkrsz/
Main code:
/* assuming that the image's height is 70px */
img.rotated {
transform: rotate(90deg);
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform-origin: 35px 35px;
-webkit-transform-origin: 35px 35px;
-moz-transform-origin: 35px 35px;
-ms-transform-origin: 35px 35px;
}
jQuery and JS:
$(img)
.css('transform-origin-x', imgWidth / 2)
.css('transform-origin-y', imgHeight / 2);
// By calculating the height and width of the image in the load function
// $(img).css('transform-origin', (imgWidth / 2) + ' ' + (imgHeight / 2) );
Logic:
Divide the image's height by 2. The transform-x
and transform-y
values should be this value
Link:
transform-origin at CSS | MDN
The purrr
package has a lot of handy functions for working on lists. The flatten
command can clean up unwanted nesting.
resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)
nested_outlist <- list(resultsa, resultsb, resultsc)
outlist <- purrr::flatten(nested_outlist)
You could use CommitMonitor. This little tool uses very little RAM and notifies you of all the commits you've missed.
To improve the user experience, Android 8.0 (API level 26) imposes limitations on what apps can do while running in the background.
Still if you need always running service, then you can use foreground service.
Background Service Limitations: While an app is idle, there are limits to its use of background services. This does not apply to foreground services, which are more noticeable to the user.
So you can make a foreground service. You will need to show a notification to user when your service is running. See this answer (There are many others)
A solution if -
You can make periodic task, 1. it starts your service, 2. service will do its work and 3. stops itself. By this your app will not be considered battery draining.
You can use periodic task with Alarm Manager, Job Scheduler, Evernote-Jobs or Work Manager.
I have tested forever running service with Work-Manager.
In my case, the error "BeanFactory not initialized or already closed - call 'refresh' before" was a consequence of a previous error that I didn't noticed in the server startup. I think that it is not always the real cause of the problem.
In github, the easy way is to delete the remote branch in the github UI, under branches tab. You have to make sure remove following settings to make the branch deletable:
Now recreate it in your local repository to point to the previous commit point. and add it back to remote repo.
git checkout -b master 734c2b9b # replace with your commit point
Then push the local branch to remote
git push -u origin master
Add back the default branch and branch protection, etc.
0123456789 is not a valid integer (usually zeros will be stripped)
I think something like this regexp would be better to use:
^[1-9]([0-9]*)$
(does not support signed numbers)
Move excel variables which are global declare in your form to local like in my form I have:
Dim xls As New MyExcel.Interop.Application
Dim xlb As MyExcel.Interop.Workbook
above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.
select age(timestamp_A, timestamp_B)
Answering to Igor's comment:
select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
age
-------------------------------
1 year 1 mon 28 days 00:01:28
If you're using overlapped (i.e. asynchronous) I/O with completion routines or completion ports, you will be notified immediately (assuming you have an outstanding read) when the client side closes the connection.
It appears from your question that you already have a second set of DNS servers available that reference the development site instead of the live site.
I would suggest that you simply run a standard SOCKS proxy either on that DNS server system or on a low-end spare system and have that system configured to use the development DNS server. You can then tell Firefox to use that proxy instead of downloading pages directly.
Doing it this way, the actual DNS lookups will be done on the proxy machine and not on the machine that's running the web browser.
No need for a function:
$assetPath : "/assets/images";
...
body {
margin: 0 auto;
background: url(#{$assetPath}/site/background.jpg) repeat-x fixed 0 0;
width: 100%; }
See the interpolation docs for details.
Plugin run Tomcat 7.0.47:
mvn org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run
...
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
This is sample to run plugin with Tomcat 8 and Java 8: Cargo embedded tomcat: custom context.xml
If View's height/width = wrap_content
use:
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
If View's height/width = match_parent
use:
android:gravity="center_vertical|center_horizontal"
The following query can be used to detemine tablespace and other params:
select df.tablespace_name "Tablespace",
totalusedspace "Used MB",
(df.totalspace - tu.totalusedspace) "Free MB",
df.totalspace "Total MB",
round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
from (select tablespace_name,
round(sum(bytes) / 1048576) TotalSpace
from dba_data_files
group by tablespace_name) df,
(select round(sum(bytes)/(1024*1024)) totalusedspace,
tablespace_name
from dba_segments
group by tablespace_name) tu
where df.tablespace_name = tu.tablespace_name
and df.totalspace <> 0;
Source: https://community.oracle.com/message/1832920
For your case if you want to know the partition name and it's size just run this query:
select owner,
segment_name,
partition_name,
segment_type,
bytes / 1024/1024 "MB"
from dba_segments
where owner = <owner_name>;
This occurs due to the availability of the previous version of the Application, that is not installed on the device but its data is present in the device memory. So it fails to upgrade this uninstalled application data on the device
Try this :
Go to Device Settings ==> Apps(All Apps) ==> search your App OR search for 'client' ==> In App info screen , press the triple dots option on top right corner ==> select 'Uninstall for All Users' ==> a promt appears select 'OK'
It works for me every time this error occurs
Try out this will solve ur problem ....
EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();
Future Readers
Check each of the following:
import { CommonModule } from '@angular/common';
ng serve
)math.sqrt
is the C implementation of square root and is therefore different from using the **
operator which implements Python's built-in pow
function. Thus, using math.sqrt
actually gives a different answer than using the **
operator and there is indeed a computational reason to prefer numpy
or math
module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas **
operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow
function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".
See this Stack Overflow question for more information on the difference between **
and math.sqrt
.
In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like **
e.g. C++. So **
is probably more Pythonic, but whether or not it's objectively better depends on the use case.
You can also check run time. Put one breakpoint in code and inside (lldb) console write
(lldb) po [yourObject class]
Like this..
Use sprintf
(or snprintf
if like me you can't count) with format string "pre_%d_suff"
.
For what it's worth, with itoa/strcat you could do:
char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");
This is how to load/use a local html with relative references.
Use the below given code. It should work like a charm.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
[webview loadRequest:[NSURLRequest requestWithURL:url]];
Now all your relative links(like img/.gif, js/.js) in the html should get resolved.
Swift 3
if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
}
I don't know why do you need this onmousedown
event here, but what you have to do is put your function above actual usage. Look at the snipplet below:
<script type="text/javascript">_x000D_
function jsFunction(value)_x000D_
{_x000D_
alert(value);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">_x000D_
<option value='1'>One</option>_x000D_
<option value='2'>Two</option>_x000D_
<option value='3'>Three</option>_x000D_
</select>
_x000D_
I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works. Tested in chrome, firefox, and Edge
today:function(){
var today = new Date();
var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
var y = today.getFullYear();
var x = String(y+"-"+m+"-"+d);
return x;
}
Below is the python function to do the same.
def sigmoid(x) :
return 1.0/(1+np.exp(-x))
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
you have to git add css/mobile.css
the new file and git rm css/iphone.css
, so git knows about it. then it will show the same output in git status
you can see it clearly in the status output (the new name of the file):
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
and (the old name):
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
i think behind the scenes git mv
is nothing more than a wrapper script which does exactly that: delete the file from the index and add it under a different name
Try this:
SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Try adding this class
class="pager"
<p class="pager" style="line-height: 70px;">
<button type="submit" class="btn">Confirm</button>
</p>
I tried mine within a <div class=pager><button etc etc></div>
which worked well
See http://getbootstrap.com/components/ look under Pagination -> Pager
This looks like the correct bootstrap class to center this, text-align: center;
is meant for text not images and blocks etc.
If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.
Just go to http://java.com/en/download/ and update your version of JRE
Use:
import os
print os.sep
to see how separator looks on a current OS.
In your code you can use:
import os
path = os.path.join('folder_name', 'file_name')
I like owlstead's original answer, and if you don't like the idea of creating a ByteBuffer
on every method call then you can reuse the ByteBuffer
by calling it's .clear()
and .flip()
methods:
ByteBuffer _intShifter = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE)
.order(ByteOrder.LITTLE_ENDIAN);
public byte[] intToByte(int value) {
_intShifter.clear();
_intShifter.putInt(value);
return _intShifter.array();
}
public int byteToInt(byte[] data)
{
_intShifter.clear();
_intShifter.put(data, 0, Integer.SIZE / Byte.SIZE);
_intShifter.flip();
return _intShifter.getInt();
}
I've implemented trees using nested dicts. It is quite easy to do, and it has worked for me with pretty large data sets. I've posted a sample below, and you can see more at Google code
def addBallotToTree(self, tree, ballotIndex, ballot=""):
"""Add one ballot to the tree.
The root of the tree is a dictionary that has as keys the indicies of all
continuing and winning candidates. For each candidate, the value is also
a dictionary, and the keys of that dictionary include "n" and "bi".
tree[c]["n"] is the number of ballots that rank candidate c first.
tree[c]["bi"] is a list of ballot indices where the ballots rank c first.
If candidate c is a winning candidate, then that portion of the tree is
expanded to indicate the breakdown of the subsequently ranked candidates.
In this situation, additional keys are added to the tree[c] dictionary
corresponding to subsequently ranked candidates.
tree[c]["n"] is the number of ballots that rank candidate c first.
tree[c]["bi"] is a list of ballot indices where the ballots rank c first.
tree[c][d]["n"] is the number of ballots that rank c first and d second.
tree[c][d]["bi"] is a list of the corresponding ballot indices.
Where the second ranked candidates is also a winner, then the tree is
expanded to the next level.
Losing candidates are ignored and treated as if they do not appear on the
ballots. For example, tree[c][d]["n"] is the total number of ballots
where candidate c is the first non-losing candidate, c is a winner, and
d is the next non-losing candidate. This will include the following
ballots, where x represents a losing candidate:
[c d]
[x c d]
[c x d]
[x c x x d]
During the count, the tree is dynamically updated as candidates change
their status. The parameter "tree" to this method may be the root of the
tree or may be a sub-tree.
"""
if ballot == "":
# Add the complete ballot to the tree
weight, ballot = self.b.getWeightedBallot(ballotIndex)
else:
# When ballot is not "", we are adding a truncated ballot to the tree,
# because a higher-ranked candidate is a winner.
weight = self.b.getWeight(ballotIndex)
# Get the top choice among candidates still in the running
# Note that we can't use Ballots.getTopChoiceFromWeightedBallot since
# we are looking for the top choice over a truncated ballot.
for c in ballot:
if c in self.continuing | self.winners:
break # c is the top choice so stop
else:
c = None # no candidates left on this ballot
if c is None:
# This will happen if the ballot contains only winning and losing
# candidates. The ballot index will not need to be transferred
# again so it can be thrown away.
return
# Create space if necessary.
if not tree.has_key(c):
tree[c] = {}
tree[c]["n"] = 0
tree[c]["bi"] = []
tree[c]["n"] += weight
if c in self.winners:
# Because candidate is a winner, a portion of the ballot goes to
# the next candidate. Pass on a truncated ballot so that the same
# candidate doesn't get counted twice.
i = ballot.index(c)
ballot2 = ballot[i+1:]
self.addBallotToTree(tree[c], ballotIndex, ballot2)
else:
# Candidate is in continuing so we stop here.
tree[c]["bi"].append(ballotIndex)
You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %>
with its successor EL ${}
. They do not share the same variable scope. The allFestivals
is not available in scriptlet scope and the i
is not available in EL scope.
You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
and then iterate over the list as follows:
<c:forEach items="${allFestivals}" var="festival">
<tr>
<td>${festival.festivalName}</td>
<td>${festival.location}</td>
<td>${festival.startDate}</td>
<td>${festival.endDate}</td>
<td>${festival.URL}</td>
</tr>
</c:forEach>
(beware of possible XSS attack holes, use <c:out>
accordingly)
Don't forget to remove the <jsp:useBean>
as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml
so that you won't accidently use them:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
In the first case you are declaring "int a" as a local variable(as declared inside a method) and local varible do not get default value.
But instance variable are given default value both for static and non-static.
Default value for instance variable:
int = 0
float,double = 0.0
reference variable = null
char = 0 (space character)
boolean = false
The org.apache.commons.text.StringSubstitutor helper class from Apache Commons Text provides named variable substitution
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String resolved = new StringSubstitutor(valuesMap).replace("The ${animal} jumped over the ${target}.");
System.out.println(resolved); // The quick brown fox jumped over the lazy dog.
I personally use if/else statement in children with this kind of block statement. It only supports on Dart version 2.3.0 above.
if / else
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else ...[
StatsScreen(),
],
],
),
if / else if
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else if(_selectedIndex == 1)...[
StatsScreen(),
],
],
),
I assume you mean you're looking for something that is faster than datetime.datetime.strftime(), and are essentially stripping the non-alpha characters from a utc timestamp.
You're approach is marginally faster, and I think you can speed things up even more by slicing the string:
>>> import timeit
>>> t=timeit.Timer('datetime.utcnow().strftime("%Y%m%d%H%M%S%f")','''
... from datetime import datetime''')
>>> t.timeit(number=10000000)
116.15451288223267
>>> def replaceutc(s):
... return s\
... .replace('-','') \
... .replace(':','') \
... .replace('.','') \
... .replace(' ','') \
... .strip()
...
>>> t=timeit.Timer('replaceutc(str(datetime.datetime.utcnow()))','''
... from __main__ import replaceutc
... import datetime''')
>>> t.timeit(number=10000000)
77.96774983406067
>>> def sliceutc(s):
... return s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
...
>>> t=timeit.Timer('sliceutc(str(datetime.utcnow()))','''
... from __main__ import sliceutc
... from datetime import datetime''')
>>> t.timeit(number=10000000)
62.378515005111694
It is possible. I searched the whole net for this, but once when i took one of microsoft's survey, I finally got the answer.
try this:
window.top.close();
this will close the current tab for you.
Please consider using some code like this:
SqlDataReader reader = command.ExecuteReader();
int numRows = 0;
DataTable dt = new DataTable();
dt.Load(reader);
numRows = dt.Rows.Count;
string attended_type = "";
for (int index = 0; index < numRows; index++)
{
attended_type = dt.Rows[indice2]["columnname"].ToString();
}
reader.Close();
Trac - by default - uses HTTP Authentication as well. Logout does not work and can not be fixed:
- This is an issue with the HTTP authentication scheme itself, and there's nothing we can do in Trac to fix it properly.
- There is currently no workaround (JavaScript or other) that works with all major browsers.
From: http://trac.edgewall.org/ticket/791#comment:103
Looks like that there is no working answer to the question, that issue has been reported seven years ago and it makes perfect sense: HTTP is stateless. Either a request is done with authentication credentials or not. But that's a matter of the client sending the request, not the server receiving it. The server can only say if a request URI needs authorization or not.
This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop contraint):
select
concat(table_name, '.', column_name) as 'foreign key',
concat(referenced_table_name, '.', referenced_column_name) as 'references',
constraint_name as 'constraint name'
from
information_schema.key_column_usage
where
referenced_table_name is not null;
If you want to check tables in a specific database, at the end of the query add the schema name:
select
concat(table_name, '.', column_name) as 'foreign key',
concat(referenced_table_name, '.', referenced_column_name) as 'references',
constraint_name as 'constraint name'
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = 'database_name';
Likewise, for a specific column name, add
and table_name = 'table_name
at the end of the query.
Inspired by this post here
If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules
and npm install
again to rebuild the local modules.
Visual Studio 2015 (Community update 3, in my scenario) uses a default template for the MVC project. You don't have to select it.
I found this tutorial and I think it answers the question: https://docs.asp.net/en/latest/tutorials/first-mvc-app/start-mvc.html
check out the old versions of this: http://www.asp.net/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part1
http://www.asp.net/mvc/overview/getting-started/introduction/getting-started
Times have changed. Including .NET
Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp
or specify the main class. In your case it would contain lines like this:
Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar
Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar
.
Then execute it with
java -jar MyJar.jar
You can use %in%
data[data$Code %in% selected,]
Code Value
1 A 1
2 B 2
7 A 3
8 A 4
Here is the simple ListView with different images. First of all you have to copy the different kinds of images and paste it to the res/drawable-hdpi in your project. Images should be (.png)file format. then copy this code.
In main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
create listview_layout.xml and paste this code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/hello"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:text="TextView1" />
<TextView
android:id="@+id/cur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:text="TextView2" />
</LinearLayout>
In your Activity
package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SimpleListImageActivity extends Activity {
// Array of strings storing country names
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
// Array of integers points to images stored in /res/drawable-hdpi/
//here you have to give image name which you already pasted it in /res/drawable-hdpi/
int[] flags = new int[]{
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8,
R.drawable.image9,
R.drawable.image10,
};
// Array of strings to store currencies
String[] currency = new String[]{
"Indian Rupee",
"Pakistani Rupee",
"Sri Lankan Rupee",
"Renminbi",
"Bangladeshi Taka",
"Nepalese Rupee",
"Afghani",
"North Korean Won",
"South Korean Won",
"Japanese Yen"
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Country : " + countries[i]);
hm.put("cur","Currency : " + currency[i]);
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
}
This is the full code.you can make changes to your need... Comments are welcome
Use o parameter of pgsql command.
-o, --output=FILENAME send query results to file (or |pipe)
psql -d DatabaseName -U UserName -c "SELECT * FROM TABLE" -o /root/Desktop/file.txt
you have to add flag:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
or you will cause error with:
startActivity()
from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK
rerezz's answer is pretty nice but it has one serious flaw. It causes User
component to re-run the ngOnInit
method.
It might be problematic when you do some heavy stuff there and don't want it to be re-run when you switch from the non-parametric route to the parametric one. Though those two routes are meant to imitate an optional url parameter, not become 2 separate routes.
Here's what I suggest to solve the problem:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: ':id', component: UserWithParam, name: 'Usernew' }
]
}
];
Then you can move the logic responsible for handling the param to the UserWithParam
component and leave the base logic in the User
component. Whatever you do in User::ngOnInit
won't be run again when you navigate from /user to /user/123.
Don't forget to put the <router-outlet></router-outlet>
in the User
's template.
In simple terms
It is better to have more coarse-grained service operations, which are composed by fine-grained operations
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))
}
In .Net 2.0 I`m pretty sure about this solution:
public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
List<T> uniques = new List<T>();
foreach (T item in source)
{
if (!uniques.Contains(item)) uniques.Add(item);
}
return uniques;
}
There might be different reasons for different people. For me these are the advantages.
End of the day, it helps me to code faster than i can do in a notepad or wordpad. That is a pretty good reason for me to prefer an IDE.
@IBDesignable
class DesignableView: UIView {
}
extension UIView
{
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
}
I did not have the issue when developing in localhost. However, once I published to a web server, the webservice was returning an empty (blank) result and I was seeing the error in my logs.
I fixed it by setting my ajax contentType to :
"application/json; charset=utf-8"
and using :
JSON.stringify()
on the object I was posting.
var postData = {data: myData};
$.ajax({
type: "POST",
url: "../MyService.asmx/MyMethod",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
dataType: "json"
});
src
folder which is immediately inside the project's folder.
Note the hollow 'J' in the image. That indicates that the file is not part of a project.
This is not code golf, but here is my shortest trick, using types.SimpleNamespace
as the container for JSON objects.
Compared to the leading namedtuple
solution, it is:
rename
option, and probably the same limitation on keys that are not valid identifiers (uses setattr
under the covers)Example:
from __future__ import print_function
import json
try:
from types import SimpleNamespace as Namespace
except ImportError:
# Python 2.x fallback
from argparse import Namespace
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
x = json.loads(data, object_hook=lambda d: Namespace(**d))
print (x.name, x.hometown.name, x.hometown.id)
Get the .column
parent of the this
element, get its previous sibling, then find any input there:
$(this).closest(".column").prev().find("input:first").val();
What you need is a quadrangle instead of a rotated rectangle.
RotatedRect
will give you incorrect results. Also you will need a perspective projection.
Basicly what must been done is:
I implemented a class Quadrangle
which takes care of contour to quadrangle conversion and will also transform it over the right perspective.
See a working implementation here: Java OpenCV deskewing a contour
Assign something to your strings. This will definitely help.
This is my solution.
Use Google Apps Script, and set time trigger.
// main.js
function ping() {
UrlFetchApp.fetch("https://<Your app>.herokuapp.com/ping_from_GAS");
}
It is very easy!
Within the environment align
from the package amsmath
it is possible to combine the use of \label
and \tag
for each equation or line. For example, the code:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
Write
\begin{align}
x+y\label{eq:eq1}\tag{Aa}\\
x+z\label{eq:eq2}\tag{Bb}\\
y-z\label{eq:eq3}\tag{Cc}\\
y-2z\nonumber
\end{align}
then cite \eqref{eq:eq1} and \eqref{eq:eq2} or \eqref{eq:eq3} separately.
\end{document}
produces:
Other answers didn't work for me, but this did (in fish
shell):
brew remove <package>
for p in (brew deps <package>)
brew remove $p
end
Because brew remove $p
fails when some other package depends on p
.
After speaking with you in the comments, I believe that you can just do this using numpy/scipy. The ideas is to read the image in the numpy
3d-array and feed it into the variable.
from scipy import misc
import tensorflow as tf
img = misc.imread('01.png')
print img.shape # (32, 32, 3)
img_tf = tf.Variable(img)
print img_tf.get_shape().as_list() # [32, 32, 3]
Then you can run your graph:
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
im = sess.run(img_tf)
and verify that it is the same:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(1,2,1)
plt.imshow(im)
fig.add_subplot(1,2,2)
plt.imshow(img)
plt.show()
P.S. you mentioned: Since it's supposed to parallelize reading, it seems useful to know.
. To which I can say that rarely in data-analysis reading of the data is the bottleneck. Most of your time you will spend training your model.
The value of event handler attributes such as onclick should just be JavaScript, without any "javascript:" prefix. The javascript: pseudo-protocol is used in a URL, for example:
<a href="javascript:func(this)">here</a>
You should use the onclick="func(this)"
form in preference to this though. Also note that in my example above using the javascript: pseudo-protocol "this" will refer to the window object rather than the <a>
element.
In my strange case, Intellij remembers forever about my project even if I delete .iml
... Thus I did the following:
.iml
file.my_proj
) to my_proj_backup
.my_proj_backup
in Intellij and close.my_proj
, and open it in Intellij. Then close it.my_proj
and move my_proj_backup
back to my_proj
. Then open my_proj
in Intellij.Then it happily forgot the old my_proj
:)
C code for matrix transpose & rotate (+/-90, +/-180)
`
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
/*
Matrix transpose & rotate (+/-90, +/-180)
Supports both 2D arrays and 1D pointers with logical rows/cols
Supports square and non-square matrices, has in-place and copy features
See tests for examples of usage
tested gcc -std=c90 -Wall -pedantic, MSVC17
*/
typedef int matrix_data_t; /* matrix data type */
void transpose(const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);
void transpose_inplace(matrix_data_t* data, int n );
void rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols);
void rotate_inplace(int direction, matrix_data_t* data, int n);
void reverse_rows(matrix_data_t* data, int rows, int cols);
void reverse_cols(matrix_data_t* data, int rows, int cols);
/* test/compare fn */
int test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols );
/* TESTS/USAGE */
void transpose_test() {
matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };/* 3x3 square, odd length side */
matrix_data_t sq3x3_cpy[9];
matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };/* 2D 3x3 square */
matrix_data_t sq3x3_2D_copy[3][3];
/* expected test values */
const matrix_data_t sq3x3_orig[9] = { 0,1,2,3,4,5,6,7,8 };
const matrix_data_t sq3x3_transposed[9] = { 0,3,6,1,4,7,2,5,8};
matrix_data_t sq4x4[16]= { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };/* 4x4 square, even length*/
const matrix_data_t sq4x4_orig[16] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
const matrix_data_t sq4x4_transposed[16] = { 0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15 };
/* 2x3 rectangle */
const matrix_data_t r2x3_orig[6] = { 0,1,2,3,4,5 };
const matrix_data_t r2x3_transposed[6] = { 0,3,1,4,2,5 };
matrix_data_t r2x3_copy[6];
matrix_data_t r2x3_2D[2][3] = { {0,1,2},{3,4,5} }; /* 2x3 2D rectangle */
matrix_data_t r2x3_2D_t[3][2];
/* matrix_data_t r3x2[6] = { 0,1,2,3,4,5 }; */
matrix_data_t r3x2_copy[6];
/* 3x2 rectangle */
const matrix_data_t r3x2_orig[6] = { 0,1,2,3,4,5 };
const matrix_data_t r3x2_transposed[6] = { 0,2,4,1,3,5 };
matrix_data_t r6x1[6] = { 0,1,2,3,4,5 }; /* 6x1 */
matrix_data_t r6x1_copy[6];
matrix_data_t r1x1[1] = { 0 }; /*1x1*/
matrix_data_t r1x1_copy[1];
/* 3x3 tests, 2D array tests */
transpose_inplace(sq3x3, 3); /* transpose in place */
assert(!test_cmp(sq3x3, sq3x3_transposed, 3, 3));
transpose_inplace(sq3x3, 3); /* transpose again */
assert(!test_cmp(sq3x3, sq3x3_orig, 3, 3));
transpose(sq3x3, sq3x3_cpy, 3, 3); /* transpose copy 3x3*/
assert(!test_cmp(sq3x3_cpy, sq3x3_transposed, 3, 3));
transpose((matrix_data_t*)sq3x3_2D, (matrix_data_t*)sq3x3_2D_copy, 3, 3); /* 2D array transpose/copy */
assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_transposed, 3, 3));
transpose_inplace((matrix_data_t*)sq3x3_2D_copy, 3); /* 2D array transpose in place */
assert(!test_cmp((matrix_data_t*)sq3x3_2D_copy, sq3x3_orig, 3, 3));
/* 4x4 tests */
transpose_inplace(sq4x4, 4); /* transpose in place */
assert(!test_cmp(sq4x4, sq4x4_transposed, 4,4));
transpose_inplace(sq4x4, 4); /* transpose again */
assert(!test_cmp(sq4x4, sq4x4_orig, 3, 3));
/* 2x3,3x2 tests */
transpose(r2x3_orig, r2x3_copy, 2, 3);
assert(!test_cmp(r2x3_copy, r2x3_transposed, 3, 2));
transpose(r3x2_orig, r3x2_copy, 3, 2);
assert(!test_cmp(r3x2_copy, r3x2_transposed, 2,3));
/* 2D array */
transpose((matrix_data_t*)r2x3_2D, (matrix_data_t*)r2x3_2D_t, 2, 3);
assert(!test_cmp((matrix_data_t*)r2x3_2D_t, r2x3_transposed, 3,2));
/* Nx1 test, 1x1 test */
transpose(r6x1, r6x1_copy, 6, 1);
assert(!test_cmp(r6x1_copy, r6x1, 1, 6));
transpose(r1x1, r1x1_copy, 1, 1);
assert(!test_cmp(r1x1_copy, r1x1, 1, 1));
}
void rotate_test() {
/* 3x3 square */
const matrix_data_t sq3x3[9] = { 0,1,2,3,4,5,6,7,8 };
const matrix_data_t sq3x3_r90[9] = { 6,3,0,7,4,1,8,5,2 };
const matrix_data_t sq3x3_180[9] = { 8,7,6,5,4,3,2,1,0 };
const matrix_data_t sq3x3_l90[9] = { 2,5,8,1,4,7,0,3,6 };
matrix_data_t sq3x3_copy[9];
/* 3x3 square, 2D */
matrix_data_t sq3x3_2D[3][3] = { { 0,1,2 },{ 3,4,5 },{ 6,7,8 } };
/* 4x4, 2D */
matrix_data_t sq4x4[4][4] = { { 0,1,2,3 },{ 4,5,6,7 },{ 8,9,10,11 },{ 12,13,14,15 } };
matrix_data_t sq4x4_copy[4][4];
const matrix_data_t sq4x4_r90[16] = { 12,8,4,0,13,9,5,1,14,10,6,2,15,11,7,3 };
const matrix_data_t sq4x4_l90[16] = { 3,7,11,15,2,6,10,14,1,5,9,13,0,4,8,12 };
const matrix_data_t sq4x4_180[16] = { 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 };
matrix_data_t r6[6] = { 0,1,2,3,4,5 }; /* rectangle with area of 6 (1x6,2x3,3x2, or 6x1) */
matrix_data_t r6_copy[6];
const matrix_data_t r1x6_r90[6] = { 0,1,2,3,4,5 };
const matrix_data_t r1x6_l90[6] = { 5,4,3,2,1,0 };
const matrix_data_t r1x6_180[6] = { 5,4,3,2,1,0 };
const matrix_data_t r2x3_r90[6] = { 3,0,4,1,5,2 };
const matrix_data_t r2x3_l90[6] = { 2,5,1,4,0,3 };
const matrix_data_t r2x3_180[6] = { 5,4,3,2,1,0 };
const matrix_data_t r3x2_r90[6] = { 4,2,0,5,3,1 };
const matrix_data_t r3x2_l90[6] = { 1,3,5,0,2,4 };
const matrix_data_t r3x2_180[6] = { 5,4,3,2,1,0 };
const matrix_data_t r6x1_r90[6] = { 5,4,3,2,1,0 };
const matrix_data_t r6x1_l90[6] = { 0,1,2,3,4,5 };
const matrix_data_t r6x1_180[6] = { 5,4,3,2,1,0 };
/* sq3x3 tests */
rotate(90, sq3x3, sq3x3_copy, 3, 3); /* +90 */
assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));
rotate(-90, sq3x3, sq3x3_copy, 3, 3); /* -90 */
assert(!test_cmp(sq3x3_copy, sq3x3_l90, 3, 3));
rotate(180, sq3x3, sq3x3_copy, 3, 3); /* 180 */
assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));
/* sq3x3 in-place rotations */
memcpy( sq3x3_copy, sq3x3, 3 * 3 * sizeof(matrix_data_t));
rotate_inplace(90, sq3x3_copy, 3);
assert(!test_cmp(sq3x3_copy, sq3x3_r90, 3, 3));
rotate_inplace(-90, sq3x3_copy, 3);
assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3)); /* back to 0 orientation */
rotate_inplace(180, sq3x3_copy, 3);
assert(!test_cmp(sq3x3_copy, sq3x3_180, 3, 3));
rotate_inplace(-180, sq3x3_copy, 3);
assert(!test_cmp(sq3x3_copy, sq3x3, 3, 3));
rotate_inplace(180, (matrix_data_t*)sq3x3_2D, 3);/* 2D test */
assert(!test_cmp((matrix_data_t*)sq3x3_2D, sq3x3_180, 3, 3));
/* sq4x4 */
rotate(90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);
assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_r90, 4, 4));
rotate(-90, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);
assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_l90, 4, 4));
rotate(180, (matrix_data_t*)sq4x4, (matrix_data_t*)sq4x4_copy, 4, 4);
assert(!test_cmp((matrix_data_t*)sq4x4_copy, sq4x4_180, 4, 4));
/* r6 as 1x6 */
rotate(90, r6, r6_copy, 1, 6);
assert(!test_cmp(r6_copy, r1x6_r90, 1, 6));
rotate(-90, r6, r6_copy, 1, 6);
assert(!test_cmp(r6_copy, r1x6_l90, 1, 6));
rotate(180, r6, r6_copy, 1, 6);
assert(!test_cmp(r6_copy, r1x6_180, 1, 6));
/* r6 as 2x3 */
rotate(90, r6, r6_copy, 2, 3);
assert(!test_cmp(r6_copy, r2x3_r90, 2, 3));
rotate(-90, r6, r6_copy, 2, 3);
assert(!test_cmp(r6_copy, r2x3_l90, 2, 3));
rotate(180, r6, r6_copy, 2, 3);
assert(!test_cmp(r6_copy, r2x3_180, 2, 3));
/* r6 as 3x2 */
rotate(90, r6, r6_copy, 3, 2);
assert(!test_cmp(r6_copy, r3x2_r90, 3, 2));
rotate(-90, r6, r6_copy, 3, 2);
assert(!test_cmp(r6_copy, r3x2_l90, 3, 2));
rotate(180, r6, r6_copy, 3, 2);
assert(!test_cmp(r6_copy, r3x2_180, 3, 2));
/* r6 as 6x1 */
rotate(90, r6, r6_copy, 6, 1);
assert(!test_cmp(r6_copy, r6x1_r90, 6, 1));
rotate(-90, r6, r6_copy, 6, 1);
assert(!test_cmp(r6_copy, r6x1_l90, 6, 1));
rotate(180, r6, r6_copy, 6, 1);
assert(!test_cmp(r6_copy, r6x1_180, 6, 1));
}
/* test comparison fn, return 0 on match else non zero */
int test_cmp(const matrix_data_t* lhs, const matrix_data_t* rhs, int rows, int cols) {
int r, c;
for (r = 0; r < rows; ++r) {
for (c = 0; c < cols; ++c) {
if ((lhs + r * cols)[c] != (rhs + r * cols)[c])
return -1;
}
}
return 0;
}
/*
Reverse values in place of each row in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols
[A B C] -> [C B A]
[D E F] [F E D]
*/
void reverse_rows(matrix_data_t* data, int rows, int cols) {
int r, c;
matrix_data_t temp;
matrix_data_t* pRow = NULL;
for (r = 0; r < rows; ++r) {
pRow = (data + r * cols);
for (c = 0; c < (int)(cols / 2); ++c) { /* explicit truncate */
temp = pRow[c];
pRow[c] = pRow[cols - 1 - c];
pRow[cols - 1 - c] = temp;
}
}
}
/*
Reverse values in place of each column in 2D matrix data[rows][cols] or in 1D pointer with logical rows/cols
[A B C] -> [D E F]
[D E F] [A B C]
*/
void reverse_cols(matrix_data_t* data, int rows, int cols) {
int r, c;
matrix_data_t temp;
matrix_data_t* pRowA = NULL;
matrix_data_t* pRowB = NULL;
for (c = 0; c < cols; ++c) {
for (r = 0; r < (int)(rows / 2); ++r) { /* explicit truncate */
pRowA = data + r * cols;
pRowB = data + cols * (rows - 1 - r);
temp = pRowA[c];
pRowA[c] = pRowB[c];
pRowB[c] = temp;
}
}
}
/* Transpose NxM matrix to MxN matrix in O(n) time */
void transpose(const matrix_data_t* src, matrix_data_t* dst, int N, int M) {
int i;
for (i = 0; i<N*M; ++i) dst[(i%M)*N + (i / M)] = src[i]; /* one-liner version */
/*
expanded version of one-liner: calculate XY based on array index, then convert that to YX array index
int i,j,x,y;
for (i = 0; i < N*M; ++i) {
x = i % M;
y = (int)(i / M);
j = x * N + y;
dst[j] = src[i];
}
*/
/*
nested for loop version
using ptr arithmetic to get proper row/column
this is really just dst[col][row]=src[row][col]
int r, c;
for (r = 0; r < rows; ++r) {
for (c = 0; c < cols; ++c) {
(dst + c * rows)[r] = (src + r * cols)[c];
}
}
*/
}
/*
Transpose NxN matrix in place
*/
void transpose_inplace(matrix_data_t* data, int N ) {
int r, c;
matrix_data_t temp;
for (r = 0; r < N; ++r) {
for (c = r; c < N; ++c) { /*start at column=row*/
/* using ptr arithmetic to get proper row/column */
/* this is really just
temp=dst[col][row];
dst[col][row]=src[row][col];
src[row][col]=temp;
*/
temp = (data + c * N)[r];
(data + c * N)[r] = (data + r * N)[c];
(data + r * N)[c] = temp;
}
}
}
/*
Rotate 1D or 2D src matrix to dst matrix in a direction (90,180,-90)
Precondition: src and dst are 2d matrices with dimensions src[rows][cols] and dst[cols][rows] or 1D pointers with logical rows/cols
*/
void rotate(int direction, const matrix_data_t* src, matrix_data_t* dst, int rows, int cols) {
switch (direction) {
case -90:
transpose(src, dst, rows, cols);
reverse_cols(dst, cols, rows);
break;
case 90:
transpose(src, dst, rows, cols);
reverse_rows(dst, cols, rows);
break;
case 180:
case -180:
/* bit copy to dst, use in-place reversals */
memcpy(dst, src, rows*cols*sizeof(matrix_data_t));
reverse_cols(dst, cols, rows);
reverse_rows(dst, cols, rows);
break;
}
}
/*
Rotate array in a direction.
Array must be NxN 2D or 1D array with logical rows/cols
Direction can be (90,180,-90,-180)
*/
void rotate_inplace( int direction, matrix_data_t* data, int n) {
switch (direction) {
case -90:
transpose_inplace(data, n);
reverse_cols(data, n, n);
break;
case 90:
transpose_inplace(data, n);
reverse_rows(data, n, n);
break;
case 180:
case -180:
reverse_cols(data, n, n);
reverse_rows(data, n, n);
break;
}
}
`
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
String withoutQuotes_line1 = line1.replace("\"", "");
have a look here
From ggplot2 2.0.0
you can use the margin =
argument of element_text()
to change the distance between the axis title and the numbers. Set the values of the margin
on t
op, r
ight, b
ottom, and l
eft side of the element.
ggplot(mpg, aes(cty, hwy)) + geom_point()+
theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
margin
can also be used for other element_text
elements (see ?theme
), such as axis.text.x
, axis.text.y
and title
.
addition
in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top")
, you'll need a different theme setting - e.g. axis.title.x.top
. See https://github.com/tidyverse/ggplot2/issues/4343.
Try this out:
grep -i 'killed process' /var/log/messages
To truncate:
// Math.trunc() is part of the ES6 spec
console.log(Math.trunc( 1.5 )); // returns 1
console.log(Math.trunc( -1.5 )); // returns -1
// Math.floor( -1.5 ) would return -2, which is probably not what you wanted
_x000D_
To round:
console.log(Math.round( 1.5 )); // 2
console.log(Math.round( 1.49 )); // 1
console.log(Math.round( -1.6 )); // -2
console.log(Math.round( -1.3 )); // -1
_x000D_
To reset your keyring.
Go into your home folder.
Press ctrl & h to show your hidden folders.
Now look in your .gnome2/keyrings directory.
Find the default.keyring file.
Move that file to a different folder.
Once done, reboot your computer.
Creation date/time is normally not stored. So no, you can't.
df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})
df.groupby(['sp', 'mt']).apply(lambda grp: grp.nlargest(1, 'count'))
khichar.anil covered most of this in his answer.
I am just adding the flag that will remove the tags from the revision names list. This gives us:
git name-rev --name-only --exclude=tags/* $SHA
Also make sure the value is not too large or too small for int like in my case.
Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.
On Ubuntu 19.10, I have done this in /etc/ImageMagick-6/policy.xml
uncomment this
<policy domain="module" rights="read | write" pattern="{PS,PDF,XPS}" />
and comment this
<!-- <policy domain="coder" rights="none" pattern="PDF" /> -->
After that, this command work without error
convert -thumbnail x300 -background white -alpha remove sample.pdf sample.png
>/dev/null 2>&1
will mute both stdout
and stderr
yum install nano >/dev/null 2>&1
Percentage values are not applicable to border-width
in CSS. This is listed in the spec.
You will need to use JavaScript to calculate the percentage of the element's width or whatever length quantity you need, and apply the result in px
or similar to the element's borders.
Never mind, figured it out:
set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)
Which I found by:
show all
And looking for some option that seemed relevant.
I have tried everything above, but none could solve my problem. I fixed it by updating the old version of youtube-dl to download playlist. To update it
sudo youtube-dl -U
or
youtube-dl -U
after you have successfully updated using the above command
youtube-dl -cit https://www.youtube.com/playlist?list=PLttJ4RON7sleuL8wDpxbKHbSJ7BH4vvCk
The accepted answer from CMS is correct, I have just added some features :
// parse a date time that can contains spaces, dashes, slashes, colons
function parseDate(input) {
// trimes and remove multiple spaces and split by expected characters
var parts = input.trim().replace(/ +(?= )/g,'').split(/[\s-\/:]/)
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2] || 1, parts[3] || 0, parts[4] || 0, parts[5] || 0); // Note: months are 0-based
}
After loading jquery.svg.js
you must load this file: http://keith-wood.name/js/jquery.svgdom.js
.
Source: http://keith-wood.name/svg.html#dom
Working example: http://jsfiddle.net/74RbC/99/
Performing a single click on an HTML element: Simply do element.click()
. Most major browsers support this.
To repeat the click more than once: Add an ID to the element to uniquely select it:
<a href="#" target="_blank" id="my-link" onclick="javascript:Test('Test');">Google Chrome</a>
and call the .click()
method in your JavaScript code via a for loop:
var link = document.getElementById('my-link');
for(var i = 0; i < 50; i++)
link.click();
web.py is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something.
"Hello, World!" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free:
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
Try This, It's working for me .
Single line of code
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
I use shortlog for this:
$ git shortlog master..
Username (3):
Write something
Add something
Bump to 1.3.8
Firefox 3.6 has a full screen option for HTML5 video's, right-click on the video and select 'full screen'.
The latest Webkit nightlies also support full screen HTML5 video, try the Sublime player with the latest nightly and hold Cmd / Ctrl while selecting the full screen option.
I guess Chrome / Opera will also support something like this. Hopefully IE9 will also support full screen HTML5 video.
Assert.That(myTestDelegate, Throws.ArgumentException
.With.Property("Message").EqualTo("your argument is invalid."));
The way to do this without use of plugins is to make a subclass of google's OverlayView() method.
https://developers.google.com/maps/documentation/javascript/reference?hl=en#OverlayView
You make a custom function and apply it to the map.
function Label() {
this.setMap(g.map);
};
Now you prototype your subclass and add HTML nodes:
Label.prototype = new google.maps.OverlayView; //subclassing google's overlayView
Label.prototype.onAdd = function() {
this.MySpecialDiv = document.createElement('div');
this.MySpecialDiv.className = 'MyLabel';
this.getPanes().overlayImage.appendChild(this.MySpecialDiv); //attach it to overlay panes so it behaves like markers
}
you also have to implement remove and draw functions as stated in the API docs, or this won't work.
Label.prototype.onRemove = function() {
... // remove your stuff and its events if any
}
Label.prototype.draw = function() {
var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); // translate map latLng coords into DOM px coords for css positioning
var pos = this.get('position');
$('.myLabel')
.css({
'top' : position.y + 'px',
'left' : position.x + 'px'
})
;
}
That's the gist of it, you'll have to do some more work in your specific implementation.
{
class Program
{
public static List<Product> list;
static void Main(string[] args)
{
list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};
Console.WriteLine("Enter ProductID to remove");
int uno = Convert.ToInt32(Console.ReadLine());
var itemToRemove = list.Find(r => r.ProductId == uno);
if (itemToRemove != null)
list.Remove(itemToRemove);
Console.WriteLine($"{itemToRemove.ProductId}{itemToRemove.Name}{itemToRemove.Brand}{itemToRemove.Price}{ itemToRemove.Quantity}");
Console.WriteLine("------------sucessfully Removed---------------");
var query2 = from x in list select x;
foreach (var item in query2)
{
/*Console.WriteLine(item.ProductId+" "+item.Name+" "+item.Brand+" "+item.Price+" "+item.Quantity );*/
Console.WriteLine($"{item.ProductId}{item.Name}{item.Brand}{item.Price}{ item.Quantity}");
}
}
}
}
!!
it's using NOT
operation twice together, !
convert the value to a boolean
and reverse it, here is a simple example to see how !!
works:
At first, the place you have:
var zero = 0;
Then you do !0
, it will be converted to boolean and be evaluated to true
, because 0 is falsy
, so you get the reversed value and converted to boolean, so it gets evaluated to true
.
!zero; //true
but we don't want the reversed boolean version of the value, so we can reverse it again to get our result! That's why we use another !
.
Basically, !!
make us sure, the value we get is boolean, not falsy, truthy or string etc...
So it's like using Boolean
function in javascript, but easy and shorter way to convert a value to boolean:
var zero = 0;
!!zero; //false
From the Perldoc page on sleep:
For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep().
Actually, it provides usleep()
(which sleeps in microseconds) and nanosleep()
(which sleeps in nanoseconds). You may want usleep()
, which should let you deal with easier numbers. 1 millisecond sleep (using each):
use strict;
use warnings;
use Time::HiRes qw(usleep nanosleep);
# 1 millisecond == 1000 microseconds
usleep(1000);
# 1 microsecond == 1000 nanoseconds
nanosleep(1000000);
If you don't want to (or can't) load a module to do this, you may also be able to use the built-in select()
function:
# Sleep for 250 milliseconds
select(undef, undef, undef, 0.25);
Check if the data attribute is present, then do the stuff...
$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
if(e.target.getAttribute('data-title')) {
var careerTitle = $(this).attr('data-title');
if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
}
});
ngStyle directive allows you to set CSS style on an HTML element dynamically.
Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys. Since some CSS style names are not valid keys for an object, they must be quoted.
ng-style="{color: myColor}"
Your code will be:
<div ng-style="{'width':'20px', 'height':'20px', 'margin-top':'10px', 'border':'solid 1px black', 'background-color':'#ff0000'}"></div>
If you want to use scope variables:
<div ng-style="{'background-color': data.backgroundCol}"></div>
Here an example on fiddle that use ngStyle
, and below the code with the running snippet:
angular.module('myApp', [])_x000D_
.controller('MyCtrl', function($scope) {_x000D_
$scope.items = [{_x000D_
name: 'Misko',_x000D_
title: 'Angular creator'_x000D_
}, {_x000D_
name: 'Igor',_x000D_
title: 'Meetup master'_x000D_
}, {_x000D_
name: 'Vojta',_x000D_
title: 'All-around superhero'_x000D_
}_x000D_
_x000D_
];_x000D_
});
_x000D_
.pending-delete {_x000D_
background-color: pink_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller='MyCtrl' ng-style="{color: myColor}">_x000D_
_x000D_
<input type="text" ng-model="myColor" placeholder="enter a color name">_x000D_
_x000D_
<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">_x000D_
name: {{item.name}}, {{item.title}}_x000D_
<input type="checkbox" ng-model="item.checked" />_x000D_
<span ng-show="item.checked"/><span>(will be deleted)</span>_x000D_
</div>_x000D_
<p>_x000D_
<div ng-hide="myColor== 'red'">I will hide if the color is set to 'red'.</div>_x000D_
</div>
_x000D_
I had some dealings with the select \ multi-select this is what did the trick for me
<select name="mySelect" multiple="multiple">
<option>Foo</option>
<option>Bar</option>
<option>Foo Bar</option>
<option>Bar Foo</option>
</select>
First, Set :
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;
The screenshot was very helpful - the following code will do the job (assuming data is located in column A starting A1):
Sub RemoveRows()
Dim i As Long
i = 1
Do While i <= ThisWorkbook.ActiveSheet.Range("A1").CurrentRegion.Rows.Count
If InStr(1, ThisWorkbook.ActiveSheet.Cells(i, 1).Text, "-", vbTextCompare) > 0 Then
ThisWorkbook.ActiveSheet.Cells(i, 1).EntireRow.Delete
Else
i = i + 1
End If
Loop
End Sub
Sample file is shared: https://www.dropbox.com/s/2vhq6vw7ov7ssya/RemoweDashRows.xlsm
I don't have enough reputation to comment on the relevant answers, but to people reading this; adding .btn does not just add the pointer cursor but adds a lot of other styling as well. Which is great if it's a button and you want the bootstap button styling, but in other cases it would mess a lot up for other elements.
The best thing you can do, like Hari Das suggested, and which I also always do, is to add the following css:
.cursor-pointer {
cursor: pointer;
}
After which you can add it to any element
<div class="cursor-pointer"> .. </div>
Just a comment on this - I've used HTML5 video for a full-screen background and it works a treat - but make sure to use either Height:100% and width:auto or the other way around - to ensure you keep aspect ratio.
As for Ipads -you can (apparently) do this, by having a hidden and then forcing the click event to fire, and having the function of the click event kick off the Load/Play().
P.s - this shouldn't require any plugins and can be done with minimal JS - If you're targeting any mobile device (I would assume you might be..) staying away from any such framework is the way forward.
I find information that I copied below answer the question
Adapt yourself to IDLE: Instead of hitting the up arrow to bring back a previous command, if you just put your cursor on the previous command you want to repeat and then press "enter", that command will be repeated at the current command prompt. Press enter again, and the command gets executed.
Force IDLE to adapt itself to you: If you insist on making the arrow keys in the IDLE command prompt window work like those in every other command prompt, you can do this. Go to the "Options" menu, select "Configure IDLE", and then "Keys". Changing the key that is associated with the "previous command" and "next command" actions to be the up arrow, and down arrow, respectively.
This worked for me on Windows
add the following to your php code where $file1 is the location and name of the first PDF file, $file2 is the location and name of the second and $newfile is the location and name of the destination file
$file1 = ' c:\\\www\\\folder1\\\folder2\\\file1.pdf';
$file2 = ' c:\\\www\\\folder1\\\folder2\\\file2.pdf';
$file3 = ' c:\\\www\\\folder1\\\folder2\\\file3.pdf';
$command = 'cmd /c C:\\\pdftk\\\bin\\\pdftk.exe '.$file1.$file2.$newfile;
$result = exec($command);
people.OrderBy(person => person.lastname).ToList();
If your table is only 2 columns across, you can easily reach the second td
with the adjacent sibling selector, which IE8 does support along with :first-child
:
.editor td:first-child
{
width: 150px;
}
.editor td:first-child + td input,
.editor td:first-child + td textarea
{
width: 500px;
padding: 3px 5px 5px 5px;
border: 1px solid #CCC;
}
Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td
, as suggested by James Allardice.
I am just answering here with the formatted version of the final sql I needed based on Bob Jarvis answer as posted in my comment above:
select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select author_id, count(1) as total_count
from names
group by author_id) n2
on (n2.author_id = n1.author_id)
You have two ways:
Lets start by looking for a specific application in my laptop:
[root@pinky:~]# ps fax | grep mozilla
3358 ? S 0:00 \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2 S+ 0:00 \_ grep mozilla
All examples now will look for PID 3358.
First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:
[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358
So your code will be:
if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
kill $PID
fi
Second way: Just look for something in the /proc/$PID
directory. I am using "exe" in this example, but you can use anything else.
[root@pinky:~]# ls -l /proc/3358/exe
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash
So your code will be:
if [ -f /proc/$PID/exe ]; then
kill $PID
fi
BTW: whats wrong with kill -9 $PID || true
?
EDIT:
After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.
First add following lines in ~/.bashrc file
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
then open terminal and source the nvm.sh script
source ~/.nvm/nvm.sh
You can always make it a function
function writeObject(color){
$('body').append('<div style="color:'+color+';">Hello!</div>')
}
writeObject('blue')
?
From jQuery.ajax()
async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
So in your request, you must do async: false
instead of async: "false"
.
Update:
The return value of ajaxSubmit
is not the return value of the success: function(){...}
. ajaxSubmit
returns no value at all, which is equivalent to undefined
, which in turn evaluates to true.
And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.
If you want to submit the form only, when the response is "Successful"
, you must return false
from ajaxSubmit
and then submit the form in the success
function, as @halilb already suggested.
Something along these lines should work
function ajaxSubmit() {
var password = $.trim($('#employee_password').val());
$.ajax({
type: "POST",
url: "checkpass.php",
data: "password="+password,
success: function(response) {
if(response == "Successful")
{
$('form').removeAttr('onsubmit'); // prevent endless loop
$('form').submit();
}
}
});
return false;
}
If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables. See the picture below.
Alternatively, if you are executing gradle commands using terminal, just type 'export KEY=VALUE', and your job is done.
The Java heap size limits for Windows are:
This doesn't help you getting a bigger Java heap, but now you know you can't go beyond these values.
My solution for BlueJ is to edit the New Class template "stdclass.tmpl" in Program Files (x86)\BlueJ\lib\english\templates\newclass and add this method:
public static <T> void p(T s)
{
System.out.println(s);
}
Or this other version:
public static void p(Object s)
{
System.out.println(s);
}
As for Eclipse I'm using the suggested shortcut syso + <Ctrl> + <Space>
:)
we can also do with this approch.
var example = {
foo1: { /* stuff1 */},
foo2: { /* stuff2 */},
foo3: { /* stuff3 */}
};
Object.entries(example)[0][1];
This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('/tmp/test.png')
EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show()
when you are ready to display the plots:
import matplotlib.pyplot as plt
# Turn interactive plotting off
plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')
# Display all "open" (non-closed) figures
plt.show()
For django 1.10 you may have to do python manage.py makemigrations appname
.
It would be nice if you could, but you can't use that syntax in SQL.
Try this:
(column1 LIKE '%this%' OR column1 LIKE '%that%') AND something = else
Note the use of brackets! You need them around the OR
expression.
Without brackets, it will be parsed as A OR (B AND C)
,which won't give you the results you expect.
This is a paragraph option. Go to Window>Paragraph then a small window will pop up. You will have two buttons on the bottom. One with a arrow on the left of P and one on the right. Select the right one.
For swedish Å Ä Ö the only solution form the ones above working was:
Encoding.GetEncoding("iso-8859-1")
Hopefully this will save someone time.
Whenever you update your Gradle files do not forget to check the compatible Gradle wrapper distibutionUrl
, in your case it happened because of the same.
distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-all.zip
Better to use android.R.drawable because it is public and documented.
Try below code:
var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;
if (sizeInKB >= sizeLimit) {
alert("Max file size 30KB");
return false;
}
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.