Try this code
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
//You can get
}
return super.onOptionsItemSelected(item);
}
Add below code to your onCreate() metod
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
Marc's answer is the approach I use for this, but for simplicity (and a friendlier API?) you can define a property in the collection base class if you have one such as:
public abstract class CollectionBase<T> : IList<T>
{
...
public Type ElementType
{
get
{
return typeof(T);
}
}
}
I have found this approach useful, and is easy to understand for any newcomers to generics.
Why not use padding with negative margins? Something like this:
<div class="parent">
<div class="child1">
</div>
<div class="child2">
</div>
</div>
And then
.parent {
padding-top: 1em;
}
.child1 {
margin-top: -1em;
height: 1em;
}
.child2 {
margin-top: 0;
height: 100%;
}
NVL and COALESCE are used to achieve the same functionality of providing a default value in case the column returns a NULL.
The differences are:
Examples for the third case. Other cases are simple.
select nvl('abc',10) from dual;
would work as NVL will do an implicit conversion of numeric 10 to string.
select coalesce('abc',10) from dual;
will fail with Error - inconsistent datatypes: expected CHAR got NUMBER
Example for UNION use-case
SELECT COALESCE(a, sysdate)
from (select null as a from dual
union
select null as a from dual
);
fails with ORA-00932: inconsistent datatypes: expected CHAR got DATE
SELECT NVL(a, sysdate)
from (select null as a from dual
union
select null as a from dual
) ;
succeeds.
More information : http://www.plsqlinformation.com/2016/04/difference-between-nvl-and-coalesce-in-oracle.html
None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:
Edit file phpMyAdmin.conf
sudo nano /etc/httpd/conf.d/phpMyAdmin.conf
And replace this at the top:
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
#Require ip 127.0.0.1
#Require ip ::1
Require all granted
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>
import java.lang.String;
This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).
Here's a simple function that will downcast floats into the smallest possible integer type that doesn't lose any information. For examples,
100.0 can be converted from float to integer, but 99.9 can't (without losing information to rounding or truncation)
Additionally, 1.0 can be downcast all the way to int8
without losing information, but the smallest integer type for 100_000.0 is int32
Code examples:
import numpy as np
import pandas as pd
def float_to_int( s ):
if ( s.astype(np.int64) == s ).all():
return pd.to_numeric( s, downcast='integer' )
else:
return s
# small integers are downcast into 8-bit integers
float_to_int( np.array([1.0,2.0]) )
Out[1]:array([1, 2], dtype=int8)
# larger integers are downcast into larger integer types
float_to_int( np.array([100_000.,200_000.]) )
Out[2]: array([100000, 200000], dtype=int32)
# if there are values to the right of the decimal
# point, no conversion is made
float_to_int( np.array([1.1,2.2]) )
Out[3]: array([ 1.1, 2.2])
This was the code that worked for me when the column Id is unknown and the AutoGenerateColumns == true;
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Drawing" %>
<html>
<head runat="server">
<script runat="server">
protected void Page_Load(object sender, EventArgs eventArgs)
{
DataTable data = new DataTable();
data.Columns.Add("Id", typeof(int));
data.Columns.Add("Notes", typeof(string));
data.Columns.Add("RequestedDate", typeof(DateTime));
for (int idx = 0; idx < 5; idx++)
{
DataRow row = data.NewRow();
row["Id"] = idx;
row["Notes"] = string.Format("Note {0}", idx);
row["RequestedDate"] = DateTime.Now.Subtract(new TimeSpan(idx, 0, 0, 0, 0));
data.Rows.Add(row);
}
listData.DataSource = data;
listData.DataBind();
}
private void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (TableCell tableCell in e.Row.Cells)
{
DataControlFieldCell cell = (DataControlFieldCell)tableCell;
if (cell.ContainingField.HeaderText == "Id")
{
cell.Visible = false;
continue;
}
if (cell.ContainingField.HeaderText == "Notes")
{
cell.Width = 400;
cell.BackColor = Color.Blue;
continue;
}
if (cell.ContainingField.HeaderText == "RequestedDate")
{
cell.Width = 130;
continue;
}
}
}
</script>
</head>
<body>
<form runat="server">
<asp:GridView runat="server" ID="listData" AutoGenerateColumns="True" HorizontalAlign="Left"
PageSize="20" OnRowDataBound="GridView_RowDataBound" EmptyDataText="No Data Available."
Width="95%">
</asp:GridView>
</form>
</body>
</html>
What's the real result here?
Your program leaked the memory. Depending on your OS, it may have been recovered.
Most modern desktop operating systems do recover leaked memory at process termination, making it sadly common to ignore the problem, as can be seen by many other answers here.)
But you are relying on a safety feature you should not rely upon, and your program (or function) might run on a system where this behaviour does result in a "hard" memory leak, next time.
You might be running in kernel mode, or on vintage / embedded operating systems which do not employ memory protection as a tradeoff. (MMUs take up die space, memory protection costs additional CPU cycles, and it is not too much to ask from a programmer to clean up after himself).
You can use and re-use memory any way you like, but make sure you deallocated all resources before exiting.
Why the value had to be given in yyyy-MM-dd?
According to the input type = date spec of HTML 5, the value has to be in the format yyyy-MM-dd
since it takes the format of a valid full-date
which is specified in RFC3339 as
full-date = date-fullyear "-" date-month "-" date-mday
There is nothing to do with Angularjs since the directive input doesn't support date
type.
How do I get Firefox to accept my formatted value in the date input?
FF doesn't support date
type of input for at least up to the version 24.0. You can get this info from here. So for right now, if you use input with type being date
in FF, the text box takes whatever value you pass in.
My suggestion is you can use Angular-ui's Timepicker and don't use the HTML5 support for the date input.
Another way is to use FIXED
function, you can specify the number of decimal places but it defaults to 2 if the places aren't specified, i.e.
=FIXED(E5,2)
or just
=FIXED(E5)
Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.
Commands are first read from /etc/zshenv this cannot be overridden.
Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
former affects all startup files, while the second only affects global
startup files (those shown here with an path starting with a /). If
one of the options is unset at any point, any subsequent startup
file(s) of the corresponding type will not be read. It is also possi-
ble for a file in $ZDOTDIR to re-enable GLOBAL_RCS. Both RCS and
GLOBAL_RCS are set by default.
Commands are then read from $ZDOTDIR/.zshenv. If the shell is a login
shell, commands are read from /etc/zprofile and then $ZDOTDIR/.zpro-
file. Then, if the shell is interactive, commands are read from
/etc/zshrc and then $ZDOTDIR/.zshrc. Finally, if the shell is a login
shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.
From this we can see the order files are read is:
/etc/zshenv # Read for every shell
~/.zshenv # Read for every shell except ones started with -f
/etc/zprofile # Global config for login shells, read before zshrc
~/.zprofile # User config for login shells
/etc/zshrc # Global config for interactive shells
~/.zshrc # User config for interactive shells
/etc/zlogin # Global config for login shells, read after zshrc
~/.zlogin # User config for login shells
~/.zlogout # User config for login shells, read upon logout
/etc/zlogout # Global config for login shells, read after user logout file
You can get more information here.
If you're struggling with such an issue using Lollipop (Android 5.*) probably you guys should do one simple step that I'd done before my ADB (I use Ubuntu) got my phone:
Change USB PC connection type to "Send images(PTP)" (before I've been using "Media device(MTP)")
Just like this:
And don't forget to activate checkbox "USB debugging".
As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]}
are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".
{16{a[15]}}
is the same as
{
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}
In bit-blasted form,
assign result = {{16{a[15]}}, {a[15:0]}};
is the same as:
assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];
Angular CLI: 8.3.4 Node : 10.16.3 Angualr : 4.2.5
I used "dotnet new angular" command to generate the project, and it has generated 3 different modules in app folder (Although a simple test with ng new project-name just generates a single module.
see the modules in your project and decide wich module you want - then specify the name
ng g c componentName --module=[name-of-your-module]
You can read more about modules here: https://angular.io/guide/architecture-modules
Output needs to be redirected with &>/dev/null
which redirects both stderr and stdout to /dev/null and is a synonym of >/dev/null 2>/dev/null
or >/dev/null 2>&1
.
The best way is to use sh -c '( ( command ) & )'
where command is anything.
ssh askapache 'sh -c "( ( nohup chown -R ask:ask /www/askapache.com &>/dev/null ) & )"'
You can also use nohup directly to launch the shell:
ssh askapache 'nohup sh -c "( ( chown -R ask:ask /www/askapache.com &>/dev/null ) & )"'
Another trick is to use nice to launch the command/shell:
ssh askapache 'nice -n 19 sh -c "( ( nohup chown -R ask:ask /www/askapache.com &>/dev/null ) & )"'
You assign to big and small before the array is initialized, i.e., big and small assume the value of whatever is on the stack at this point. As they are just plain value types and no references, they won't assume a new value once values[0] is written to via cin >>.
Just move the assignment after your first loop and it should be fine.
This is what I did in my makefile based on others solutions. Note not only does this give your code a revision number, it also appends the hash which allows you to recreate the release.
# Set the source control revision similar to subversion to use in 'c'
# files as a define.
# You must build in the master branch otherwise the build branch will
# be prepended to the revision and/or "dirty" appended. This is to
# clearly ID developer builds.
REPO_REVISION_:=$(shell git rev-list HEAD --count)
BUILD_BRANCH:=$(shell git rev-parse --abbrev-ref HEAD)
BUILD_REV_ID:=$(shell git rev-parse HEAD)
BUILD_REV_ID_SHORT:=$(shell git describe --long --tags --dirty --always)
ifeq ($(BUILD_BRANCH), master)
REPO_REVISION:=$(REPO_REVISION_)_g$(BUILD_REV_ID_SHORT)
else
REPO_REVISION:=$(BUILD_BRANCH)_$(REPO_REVISION_)_r$(BUILD_REV_ID_SHORT)
endif
export REPO_REVISION
export BUILD_BRANCH
export BUILD_REV_ID
Set a cookie value on the page, and then read it back server side.
You won't be able to set a specific header, but the value will be accessible in the headers section and not the content body.
C# Controller:
var result = await _roleManager.CreateAsync(identityRole);
if (result.Succeeded == true)
TempData["roleCreateAlert"] = "Added record successfully";
Razor Page:
@if (TempData["roleCreateAlert"] != null)
{
<div class="alert alert-success">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>@TempData["roleCreateAlert"]</p>
</div>
}
Any Alert Auto Close:
<script type="text/javascript">
$(".alert").delay(5000).slideUp(200, function () {
$(this).alert('close');
});
</script>
Here's the source code of an HttpHandler which does that, maybe it'll help you
If you have existing password for mysql then write as mentioned below :
Find config(dot)inc file under C:\wamp\apps\phpmyadmin3.5.1 Inside this file find this one line
$cfg['Servers'][$i]['password'] =";
and replace it with
$cfg['Servers'][$i]['password'] = **'your-password'**;
Hey guys here is a simple test program that shows how to allocate and pass an array using new or malloc. Just cut, paste and run it. Have fun!
struct Coordinate
{
int x,y;
};
void resize( int **p, int size )
{
free( *p );
*p = (int*) malloc( size * sizeof(int) );
}
void resizeCoord( struct Coordinate **p, int size )
{
free( *p );
*p = (Coordinate*) malloc( size * sizeof(Coordinate) );
}
void resizeCoordWithNew( struct Coordinate **p, int size )
{
delete [] *p;
*p = (struct Coordinate*) new struct Coordinate[size];
}
void SomeMethod(Coordinate Coordinates[])
{
Coordinates[0].x++;
Coordinates[0].y = 6;
}
void SomeOtherMethod(Coordinate Coordinates[], int size)
{
for (int i=0; i<size; i++)
{
Coordinates[i].x = i;
Coordinates[i].y = i*2;
}
}
int main()
{
//static array
Coordinate tenCoordinates[10];
tenCoordinates[0].x=0;
SomeMethod(tenCoordinates);
SomeMethod(&(tenCoordinates[0]));
if(tenCoordinates[0].x - 2 == 0)
{
printf("test1 coord change successful\n");
}
else
{
printf("test1 coord change unsuccessful\n");
}
//dynamic int
int *p = (int*) malloc( 10 * sizeof(int) );
resize( &p, 20 );
//dynamic struct with malloc
int myresize = 20;
int initSize = 10;
struct Coordinate *pcoord = (struct Coordinate*) malloc (initSize * sizeof(struct Coordinate));
resizeCoord(&pcoord, myresize);
SomeOtherMethod(pcoord, myresize);
bool pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord[i].x == i) && (pcoord[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord[i].x,pcoord[i].y);
pass = false;
}
}
if (pass)
{
printf("test2 coords for dynamic struct allocated with malloc worked correctly\n");
}
//dynamic struct with new
myresize = 20;
initSize = 10;
struct Coordinate *pcoord2 = (struct Coordinate*) new struct Coordinate[initSize];
resizeCoordWithNew(&pcoord2, myresize);
SomeOtherMethod(pcoord2, myresize);
pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord2[i].x == i) && (pcoord2[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord2[i].x,pcoord2[i].y);
pass = false;
}
}
if (pass)
{
printf("test3 coords for dynamic struct with new worked correctly\n");
}
return 0;
}
I waited a bit on @QuinnTaylor to update his answer, but since he didn't, here's the answer a bit more clearly and in a way that it will load on XCode7 (and perhaps greater). I used this in a Cocoa application, but it likely will work okay with an iOS application as well. Has no ARC errors.
Paste before any @implementation section in your AppDelegate.m or AppDelegate.mm file.
#import <CommonCrypto/CommonCryptor.h>
@implementation NSData (AES256)
- (NSData *)AES256EncryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (NSData *)AES256DecryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
@end
Paste these two functions in the @implementation class you desire. In my case, I chose @implementation AppDelegate in my AppDelegate.mm or AppDelegate.m file.
- (NSString *) encryptString:(NSString*)plaintext withKey:(NSString*)key {
NSData *data = [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
return [data base64EncodedStringWithOptions:kNilOptions];
}
- (NSString *) decryptString:(NSString *)ciphertext withKey:(NSString*)key {
NSData *data = [[NSData alloc] initWithBase64EncodedString:ciphertext options:kNilOptions];
return [[NSString alloc] initWithData:[data AES256DecryptWithKey:key] encoding:NSUTF8StringEncoding];
}
Either delete the selector or set it to the same color as your text appears normally.
Try recreate()
it will cause this Activity to be recreated.
You can do it easily like this.
String cls=student.getStudentClass();
class_spinner.setSelection(classArray.indexOf(cls),true);
Prior to Microsoft introducing their new "Linux subsystem for Windows" option, CreateProcess()
was the closest thing Windows has to fork()
, but Windows requires you to specify an executable to run in that process.
The UNIX process creation is quite different to Windows. Its fork()
call basically duplicates the current process almost in total, each in their own address space, and continues running them separately. While the processes themselves are different, they are still running the same program. See here for a good overview of the fork/exec
model.
Going back the other way, the equivalent of the Windows CreateProcess()
is the fork()/exec()
pair of functions in UNIX.
If you were porting software to Windows and you don't mind a translation layer, Cygwin provided the capability that you want but it was rather kludgey.
Of course, with the new Linux subsystem, the closest thing Windows has to fork()
is actually fork()
:-)
You can not run/execute an .exe file that is in the users local machine or through a site. The user must first download the exe file and then run the executable file.
So there is no possible way
The following code works only when the EXE is Present in the User's Machine.
<a href = "C:\folder_name\program.exe">
How about the simple:
constexpr char const* toString(bool b)
{
return b ? "true" : "false";
}
There isn't any need for table and table-cells. It can be achieved easily using transform.
Example: http://codepen.io/arvind/pen/QNbwyM
Code:
.child {_x000D_
height: 10em;_x000D_
border: 1px solid green;_x000D_
position: relative;_x000D_
}_x000D_
.child-content {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
-webkit-transform: translate(-50%, -50%);_x000D_
transform: translate(-50%, -50%);_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="row parent">_x000D_
<div class="col-xs-6 col-lg-6 child">_x000D_
<div class="child-content">_x000D_
<div style="height:4em;border:1px solid #000">Big</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-6 col-lg-6 child">_x000D_
<div class="child-content">_x000D_
<div style="height:3em;border:1px solid #F00">Small</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Many people use both 2.X and 3.X python. You can use pip -V
to show default pip version.
If you have many python versions, and you want to install some packages through different pip, I advise this way:
sudo python2.X -m pip install some-package==0.16
setting direction CSS property to rtl should work with you. I guess it isn't supported on IE6.
e.g
<ul style="direction:rtl;">
<li> item </li>
<li> item </li>
</ul>
If you are willing to change your uri, you could also use PathVariable
.
@RequestMapping(value="/mapping/foo/{foo}/{bar}", method=RequestMethod.GET)
public String process(@PathVariable String foo,@PathVariable String bar) {
//Perform logic with foo and bar
}
NB: The first foo is part of the path, the second one is the PathVariable
I developed an ultimate solution for image scaling in Swift.
You can use it to resize image to fill, aspect fill or aspect fit specified size.
You can align image to center or any of four edges and four corners.
And also you can trim extra space which is added if aspect ratios of original image and target size are not equal.
enum UIImageAlignment {
case Center, Left, Top, Right, Bottom, TopLeft, BottomRight, BottomLeft, TopRight
}
enum UIImageScaleMode {
case Fill,
AspectFill,
AspectFit(UIImageAlignment)
}
extension UIImage {
func scaleImage(width width: CGFloat? = nil, height: CGFloat? = nil, scaleMode: UIImageScaleMode = .AspectFit(.Center), trim: Bool = false) -> UIImage {
let preWidthScale = width.map { $0 / size.width }
let preHeightScale = height.map { $0 / size.height }
var widthScale = preWidthScale ?? preHeightScale ?? 1
var heightScale = preHeightScale ?? widthScale
switch scaleMode {
case .AspectFit(_):
let scale = min(widthScale, heightScale)
widthScale = scale
heightScale = scale
case .AspectFill:
let scale = max(widthScale, heightScale)
widthScale = scale
heightScale = scale
default:
break
}
let newWidth = size.width * widthScale
let newHeight = size.height * heightScale
let canvasWidth = trim ? newWidth : (width ?? newWidth)
let canvasHeight = trim ? newHeight : (height ?? newHeight)
UIGraphicsBeginImageContextWithOptions(CGSizeMake(canvasWidth, canvasHeight), false, 0)
var originX: CGFloat = 0
var originY: CGFloat = 0
switch scaleMode {
case .AspectFit(let alignment):
switch alignment {
case .Center:
originX = (canvasWidth - newWidth) / 2
originY = (canvasHeight - newHeight) / 2
case .Top:
originX = (canvasWidth - newWidth) / 2
case .Left:
originY = (canvasHeight - newHeight) / 2
case .Bottom:
originX = (canvasWidth - newWidth) / 2
originY = canvasHeight - newHeight
case .Right:
originX = canvasWidth - newWidth
originY = (canvasHeight - newHeight) / 2
case .TopLeft:
break
case .TopRight:
originX = canvasWidth - newWidth
case .BottomLeft:
originY = canvasHeight - newHeight
case .BottomRight:
originX = canvasWidth - newWidth
originY = canvasHeight - newHeight
}
default:
break
}
self.drawInRect(CGRectMake(originX, originY, newWidth, newHeight))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
There are examples of applying this solution below.
Gray rectangle is target site image will be resized to.
Blue circles in light blue rectangle is the image (I used circles because it's easy to see when it's scaled without preserving aspect).
Light orange color marks areas that will be trimmed if you pass trim: true
.
Aspect fit before and after scaling:
Another example of aspect fit:
Aspect fit with top alignment:
Aspect fill:
Fill:
I used upscaling in my examples because it's simpler to demonstrate but solution also works for downscaling as in question.
For JPEG compression you should use this :
let compressionQuality: CGFloat = 0.75 // adjust to change JPEG quality
if let data = UIImageJPEGRepresentation(image, compressionQuality) {
// ...
}
You can check out my gist with Xcode playground.
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
Did you check the string concatenation function? Something like:
update table_c set column_a = column_b || column_c
should work. More here
This answer is likely wrong wrong the context. I thought VBA now run on the CLR these days, but it does not. In any case, this reply may be useful to someone. Or not.
If you run Office 2010 32-bit mode then it's the same as Office 2007. (The "issue" is Office running in 64-bit mode). It's the bitness of the execution context (VBA/CLR) which is important here and the bitness of the loaded VBA/CLR depends upon the bitness of the host process.
Between 32/64-bit calls, most notable things that go wrong are using long
or int
(constant-sized in CLR) instead of IntPtr
(dynamic sized based on bitness) for "pointer types".
The ShellExecute function has a signature of:
HINSTANCE ShellExecute(
__in_opt HWND hwnd,
__in_opt LPCTSTR lpOperation,
__in LPCTSTR lpFile,
__in_opt LPCTSTR lpParameters,
__in_opt LPCTSTR lpDirectory,
__in INT nShowCmd
);
In this case, it is important HWND is IntPtr
(this is because a HWND is a "HANDLE" which is void*
/"void pointer") and not long
. See pinvoke.net ShellExecute as an example. (While some "solutions" are shady on pinvoke.net, it's a good place to look initially).
Happy coding.
As far as any "new syntax", I have no idea.
You can do something like this:
users = users.Where(x => x.userId != userIdToRemove);
Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.
Step 1. Use the following namespaces
using System.Windows;
using System.Threading;
using System.Windows.Threading;
Step 2. Put the following line where you need to update UI
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
//Update UI here
}));
Syntax
[BrowsableAttribute(false)] public object Invoke( DispatcherPriority priority, Delegate method )
Parameters
priority
Type:
System.Windows.Threading.DispatcherPriority
The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.
method
Type:
System.Delegate
A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.
Return Value
Type:
System.Object
The return value from the delegate being invoked or null if the delegate has no return value.
Version Information
Available since .NET Framework 3.0
A single line of code using Linq
public static bool IsPalindrome(string str)
{
return str.SequenceEqual(str.Reverse());
}
If you want to get slug of the post from the loop then use:
global $post;
echo $post->post_name;
If you want to get slug of the post outside the loop then use:
$post_id = 45; //specify post id here
$post = get_post($post_id);
$slug = $post->post_name;
Based on Anastasiya's answer. I think this is the shortest vba command:
Option Explicit
Sub Sample()
Dim sColumnLetter as String
Dim iColumnNumber as Integer
sColumnLetter = "C"
iColumnNumber = Columns(sColumnLetter).Column
MsgBox "The column number is " & iColumnNumber
End Sub
Caveat: The only condition for this code to work is that a worksheet is active, because Columns
is equivalent to ActiveSheet.Columns
. ;)
When you say adding antMatchers doesnt help - what do you mean? antMatchers is exactly how you do it. Something like the following should work (obviously changing your URL appropriately):
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/authFailure").permitAll()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
If you are still not having any joy, then you will need to provide more details/stacktrace etc.
REST is a generic design technique used to describe how a web service can be accessed. Using REST you can make http requests to get data. If you try it in your browser it would be just like going to a website except instead of returning a web page you would get back XML. Some services will also return data in JSON format which is easier to use with Javascript.
OData is a specific technology that exposes data through REST.
If you want to sum it up real quick, think of it as:
A pivot is used to convert one of the columns in your data set from rows into columns (this is typically referred to as the spreading column). In the example you have given, this means converting the PhaseID
rows into a set of columns, where there is one column for each distinct value that PhaseID
can contain - 1, 5 and 6 in this case.
These pivoted values are grouped via the ElementID
column in the example that you have given.
Typically you also then need to provide some form of aggregation that gives you the values referenced by the intersection of the spreading value (PhaseID
) and the grouping value (ElementID
). Although in the example given the aggregation that will be used is unclear, but involves the Effort
column.
Once this pivoting is done, the grouping and spreading columns are used to find an aggregation value. Or in your case, ElementID
and PhaseIDX
lookup Effort
.
Using the grouping, spreading, aggregation terminology you will typically see example syntax for a pivot as:
WITH PivotData AS
(
SELECT <grouping column>
, <spreading column>
, <aggregation column>
FROM <source table>
)
SELECT <grouping column>, <distinct spreading values>
FROM PivotData
PIVOT (<aggregation function>(<aggregation column>)
FOR <spreading column> IN <distinct spreading values>));
This gives a graphical explanation of how the grouping, spreading and aggregation columns convert from the source to pivoted tables if that helps further.
You should enable your interceptor extension man manually, it locate in the top-right of your postman window. There are several buttons, find the interceptor button and enable it, then you can send cookies after set Cookie field in your request headers.
Many others have done an excellent job here giving a basic answer, especially Tobias Mühl. As mentioned, GMail's Api very closely matches the definition given by RFC2368 and RFC6068. This is true of the extended form of the mailto: links, but it's also true in the commonly-used forms found in the other answers. Of the five parameters, four are identical (such as to
, cc
, bcc
and body
) and one received only slight modification (su
is gmail's version of subject
).
If you want to know more about what you can do with mailTo gmail URLs, then these RFCs might be of help. Unfortunately, Google has not published any source themselves.
To clarify the parameters:
to
- Email to whosu
(gmail API) / subject
(mailTo API) - Email Titlebody
- Email Bodybcc
- Email Blind-Carbon Copycc
- Email Carbon Copy addressSlightly more concise now with jQuery 1.6+:
var e = jQuery.Event( 'keydown', { which: $.ui.keyCode.ENTER } );
$('input').trigger(e);
(If you're not using jQuery UI, sub in the appropriate keycode instead.)
In my case it was the security constraints defined in web.xml. Make sure they have the same roles you use in your tomcat-users.xml
file.
For example, this is one of the out-of-the-box tags and will work with the standard tomcat-users.xml.
<security-constraint>
<web-resource-collection>
<web-resource-name>HTML Manager interface (for humans)</web-resource-name>
<url-pattern>/html/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>manager-gui</role-name>
</auth-constraint>
</security-constraint>
In my case an admin had used a different role-name which prevented me from accessing the manager.
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);
The unfortunate truth about AJAX and the 302 redirect is that you can't get the headers from the return because the browser never gives them to the XHR. When a browser sees a 302 it automatically applies the redirect. In this case, you would see the header in firebug because the browser got it, but you would not see it in ajax, because the browser did not pass it. This is why the success and the error handlers never get called. Only the complete handler is called.
http://www.checkupdown.com/status/E302.html
The 302 response from the Web server should always include an alternative URL to which redirection should occur. If it does, a Web browser will immediately retry the alternative URL. So you never actually see a 302 error in a Web browser
Here are some stackoverflow posts on the subject. Some of the posts describe hacks to get around this issue.
How to manage a redirect request after a jQuery Ajax call
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
#include <stdlib.h>
int main()
{
int x;
x = rand(6);
printf("%d", x);
}
Especially as a beginner, you should ask your compiler to print every warning about bad code that it can generate. Modern compilers know lots of different warnings which help you to program better. For example, when you compile this program with the GNU C Compiler:
$ gcc -W -Wall rand.c
rand.c: In function `main':
rand.c:5: error: too many arguments to function `rand'
rand.c:6: warning: implicit declaration of function `printf'
You get two warnings here. The first one says that the rand
function only takes zero arguments, not one as you tried. To get a random number between 0 and n
, you can use the expression rand() % n
, which is not perfect but ok for small n
. The resulting random numbers are normally not evenly distributed; smaller values are returned more often.
The second warning tells you that you are calling a function that the compiler doesn't know at that point. You have to tell the compiler by saying #include <stdio.h>
. Which include files are needed for which functions is not always simple, but asking the Open Group specification for portable operating systems works in many cases: http://www.google.com/search?q=opengroup+rand.
These two warnings tell you much about the history of the C programming language. 40 years back, the definition of a function didn't include the number of parameters or the types of the parameters. It was also ok to call an unknown function, which in most cases worked. If you want to write code today, you should not rely on these old features but instead enable your compiler's warnings, understand the warnings and then fix them properly.
viewNoteDateMonth.text = [[displayDate objectAtIndex:2] uppercaseString];
You can also use lowercaseString and capitalizedString
I realize that this is an old question with many fine answers. However when I found this I also found a more recent article on TechNet by Saeid Hasani
T-SQL: How to Generate Random Passwords
While the solution focuses on passwords it applies to the general case. Saeid works through various considerations to arrive at a solution. It is very instructive.
A script containing all the code blocks form the article is separately available via the TechNet Gallery, but I would definitely start at the article.
Based on this blog, one could share a docker image without a docker registry by executing:
docker save --output latestversion-1.0.0.tar dockerregistry/latestversion:1.0.0
Once this command has been completed, one could copy the image to a server and import it as follows:
docker load --input latestversion-1.0.0.tar
There are two methods to do this:
1] By overriding base_site.html
in django/contrib/admin/templates/admin/base_site.html
:
Following is the content of base_site.html
:
{% extends "admin/base.html" %}
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>
{% endblock %}
{% block nav-global %}{% endblock %}
Edit the site_title & site_header in the above code snippet. This method works but it is not recommendable since its a static change.
2] By adding following lines in urls.py
of project's directory:
admin.site.site_header = "AppHeader"
admin.site.site_title = "AppTitle"
admin.site.index_title = "IndexTitle"
admin.site.site_url = "Url for view site button"
This method is recommended one since we can change the site-header, site-title & index-title without editing base_site.html
.
If you want to do this without VBA, you can use a combination of IF
, ISERROR
, and MATCH
.
So if all values are in column A, enter this formula in column B:
=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0))
This will look for the value "12345" (which can also be a cell reference). If the value isn't found, MATCH
returns "#N/A" and ISERROR
tries to catch that.
If you want to use VBA, the quickest way is to use a FOR loop:
Sub FindMatchingValue()
Dim i as Integer, intValueToFind as integer
intValueToFind = 12345
For i = 1 to 500 ' Revise the 500 to include all of your values
If Cells(i,1).Value = intValueToFind then
MsgBox("Found value on row " & i)
Exit Sub
End If
Next i
' This MsgBox will only show if the loop completes with no success
MsgBox("Value not found in the range!")
End Sub
You can use Worksheet Functions in VBA, but they're picky and sometimes throw nonsensical errors. The FOR
loop is pretty foolproof.
feof()
indicates if one has tried to read past the end of file. That means it has little predictive effect: if it is true, you are sure that the next input operation will fail (you aren't sure the previous one failed BTW), but if it is false, you aren't sure the next input operation will succeed. More over, input operations may fail for other reasons than the end of file (a format error for formatted input, a pure IO failure -- disk failure, network timeout -- for all input kinds), so even if you could be predictive about the end of file (and anybody who has tried to implement Ada one, which is predictive, will tell you it can complex if you need to skip spaces, and that it has undesirable effects on interactive devices -- sometimes forcing the input of the next line before starting the handling of the previous one), you would have to be able to handle a failure.
So the correct idiom in C is to loop with the IO operation success as loop condition, and then test the cause of the failure. For instance:
while (fgets(line, sizeof(line), file)) {
/* note that fgets don't strip the terminating \n, checking its
presence allow to handle lines longer that sizeof(line), not showed here */
...
}
if (ferror(file)) {
/* IO failure */
} else if (feof(file)) {
/* format error (not possible with fgets, but would be with fscanf) or end of file */
} else {
/* format error (not possible with fgets, but would be with fscanf) */
}
Product Version
may be preferred if you're using versioning via GitVersion or other versioning software.
To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion
:
using System.Diagnostics;
using System.Reflection;
//...
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion
UPDATE:
New link for the icons image size by apple.
https://developer.apple.com/ios/human-interface-guidelines/graphics/image-size-and-resolution/
Yes it's True here it is Apple provide Official documentation regarding icon's or image size
you have to set images for iPhone6 and iPhone6+
For iPhone 6:
750 x 1334 (@2x) for portrait
1334 x 750 (@2x) for landscape
For iPhone 6 Plus:
1242 x 2208 (@3x) for portrait
2208 x 1242 (@3x) for landscape
For more info regarding Images and it's resolution this is best ever helpful post
For setting images size for controls you can set 1x @2x and @3x like following:
Try: http://www.mattweber.org/2007/03/04/python-script-renamepy/
I like to have my music, movie, and picture files named a certain way. When I download files from the internet, they usually don’t follow my naming convention. I found myself manually renaming each file to fit my style. This got old realy fast, so I decided to write a program to do it for me.
This program can convert the filename to all lowercase, replace strings in the filename with whatever you want, and trim any number of characters from the front or back of the filename.
The program's source code is also available.
You can use the map
construct to do this. It looks quite ok, but beware that the map
line itself will return a list of None
s.
a = [1, 2, 3]
b = [2, 3]
map(lambda x:a.remove(x), b)
a
32 bits, one for the sign, 31 bits of information:
2^31 - 1 = 2147483647
Why -1?
Because the first is zero, so the greatest is the count minus one.
EDIT for cantfindaname88
The count is 2^31 but the greatest can't be 2147483648 (2^31) because we count from 0, not 1.
Rank 1 2 3 4 5 6 ... 2147483648
Number 0 1 2 3 4 5 ... 2147483647
Another explanation with only 3 bits : 1 for the sign, 2 for the information
2^2 - 1 = 3
Below all the possible values with 3 bits: (2^3 = 8 values)
1: 100 ==> -4
2: 101 ==> -3
3: 110 ==> -2
4: 111 ==> -1
5: 000 ==> 0
6: 001 ==> 1
7: 010 ==> 2
8: 011 ==> 3
There are 2 solutions for this, but it return all columns separately:
import functools
dfs = [df1, df2, df3]
df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
date a_x b_x a_y b_y c_x a b c_y
0 May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
0_a 0_b 1_a 1_b 1_c 2_a 2_b 2_c
date
May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
use:
$scope.users.length;
Instead of:
$scope.users.lenght;
And next time "spell-check" your code.
select InitialPayment * MonthlyPayRate as SomeRandomCalculation from Payment
str.strip()
returns a string with leading+trailing whitespace removed, .lstrip
and .rstrip
for only leading and trailing respectively.
grades.append(lists[i].rstrip('\n').split(','))
Java and JavaScript are a fairly bad example to demonstrate this difference, because both are interpreted languages. Java (interpreted) and C (or C++) (compiled) might have been a better example.
Why the striked-through text? As this answer correctly points out, interpreted/compiled is about a concrete implementation of a language, not about the language per se. While statements like "C is a compiled language" are generally true, there's nothing to stop someone from writing a C language interpreter. In fact, interpreters for C do exist.
Basically, compiled code can be executed directly by the computer's CPU. That is, the executable code is specified in the CPU's "native" language (assembly language).
The code of interpreted languages however must be translated at run-time from any format to CPU machine instructions. This translation is done by an interpreter.
Another way of putting it is that interpreted languages are code is translated to machine instructions step-by-step while the program is being executed, while compiled languages have code has been translated before program execution.
Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!
list_of_lists = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
flattened = [val for sublist in list_of_lists for val in sublist]
Nested list comprehensions evaluate in the same manner that they unwrap (i.e. add newline and tab for each new loop. So in this case:
flattened = [val for sublist in list_of_lists for val in sublist]
is equivalent to:
flattened = []
for sublist in list_of_lists:
for val in sublist:
flattened.append(val)
The big difference is that the list comp evaluates MUCH faster than the unraveled loop and eliminates the append calls!
If you have multiple items in a sublist the list comp will even flatten that. ie
>>> list_of_lists = [[180.0, 1, 2, 3], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> flattened = [val for sublist in list_of_lists for val in sublist]
>>> flattened
[180.0, 1, 2, 3, 173.8, 164.2, 156.5, 147.2,138.2]
convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.
if(!number.split(".")[1]){
//do stuff
}
This way you can also know what the integer and decimal actually are. a more advanced example would be.
number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1];
if(!dece){
//do stuff
}
After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.
Dim intChoice As Integer
Dim strPath As String
' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show
' Get back the user option
If intChoice <> 0 Then
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
Exit Sub
End If
Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String
Set fsoStream = FSO.OpenTextFile(strPath)
Do Until fsoStream.AtEndOfStream = True
strLine = fsoStream.ReadLine
' ... do your work ...
Loop
fsoStream.Close
Set FSO = Nothing
Hope it help!
Best regards
Fabio
div {_x000D_
display: flex;_x000D_
_x000D_
width: 200px;_x000D_
height: 80px;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
a {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
text-align: center; /* only important for multiple lines */_x000D_
_x000D_
padding: 0 20px;_x000D_
background-color: silver;_x000D_
border: 2px solid blue;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">text</a>_x000D_
<a href="#">text with two lines</a>_x000D_
</div>
_x000D_
for 1D and 2D arrays you can use np.savetxt to print using a specific format string:
>>> import sys
>>> x = numpy.arange(20).reshape((4,5))
>>> numpy.savetxt(sys.stdout, x, '%5.2f')
0.00 1.00 2.00 3.00 4.00
5.00 6.00 7.00 8.00 9.00
10.00 11.00 12.00 13.00 14.00
15.00 16.00 17.00 18.00 19.00
Your options with numpy.set_printoptions or numpy.array2string in v1.3 are pretty clunky and limited (for example no way to suppress scientific notation for large numbers). It looks like this will change with future versions, with numpy.set_printoptions(formatter=..) and numpy.array2string(style=..).
How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.
As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.
(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).
def read_config(filename):
f = open(filename)
config_dict = {}
for lines in f:
items = lines.split(': ', 1)
config_dict[items[0]] = eval(items[1])
return config_dict
The main reason for primary and foreign keys is to enforce data consistency.
A primary key enforces the consistency of uniqueness of values over one or more columns. If an ID column has a primary key then it is impossible to have two rows with the same ID value. Without that primary key, many rows could have the same ID value and you wouldn't be able to distinguish between them based on the ID value alone.
A foreign key enforces the consistency of data that points elsewhere. It ensures that the data which is pointed to actually exists. In a typical parent-child relationship, a foreign key ensures that every child always points at a parent and that the parent actually exists. Without the foreign key you could have "orphaned" children that point at a parent that doesn't exist.
None of the previous answers are complete and most contain misinformation.
There are three ways of accessing the attributes of a DOM Element in JavaScript. All three work reliably in modern browsers as long as you understand how to utilize them.
element.attributes
Elements have a property attributes that returns a live NamedNodeMap of Attr objects. The indexes of this collection may be different among browsers. So, the order is not guaranteed. NamedNodeMap
has methods for adding and removing attributes (getNamedItem
and setNamedItem
, respectively).
Notice that though XML is explicitly case sensitive, the DOM spec calls for string names to be normalized, so names passed to getNamedItem
are effectively case insensitive.
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//you can look up specific attributes_x000D_
var classAttr = div.attributes.getNamedItem('CLASS');_x000D_
document.write('attributes.getNamedItem() Name: ' + classAttr.name + ' Value: ' + classAttr.value + '<br>');_x000D_
_x000D_
//you can enumerate all defined attributes_x000D_
for(var i = 0; i < div.attributes.length; i++) {_x000D_
var attr = div.attributes[i];_x000D_
document.write('attributes[] Name: ' + attr.name + ' Value: ' + attr.value + '<br>');_x000D_
}_x000D_
_x000D_
//create custom attribute_x000D_
var customAttr = document.createAttribute('customTest');_x000D_
customAttr.value = '567';_x000D_
div.attributes.setNamedItem(customAttr);_x000D_
_x000D_
//retreive custom attribute_x000D_
customAttr = div.attributes.getNamedItem('customTest');_x000D_
document.write('attributes.getNamedItem() Name: ' + customAttr.name + ' Value: ' + customAttr.value + '<br>');
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
element.getAttribute
& element.setAttribute
These methods exist directly on the Element
without needing to access attributes
and its methods but perform the same functions.
Again, notice that string name are case insensitive.
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//get specific attributes_x000D_
document.write('Name: class Value: ' + div.getAttribute('class') + '<br>');_x000D_
document.write('Name: ID Value: ' + div.getAttribute('ID') + '<br>');_x000D_
document.write('Name: DATA-TEST Value: ' + div.getAttribute('DATA-TEST') + '<br>');_x000D_
document.write('Name: nonStandard Value: ' + div.getAttribute('nonStandard') + '<br>');_x000D_
_x000D_
_x000D_
//create custom attribute_x000D_
div.setAttribute('customTest', '567');_x000D_
_x000D_
//retreive custom attribute_x000D_
document.write('Name: customTest Value: ' + div.getAttribute('customTest') + '<br>');
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
element.id
Many attributes can be accessed using convenient properties on the DOM object. Which attributes exist depends on the DOM node's type, not which attributes are defined in the HTML. The properties are defined somewhere in the prototype chain of DOM object in question. The specific properties defined will depend on the type of Element you are accessing. For example, className
and id
are defined on Element
and exist on all DOM nodes that are elements (ie. not text or comment nodes). But value
is more narrow. It's defined on HTMLInputElement
and may not exist on other elements.
Notice that JavaScript properties are case sensitive. Although most properties will use lowercase, some are camelCase. So always check the spec to be sure.
This "chart" captures a portion of the prototype chain for these DOM objects. It's not even close to complete, but it captures the overall structure.
____________Node___________
| | |
Element Text Comment
| |
HTMLElement SVGElement
| |
HTMLInputElement HTMLSpanElement
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//get specific attributes_x000D_
document.write('Name: class Value: ' + div.className + '<br>');_x000D_
document.write('Name: id Value: ' + div.id + '<br>');_x000D_
document.write('Name: ID Value: ' + div.ID + '<br>'); //undefined_x000D_
document.write('Name: data-test Value: ' + div.dataset.test + '<br>'); //.dataset is a special case_x000D_
document.write('Name: nonStandard Value: ' + div.nonStandard + '<br>'); //undefined
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
Caveat: This is an explanation of how the HTML spec defines and modern browsers handle attributes. I did not attempt to deal with limitations of ancient, broken browsers. If you need to support old browsers, in addition to this information, you will need to know what is broken in the those browsers.
NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];
Turning the firewall off resolved it for me.
If you can construct the vector after you've gotten the array and array size, you can just say:
std::vector<ValueType> vec(a, a + n);
...assuming a
is your array and n
is the number of elements it contains. Otherwise, std::copy()
w/resize()
will do the trick.
I'd stay away from memcpy()
unless you can be sure that the values are plain-old data (POD) types.
Also, worth noting that none of these really avoids the for loop--it's just a question of whether you have to see it in your code or not. O(n) runtime performance is unavoidable for copying the values.
Finally, note that C-style arrays are perfectly valid containers for most STL algorithms--the raw pointer is equivalent to begin()
, and (ptr + n
) is equivalent to end()
.
The answers above are still using the old Python 3.4 style coroutines. Here is what you would write if you got Python 3.5+.
aiohttp
supports http proxy now
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'http://python.org',
'https://google.com',
'http://yifei.me'
]
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
tasks.append(fetch(session, url))
htmls = await asyncio.gather(*tasks)
for html in htmls:
print(html[:100])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I use code below:
var fileSplit = filename.split('.');
var fileExt = '';
if (fileSplit.length > 1) {
fileExt = fileSplit[fileSplit.length - 1];
}
return fileExt;
Nothing in the example says that the "classes implementing the same interface". MovieCatalog
is a type and CustomerPreferenceDao
is another type. Spring can easily tell them apart.
In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".
What the examples show is various ways that you can use to inject beans into fields, methods and constructors.
The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:
This autowiring will fail:
@Autowired
public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }
Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier
:
@Autowired
public void prepare( @Qualifier("bean1") Interface1 bean1,
@Qualifier("bean2") Interface1 bean2 ) { ... }
I pre-allocate a vector with
> (a <- rep(NA, 10))
[1] NA NA NA NA NA NA NA NA NA NA
You can then use [] to insert values into it.
$("ul").empty()
works fine. Is there some other error?
$('input').click(function() {_x000D_
$('ul').empty()_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
<li>test</li>_x000D_
<li>test</li>_x000D_
</ul>_x000D_
_x000D_
<input type="button" value="click me" />
_x000D_
I had a similar issue, for an element of type image. I needed to check whether the element was of a certain class. First I tried with:
$('<img>').hasClass("nameOfMyClass");
but I got a nice "this function is not available for this element".
Then I inspected my element on the DOM explorer and I saw a very nice attribute that I could use: className. It contained the names of all the classes of my element separated by blank spaces.
$('img').className // it contains "class1 class2 class3"
Once you get this, just split the string as usual.
In my case this worked:
var listOfClassesOfMyElement= $('img').className.split(" ");
I am assuming this would work with other kinds of elements (besides img).
Hope it helps.
I use this extension class:
public static class StreamExtensions
{
public static byte[] ReadAllBytes(this Stream instream)
{
if (instream is MemoryStream)
return ((MemoryStream) instream).ToArray();
using (var memoryStream = new MemoryStream())
{
instream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
}
Just copy the class to your solution and you can use it on every stream:
byte[] bytes = myStream.ReadAllBytes()
Works great for all my streams and saves a lot of code! Of course you can modify this method to use some of the other approaches here to improve performance if needed, but I like to keep it simple.
In regards to @Anthonyeef great answer, here is a sample code in Java:
private boolean shouldShowFragmentInOnResume;
private void someMethodThatShowsTheFragment() {
if (this.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
showFragment();
} else {
shouldShowFragmentInOnResume = true;
}
}
private void showFragment() {
//Your code here
}
@Override
protected void onResume() {
super.onResume();
if (shouldShowFragmentInOnResume) {
shouldShowFragmentInOnResume = false;
showFragment();
}
}
Use the SQL In
function
Something like this:
SELECT * FROM mytable WHERE:
"VALUE" In (1,2,3,7,90,500)
Works a treat in ArcGIS
ES6 features like promises aren't defined when targeting ES5. There are other libraries, but core-js is the javascript library that the Angular team uses. It contains polyfills for ES6.
Angular 2 has changed a lot since this question was asked. Type declarations are much easier to use in Typescript 2.0.
npm install -g typescript
For ES6 features in Angular 2, you don't need Typings. Just use typescript 2.0 or higher and install @types/core-js with npm:
npm install --save-dev @types/core-js
Then, add the TypeRoots and Types attributes to your tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "es6",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"typeRoots": [
"../node_modules/@types"
],
"types" : [
"core-js"
]
},
"exclude": [
"node_modules"
]
}
This is much easier than using Typings, as explained in other answers. See Microsoft's blog post for more info: Typescript: The Future of Declaration Files
Unless I'm missing something, the question is not about increasing the array size. In the example the array size remains the same. (Like a bit shift.) In this case, there is really no reason to create a new array or to copy it. This should do the trick:
static void addPos(int[] array, int pos, int value) {
// initially set to value parameter so the first iteration, the value is replaced by it
int prevValue = value;
// Shift all elements to the right, starting at pos
for (int i = pos; i < array.length; i++) {
int tmp = prevValue;
prevValue = array[i];
array[i] = tmp;
}
}
int[] a = {1, 2, 3, 4, 5, 6};
addPos(a, 4, 87);
// output: {1, 2, 3, 4, 87, 5}
The first thing you need to study is the java.util.Set
API.
Here's a small example of how to use its methods:
Set<Integer> numbers = new TreeSet<Integer>();
numbers.add(2);
numbers.add(5);
System.out.println(numbers); // "[2, 5]"
System.out.println(numbers.contains(7)); // "false"
System.out.println(numbers.add(5)); // "false"
System.out.println(numbers.size()); // "2"
int sum = 0;
for (int n : numbers) {
sum += n;
}
System.out.println("Sum = " + sum); // "Sum = 7"
numbers.addAll(Arrays.asList(1,2,3,4,5));
System.out.println(numbers); // "[1, 2, 3, 4, 5]"
numbers.removeAll(Arrays.asList(4,5,6,7));
System.out.println(numbers); // "[1, 2, 3]"
numbers.retainAll(Arrays.asList(2,3,4,5));
System.out.println(numbers); // "[2, 3]"
Once you're familiar with the API, you can use it to contain more interesting objects. If you haven't familiarized yourself with the equals
and hashCode
contract, already, now is a good time to start.
In a nutshell:
@Override
both or none; never just one. (very important, because it must satisfied property: a.equals(b) == true --> a.hashCode() == b.hashCode()
boolean equals(Thing other)
instead; this is not a proper @Override
.x, y, z
, equals
must be:
x.equals(x)
.x.equals(y)
if and only if y.equals(x)
x.equals(y) && y.equals(z)
, then x.equals(z)
x.equals(y)
must not change unless the objects have mutatedx.equals(null) == false
hashCode
is:
equals
: if x.equals(y)
, then x.hashCode() == y.hashCode()
equals
and hashCode
.Next, you may want to impose an ordering of your objects. You can do this by making your type implements Comparable
, or by providing a separate Comparator
.
Having either makes it easy to sort your objects (Arrays.sort
, Collections.sort(List)
). It also allows you to use SortedSet
, such as TreeSet
.
Further readings on stackoverflow:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.Configure<MvcOptions>(options => {
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
});
}
I just add this line of code into onCreate()
:
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Problem solved.
Just to keep this subject complete, I found a solution not explored Here using Fixed position.
html, body, .wrapper, .parent, .child {_x000D_
position: fixed;_x000D_
top: 0; _x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
overflow: auto;_x000D_
background: gray;_x000D_
}_x000D_
_x000D_
.height-50 {_x000D_
height: 50%;_x000D_
width: 5em;_x000D_
margin: 10px auto;_x000D_
background: cyan;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
_x000D_
<div class="height-50"></div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
html, body, .wrapper, .parent, .child {_x000D_
position: fixed;_x000D_
top: 0; _x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
overflow: auto;_x000D_
background: gray;_x000D_
}_x000D_
_x000D_
.height-150 {_x000D_
height: 150%;_x000D_
width: 5em;_x000D_
margin: 10px auto;_x000D_
background: cyan;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">_x000D_
<div class="child">_x000D_
_x000D_
<div class="height-150"></div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
i had this question and found another answer here: copy region of interest
If we consider (0,0) as top left corner of image called im
with left-to-right as x direction and top-to-bottom as y direction. and we have (x1,y1) as the top-left vertex and (x2,y2) as the bottom-right vertex of a rectangle region within that image, then:
roi = im[y1:y2, x1:x2]
here is a comprehensive resource on numpy array indexing and slicing which can tell you more about things like cropping a part of an image. images would be stored as a numpy array in opencv2.
:)
input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}
I did work on something like this once, but sending a video and playing it in real time is a really complex thing. I suggest you work with PNG's only. In my implementation What i did was capture PNGs using the host camera and then sending them over the network to the client, Which will display the image as soon as received and request the next image from the host. Since you are on wifi that communication will be fast enough to get around 8-10 images per-second(approximation only, i worked on Bluetooth). So this will look like a continuous video but with much less effort. For communication you may use UDP sockets(Faster and less complex) or DLNA (Not sure how that works).
If you are using HTML5 date
use this code
HTML
<input type="date" name="bday" id="start_date"/>
Java Script
document.getElementById('start_date').value = Date();
<a href="javascript:void(0)" class="aaf" id="users_id">add as a friend</a>
on jquery
$('.aaf').on("click",function(){
var usersid = $(this).attr("id");
//post code
})
//other method is to use the data attribute
<a href="javascript:void(0)" class="aaf" data-id="102" data-username="sample_username">add as a friend</a>
on jquery
$('.aaf').on("click",function(){
var usersid = $(this).data("id");
var username = $(this).data("username");
})
Start the project structure( file>structure
)
You can see:
on the left, modules list;
on the right, Properties>Build
Tools Version
there maybe are more than one modules.
change "Build Tools Version"
for every Module.
it works.
I use this kind of pattern often. It's very compact:
// Define a constant in your class. Use a HashSet for performance
private static final Set<Integer> values = new HashSet<Integer>(Arrays.asList(12, 16, 19));
// In your method:
if (values.contains(x)) {
...
}
A HashSet
is used here to give good look-up performance - even very large hash sets are able to execute contains()
extremely quickly.
If performance is not important, you can code the gist of it into one line:
if (Arrays.asList(12, 16, 19).contains(x))
but know that it will create a new ArrayList
every time it executes.
I can't imagine that anyone else reading this is a stupid as I was but just in case... I had accidentally removed "laravel/framework": "^5.6" from my composer.json when resolving merge conflicts.
Is it proper to "reach into" an object and use its dict property?
In general, I would say "no". However Namespace
has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.
On the other hand, Namespace
does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__
, but the limits of my imagination are not the same as yours.
In simple DOM usage you can check the condition
element.scrollTop + element.clientHeight == element.scrollHeight
if true then you have reached the end.
For link button,
Calling .button('enable')
method only gives effect, but functionally don't.
But I have a trick. We could use HTML5 data-
attribute to save/swap value of href
and onclick
.
see:
source code mode:
If you need this for several words or elements, but can't apply it to a whole TD or similar, the Span tag can be used.
<span style="white-space: nowrap">Text to break together</span>
or
<span class=nobr>Text to break together</span>
If you use the class version, remember to set up the CSS as detailed in the accepted answer.
If you have values in a short set of possible values then you can use something like Counting Sort
If not you have to use another data structure like a Dictionary, in java a Map
int[] array
Map<Integer, Integer>
where Key = array value for example array[i] and value = a counter
Example:
int[] array = new int [50];
Map<Integer,Integer> counterMap = new HashMap<>();
//fill the array
for(int i=0;i<array.length;i++){
if(counterMap.containsKey(array[i])){
counterMap.put(array[i], counterMap.get(array[i])+1 );
}else{
counterMap.put(array[i], 1);
}
}
I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:
Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......
A simple alternative to this is to use threads along with join. Refer : Joining Threads
Rather than sending as just an object .
Create a public class of properties that is accessible and send the data to the Webmethod.
[WebMethod]
public static void SaveTeam(useSomeClassHere user)
{
}
use same parameters names in ajax call to send data.
By the looks of it you need to actually pass drawImage an image object like so
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
I've tried it in chrome and it works fine.
For Windows Users:
In Environment Variables, add a new variable in system variable with name "TESSDATA_PREFIX" and value is "C:\Program Files (x86)\Tesseract-OCR\tessdata"
$git log
commit-1(new/latest/recent commit)
commit-2
commit-3
commit-4
*
*
commit-n(first commit)
$git diff commit-2 commit-1
display's all changes between commit-2 to commit-1 (patch of commit-1 alone & equivalent to
git diff HEAD~1 HEAD
)
similarly $git diff commit-4 commit-1
display's all changes between commit-4 to commit-1 (patch of commit-1, commit-2 & commit-3 together. Equivalent to
git diff HEAD~3 HEAD
)
$git diff commit-1 commit-2
By changing order commit ID's it is possible to get
revert patch
. ("$git diff commit-1 commit-2 > revert_patch_of_commit-1.diff")
I assume by "key" and "value" you mean:
<select>
<option value="KEY">VALUE</option>
</select>
If that's the case, this will get you the "VALUE":
$(this).find('option:selected').text();
And you can get the "KEY" like this:
$(this).find('option:selected').val();
You can use both of ',' OR divide '/' symbols.
But, '/' is better.
Suppose the case of 'every 5 minutes'. If you use ',', you have to write the cron job as following:
0,5,10,15,20,25,30,35,.... * * * * your_command
It means run your_command in every hour in all of defined minutes: 0,5,10,...
However, if you use '/', you can write the following simple and short job:
*/5 * * * * your_command
It means run your_command in the minutes that are dividable by 5 or in the simpler words, '0,5,10,...'
So, dividable symbol '/' is the best choice always;
There isn't a direct 1:1 equivalent.
You can password protect a folder or file using file system permissions. If you are using ASP.Net you can also use some of its built in functions to protect various urls.
If you are trying to port .htaccess files used for url rewriting, check out ISAPI Rewrite: http://www.isapirewrite.com/
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
select * from table where id not in (select id from table limit 10)
where id
be the key in your table.
Select-String
worked best for me. All the other options listed here, such as findstr
, didn't work with large files.
Here's an example:
select-string -pattern "<pattern>" -path "<path>"
note: This requires Powershell
You can use chars as is as single byte integers.
Consider the fast FILTER method:
$('.rnd').filter('h2,h4')
returns:
[<h2 id=?"foo" class=?"rnd">?Second?</h2>?, <h4 id=?"bar" class=?"rnd">?Fourth?</h4>?]
so:
$('.rnd').filter('h2,h4').each(function() { /*...$(this)...*/ });
In working with a similar problem I created the following function after combining a lot of resources I ran into on the web, and adding my own cookie handling. Hopefully this is useful to someone else.
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => true, // Validate SSL Certificates
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
return $header;
}
I had a similar issue, but it was related to Hibernate's bi-directional relationships. I wanted to show one side of the relationship and programmatically ignore the other, depending on what view I was dealing with. If you can't do that, you end up with nasty StackOverflowException
s. For instance, if I had these objects
public class A{
Long id;
String name;
List<B> children;
}
public class B{
Long id;
A parent;
}
I would want to programmatically ignore the parent
field in B if I were looking at A, and ignore the children
field in A if I were looking at B.
I started off using mixins to do this, but that very quickly becomes horrible; you have so many useless classes laying around that exist solely to format data. I ended up writing my own serializer to handle this in a cleaner way: https://github.com/monitorjbl/json-view.
It allows you programmatically specify what fields to ignore:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
List<A> list = getListOfA();
String json = mapper.writeValueAsString(JsonView.with(list)
.onClass(B.class, match()
.exclude("parent")));
It also lets you easily specify very simplified views through wildcard matchers:
String json = mapper.writeValueAsString(JsonView.with(list)
.onClass(A.class, match()
.exclude("*")
.include("id", "name")));
In my original case, the need for simple views like this was to show the bare minimum about the parent/child, but it also became useful for our role-based security. Less privileged views of objects needed to return less information about the object.
All of this comes from the serializer, but I was using Spring MVC in my app. To get it to properly handle these cases, I wrote an integration that you can drop in to existing Spring controller classes:
@Controller
public class JsonController {
private JsonResult json = JsonResult.instance();
@Autowired
private TestObjectService service;
@RequestMapping(method = RequestMethod.GET, value = "/bean")
@ResponseBody
public List<TestObject> getTestObject() {
List<TestObject> list = service.list();
return json.use(JsonView.with(list)
.onClass(TestObject.class, Match.match()
.exclude("int1")
.include("ignoredDirect")))
.returnValue();
}
}
Both are available on Maven Central. I hope it helps someone else out there, this is a particularly ugly problem with Jackson that didn't have a good solution for my case.
You can use single line comments:
-- this is a comment
# this is also a comment
Or a multiline comment:
/*
multiline
comment
*/
Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.
If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).
This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.
https://support.microsoft.com/en-us/kb/938397
For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:
http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe
you can use toggleClass()
to toggle class it is really handy.
case:1
<div id='mydiv' class="class1"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class2"></div>
case:2
<div id='mydiv' class="class2"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class1"></div>
case:3
<div id='mydiv' class="class1 class2 class3"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class3"></div>
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pType_in_your_current_password_here password ''
Client side data validation can be useful for a better user experience: for example, I a user who types wrongly his email address, should not wait til his request is processed by a remote server to learn about the typo he did.
Nevertheless, as an attacker can bypass client side validation (and may even not use the browser at all), server side validation is required, and must be the real gate to protect your backend from nefarious users.
Using width/height on inline elements is not always a good idea.
You can use display: inline-block
instead
In Eclipse you have option to export executable jar. You have an option to package all project related jars into generated jar and in this way eclipse add custom class loader which will refer to you integrated jars within new jar.
Dynamically added items have to be added to the DOM... clone().append()
adds it to the DOM... which allows it to be selected via jquery.
JStack is quite inexpensive - one option would be to pipe the output through grep to find active threads and then pipe through wc -l.
More graphically is JConsole, which displays the thread count for a given process.
You're not loading the validation plugin. You need:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
Put this before the line that loads the additional methods.
Also, you should get the additional methods from the CDN as well, rather than jquery.bassistance.de.
Other errors:
[4.20]
should be
[4,20]
and
rangelenght:
should be:
rangelength:
Have you tried jQuery.contents() ?
Use and empty()
whit negation (for test if not empty)
if(!empty($_GET['id'])) {
// if get id is not empty
}
(copied this piece from my other answer in your other question)
Show progress when searching all files in a directory
Of course, as you already know, there are a lot of ways of doing the enumeration itself... but none will be instantaneous. You could try using the USN Journal of the file system to do the scan. Take a look at this project in CodePlex: MFT Scanner in VB.NET... it found all the files in my IDE SATA (not SSD) drive in less than 15 seconds, and found 311000 files.
You will have to filter the files by path, so that only the files inside the path you are looking are returned. But that is the easy part of the job!
From MySQL docs: Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC:
In standard SQL, the syntax
DECIMAL(M)
is equivalent toDECIMAL(M,0)
So, you are converting to a number with 2 integer digits and 0 decimal digits. Try this instead:
CAST((COUNT(*) * 1.5) AS DECIMAL(12,2))
You have to pass the route parameters to the route
method, for example:
<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>
It's because, both routes have a {nickname}
in the route declaration. I've used $nickname
for example but make sure you change the $nickname
to appropriate value/variable, for example, it could be something like the following:
<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>
I like to use the tcomment plugin: http://www.vim.org/scripts/script.php?script_id=1173
I have mapped gc and gcc to comment a line or a highlighted block of code. It detects the file type and works really well.
Please see Python OS X development environment. The best way is to use MacPorts. Download and install MacPorts, then install Python via MacPorts by typing the following commands in the Terminal:
sudo port install python26 python_select sudo port select --set python python26
OR
sudo port install python30 python_select sudo port select --set python python30
Use the first set of commands to install Python 2.6 and the second set to install Python 3.0. Then use:
sudo port install py26-packagename
OR
sudo port install py30-packagename
In the above commands, replace packagename with the name of the package, for example:
sudo port install py26-setuptools
These commands will automatically install the package (and its dependencies) for the given Python version.
For a full list of available packages for Python, type:
port list | grep py26-
OR
port list | grep py30-
Which command you use depends on which version of Python you chose to install.
There is a @Cleanup annotation in Lombok that mostly resembles C++ destructors:
@Cleanup
ResourceClass resource = new ResourceClass();
When processing it (at compilation time), Lombok inserts appropriate try-finally
block so that resource.close()
is invoked, when execution leaves the scope of the variable. You can also specify explicitly another method for releasing the resource, e.g. resource.dispose()
:
@Cleanup("dispose")
ResourceClass resource = new ResourceClass();
DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");
Ref: http://www.csharp-examples.net/dataview-rowfilter/
http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx
Try
isSubstring = first in theOther
Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.
For example, using GridBagLayout:
import java.awt.*;
import javax.swing.*;
public class LayoutEg1 extends JPanel{
private static final int ROWS = 10;
public LayoutEg1() {
setLayout(new GridBagLayout());
for (int i = 0; i < ROWS; i++) {
GridBagConstraints gbc = makeGbc(0, i);
JLabel label = new JLabel("Row Label " + (i + 1));
add(label, gbc);
JPanel panel = new JPanel();
panel.add(new JCheckBox("check box"));
panel.add(new JTextField(10));
panel.add(new JButton("Button"));
panel.setBorder(BorderFactory.createEtchedBorder());
gbc = makeGbc(1, i);
add(panel, gbc);
}
}
private GridBagConstraints makeGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = x;
gbc.weighty = 1.0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
return gbc;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Layout Eg1");
frame.getContentPane().add(new LayoutEg1());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
One more procedural style example with mysqli_multi_query
, assumes $query
is filled with semicolon-separated statements.
mysqli_begin_transaction ($link);
for (mysqli_multi_query ($link, $query);
mysqli_more_results ($link);
mysqli_next_result ($link) );
! mysqli_errno ($link) ?
mysqli_commit ($link) : mysqli_rollback ($link);
(tl;dr: The exact answer to your question is numpy.empty
or numpy.empty_like
, but you likely don't care and can get away with using myList = [None]*10000
.)
You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an error later if you use it, which is a good thing) or something like 0 (unusual? maybe useful if you're writing a sparse matrix or the 'default' value should be 0 and you're not worried about bugs) is up to you:
>>> [None for _ in range(10)]
[None, None, None, None, None, None, None, None, None, None]
(Here _
is just a variable name, you could have used i
.)
You can also do so like this:
>>> [None]*10
[None, None, None, None, None, None, None, None, None, None]
You probably don't need to optimize this. You can also append to the array every time you need to:
>>> x = []
>>> for i in range(10):
>>> x.append(i)
Which is best?
>>> def initAndWrite_test():
... x = [None]*10000
... for i in range(10000):
... x[i] = i
...
>>> def initAndWrite2_test():
... x = [None for _ in range(10000)]
... for i in range(10000):
... x[i] = i
...
>>> def appendWrite_test():
... x = []
... for i in range(10000):
... x.append(i)
Results in python2.7:
>>> import timeit
>>> for f in [initAndWrite_test, initAndWrite2_test, appendWrite_test]:
... print('{} takes {} usec/loop'.format(f.__name__, timeit.timeit(f, number=1000)*1000))
...
initAndWrite_test takes 714.596033096 usec/loop
initAndWrite2_test takes 981.526136398 usec/loop
appendWrite_test takes 908.597946167 usec/loop
Results in python 3.2:
initAndWrite_test takes 641.3581371307373 usec/loop
initAndWrite2_test takes 1033.6499214172363 usec/loop
appendWrite_test takes 895.9040641784668 usec/loop
As we can see, it is likely better to do the idiom [None]*10000
in both python2 and python3. However, if one is doing anything more complicated than assignment (such as anything complicated to generate or process every element in the list), then the overhead becomes a meaninglessly small fraction of the cost. That is, such optimization is premature to worry about if you're doing anything reasonable with the elements of your list.
These are all however inefficient because they go through memory, writing something in the process. In C this is different: an uninitialized array is filled with random garbage memory (sidenote: that has been reallocated from the system, and can be a security risk when you allocate or fail to mlock and/or fail to delete memory when closing the program). This is a design choice, designed for speedup: the makers of the C language thought that it was better not to automatically initialize memory, and that was the correct choice.
This is not an asymptotic speedup (because it's O(N)
), but for example you wouldn't need to first initialize your entire memory block before you overwrite with stuff you actually care about. This, if it were possible, is equivalent to something like (pseudo-code) x = list(size=10000)
.
If you want something similar in python, you can use the numpy
numerical matrix/N-dimensional-array manipulation package. Specifically, numpy.empty
or numpy.empty_like
That is the real answer to your question.
The documentation says that you can also do:
$str = "$foo";
It's the same as cast, but I think it looks prettier.
Source:
open jdk once installed resides generally in your /usr/lib/java-6-openjdk As usual you would need to set the JAVA_HOME, calsspath and Path In ubuntu 11.04 there is a environment file available in /etc where you need to set all the three paths . And then you would need to restart your system for the changes to take effect..
Here is a site to help you around http://aliolci.blogspot.com/2011/05/ubuntu-1104-set-new-environment.html
Solution using the destructuring assignment syntax of ES6:
var temp = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };_x000D_
var { [Object.keys(temp).pop()]: lastItem } = temp;_x000D_
console.info(lastItem); //"carrot"
_x000D_
Here is a complete AsyncTask
class
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
@Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
To Call this AsyncTask
class
new GetMethodDemo().execute("your web-service url");
A better way, instead of using a conditional like:
if (json.has("club")) {
String club = json.getString("club"));
}
is to simply use the existing method optString(), like this:
String club = json.optString("club);
the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.
Your version does not support that character set, I believe it was 5.5.3
that introduced it. You should upgrade your mysql to the version you used to export this file.
The error is then quite clear: you set a certain character set in your code, but your mysql version does not support it, and therefore does not know about it.
According to https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html :
utf8mb4 is a superset of utf8
so maybe there is a chance you can just make it utf8, close your eyes and hope, but that would depend on your data, and I'd not recommend it.
I'll post this comment as answer, as I'm confident enough that what I asked is not possible.
I) Couple of similar questions trying to do the same, without success:
II) This article: Excel Pivot Table Calculated Field for example lists many restrictions of Calculated Field:
III) There is tiny limited possibility to use AVERAGE()
and similar function for a range of cells, but that applies only if Pivot table doesn't have grouped cells, which allows listing the cells as items in new group (right to "Fileds" listbox in above screenshot) and then user can calculate AVERAGE()
, referencing explicitly every item (cell), from Items listbox, as argument. Maybe it's better explained here: Calculate values in a PivotTable report
For my Pivot table it wasn't applicable because my range wasn't small enough, this option to be sane choice.
Consider using NumberFormatter for this purpose, it provides more flexibility if you want to print the percentage sign of the ratio or if you have things like currency and large numbers.
let amount = 10.000001
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
let formattedAmount = formatter.string(from: amount as NSNumber)!
print(formattedAmount) // 10
Making use of the tricks in "Getting the last argument passed to a shell script" we can make a simple shell function that should work no matter how many files you want to move:
# Bash only
mvdir() { mkdir -p "${@: -1}" && mv "$@"; }
# Other shells may need to search for the last argument
mvdir() { for last; do true; done; mkdir -p "$last" && mv "$@"; }
Don't do anything on DataGridView
, just clear the data source. I tried clearing myDataset.clear()
method, then it worked.
In short, function pointer is just a pointer to a location in the program code base (like program counter). Whereas Closure = Function pointer + Stack frame.
.
Msg 8155, Level 16, State 2, Line 1 No column was specified for column 1 of 'd'. Msg 8155, Level 16, State 2, Line 1 No column was specified for column 2 of 'd'. ANSWER:
ROUND(AVG(CAST(column_name AS FLOAT)), 2) as column_name
FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.
Also you can try this:
[style.background-image]="'url(' + photo + ')'"
Copying and pasting by user interactions emulation could be not reliable (for example, popup appears and it switches the focus). You may be interested in trying the commercial ByteScout PDF Extractor SDK that is specifically designed to extract data from PDF and it works from VBA. It is also capable of extracting data from invoices and tables as CSV using VB code.
Here is the VBA code for Excel to extract text from given locations and save them into cells in the Sheet1
:
Private Sub CommandButton1_Click()
' Create TextExtractor object
' Set extractor = CreateObject("Bytescout.PDFExtractor.TextExtractor")
Dim extractor As New Bytescout_PDFExtractor.TextExtractor
extractor.RegistrationName = "demo"
extractor.RegistrationKey = "demo"
' Load sample PDF document
extractor.LoadDocumentFromFile ("c:\sample1.pdf")
' Get page count
pageCount = extractor.GetPageCount()
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng As Range
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
For i = 0 To pageCount - 1
RectLeft = 10
RectTop = 10
RectWidth = 100
RectHeight = 100
' check the same text is extracted from returned coordinates
extractor.SetExtractionArea RectLeft, RectTop, RectWidth, RectHeight
' extract text from given area
extractedText = extractor.GetTextFromPage(i)
' insert rows
' Rows(1).Insert shift:=xlShiftDown
' write cell value
Set TxtRng = ws.Range("A" & CStr(i + 2))
TxtRng.Value = extractedText
Next
Set extractor = Nothing
End Sub
Disclosure: I am related to ByteScout
You can use auto in data placement like data-placement="auto left". It will automatic adjust according to your screen size and default placement will be left.
You're close.
The LIKE operator works with strings (CHAR, NVARCHAR, etc). so you need to concattenate the '%' symbol to the string...
MS SQL Server:
SELECT * FROM table1,table2 WHERE table1.x LIKE table2.y + '%'
Use of LIKE, however, is often slower than other operations. It's useful, powerful, flexible, but has performance considerations. I'll leave those for another topic though :)
EDIT:
I don't use MySQL, but this may work...
SELECT * FROM table1,table2 WHERE table1.x LIKE CONCAT(table2.y, '%')
Easiest Way!!!
If you are using Entity Framework and your Visual Studio Version is 2012 or higher,then
Its done. Now restart your visual studio and build your code.
What do these packages do?
After installing these packages no additional Oracle client software is required to be installed to connect to database.
JUnit+Webdriver
assertEquals(driver.findElement(By.xpath("//this/is/the/xpath/location/where/the/text/sits".getText(),"insert the text you're expecting to see here");
If in the event your expected text doesn't match the xpath text, webdriver will tell you what the actual text was vs what you were expecting.
Probably there are some files inside C:\cygwin\bin called xxxxxmake.exe
, try renaming it to make.exe
I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked
html2canvas(document.querySelector('#toPrint')).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
Have a look at this one. It is the Ternary operator in C#.
bool BooleanValue = (num % 3 != 0) ? true : false;
This is just to show the principle; you can return True or False (or even integer or string) depending on the outcome of something on the left side of the question mark. Nice operator, this.
Three alternatives together:
public bool test1()
{
int num = 21;
bool BooleanValue = (num % 3 != 0) ? true : false;
return BooleanValue;
}
public bool test2()
{
int num = 20;
bool test = (num % 3 != 0);
return test;
}
Even Shorter:
public bool test3()
{
int num = 20;
return (bool)(num % 3 != 0);
}
In Linux:
java -version
In Windows:
java.exe -version
If you need more info about the JVM you can call the executable with the parameter -XshowSettings:properties
. It will show a lot of System Properties. These properties can also be accessed by means of the static method System.getProperty(String)
in a Java class. As example this is an excerpt of some of the properties that can be obtained:
$ java -XshowSettings:properties -version
[...]
java.specification.version = 1.7
java.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
java.version = 1.7.0_95
[...]
So if you need to access any of these properties from Java code you can use:
System.getProperty("java.specification.version");
System.getProperty("java.vendor");
System.getProperty("java.vendor.url");
System.getProperty("java.version");
Take into account that sometimes the vendor is not exposed as clear as Oracle or IBM. For example,
$ java version
"1.6.0_22" Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
HotSpot is what Oracle calls their implementation of the JVM. Check this list if the vendor does not seem to be shown with -version
.
You need to use something like this:
OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
WHERE domain_user_name = :userName", db);
More can be found in this MSDN article: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.100%29.aspx
It is advised you use the : character instead of @ for Oracle.
Use the json
module to produce JSON output:
import json
with open(outputfilename, 'wb') as outfile:
json.dump(row, outfile)
This writes the JSON result directly to the file (replacing any previous content if the file already existed).
If you need the JSON result string in Python itself, use json.dumps()
(added s
, for 'string'):
json_string = json.dumps(row)
The L
is just Python syntax for a long integer value; the json
library knows how to handle those values, no L
will be written.
Demo string output:
>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'
Here is the code snippet for creating a matrix in python:
# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))
# initialize the list
l=[[0]*cols for i in range(rows)]
# fill some random values in it
for i in range(0,rows):
for j in range(0,cols):
l[i][j] = i+j
# print the list
for i in range(0,rows):
print()
for j in range(0,cols):
print(l[i][j],end=" ")
Please suggest if I have missed something.
Because Firefox does not support mp3 format. To make this work with Firefox, you should use the ogg format.
I prefer the answer of tabSF . implementing the same to your answer. here below is my approach
Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
Get rid from your <Button>
wrap div using display:block
and float:left
in both <Button>
and <h1>
and specifying their width
with a position:relative
to your Section
. This approach has the advantage of not needing another div
only to position your <Button>
html
<section>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
<button>button</button>
</section>
? css
section {
position: relative;
width: 50%;
border: 1px solid;
float:left;
}
h1 {
display: block;
width:70%;
float:left;
}
button
{
position:relative;
top:0;
left:0;
float:left;
}
?
All Google Maps JavaScript API applications require authentication( API KEY )
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=(Paste YOUR API KEY)"></script>
For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist
.For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
, create a string value with name 1
and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
, and a second value with name 2
and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
. This can be sum up by this registry file:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
EDIT: actually, Chromium docs also indicate how to do it for other OS.
Do you really need to do that programmatically?
Just considering the title: You could use a ShapeDrawable as android:background…
For example, let's define res/drawable/my_custom_background.xml
as:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="2dp"
android:topRightRadius="0dp"
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp" />
<stroke
android:width="1dp"
android:color="@android:color/white" />
</shape>
and define android:background="@drawable/my_custom_background".
I've not tested but it should work.
Update:
I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/border"
android:padding="10dip" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
[... more TextView ...]
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
</LinearLayout>
and a res/drawable/border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="5dip"
android:color="@android:color/white" />
</shape>
Reported to work on a gingerbread device. Note that you'll need to relate android:padding
of the LinearLayout to the android:width
shape/stroke's value. Please, do not use @android:color/white
in your final application but rather a project defined color.
You could apply android:background="@drawable/border" android:padding="10dip"
to each of the LinearLayout from your provided sample.
As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…
Your problem resides clearly in the use of getBorder.set{Width,Height}(100);
. Why do you do that in an onClick method?
I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.
To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…
If you are using Zsh, then try to add this line in ~/.zshrc file & restart terminal.
export JAVA_HOME=$(/usr/libexec/java_home)
I solved this with one code line, as follow: In file index.php, at your template root, after this code line:
defined( '_JEXEC' ) or die( 'Restricted access' );
paste this line: ini_set ('display_errors', 'Off');
Don't worry, be happy...
posted by Jenio.
If you use Spring frameworks, then you can use CollectionUtils
to check against both Collections (List, Array) and Map etc.
if(CollectionUtils.isEmpty(...)) {...}
Instead of getting all the table columns using * in your sql statement, you use to specify the table columns you need.
You can use the SQL statement something like:
SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS FIRSTNAME FROM customer;
BTW, why couldn't you use FullName instead of FirstName? Like this:
SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'CUSTOMER NAME' FROM customer;
This should do it. You were missing a )
and you only need """
not 4 of them. Also you don't need a elif at the end.
ans=True
while ans:
print("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")
This worked for me on my VM instance of Ubuntu.
hdfs dfs -copyToLocal [hadoop directory] [local directory]
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
If you use this method, you'll prevent that the process zombies are lying around for too long.
(Alternatively, you can use subprocess.call()
or subprocess.check_call()
for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_
)call()
.)
If you have several subprocesses to wait for, you can do
exit_codes = [p.wait() for p in p1, p2]
which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.
You can use the datetime
module for working with dates and times in Python. The strftime
method allows you to produce string representation of dates and times with a format you specify.
>>> import datetime
>>> datetime.date.today().strftime("%B %d, %Y")
'July 23, 2010'
>>> datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
'10:36AM on July 23, 2010'
There are several methods, two of which are as follows. Provide a custom installer or a setup project.
Here is how to create a custom installer
[RunInstaller(true)]
public class MyInstaller : Installer
{
public HelloInstaller()
: base()
{
}
public override void Commit(IDictionary mySavedState)
{
base.Commit(mySavedState);
System.IO.File.CreateText("Commit.txt");
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
System.IO.File.CreateText("Install.txt");
}
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
File.Delete("Commit.txt");
File.Delete("Install.txt");
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
File.Delete("Install.txt");
}
}
To add a setup project
Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment
Set properties of the project, using the properties window
The article How to create a Setup package by using Visual Studio .NET provides the details.
Worked for me..
$timestamp = strtotime('10:09') + 60*60;
$time = date('H:i', $timestamp);
echo $time;//11:09
Explanation:
strtotime('10:09')
creates a numerical timestamp in seconds, something like 1510450372
. Simply add or remove the amount of seconds you need and use date()
to convert it back into a human readable format.
$timestamp = strtotime('10:09') + 60*60; // 10:09 + 1 hour
$timestamp = strtotime('10:09') + 60*60*2; // 10:09 + 2 hours
$timestamp = strtotime('10:09') - 60*60; // 10:09 - 1 hour
time()
also creates a numerical timestamp but for right now. You can use it in the same way.
$timestamp = time() + 60*60; // now + 1 hour
There's been a fair amount of recent research in considering how REST HTTP calls could replace the message queue concept.
If you introduce the concept of a process and a task as a resource, the need for middle messaging layer starts to evaporate.
Ex:
POST /task/name
- Returns a 202 accepted status immediately
- Returns a resource url for the created task: /task/name/X
- Returns a resource url for the started process: /process/Y
GET /process/Y
- Returns status of ongoing process
A task can have multiple steps for initialization, and a process can return status when polled or POST to a callback URL when complete.
This is dead simple, and becomes quite powerful when you realize that you can now subscribe to an rss/atom feed of all running processes and tasks without any middle layer. Any queuing system is going to require some sort of web front end anyway, and this concept has it built in without another layer of custom code.
Your resources exist until you delete them, which means you can view historical information long after the process and task complete.
You have built in service discovery, even for a task that has multiple steps, without any extra complicated protocols.
GET /task/name
- returns form with required fields
POST (URL provided form's "action" attribute)
Your service discovery is an HTML form - a universal and human readable format.
The entire flow can be used programmatically or by a human, using universally accepted tools. It's a client driven, and therefore RESTful. Every tool created for the web can drive your business processes. You still have alternate message channels by POSTing asynchronously to a separate array of log servers.
After you consider it for a while, you sit back and start to realize that REST may just eliminate the need for a messaging queue and an ESB altogether.
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
I usually go for setup an extension of UIBotton. Swift 5.
let button: UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
button.setup(title: "OK", x: 100, y: 430, width: 220, height: 80, color: .yellow)
buttonD.setTitleColor(.black, for: .normal)
}
extension UIButton {
func setup(title: String, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor){
frame = CGRect(x: x, y: y, width: width, height: height)
backgroundColor = color
setTitle(title , for: .normal)
}
}
Yes, and basically you can also use inline style:
<span style="font-size: 15px" class="glyphicon glyphicon-cog"></span>
And if you want to put it into string within some text context, forget about +
operator.
Simply do:
// Qt 5 + C++11
auto i = 13;
auto printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 5
int i = 13;
QString printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 4
int i = 13;
QString printable = QString::fromLatin1("My magic number is %1. That's all!").arg(i);
The steps you listed will work, but there's a longer way that gives you more options:
git checkout dmgr2 # gets you "on branch dmgr2"
git fetch origin # gets you up to date with origin
git merge origin/master
The fetch
command can be done at any point before the merge
, i.e., you can swap the order of the fetch and the checkout, because fetch
just goes over to the named remote (origin
) and says to it: "gimme everything you have that I don't", i.e., all commits on all branches. They get copied to your repository, but named origin/branch
for any branch named branch
on the remote.
At this point you can use any viewer (git log
, gitk
, etc) to see "what they have" that you don't, and vice versa. Sometimes this is only useful for Warm Fuzzy Feelings ("ah, yes, that is in fact what I want") and sometimes it is useful for changing strategies entirely ("whoa, I don't want THAT stuff yet").
Finally, the merge
command takes the given commit, which you can name as origin/master
, and does whatever it takes to bring in that commit and its ancestors, to whatever branch you are on when you run the merge
. You can insert --no-ff
or --ff-only
to prevent a fast-forward, or merge only if the result is a fast-forward, if you like.
When you use the sequence:
git checkout dmgr2
git pull origin master
the pull
command instructs git to run git fetch
, and then the moral equivalent of git merge origin/master
. So this is almost the same as doing the two steps by hand, but there are some subtle differences that probably are not too concerning to you. (In particular the fetch
step run by pull
brings over only origin/master
, and it does not update the ref in your repo:1 any new commits winds up referred-to only by the special FETCH_HEAD
reference.)
If you use the more-explicit git fetch origin
(then optionally look around) and then git merge origin/master
sequence, you can also bring your own local master
up to date with the remote, with only one fetch
run across the network:
git fetch origin
git checkout master
git merge --ff-only origin/master
git checkout dmgr2
git merge --no-ff origin/master
for instance.
1This second part has been changed—I say "fixed"—in git 1.8.4, which now updates "remote branch" references opportunistically. (It was, as the release notes say, a deliberate design decision to skip the update, but it turns out that more people prefer that git update it. If you want the old remote-branch SHA-1, it defaults to being saved in, and thus recoverable from, the reflog. This also enables a new git 1.9/2.0 feature for finding upstream rebases.)
Solution:
SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','your text')),3,32)
How to create encrypted password for passing to password
var to Ansible user
task (from @Brendan Wood's comment):
openssl passwd -salt 'some_plain_salt' -1 'some_plain_pass'
The result will look like:
$1$some_pla$lmVKJwdV3Baf.o.F0OOy71
Example of user
task:
- name: Create user
user: name="my_user" password="$1$some_pla$lmVKJwdV3Baf.o.F0OOy71"
UPD: crypt using SHA-512 see here and here:
$ python -c "import crypt, getpass, pwd; print crypt.crypt('password', '\$6\$saltsalt\$')"
$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/
$ perl -e 'print crypt("password","\$6\$saltsalt\$") . "\n"'
$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/
$ ruby -e 'puts "password".crypt("$6$saltsalt$")'
$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/
Your struct can have methods and properties... why not try
public struct MyStruct {
public string s;
public int length { return s.Length; }
}
Correction @Guffa's answer shows that it is possible... more info here: http://www.codeproject.com/KB/cs/Csharp_implicit_operator.aspx
you can:
itemsCart.Select(c=>c.Price).Sum();
To hit the db only once do:
var itemsInCart = (from o in db.OrderLineItems
where o.OrderId == currentOrder.OrderId
select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();
The extra round-trip saved is worth it :)