Generating ssh keys on the client solved it for me
$ ssh-keygen -t rsa
$('.second').find('div:first')
Improvement to kaiser's answer:
var myEl = $document.find('#some-id');
Don't forget to inject $document
into your directive
October 2017
I would like to add another Bootstrap 4 solution. One that worked for me.
The CSS "Order" property, combined with a media query, can be used to re-order columns when they get stacked in smaller screens.
Something like this:
@media only screen and (max-width: 768px) {
#first {
order: 2;
}
#second {
order: 4;
}
#third {
order: 1;
}
#fourth {
order: 3;
}
}
CodePen Link: https://codepen.io/preston206/pen/EwrXqm
Adjust the screen size and you'll see the columns get stacked in a different order.
I'll tie this in with the original poster's question. With CSS, the navbar, sidebar, and content can be targeted and then order properties applied within a media query.
mysqli_error()
As in:
$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);
Trigger error is better than die because you can use it for development AND production, it's the permanent solution.
Both null
and an empty string are falsy values in JS. Therefore,
if (data) { ... }
is completely sufficient.
A note on the side though: I would avoid having a variable in my code that could manifest in different types. If the data will eventually be a string, then I would initially define my variable with an empty string, so you can do this:
if (data !== '') { ... }
without the null (or any weird stuff like data = "0"
) getting in the way.
exampleLabel.text = String(yourInt)
This is the setup I use:
Before running the tests, execute:
export DISPLAY=:99 /etc/init.d/xvfb start
And after the tests:
/etc/init.d/xvfb stop
The init.d
file I use looks like this:
#!/bin/bash XVFB=/usr/bin/Xvfb XVFBARGS="$DISPLAY -ac -screen 0 1024x768x16" PIDFILE=${HOME}/xvfb_${DISPLAY:1}.pid case "$1" in start) echo -n "Starting virtual X frame buffer: Xvfb" /sbin/start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS echo "." ;; stop) echo -n "Stopping virtual X frame buffer: Xvfb" /sbin/start-stop-daemon --stop --quiet --pidfile $PIDFILE echo "." ;; restart) $0 stop $0 start ;; *) echo "Usage: /etc/init.d/xvfb {start|stop|restart}" exit 1 esac exit 0
There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.
This being said, there are some things that you can indeed do:
You can place images within cells using IMAGE(URL)
, but they cannot be linked to Apps Script functions.
You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))
You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.
The chosen answer works but will fail if the popover is initialized with the body
as the container.
$('a').popover({ container: 'body' });
A solution based on the chosen answer is the following code that needs to be placed before using the popover.
var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj) {
var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type);
originalLeave.call(this, obj);
if (obj.currentTarget) {
self.$tip.one('mouseenter', function() {
clearTimeout(self.timeout);
self.$tip.one('mouseleave', function() {
$.fn.popover.Constructor.prototype.leave.call(self, self);
});
})
}
};
The change is minimal using self.$tip
instead of traversing the DOM expecting the popover to be always a siblings of the element.
w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w+"); //write and read mode
fprintf(fp, "This is testing for fprintf...\n");
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
w and r to form w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w"); //only write mode
fprintf(fp, "This is testing for fprintf...\n");
fclose(fp);
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
r+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r+"); //read and write mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
r and w to form r+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","w");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a+"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
a and r to form a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","r");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
It happens when you have a file with the same name as Makefile target name in the directory where the Makefile is present.
You can't: It's a security feature in all modern browsers.
For IE8, it's off by default, but can be reactivated using a security setting:
When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.
The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.
In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.
More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.
This seems a little confused.
Opening your application in another window or tab will require your entire application to be re-bootstrapped, and then for your router to... pick up that url, convert it into a route, and load the appropriate component.
This is exactly what will happen if you just use a link instead. In fact, that's all that's happening.
The point of the router is to swap components in and out of your router-outlet, which is something that's been bootstrapped and exists within the confines of your running application and isn't shared across multiple windows.
Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines
I've used next function to get scrollbar height/width:
function getBrowserScrollSize(){
var css = {
"border": "none",
"height": "200px",
"margin": "0",
"padding": "0",
"width": "200px"
};
var inner = $("<div>").css($.extend({}, css));
var outer = $("<div>").css($.extend({
"left": "-1000px",
"overflow": "scroll",
"position": "absolute",
"top": "-1000px"
}, css)).append(inner).appendTo("body")
.scrollLeft(1000)
.scrollTop(1000);
var scrollSize = {
"height": (outer.offset().top - inner.offset().top) || 0,
"width": (outer.offset().left - inner.offset().left) || 0
};
outer.remove();
return scrollSize;
}
This jQuery-based solutions works in IE7+ and all other modern browsers (including mobile devices where scrollbar height/width will be 0).
There's no need for multiple shadows or anything fancy like that, you just have to offset your shadow in the negative y-axis.
For dark text on a light background:
text-shadow: 0px -1px 0px rgba(0, 0, 0, .75);
If you have a dark background then you can simply invert the color and y-position:
text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.75);
Play around with the rgba values, the opacity, and the blur to get the effect just right. It will depend a lot on what color font and background you have, and the weightier the font, the better.
HTML - InputFile component can be hide by writing some css. Here I am adding an icon which overrides inputfile component.
<label class="custom-file-upload">
<InputFile OnChange="HandleFileSelected" />
<i class="fa fa-cloud-upload"></i> Upload
</label>
css-
<style>
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
</style>
In Windows 8.1 x64 bit os, Currently I am using MySQL
version :
Server version: 5.7.11-log MySQL Community Server (GPL)
For changing your MySQL
port number, Go to installation directory, my installation directory is :
C:\Program Files\MySQL\MySQL Server 5.7
open the my-default.ini
Configuration Setting file in any text editor.
search the line in the configuration file.
# port = .....
replace it with :
port=<my_new_port_number>
like my self changed to :
port=15800
To apply the changes don't forget to immediate either restart the MySQL Server or your OS.
Hope this would help many one.
Oracle 11G Express Edition is now available to install on 64-bit versions of Windows.
If you want to scan to the end of the string (stripping out a newline if there), just use:
char *x = "19 cool kid";
sscanf (x, "%d %[^\n]", &age, buffer);
That's because %s
only matches non-whitespace characters and will stop on the first whitespace it finds. The %[^\n]
format specifier will match every character that's not (because of ^
) in the selection given (which is a newline). In other words, it will match any other character.
Keep in mind that you should have allocated enough space in your buffer to take the string since you cannot be sure how much will be read (a good reason to stay away from scanf/fscanf
unless you use specific field widths).
You could do that with:
char *x = "19 cool kid";
char *buffer = malloc (strlen (x) + 1);
sscanf (x, "%d %[^\n]", &age, buffer);
(you don't need * sizeof(char)
since that's always 1 by definition).
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Look in your settings.xml
(or, possibly your project's parent or corporate parent POM) for the <repositories>
element. It will look something like the below.
<repositories>
<repository>
<id>central</id>
<url>http://gotoNexus</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</releases>
</repository>
</repositories>
Note the <updatePolicy>
element. The example tells Maven to contact the remote repo (Nexus in my case, Maven Central if you're not using your own remote repo) any time Maven needs to retrieve a snapshot artifact during a build, checking to see if there's a newer copy. The metadata is required for this. If there is a newer copy Maven downloads it to your local repo.
In the example, for releases, the policy is daily
so it will check during your first build of the day. never
is also a valid option, as described in Maven settings docs.
Plugins are resolved separately. You may have repositories configured for those as well, with different update policies if desired.
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://gotoNexus</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
</pluginRepository>
</pluginRepositories>
Someone else mentioned the -o
option. If you use that, Maven runs in "offline" mode. It knows it has a local repo only, and it won't contact the remote repo to refresh the artifacts no matter what update policies you use.
Call SOAP webservice in c#
using (var client = new UpdatedOutlookServiceReferenceAPI.OutlookServiceSoapClient("OutlookServiceSoap"))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
var result = client.UploadAttachmentBase64(GUID, FinalFileName, fileURL);
if (result == true)
{
resultFlag = true;
}
else
{
resultFlag = false;
}
LogWriter.LogWrite1("resultFlag : " + resultFlag);
}
This should help you
HTML
<!-- pretty much i just need to click a link within the regions table and it changes to the neccesary div. -->
<table>
<tr class="thumb"></tr>
<td><a href="#" class="showall">All Regions</a> (shows main map) (link)</td>
<tr class="thumb"></tr>
<td>Northern Region (link)</td>
</tr>
<tr class="thumb"></tr>
<td>Southern Region (link)</td>
</tr>
<tr class="thumb"></tr>
<td>Eastern Region (link)</td>
</tr>
</table>
<br />
<div id="mainmapplace">
<div id="mainmap">
All Regions image
</div>
</div>
<div id="region">
<div class="replace">northern image</div>
<div class="replace">southern image</div>
<div class="replace">Eastern image</div>
</div>
JavaScript
var originalmap;
var flag = false;
$(function (){
$(".replace").click(function(){
flag = true;
originalmap = $('#mainmap');
$('#mainmap').replaceWith($(this));
});
$('.showall').click(
function(){
if(flag == true){
$('#region').append($('#mainmapplace .replace'));
$('#mainmapplace').children().remove();
$('#mainmapplace').append($(originalmap));
//$('#mapplace').append();
}
}
)
})
CSS
#mainmapplace{
width: 100px;
height: 100px;
background: red;
}
#region div{
width: 100px;
height: 100px;
background: blue;
margin: 10px 0 0 0;
}
The content is not ready yet, you can move your js to the end of the file or do
<script>
$(function () {
$( '.expand' ).click(function() {
$( '.img_display_content' ).show();
});
});
So that the document waits to be loaded before running.
Maybe slight overkill but created library ngx-if-empty-or-has-items it checks if an object, set, map or array is not empty. Maybe it will help somebody. It has the same functionality as ngIf (then, else and 'as' syntax is supported).
arrayOrObjWithData = ['1'] || {id: 1}
<h1 *ngxIfNotEmpty="arrayOrObjWithData">
You will see it
</h1>
or
// store the result of async pipe in variable
<h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj">
{{obj.id}}
</h1>
or
noData = [] || {}
<h1 *ngxIfHasItems="noData">
You will NOT see it
</h1>
Put quite simply:
SELECT 'This is Ashok''s Pen.';
So inside the string, replace each single quote with two of them.
Or:
SELECT 'This is Ashok\'s Pen.'
Escape it =)
You should really use .test()
:
if (!re16digit.test(document.myform.CreditCardNumber.value)) {
alert("Please ... ");
}
You should also look around for implementations of (one or more of) the card number checksum algorithms. They're very simple.
You mean the tellItLikeItIs
method? Yes, you have to specify void
to specify that the method doesn't return anything. All methods have to have a return type specified, even if it's void
.
It certainly doesn't return a string - look, there are no return statements anywhere. It's not really clear why you think it is returning a string. It's printing strings to the console, but that's not the same thing as returning one from the method.
Enclose Link component inside BrowserRouter component
export default () => (
<div>
<h1>
<BrowserRouter>
<Link to="/">Redux example</Link>
</BrowserRouter>
</h1>
</div>
)
Same from above, bit more detailed
Using .Net Core
Controller
public class TestController : Controller
{
private string connectionString;
public IDbConnection Connection
{
get { return new SqlConnection(connectionString); }
}
public TestController()
{
connectionString = @"Data Source=OCIUZWORKSPC;Initial Catalog=SocialStoriesDB;Integrated Security=True";
}
public JsonResult GetEventCategory(string q)
{
using (IDbConnection dbConnection = Connection)
{
var categories = dbConnection.Query<ResultTokenInput>("GetEventCategories", new { keyword = q },
commandType: CommandType.StoredProcedure).FirstOrDefault();
return Json(categories);
}
}
public class ResultTokenInput
{
public int ID { get; set; }
public string name { get; set; }
}
}
Stored Procedure ( parent child relation )
create PROCEDURE GetEventCategories
@keyword as nvarchar(100)
AS
BEGIN
WITH CTE(Id, Name, IdHierarchy,parentId) AS
(
SELECT
e.EventCategoryID as Id, cast(e.Title as varchar(max)) as Name,
cast(cast(e.EventCategoryID as char(5)) as varchar(max)) IdHierarchy,ParentID
FROM
EventCategory e where e.Title like '%'+@keyword+'%'
-- WHERE
-- parentid = @parentid
UNION ALL
SELECT
p.EventCategoryID as Id, cast(p.Title + '>>' + c.name as varchar(max)) as Name,
c.IdHierarchy + cast(p.EventCategoryID as char(5)),p.ParentID
FROM
EventCategory p
JOIN CTE c ON c.Id = p.parentid
where p.Title like '%'+@keyword+'%'
)
SELECT
*
FROM
CTE
ORDER BY
IdHierarchy
References in case
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using SocialStoriesCore.Data;
using Microsoft.EntityFrameworkCore;
using Dapper;
using System.Data;
using System.Data.SqlClient;
The CSS Tooltip allows you to format the popup as you like as any div
section! And no Javascript needed.
I needed to do the same concept of having UITableCells have a "space" between them. Since you can't literally add space between cells you can fake it by manipulating the UITableView's cell height and then adding a UIView to the contentView of your cell. Here is a screen shot of a prototype I did in another test project when I was simulating this:
Here is some code (Note: there are lots of hard coded values for demonstration purposes)
First, I needed to set the heightForRowAtIndexPath
to allow for different heights on the UITableViewCell.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = [self.newsArray objectAtIndex:[indexPath row]];
if ([text isEqual:@"December 2012"])
{
return 25.0;
}
return 80.0;
}
Next, I want to manipulate the look and feel of the UITableViewCells so I do that in the willDisplayCell:(NewsUITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
method.
- (void)tableView:(UITableView *)tableView willDisplayCell:(NewsUITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (cell.IsMonth)
{
UIImageView *av = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 20, 20)];
av.backgroundColor = [UIColor clearColor];
av.opaque = NO;
av.image = [UIImage imageNamed:@"month-bar-bkgd.png"];
UILabel *monthTextLabel = [[UILabel alloc] init];
CGFloat font = 11.0f;
monthTextLabel.font = [BVFont HelveticaNeue:&font];
cell.backgroundView = av;
cell.textLabel.font = [BVFont HelveticaNeue:&font];
cell.textLabel.textColor = [BVFont WebGrey];
}
if (indexPath.row != 0)
{
cell.contentView.backgroundColor = [UIColor clearColor];
UIView *whiteRoundedCornerView = [[UIView alloc] initWithFrame:CGRectMake(10,10,300,70)];
whiteRoundedCornerView.backgroundColor = [UIColor whiteColor];
whiteRoundedCornerView.layer.masksToBounds = NO;
whiteRoundedCornerView.layer.cornerRadius = 3.0;
whiteRoundedCornerView.layer.shadowOffset = CGSizeMake(-1, 1);
whiteRoundedCornerView.layer.shadowOpacity = 0.5;
[cell.contentView addSubview:whiteRoundedCornerView];
[cell.contentView sendSubviewToBack:whiteRoundedCornerView];
}
}
Note that I made my whiteRoundedCornerView height 70.0 and that's what causes the simulated space because the cell's height is actually 80.0 but my contentView is 70.0 which gives it the appearance.
There might be other ways of accomplishing this even better but it's just how I found how to do it. I hope it can help someone else.
If you are running a standalone application then you have to use SparkContext
instead of SparkSession
val conf = new SparkConf().setAppName("Samples").setMaster("local")
val sc = new SparkContext(conf)
val textData = sc.textFile("sample.txt").cache()
Depending on your problem slicing can be a really neat solution:
>>> b = (1, 2, 3, 4, 5)
>>> b[:2] + (8,9) + b[3:]
(1, 2, 8, 9, 4, 5)
>>> b[:2] + (8,) + b[3:]
(1, 2, 8, 4, 5)
This allows you to add multiple elements or also to replace a few elements (especially if they are "neighbours". In the above case casting to a list is probably more appropriate and readable (even though the slicing notation is much shorter).
On Centos 5 I was getting all sorts of errors trying to make changes to some variable values from the MySQL shell, after having logged in with the proper uid and pw (with root access). The error that I was getting was something like this:
mysql> -- Set some variable value, for example
mysql> SET GLOBAL general_log='ON';
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation
In a moment of extreme serendipity I did the following:
OS-Shell> sudo mysql # no DB uid, no DB pw
Kindly note that I did not provide the DB uid and password
mysql> show variables;
mysql> -- edit the variable of interest to the desired value, for example
mysql> SET GLOBAL general_log='ON';
It worked like a charm
I know this is a resolved old topic, but I just answered a similar question, and though my answer could help someone else as it covers other solution options:
Click events work a little differently on touch enabled devices. There is no mouse, so technically there is no click. According to this article - http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html - due to memory limitations, click events are only emulated and dispatched from anchor and input elements. Any other element could use touch events, or have click events manually initialized by adding a handler to the raw html element, for example, to force click events on list items:
$('li').each(function(){
this.onclick = function() {}
});
Now click will be triggered by li, therefore can be listened by jQuery.
On your case, you could just change the listener to the anchor element as very well put by @mason81, or use a touch event on the li:
$('.menu').on('touchstart', '.publications', function(){
$('#filter_wrapper').show();
});
Here is a fiddle with a few experiments - http://jsbin.com/ukalah/9/edit
Example:
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Without curly braces PHP would try to find a variable named $numberth
, that doesn't exist!
here put this in your .htaccess
AddType application/x-httpd-php .php .htm .html
more info on this page
There exist special libraries to do just that. (Plus wrappers for python)
netCDF4 Python interface: http://www.unidata.ucar.edu/software/netcdf/software.html#Python
hope this helps
Well if you have given
@ManyToOne ()
@JoinColumn (name = "countryId")
private Country country;
then object of that class i mean Country need to be save first.
because it will only allow User to get saved into the database if there is key available for the Country of that user for the same. means it will allow user to be saved if and only if that country is exist into the Country table.
So for that you need to save that Country first into the table.
As simple as you can use const adults = family.filter(({ age }) => age > 18 );
const family =[{"name":"Jack", "age": 26},_x000D_
{"name":"Jill", "age": 22},_x000D_
{"name":"James", "age": 5 },_x000D_
{"name":"Jenny", "age": 2 }];_x000D_
_x000D_
const adults = family.filter(({ age }) => age > 18 );_x000D_
_x000D_
console.log(adults)
_x000D_
Maybe the condition you are using is incorrect:
$str1 == "taste" && $str2 == "waste"
The program will enter into THEN
part only when both of the stated conditions are true.
You can try with $str1 == "taste" || $str2 == "waste"
. This will execute the THEN
part if anyone of the above conditions are true.
I followed the steps mentioned in this SO and everything is fine except when my Collection View has less data (text) to make it wide enough. Checking the documentation in systemLyaoutSizeFittingSize
, I have this solution so my cell take up the width as I requested:
- (CGSize)calculateSizeForSizingCell:(UICollectionViewCell *)sizingCell width:(CGFloat)width {
CGRect frame = sizingCell.frame;
frame.size.width = width;
sizingCell.frame = frame;
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize
withHorizontalFittingPriority:UILayoutPriorityRequired
verticalFittingPriority:UILayoutPriorityFittingSizeLevel];
return size;
}
Hope this would help someone.
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize NS_AVAILABLE_IOS(6_0);
Apple doc:
Equivalent to sending -systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: with UILayoutPriorityFittingSizeLevel for both priorities.
While the default value is "pretty low" according to Apple's doc:
When you send -[UIView systemLayoutSizeFittingSize:], the size fitting most closely to the target size (the argument) is computed. UILayoutPriorityFittingSizeLevel is the priority level with which the view wants to conform to the target size in that computation. It's quite low. It is generally not appropriate to make a constraint at exactly this priority. You want to be higher or lower.
So my change of default behavior is to enforce the width (horizontal fitting) with UILayoutPriorityRequired
.
Run this
$ rbenv init
# Load rbenv automatically by appending
# the following to ~/.zshrc:
eval "$(rbenv init -)"
Follow instructions, (in my case add to ~/.zshrc) ;)
Also important: Changes only take effect if you reboot your console. Two options
source <modified file>
Like this :
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));
or
List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);
Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of code of input an integer number:
<!doctype html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" >_x000D_
<head>_x000D_
<title>Input Key Filter Test</title>_x000D_
<meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>_x000D_
_x000D_
<!-- For compatibility of IE browser with audio element in the beep() function._x000D_
https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=9"/>_x000D_
_x000D_
<link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css"> _x000D_
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>_x000D_
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<h1>Integer field</h1>_x000D_
<input id="Integer">_x000D_
<script>_x000D_
CreateIntFilter("Integer", function(event){//onChange event_x000D_
inputKeyFilter.RemoveMyTooltip();_x000D_
var elementNewInteger = document.getElementById("NewInteger");_x000D_
var integer = parseInt(this.value);_x000D_
if(inputKeyFilter.isNaN(integer, this)){_x000D_
elementNewInteger.innerHTML = "";_x000D_
return;_x000D_
}_x000D_
//elementNewInteger.innerText = integer;//Uncompatible with FireFox_x000D_
elementNewInteger.innerHTML = integer;_x000D_
}_x000D_
_x000D_
//onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)_x000D_
, function(event){ inputKeyFilter.isNaN(parseInt(this.value), this); }_x000D_
);_x000D_
</script>_x000D_
New integer: <span id="NewInteger"></span>_x000D_
</body>_x000D_
</html>
_x000D_
Also see my page "Integer field:" of the example of the input key filter
I had a ;
in the environment variable name, put it out and it will works !
A while ago i wrote a detailed article about Hibernate key generators: http://blog.eyallupu.com/2011/01/hibernatejpa-identity-generators.html
Choosing the correct generator is a complicated task but it is important to try and get it right as soon as possible - a late migration might be a nightmare.
A little off topic but a good chance to raise a point usually overlooked which is sharing keys between applications (via API). Personally I always prefer surrogate keys and if I need to communicate my objects with other systems I don't expose my key (even though it is a surrogate one) – I use an additional ‘external key’. As a consultant I have seen more than once 'great' system integrations using object keys (the 'it is there let's just use it' approach) just to find a year or two later that one side has issues with the key range or something of the kind requiring a deep migration on the system exposing its internal keys. Exposing your key means exposing a fundamental aspect of your code to external constrains shouldn’t really be exposed to.
Why perform the summation forwards when you can do it backwards? Given:
std::vector<int> v; // vector to be summed
int sum_of_elements(0); // result of the summation
We can use subscripting, counting backwards:
for (int i(v.size()); i > 0; --i)
sum_of_elements += v[i-1];
We can use range-checked "subscripting," counting backwards (just in case):
for (int i(v.size()); i > 0; --i)
sum_of_elements += v.at(i-1);
We can use reverse iterators in a for loop:
for(std::vector<int>::const_reverse_iterator i(v.rbegin()); i != v.rend(); ++i)
sum_of_elements += *i;
We can use forward iterators, iterating backwards, in a for loop (oooh, tricky!):
for(std::vector<int>::const_iterator i(v.end()); i != v.begin(); --i)
sum_of_elements += *(i - 1);
We can use accumulate
with reverse iterators:
sum_of_elems = std::accumulate(v.rbegin(), v.rend(), 0);
We can use for_each
with a lambda expression using reverse iterators:
std::for_each(v.rbegin(), v.rend(), [&](int n) { sum_of_elements += n; });
So, as you can see, there are just as many ways to sum the vector backwards as there are to sum the vector forwards, and some of these are much more exciting and offer far greater opportunity for off-by-one errors.
What happens is that the recursive call itself results in further recursive behaviour. If you were to write it out you get:
fact(4)
fact(3) * 4;
(fact(2) * 3) * 4;
((fact(1) * 2) * 3) * 4;
((1 * 2) * 3) * 4;
For those getting blank/black screens this code worked for me.
let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
self.present(vc, animated: true, completion: nil)
To set the "Identifier" to your VC just go to identity inspector for the VC in the storyboard. Set the 'Storyboard ID' to what ever you want to identifier to be. Look at the image below for reference.
Technically speaking the answer is correct, but there is a potential problem remaining.
string test = rb.SelectedValue
is an object and while this implicit cast works. It may not work correction if you were sending it to another method (and granted this may depend on the version of framework, I am unsure) it may not recognize the value.
string test = rb.SelectedValue; //May work fine
SomeMethod(rb.SelectedValue);
where SomeMethod
is expecting a string may not.
Sadly the rb.SelectedValue.ToString();
can save a few unexpected issues.
Double importing jquery can cause Error
<script src="static/public/js/jquery/jquery.min.js"></script>
OR
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="" crossorigin="anonymous"></script>
Solution for Kotlin:
val sourceContent = File("test.txt").readText(Charset.forName("windows-1251"))
val result = String(sourceContent.toByteArray())
Kotlin uses UTF-8 everywhere as default encoding.
Method toByteArray()
has default argument - Charsets.UTF_8
.
I just planned to share some knowledge.
Deadlocks A set of threads/processes is deadlocked, if each thread/process in the set is waiting for an event that only another process in the set can cause.
The important thing here is another process is also in the same set. that means another process also blocked and no one can proceed.
Deadlocks occur when processes are granted exclusive access to resources.
These four conditions should be satisfied to have a deadlock.
If we found these conditions then we can say there may be occurred a situation like a deadlock.
LiveLock
Each thread/process is repeating the same state again and again but doesn't progress further. Something similar to a deadlock since the process can not enter the critical section. However in a deadlock, processes are wait without doing anything but in livelock, the processes are trying to proceed but processes are repeated to the same state again and again.
(In a deadlocked computation there is no possible execution sequence which succeeds. but In a livelocked computation, there are successful computations, but there are one or more execution sequences in which no process enters its critical section.)
Difference from deadlock and livelock
When deadlock happens, No execution will happen. but in livelock, some executions will happen but those executions are not enough to enter the critical section.
You're looking for the JavaScriptSerializer
class, which is used internally by JsonResult:
string json = new JavaScriptSerializer().Serialize(jsonResult.Data);
Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:
var http = require('http')
var fs = require('fs')
fs.readFile('image.jpg', function(err, data) {
if (err) throw err // Fail if the file can't be read.
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'})
res.end(data) // Send the file data to the browser.
}).listen(8124)
console.log('Server running at http://localhost:8124/')
})
Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg
.
[Edit] You could even embed the image in an HTML page directly by using an <img>
with a data URI source. For example:
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><body><img src="data:image/jpeg;base64,')
res.write(Buffer.from(data).toString('base64'));
res.end('"/></body></html>');
Ok found out the Tomcat file server.xml must be configured as well for the data source to work. So just add:
<Resource
auth="Container"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
maxActive="20"
maxIdle="10"
maxWait="-1"
name="ds/flexeraDS"
type="javax.sql.DataSource"
url="jdbc:derby:flexeraDB;create=true"
/>
you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual
Notice the data-type and size
>describe all_tab_columns
VIEW all_tab_columns
Name Null? Type
----------------------------------------- -------- ----------------------------
OWNER NOT NULL VARCHAR2(30)
TABLE_NAME NOT NULL VARCHAR2(30)
COLUMN_NAME NOT NULL VARCHAR2(30)
DATA_TYPE VARCHAR2(106)
DATA_TYPE_MOD VARCHAR2(3)
DATA_TYPE_OWNER VARCHAR2(30)
DATA_LENGTH NOT NULL NUMBER
DATA_PRECISION NUMBER
DATA_SCALE NUMBER
NULLABLE VARCHAR2(1)
COLUMN_ID NUMBER
DEFAULT_LENGTH NUMBER
DATA_DEFAULT LONG
NUM_DISTINCT NUMBER
LOW_VALUE RAW(32)
HIGH_VALUE RAW(32)
DENSITY NUMBER
NUM_NULLS NUMBER
NUM_BUCKETS NUMBER
LAST_ANALYZED DATE
SAMPLE_SIZE NUMBER
CHARACTER_SET_NAME VARCHAR2(44)
CHAR_COL_DECL_LENGTH NUMBER
GLOBAL_STATS VARCHAR2(3)
USER_STATS VARCHAR2(3)
AVG_COL_LEN NUMBER
CHAR_LENGTH NUMBER
CHAR_USED VARCHAR2(1)
V80_FMT_IMAGE VARCHAR2(3)
DATA_UPGRADED VARCHAR2(3)
HISTOGRAM VARCHAR2(15)
You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href
.
advance code for the search for all attributes of the object in arrays
b=[];
yourArray.forEach(x => {
Object.keys(x).forEach(i => {if (x[i].match('5') && !b.filter(y => y === x).length) { b.push(x) }})
});
console.log(b)
Once I had this problem after renaming a file. I renamed the file from within Xcode, but afterwards Xcode couldn't find the function in the file. Even a clean rebuild didn't fix the problem, but closing and then re-opening the project got the build to work.
A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)
Solution
id
is unsigned integer, auto_incrementid
columnBam, immediate 10x+ insert improvement.
A complete example in data binding Fragments
FragmentMyProgramsBinding is binding class generated for res/layout/fragment_my_programs
public class MyPrograms extends Fragment {
FragmentMyProgramsBinding fragmentMyProgramsBinding;
public MyPrograms() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
FragmentMyProgramsBinding fragmentMyProgramsBinding = DataBindingUtil.inflate(inflater, R
.layout.fragment_my_programs, container, false);
return fragmentMyProgramsBinding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
I always thought it was lazy not to use them. I was taught it should always be done. But then, I didnt listen to Joel's discussion. He may have had a good reason, I don't know.
The for-in
statement by itself is not a "bad practice", however it can be mis-used, for example, to iterate over arrays or array-like objects.
The purpose of the for-in
statement is to enumerate over object properties. This statement will go up in the prototype chain, also enumerating over inherited properties, a thing that sometimes is not desired.
Also, the order of iteration is not guaranteed by the spec., meaning that if you want to "iterate" an array object, with this statement you cannot be sure that the properties (array indexes) will be visited in the numeric order.
For example, in JScript (IE <= 8), the order of enumeration even on Array objects is defined as the properties were created:
var array = [];
array[2] = 'c';
array[1] = 'b';
array[0] = 'a';
for (var p in array) {
//... p will be "2", "1" and "0" on IE
}
Also, speaking about inherited properties, if you, for example, extend the Array.prototype
object (like some libraries as MooTools do), that properties will be also enumerated:
Array.prototype.last = function () { return this[this.length-1]; };
for (var p in []) { // an empty array
// last will be enumerated
}
As I said before to iterate over arrays or array-like objects, the best thing is to use a sequential loop, such as a plain-old for
/while
loop.
When you want to enumerate only the own properties of an object (the ones that aren't inherited), you can use the hasOwnProperty
method:
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// prop is not inherited
}
}
And some people even recommend calling the method directly from Object.prototype
to avoid having problems if somebody adds a property named hasOwnProperty
to our object:
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// prop is not inherited
}
}
Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.
Swift 3 / Swift 4 solution that also works with NIBs/XIB files in iOS 10+:
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = []
}
In addition to the above mentioned answers ,recheck your url
EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html
Try this
DataSet ds = new DataSet("TimeRanges");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("Procedure1", conn);
sqlComm.Parameters.AddWithValue("@Start", StartTime);
sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
If you have two bindings {{item.name}}
and {{item.directory}}
.
And want to show the data as a directory followed by the name, assuming '/root' as the directory and 'Machine' as the name (/root-machine).
{{[item.directory]+[isLast ? '': '/'] + [ item.name] | limitTo:5}}
Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/
Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.
EDIT: Youtube renders the object
and embed
with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:
a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements
b) Find a way for youtube to specify those.
You might have a typo.. In my case I was saying %w where I meant to say %s.
I had the same error. Creating a new AVD with the appropriate API level solved my problem.
why do that to yourself?
jQuery:
$("#element").fadeOut();
$("#element").fadeIn();
I think that's easier.
I am new to Rust, but this solution seems to work:
#[macro_use]
extern crate lazy_static;
use std::sync::{Arc, Mutex};
lazy_static! {
static ref GLOBAL: Arc<Mutex<GlobalType> =
Arc::new(Mutex::new(GlobalType::new()));
}
Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.
Both solutions should provide a safe approach to using global variables.
When a JSON start's with {} it is a ObjectJSON object and when it start's with [] it is an Array JOSN Array
An JSON array can consist of a/many objects and that is called an array of objects
This file will serve you as a good sendfile
example : http://tldp.org/LDP/LGNET/91/misc/tranter/server.c.txt
If you only have one line of text and your div has a fixed height, you can do this:
div {
line-height: (2*height - font-size);
text-align: right;
}
See fiddle.
template.yml
, which is your docker-compose.yml
with environment variable.source env.sh; rm -rf docker-compose.yml; envsubst < "template.yml" > "docker-compose.yml";
A new file docker-compose.yml
will be generated with the correct values of environment variables.
Sample template.yml file:
oracledb:
image: ${ORACLE_DB_IMAGE}
privileged: true
cpuset: "0"
ports:
- "${ORACLE_DB_PORT}:${ORACLE_DB_PORT}"
command: /bin/sh -c "chmod 777 /tmp/start; /tmp/start"
container_name: ${ORACLE_DB_CONTAINER_NAME}
Sample env.sh file:
#!/bin/bash
export ORACLE_DB_IMAGE=<image-name>
export ORACLE_DB_PORT=<port to be exposed>
export ORACLE_DB_CONTAINER_NAME=ORACLE_DB_SERVER
As the error states - the database is not open - it was previously shut down, and someone left it in the middle of the startup process. They may either be intentional, or unintentional (i.e., it was supposed to be open, but failed to do so).
Assuming that's nothing wrong with the database itself, you could open it with a simple statement:(Since the question is asked specifically in the context of SQLPlus, kindly remember to put a statement terminator(Semicolon) at the end mandatorily, otherwise, it will result in an error.)
ALTER DATABASE OPEN;
IT IS POSSIBLE!
var i = 0;_x000D_
_x000D_
with({_x000D_
get a() {_x000D_
return ++i;_x000D_
}_x000D_
}) {_x000D_
if (a == 1 && a == 2 && a == 3)_x000D_
console.log("wohoo");_x000D_
}
_x000D_
This uses a getter inside of a with
statement to let a
evaluate to three different values.
... this still does not mean this should be used in real code...
Even worse, this trick will also work with the use of ===
.
var i = 0;_x000D_
_x000D_
with({_x000D_
get a() {_x000D_
return ++i;_x000D_
}_x000D_
}) {_x000D_
if (a !== a)_x000D_
console.log("yep, this is printed.");_x000D_
}
_x000D_
I tried this query and it works for me.
SELECT username FROM dba_users
ORDER BY username;
If you want to get the list of all that users which are created by end-user, then you can try this:
SELECT username FROM dba_users where Default_TableSpace not in ('SYSAUX', 'SYSTEM', 'USERS')
ORDER BY username;
UPDATE
This answer was submitted when Angular 2 was still in alpha and many of the features were unavailable / undocumented. While the below will still work, this method is now entirely outdated. I strongly recommend the accepted answer over the below.
Original Answer
Yes in fact it is, however you will want to make sure that it is scoped correctly. For this I've used a property to ensure that this
means what I want it to.
@Component({
...
template: '<child [myCallback]="theBoundCallback"></child>',
directives: [ChildComponent]
})
export class ParentComponent{
public theBoundCallback: Function;
public ngOnInit(){
this.theBoundCallback = this.theCallback.bind(this);
}
public theCallback(){
...
}
}
@Component({...})
export class ChildComponent{
//This will be bound to the ParentComponent.theCallback
@Input()
public myCallback: Function;
...
}
The only issue I see are relative links and templates not being properly loaded because of this.
from the docs regarding HTML5 mode
Relative links
Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (
<base href="/my-base">
) or you must use absolute urls (starting with/
) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.
In your case you can add a forward slash /
in href
attributes ($location.path
does this automatically) and also to templateUrl
when configuring routes. This avoids routes like example.com/tags/another
and makes sure templates load properly.
Here's an example that works:
<div>
<a href="/">Home</a> |
<a href="/another">another</a> |
<a href="/tags/1">tags/1</a>
</div>
<div ng-view></div>
And
app.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.when('/tags/:tagId', {
templateUrl: '/partials/template2.html',
controller: 'ctrl2'
})
.when('/another', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.otherwise({ redirectTo: '/' });
});
If using Chrome you will need to run this from a server.
Best would be not using LinkedList
at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)
Use ArrayList
, and iterate with
int len = list.size();
for (int i = 0; i < len; i++) {
Element ele = list.get(i);
}
Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:
iter = list.listIterator();
(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)
Try this, I've used it in a personal wiki-like app:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("foo://")) {
// magic
return true;
}
return false;
}
});
You can define a generic function like this:
@SuppressWarnings("unchecked")
public static <T> List<T> newFixedSizeList(int size) {
return (List<T>)Arrays.asList(new Object[size]);
}
And
List<String> s = newFixedSizeList(3); // All elements are initialized to null
s.set(0, "zero");
s.add("three"); // throws java.lang.UnsupportedOperationException
@SETLOCAL ENABLEDELAYEDEXPANSION
@REM Use WMIC to retrieve date and time
@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF NOT "%%~F"=="" (
SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
set YEAR=!SortDate:~0,4!
set MON=!SortDate:~4,2!
set DAY=!SortDate:~6,2!
@REM Add 1000000 so as to force a prepended 0 if hours less than 10
SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E
set HOUR=!SortTime:~1,2!
set MIN=!SortTime:~3,2!
set SEC=!SortTime:~5,2!
)
)
@echo on
@echo DATE=%DATE%, TIME=%TIME%
@echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC!
@echo YR=!YEAR! MON=!MON! DAY=!DAY!
@echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!'
Output:
DATE=2015-05-20, TIME= 1:30:38.59
HOUR=01 MIN=30 SEC=38
YR=2015 MON=05 DAY=20
DATECODE= '201505200130'
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
Alerts aren't the best for displaying objects. Try console.log? If you still see Object Object in the console, use JSON.parse like this > var obj = JSON.parse(yourObject); console.log(obj)
A button accepts a "title" attribute. You can then assign it the value you want to make a label appear when you hover the mouse over the button.
<button type="submit" title="Login">_x000D_
Login</button>
_x000D_
just give elem.fadeOut(10).fadeIn(10);
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
Just to add that if your truth value can vary, for instance if it is an input from different programming languages or from different types, a more robust method would be:
flag = value in ['True','true',1,'T','t','1'] # this can be as long as you want to support
And a more performant variant would be (set lookup is O(1)):
TRUTHS = set(['True','true',1,'T','t','1'])
flag = value in truths
This code is a part of a login form where the users wait for the authentication server to respond.
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace LoginWithProgressBar
{
public partial class TheForm : Form
{
// BackgroundWorker object deals with the long running task
private readonly BackgroundWorker _bw = new BackgroundWorker();
public TheForm()
{
InitializeComponent();
// set MarqueeAnimationSpeed
progressBar.MarqueeAnimationSpeed = 30;
// set Visible false before you start long running task
progressBar.Visible = false;
_bw.DoWork += Login;
_bw.RunWorkerCompleted += BwRunWorkerCompleted;
}
private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// hide the progress bar when the long running process finishes
progressBar.Hide();
}
private static void Login(object sender, DoWorkEventArgs doWorkEventArgs)
{
// emulate long (3 seconds) running task
Thread.Sleep(3000);
}
private void ButtonLoginClick(object sender, EventArgs e)
{
// show the progress bar when the associated event fires (here, a button click)
progressBar.Show();
// start the long running task async
_bw.RunWorkerAsync();
}
}
}
Please try this online tool sql2builder
DB::table('products')
->whereIn('products.id',function($query) {
DB::table('product_category')
->whereIn('category_id',['223','15'])
->select('product_id');
})
->where('products.active',1)
->select('products.id','products.name','products.img','products.safe_name','products.sku','products.productstatusid')
->get();
I have fixed my issue by setting the position of the element inside a div to relative;
I would recommend keeping the object you have, and just utilizing the properties that you want, rather than removing the resolution you already have.
If you want to print it in a certain format you may want to look at this...That way you can preserve your resolution further down the line.
That being said you can create a new DateTime
object using only the properties you want as @romkyns has in his answer.
I don't know why but i just renamed my source file COLARR.C to colarr.c and the error vanished! probably you need this
sudo apt-get install g++
The csv
module handles csv files by row.
If you want to handle it by column, pandas
is a good solution.
Besides, there are 2 ways to get all (or specific) columns with pure simple Python code.
with open('demo.csv') as file:
data = {}
for row in csv.DictReader(file):
for key, value in row.items():
if key not in data:
data[key] = []
data[key].append(value)
It is easy to understand.
with open('demo.csv') as file:
data = {values[0]: values[1:] for values in zip(*csv.reader(file))}
This is not very clear, but efficient.
zip(x, y, z)
transpose (x, y, z)
, while x
, y
, z
are lists.
*csv.reader(file)
make (x, y, z)
for zip
, with column names.
The content of demo.csv
:
a,b,c
1,2,3
4,5,6
7,8,9
The result of 1:
>>> print(data)
{'c': ['3', '6', '9'], 'b': ['2', '5', '8'], 'a': ['1', '4', '7']}
The result of 2:
>>> print(data)
{'c': ('3', '6', '9'), 'b': ('2', '5', '8'), 'a': ('1', '4', '7')}
If you're using Perl or PHP, you can replace
[0-9a-fA-F]
with:
[[:xdigit:]]
The magic happens when calling SaveChanges()
and depends on the current EntityState
. If the entity has an EntityState.Added
, it will be added to the database, if it has an EntityState.Modified
, it will be updated in the database. So you can implement an InsertOrUpdate()
method as follows:
public void InsertOrUpdate(Blog blog)
{
using (var context = new BloggingContext())
{
context.Entry(blog).State = blog.BlogId == 0 ?
EntityState.Added :
EntityState.Modified;
context.SaveChanges();
}
}
If you can't check on Id = 0
to determine if it's a new entity or not, check the answer of Ladislav Mrnka.
I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :
Create an Interface :
public interface AsyncResponse {
void processFinish(String output);
}
Then in asynctask
@Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
Then in yout main activity
@Override
public void processFinish(String data) {
// do things
}
You can try creating a css for your font with font-face (like explained here)
Step #1
Create a css file with font face and place it somewhere, like in assets/fonts
customfont.css
@font-face {
font-family: YourFontFamily;
src: url("/assets/font/yourFont.otf") format("truetype");
}
Step #2
Add the css to your .angular-cli.json in the styles
config
"styles":[
//...your other styles
"assets/fonts/customFonts.css"
]
Do not forget to restart ng serve
after doing this
Step #3
Use the font in your code
component.css
span {font-family: YourFontFamily; }
While you may wish to use a library, such as the excellent jQuery, you don't have to: all modern browsers support HTTP very well in their JavaScript implementations via the XMLHttpRequest API, which, despite its name, is not limited to XML representations.
Here's an example of making a synchronous HTTP PUT request in JavaScript:
var url = "http://host/path/to/resource";
var representationOfDesiredState = "The cheese is old and moldy, where is the bathroom?";
var client = new XMLHttpRequest();
client.open("PUT", url, false);
client.setRequestHeader("Content-Type", "text/plain");
client.send(representationOfDesiredState);
if (client.status == 200)
alert("The request succeeded!\n\nThe response representation was:\n\n" + client.responseText)
else
alert("The request did not succeed!\n\nThe response status was: " + client.status + " " + client.statusText + ".");
This example is synchronous because that makes it a little easier, but it's quite easy to make asynchronous requests using this API as well.
There are thousands of pages and articles on the web about learning XmlHttpRequest — they usually use the term AJAX – unfortunately I can't recommend a specific one. You may find this reference handy though.
Upcasting and Downcasting:
Upcasting: Casting from Derived-Class to Base Class Downcasting: Casting from Base Class to Derived Class
Let's understand the same as an example:
Consider two classes Shape as My parent class and Circle as a Derived class, defined as follows:
class Shape
{
public int Width { get; set; }
public int Height { get; set; }
}
class Circle : Shape
{
public int Radius { get; set; }
public bool FillColor { get; set; }
}
Upcasting:
Shape s = new Shape();
Circle c= s;
Both c and s are referencing to the same memory location, but both of them have different views i.e using "c" reference you can access all the properties of the base class and derived class as well but using "s" reference you can access properties of the only parent class.
A practical example of upcasting is Stream class which is baseclass of all types of stream reader of .net framework:
StreamReader reader = new StreamReader(new FileStreamReader());
here, FileStreamReader() is upcasted to streadm reder.
Downcasting:
Shape s = new Circle(); here as explained above, view of s is the only parent, in order to make it for both parent and a child we need to downcast it
var c = (Circle) s;
The practical example of Downcasting is button class of WPF.
Try This:
sqlplus -s ${ORA_CONN_STR} <<EOF >/dev/null
You can cast the DATETIME field into DATE as:
SELECT * FROM `calendar` WHERE CAST(startTime AS DATE) = '2010-04-29'
This is very much efficient.
You basically put the files you want to commit on the command line
svn ci file1 file2 dir1/file3
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:top="-6dp"
android:left="-6dp"
android:right="-6dp"
android:bottom="0dp">
<shape android:shape="rectangle">
<solid android:color="#88FFFF00"/>
<stroke
android:width="5dp"
android:color="#FF000000"/>
</shape>
</item>
</layer-list>
For example, your remote host is example.com and remote login name is user1:
scp [email protected]:/path/to/file /path/to/store/file
You can use the built-in javascript setInterval.
var ajax_call = function() {
//your jQuery ajax code
};
var interval = 1000 * 60 * X; // where X is your every X minutes
setInterval(ajax_call, interval);
or if you are the more terse type ...
setInterval(function() {
//your jQuery ajax code
}, 1000 * 60 * X); // where X is your every X minutes
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
To test a year in a string which contains other words along with the year you can use the following regex: \b\d{4}\b
i found an easy solution, export the database, edit it what you want to edit in a text editor, then import it. Done
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
How about this:
SELECT DEF.Rate, ACTUAL.Rate, COALESCE(ACTUAL.Rate, DEF.Rate) AS UseThisRate
FROM
(SELECT 0) DEF (Rate) -- This is your default rate
LEFT JOIN (
select rate
from d_payment_index
--WHERE 1=2 -- Uncomment this line to simulate a missing value
--...HERE IF YOUR ACTUAL WHERE CLAUSE. Removed for testing purposes...
--where fy = 2007
-- and payment_year = 2008
-- and program_id = 18
) ACTUAL (Rate) ON 1=1
Results
Valid Rate Exists
Rate Rate UseThisRate
----------- ----------- -----------
0 1 1
Default Rate Used
Rate Rate UseThisRate
----------- ----------- -----------
0 NULL 0
Test DDL
CREATE TABLE d_payment_index (rate int NOT NULL)
INSERT INTO d_payment_index VALUES (1)
This works fine:
os.path.join(dir_name, base_filename + "." + filename_suffix)
Keep in mind that os.path.join()
exists only because different operating systems use different path separator characters. It smooths over that difference so cross-platform code doesn't have to be cluttered with special cases for each OS. There is no need to do this for file name "extensions" (see footnote) because they are always connected to the rest of the name with a dot character, on every OS.
If using a function anyway makes you feel better (and you like needlessly complicating your code), you can do this:
os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))
If you prefer to keep your code clean, simply include the dot in the suffix:
suffix = '.pdf'
os.path.join(dir_name, base_filename + suffix)
That approach also happens to be compatible with the suffix conventions in pathlib, which was introduced in python 3.4 after this question was asked. New code that doesn't require backward compatibility can do this:
suffix = '.pdf'
pathlib.PurePath(dir_name, base_filename + suffix)
You might prefer the shorter Path
instead of PurePath
if you're only handling paths for the local OS.
Warning: Do not use pathlib's with_suffix()
for this purpose. That method will corrupt base_filename
if it ever contains a dot.
Footnote: Outside of Micorsoft operating systems, there is no such thing as a file name "extension". Its presence on Windows comes from MS-DOS and FAT, which borrowed it from CP/M, which has been dead for decades. That dot-plus-three-letters that many of us are accustomed to seeing is just part of the file name on every other modern OS, where it has no built-in meaning.
esModuleInterop
generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:
//ts
import React from 'react'
//js
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
__importDefault
: If the module is not an es
module then what is returned by require becomes the default. This means that if you use default import on a commonjs
module, the whole module is actually the default.
__importStar
is best described in this PR:
TypeScript treats a namespace import (i.e.
import * as foo from "foo"
) as equivalent toconst foo = require("foo")
. Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.Babel first requires in the module, and checks for a property named
__esModule
. If__esModule
is set totrue
, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:
- All properties are plucked off of the require'd module and made available as named imports.
- The originally require'd module is made available as a default import.
So we get this:
// ts
import * as React from 'react'
// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));
allowSyntheticDefaultImports
is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react'
will raise the error Module '".../node_modules/@types/react/index"' has no default export.
if allowSyntheticDefaultImports
is false
.
Create a tensor on the GPU as follows:
$ python
>>> import torch
>>> print(torch.rand(3,3).cuda())
Do not quit, open another terminal and check if the python process is using the GPU using:
$ nvidia-smi
Chris Beeley is rigth, you only need the proportions by column. Using your data is:
your_matrix<-(
rbind(
c(23,234,324),
c(34,534,12),
c(56,324,124),
c(34,234,124),
c(123,534,654)
)
)
barplot(prop.table(your_matrix, 2) )
Flat and simple config without rewrite, can work in some cases:
location / {
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /home/webuser/site/index.php;
}
CakePHP has two methods for getting the last inserted id: Model::getLastInsertID()
and Model::getInsertID()
.
Actually these methods are identical so it really doesn't matter which method you use.
echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
This methods can be found in cake/libs/model/model.php
on line 2768
What bout this query (based on the description from manual)?
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public'
AND table_type='BASE TABLE';
Oh, I hate % design for this too....
You may convert dividend to unsigned in a way like:
unsigned int offset = (-INT_MIN) - (-INT_MIN)%divider
result = (offset + dividend) % divider
where offset is closest to (-INT_MIN) multiple of module, so adding and subtracting it will not change modulo. Note that it have unsigned type and result will be integer. Unfortunately it cannot correctly convert values INT_MIN...(-offset-1) as they cause arifmetic overflow. But this method have advandage of only single additional arithmetic per operation (and no conditionals) when working with constant divider, so it is usable in DSP-like applications.
There's special case, where divider is 2N (integer power of two), for which modulo can be calculated using simple arithmetic and bitwise logic as
dividend&(divider-1)
for example
x mod 2 = x & 1
x mod 4 = x & 3
x mod 8 = x & 7
x mod 16 = x & 15
More common and less tricky way is to get modulo using this function (works only with positive divider):
int mod(int x, int y) {
int r = x%y;
return r<0?r+y:r;
}
This just correct result if it is negative.
Also you may trick:
(p%q + q)%q
It is very short but use two %-s which are commonly slow.
https://www.ripe.net/internet-coordination/press-centre/understanding-ip-addressing
For IPv4, this pool is 32-bits (2³²) in size and contains 4,294,967,296 IPv4 addresses.
In case of IPv6
The IPv6 address space is 128-bits (2¹²8) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses.
inclusive of RESERVED IP
Reserved address blocks
Range Description Reference
0.0.0.0/8 Current network (only valid as source address) RFC 6890
10.0.0.0/8 Private network RFC 1918
100.64.0.0/10 Shared Address Space RFC 6598
127.0.0.0/8 Loopback RFC 6890
169.254.0.0/16 Link-local RFC 3927
172.16.0.0/12 Private network RFC 1918
192.0.0.0/24 IETF Protocol Assignments RFC 6890
192.0.2.0/24 TEST-NET-1, documentation and examples RFC 5737
192.88.99.0/24 IPv6 to IPv4 relay (includes 2002::/16) RFC 3068
192.168.0.0/16 Private network RFC 1918
198.18.0.0/15 Network benchmark tests RFC 2544
198.51.100.0/24 TEST-NET-2, documentation and examples RFC 5737
203.0.113.0/24 TEST-NET-3, documentation and examples RFC 5737
224.0.0.0/4 IP multicast (former Class D network) RFC 5771
240.0.0.0/4 Reserved (former Class E network) RFC 1700
255.255.255.255 Broadcast RFC 919
I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!
I just encountered this. You may be accessing a method/type from within the same package using the package name itself.
Here is an example to illustrate what I mean:
In foo.go:
// foo.go
package foo
func Foo() {...}
In foo_test.go:
// foo_test.go
package foo
// try to access Foo()
foo.Foo() // WRONG <== This was the issue. You are already in package foo, there is no need to use foo.Foo() to access Foo()
Foo() // CORRECT
You need the ip of the other pc and do:
scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop
it will ask you for 'user's password on the other pc.
OK, I don't think the official snippet mentioned by galuszkak should be used everywhere, we should concern the case that some bug may be triggered during the handler such as hello_world
function. Whether the response is correct or uncorrect, the Access-Control-Allow-Origin
header is what we should concern. So, thing is very simple, just like bellow:
@blueprint.after_request # blueprint can also be app~~
def after_request(response):
header = response.headers
header['Access-Control-Allow-Origin'] = '*'
return response
That is all~~
Click settings and search for "Repositories", then select the local repo and click "Update". That's all. This action meets my need.
This seems to also happen when you use the new SSIS 2012 "Shared Connection Manager" concept where the connection managers are not defined within your package but the Visual Studio project and just get referenced in the package. Executing it via SQL Agent or DTEXEC yields the same error message.
I haven't found a solution for that yet but would love to get some feedback if anybody experienced it before.
private void Fetching_Record_Grid_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
{
IInputElement element = e.MouseDevice.DirectlyOver;
if (element != null && element is FrameworkElement)
{
if (((FrameworkElement)element).Parent is DataGridCell)
{
var grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
//var rowView = grid.SelectedItem as DataRowView;
try
{
Station station = (Station)grid.SelectedItem;
id_txt.Text = station.StationID.Trim() ;
description_txt.Text = station.Description.Trim();
}
catch
{
}
}
}
}
}
You can change this in preferences:
DD-MON-RR HH24:MI:SS
into the Date Format field.Here is a screenshot:
AS datatype in Javascript are determined dynamically it treats 04 as 4 Use conditional statement if value is lesser then 10 then add 0 before it by make it string E.g,
var x=4;
x = x<10?"0"+x:x
console.log(x); // 04
I check for both Wi-fi and Mobile internet as follows...
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Obviously, It could easily be modified to check for individual specific connection types, e.g., if your app needs the potentially higher speeds of Wi-fi to work correctly etc.
Updated 2018
Do you want to close the modal after submit? Whether the form in inside the modal or external to it you should be able to use jQuery ajax to submit the form.
Here is an example with the form inside the modal:
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<form id="myForm" method="post">
<input type="hidden" value="hello" id="myField">
<button id="myFormSubmit" type="submit">Submit</button>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
And the jQuery ajax to get the form fields and submit it..
$('#myFormSubmit').click(function(e){
e.preventDefault();
alert($('#myField').val());
/*
$.post('http://path/to/post',
$('#myForm').serialize(),
function(data, status, xhr){
// do something here with response;
});
*/
});
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(12.924640523603115,77.61965398949724),
map: map
});
this.placeMarker(coordinates, this.map);
placeMarker(location, map) {
var marker = new google.maps.Marker({
position: location,
map: map
});
this.markersArray.push(marker);
}
While you should generally prefer sys.exit
because it is more "friendly" to other code, all it actually does is raise an exception.
If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch SystemExit
, there is another function - os._exit
- which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter; for example, hooks registered with the "atexit" module are not executed.
You've got a couple regexes now which will do what you want, so that's adequately covered.
What hasn't been mentioned is why your attempt won't work: Inside a character class, $
(as well as ^
, .
, and /
) has no special meaning, so [/$]
matches either a literal /
or a literal $
rather than terminating the regex (/
) or matching end-of-line ($
).
Some of the answers I've seen explain how to make the contents of a cell invisible, but not how to hide the entire column, which is what I wanted to do.
If you have AutoGenerateColumns = "false"
and are actually using BoundField
for the column you want to hide, Bala's answer is slick. But if you are using TemplateField
for the column, you can handle the DataBound
event and do something like this:
protected void gridView_DataBound(object sender, EventArgs e)
{
const int countriesColumnIndex = 4;
if (someCondition == true)
{
// Hide the Countries column
this.gridView.Columns[countriesColumnIndex].Visible = false;
}
}
This may not be what the OP was looking for, but it's the solution I was looking for when I found myself asking the same question.
On windows 7:
Every time you click on the cmd in your start menu or your desktop shortcut, the CMD will open in your default location
<input type="text" name="PhoneNumber" pattern="[0-9]{10}" title="Phone number">
Using this code, the input to the text field limits to enter only digits. Pattern is the new attribute available in HTML 5.
Running os.chdir(NEW_PATH)
will change the working directory.
import os
os.getcwd()
Out[2]:
'/tmp'
In [3]:
os.chdir('/')
In [4]:
os.getcwd()
Out[4]:
'/'
In [ ]:
BE VERY CAREFUL, the problem may come from multibytes encoding and inappropriate PHP functions used...
It was the case for me and it took me a while to figure it out.
For example, I get the a string from MySQL using utf8mb4 (very common now to encode emojis):
$formattedString = strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WILL RETURN THE ERROR 'Detected an illegal character in input string'
The problem does not stand in
iconv()
but stands instrtolower()
in this case.
The appropriate way is to use Multibyte String Functions mb_strtolower()
instead of strtolower()
$formattedString = mb_strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WORK FINE
More examples of this issue are available at this SO answer
PHP Manual on the Multibyte String
I order to change the dialog buttons and background colors, you will need to extend the Dialog theme, eg.:
<style name="MyDialogStyle" parent="android:Theme.Material.Light.Dialog.NoActionBar">
<item name="android:buttonBarButtonStyle">@style/MyButtonsStyle</item>
<item name="android:colorBackground">@color/white</item>
</style>
<style name="MyButtonsStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">@color/light.blue</item>
</style>
After that, you need to pass this custom style to the dialog builder, eg. like this:
AlertDialog.Builder(requireContext(), R.style.MyDialogStyle)
If you want to change the color of the text inside the dialog, you can pass a custom view to this Builder:
AlertDialog.Builder.setView(View)
or
AlertDialog.Builder.setView(@LayoutResource int)
Add try-catch otherwise phones without sim will crash.
void sentMessage(String msg) {
try {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("sms_body", msg);
startActivity(smsIntent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "No SIM Found", Toast.LENGTH_LONG).show();
}
}
I found a good article about using the WMP with Firefox on MSDN.
Based on MSDN's article and after doing some trials and errors, I found using JavaScript is better than using conditional comments or nested "EMBED/OBJECT" tags.
I made a JS function that generate WMP object based on given arguments:
<script type="text/javascript">
function generateWindowsMediaPlayer(
holderId, // String
height, // Number
width, // Number
videoUrl // String
// you can declare more arguments for more flexibility
) {
var holder = document.getElementById(holderId);
var player = '<object ';
player += 'height="' + height.toString() + '" ';
player += 'width="' + width.toString() + '" ';
videoUrl = encodeURI(videoUrl); // Encode for special characters
if (navigator.userAgent.indexOf("MSIE") < 0) {
// Chrome, Firefox, Opera, Safari
//player += 'type="application/x-ms-wmp" '; //Old Edition
player += 'type="video/x-ms-wmp" '; //New Edition, suggested by MNRSullivan (Read Comments)
player += 'data="' + videoUrl + '" >';
}
else {
// Internet Explorer
player += 'classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" >';
player += '<param name="url" value="' + videoUrl + '" />';
}
player += '<param name="autoStart" value="false" />';
player += '<param name="playCount" value="1" />';
player += '</object>';
holder.innerHTML = player;
}
</script>
Then I used that function by writing some markups and inline JS like these:
<div id='wmpHolder'></div>
<script type="text/javascript">
window.addEventListener('load', generateWindowsMediaPlayer('wmpHolder', 240, 320, 'http://mysite.com/path/video.ext'));
</script>
You can use jQuery.ready instead of window load event to making the codes more backward-compatible and cross-browser.
I tested the codes over IE 9-10, Chrome 27, Firefox 21, Opera 12 and Safari 5, on Windows 7/8.
Docker really needs to implement this as a new feature, but here's another workaround option for situations in which you have an Entrypoint that terminates after success or failure, which can make it difficult to debug.
If you don't already have an Entrypoint script, create one that runs whatever command(s) you need for your container. Then, at the top of this file, add these lines to entrypoint.sh
:
# Run once, hold otherwise
if [ -f "already_ran" ]; then
echo "Already ran the Entrypoint once. Holding indefinitely for debugging."
cat
fi
touch already_ran
# Do your main things down here
To ensure that cat
holds the connection, you may need to provide a TTY. I'm running the container with my Entrypoint script like so:
docker run -t --entrypoint entrypoint.sh image_name
This will cause the script to run once, creating a file that indicates it has already run (in the container's virtual filesystem). You can then restart the container to perform debugging:
docker start container_name
When you restart the container, the already_ran
file will be found, causing the Entrypoint script to stall with cat
(which just waits forever for input that will never come, but keeps the container alive). You can then execute a debugging bash
session:
docker exec -i container_name bash
While the container is running, you can also remove already_ran
and manually execute the entrypoint.sh
script to rerun it, if you need to debug that way.
Make it simple by using this one line
Environment.MachineName;
extend()
can be used with an iterator argument. Here is an example. You wish to make a list out of a list of lists this way:
From
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
you want
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]
You may use itertools.chain.from_iterable()
to do so. This method's output is an iterator. Its implementation is equivalent to
def from_iterable(iterables):
# chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
for it in iterables:
for element in it:
yield element
Back to our example, we can do
import itertools
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
merged = list(itertools.chain.from_iterable(list2d))
and get the wanted list.
Here is how equivalently extend()
can be used with an iterator argument:
merged = []
merged.extend(itertools.chain.from_iterable(list2d))
print(merged)
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]
An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new
), whereas a class variable is a member of the class itself.
Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.
What’s the difference between a class variable and an instance variable?
This test class illustrates the difference:
public class Test {
public static String classVariable = "I am associated with the class";
public String instanceVariable = "I am associated with the instance";
public void setText(String string){
this.instanceVariable = string;
}
public static void setClassText(String string){
classVariable = string;
}
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
// Change test1's instance variable
test1.setText("Changed");
System.out.println(test1.instanceVariable); // Prints "Changed"
// test2 is unaffected
System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
// Change class variable (associated with the class itself)
Test.setClassText("Changed class text");
System.out.println(Test.classVariable); // Prints "Changed class text"
// Can access static fields through an instance, but there still is only one
// (not best practice to access static variables through instance)
System.out.println(test1.classVariable); // Prints "Changed class text"
System.out.println(test2.classVariable); // Prints "Changed class text"
}
}
Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec
Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec
, as I have ~/bin
in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...
Launch it from the root of your project, where you can see src and target dirs.
The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)
$ mvnexec
1) org.jmeld.ui.JMeldComponent
2) org.jmeld.ui.text.FileDocument
3) org.jmeld.JMeld
4) org.jmeld.util.UIDefaultsPrint
5) org.jmeld.util.PrintProperties
6) org.jmeld.util.file.DirectoryDiff
7) org.jmeld.util.file.VersionControlDiff
8) org.jmeld.vc.svn.InfoCmd
9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#?
If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P
)
By default it compiles project every run. but you can avoid that using mvnexec -B
It allows to search only in test classes -M
or --no-main
, or only in main classes -T
or --no-test
. also has a filter by name option -f <whatever>
Hope this could save you some time, for me it does.
Sort of magically, but today I ran
git submodule init
followed bygit submodule sync
followed bygit submodule update
and it started pulling my submodules... Magic? Perhaps! This is truly one of the most annoying experiences with Git…
Scratch that. I actually got it working by doing git submodule update --init --recursive
. Hope this helps.
PS: Make sure you are in the root git directory, not the submodule's.
public String decodeString(String URL)
{
String urlString="";
try {
urlString = URLDecoder.decode(URL,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
return urlString;
}
Java 8 provides the option of using streams and you can get a list from Set<String> setString
as:
List<String> stringList = setString.stream().collect(Collectors.toList());
Though the internal implementation as of now provides an instance of ArrayList
:
public static <T>
Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
(left, right) -> { left.addAll(right); return left; },
CH_ID);
}
but JDK does not guarantee it. As mentioned here:
There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).
In case you want to be sure always then you can request for an instance specifically as:
List<String> stringArrayList = setString.stream()
.collect(Collectors.toCollection(ArrayList::new));
Use fmod()
from <cmath>
. If you do not want to include the C header file:
template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
return !mod ? x : x - mod * static_cast<long long>(x / mod);
}
//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);
Deprecation note:
As per the official Matplotlib guide, usage of thepylab
module is no longer recommended. Please consider using thematplotlib.pyplot
module instead, as described by this other answer.
The following seems to work:
from pylab import rcParams
rcParams['figure.figsize'] = 5, 10
This makes the figure's width 5 inches, and its height 10 inches.
The Figure class then uses this as the default value for one of its arguments.
Working solution with validate email,mobile number
public class ExcelProcessing
{
public List<ExcelUserData> ReadExcel()
{
string path = Config.folderPath + @"\MemberUploadFormat.xlsx";
using (var excelPack = new ExcelPackage())
{
//Load excel stream
using (var stream = File.OpenRead(path))
{
excelPack.Load(stream);
}
//Lets Deal with first worksheet.(You may iterate here if dealing with multiple sheets)
var ws = excelPack.Workbook.Worksheets[0];
List<ExcelUserData> userList = new List<ExcelUserData>();
int colCount = ws.Dimension.End.Column; //get Column Count
int rowCount = ws.Dimension.End.Row;
for (int row = 2; row <= rowCount; row++) // start from to 2 omit header
{
bool IsValid = true;
ExcelUserData _user = new ExcelUserData();
for (int col = 1; col <= colCount; col++)
{
if (col == 1)
{
_user.FirstName = ws.Cells[row, col].Value?.ToString().Trim();
if (string.IsNullOrEmpty(_user.FirstName))
{
_user.ErrorMessage += "Enter FirstName <br/>";
IsValid = false;
}
}
else if (col == 2)
{
_user.Email = ws.Cells[row, col].Value?.ToString().Trim();
if (string.IsNullOrEmpty(_user.Email))
{
_user.ErrorMessage += "Enter Email <br/>";
IsValid = false;
}
else if (!IsValidEmail(_user.Email))
{
_user.ErrorMessage += "Invalid Email Address <br/>";
IsValid = false;
}
}
else if (col ==3)
{
_user.MobileNo = ws.Cells[row, col].Value?.ToString().Trim();
if (string.IsNullOrEmpty(_user.MobileNo))
{
_user.ErrorMessage += "Enter Mobile No <br/>";
IsValid = false;
}
else if (_user.MobileNo.Length != 10)
{
_user.ErrorMessage += "Invalid Mobile No <br/>";
IsValid = false;
}
}
else if (col == 4)
{
_user.IsAdmin = ws.Cells[row, col].Value?.ToString().Trim();
if (string.IsNullOrEmpty(_user.IsAdmin))
{
_user.IsAdmin = "0";
}
}
_user.IsValid = IsValid;
}
userList.Add(_user);
}
return userList;
}
}
public static bool IsValidEmail(string email)
{
Regex regex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Singleline);
return regex.IsMatch(email);
}
}
The only way UTF-8 affects std::string
is that size()
, length()
, and all the indices are measured in bytes, not characters.
And, as sbi points out, incrementing the iterator provided by std::string
will step forward by byte, not by character, so it can actually point into the middle of a multibyte UTF-8 codepoint. There's no UTF-8-aware iterator provided in the standard library, but there are a few available on the 'Net.
If you remember that, you can put UTF-8 into std::string
, write it to a file, etc. all in the usual way (by which I mean the way you'd use a std::string
without UTF-8 inside).
You may want to start your file with a byte order mark so that other programs will know it is UTF-8.
For me, IntelliJ could autocomplete packages, but never seemed to admit there were actual classes at any level of the hierarchy. Neither re-choosing the SDK nor re-creating the project seemed to fix it.
What did fix it was to delete the per-user IDEA directory ( in my case ~/.IntelliJIdea2017.1/
) which meant losing all my other customizations... But at least it made the issue go away.
I use these two methods depending on the usage. FIDDLE
<div class="img-div">
<img src="http://placekitten.com/g/400/200" />
</div>
<div class="circle-image"></div>
div.img-div{
height:200px;
width:200px;
overflow:hidden;
border-radius:50%;
}
.img-div img{
-webkit-transform:translate(-50%);
margin-left:100px;
}
.circle-image{
width:200px;
height:200px;
border-radius:50%;
background-image:url("http://placekitten.com/g/200/400");
display:block;
background-position-y:25%
}
run the code after your html structure in the body statement
<html>
<body>
<p>asdasd</p>
<p>asdasd</p>
<p>asdasd</p>
<script src="myfile.js"></script>
</body>
</html>
yes it is possible using @import and providing the path of css file e.g.
@import url("mycssfile.css");
or
@import "mycssfile.css";
The straight up answer to your question is: No. The signature for the PostAsync
method is as follows:
public Task PostAsync(Uri requestUri, HttpContent content)
So, while you can pass an object
to PostAsync
it must be of type HttpContent
and your anonymous type does not meet that criteria.
However, there are ways to accomplish what you want to accomplish. First, you will need to serialize your anonymous type to JSON, the most common tool for this is Json.NET. And the code for this is pretty trivial:
var myContent = JsonConvert.SerializeObject(data);
Next, you will need to construct a content object to send this data, I will use a ByteArrayContent
object, but you could use or create a different type if you wanted.
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
Next, you want to set the content type to let the API know this is JSON.
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Then you can send your request very similar to your previous example with the form content:
var result = client.PostAsync("", byteContent).Result
On a side note, calling the .Result
property like you're doing here can have some bad side effects such as dead locking, so you want to be careful with this.
AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;
// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away
If you are looking for the most compact way of initializing a set then that was in Java9
:
Set<String> strSet = Set.of("Apple", "Ball", "Cat", "Dog");
===================== Detailed answer below =================================
Set<String> strSet1 = Stream.of("A", "B", "C", "D")
.collect(Collectors.toUnmodifiableSet());
Here the collector would actually return the unmodifiable set introduced in Java 9 as evident from the statement set -> (Set<T>)Set.of(set.toArray())
in the source code.
One point to note is that the method Collections.unmodifiableSet()
returns an unmodifiable view of the specified set (as per documentation). An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the method Collectors.toUnmodifiableSet()
returns truly immutable set in Java 10.
The following is the most compact way of initializing a set:
Set<String> strSet6 = Set.of("Apple", "Ball", "Cat", "Dog");
We have 12 overloaded versions of this convenience factory method:
static <E> Set<E> of()
static <E> Set<E> of(E e1)
static <E> Set<E> of(E e1, E e2)
// ....and so on
static <E> Set<E> of(E... elems)
Then a natural question is why we need overloaded versions when we have var-args? The answer is: every var-arg method creates an array internally and having the overloaded versions would avoid unnecessary creation of object and will also save us from the garbage collection overhead.
Using Stream in Java 8.
Set<String> strSet1 = Stream.of("A", "B", "C", "D")
.collect(Collectors.toCollection(HashSet::new));
// stream from an array (String[] stringArray)
Set<String> strSet2 = Arrays.stream(stringArray)
.collect(Collectors.toCollection(HashSet::new));
// stream from a list (List<String> stringList)
Set<String> strSet3 = stringList.stream()
.collect(Collectors.toCollection(HashSet::new));
We can use Collections.unmodifiableSet()
as:
Set<String> strSet4 = Collections.unmodifiableSet(strSet1);
But it looks slightly awkward and we can write our own collector like this:
class ImmutableCollector {
public static <T> Collector<T, Set<T>, Set<T>> toImmutableSet() {
return Collector.of(HashSet::new, Set::add, (l, r) -> {
l.addAll(r);
return l;
}, Collections::unmodifiablSet);
}
}
And then use it as:
Set<String> strSet4 = Stream.of("A", "B", "C", "D")
.collect(ImmutableCollector.toImmutableSet());
import static java.util.stream.Collectors.*;
Set<String> strSet5 = Stream.of("A", "B", "C", "D").collect(collectingAndThen(
toCollection(HashSet::new),Collections::unmodifiableSet));
If we only care about Set
then we can also use Collectors.toSet()
in place of Collectors.toCollection(HashSet::new)
.
In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).
You can manually trigger the garbage collection using
import gc
gc.collect()
But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.
from psutil import process_iter
from termcolor import colored
names = []
ids = []
x = 0
z = 0
k = 0
for proc in process_iter():
name = proc.name()
y = len(name)
if y>x:
x = y
if y<x:
k = y
id = proc.pid
names.insert(z, name)
ids.insert(z, id)
z += 1
print(colored("Process Name", 'yellow'), (x-k-5)*" ", colored("Process Id", 'magenta'))
for b in range(len(names)-1):
z = x
print(colored(names[b], 'cyan'),(x-len(names[b]))*" ",colored(ids[b], 'white'))
You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct()
you'll get an error).
Therefore you'd have to create an initialize()
function and call it in each method:
<?php
class Hello
{
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
<div class="info">
<h2>Takvim</h2>
<a href="item-list.php"> Click Me !</a>
</div>
$(document).delegate("div.info", "click", function() {
window.location = $(this).find("a").attr("href");
});
The best answer is to add a Resources/.gitignore file under Resources containing:
# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo
If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:
# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo
You will need to edit that pattern if you add directories deeper than specified.
It is very friendly framework for Notification Area Application... it is enough to add NotificationIcon to base form and change auto-generated code to code below:
public partial class Form1 : Form
{
private bool hidden = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.ShowInTaskbar = false;
//this.WindowState = FormWindowState.Minimized;
this.Hide();
hidden = true;
}
private void notifyIcon1_Click(object sender, EventArgs e)
{
if (hidden) // this.WindowState == FormWindowState.Minimized)
{
// this.WindowState = FormWindowState.Normal;
this.Show();
hidden = false;
}
else
{
// this.WindowState = FormWindowState.Minimized;
this.Hide();
hidden = true;
}
}
}
An unordered list starts with the ul tag. Each list item starts with the The list items will be marked with bullets (small black circles) by default:
<!DOCTYPE html>
<html>
<body>
<h2>Normal List </h2>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</body>
</html>
Output:
<!DOCTYPE html>
<html>
<body>
<h2>Normal List </h2>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</body>
</html>
The text-indent property specifies the indentation of the first line in a text-block.
Note: Negative values are allowed. The first line will be indented to the left if the value is negative.
<ul style='text-indent: -7px;'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
I don't know if it would work, but maybe you could break the page into columns using the multicol package.
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}[Your list here]
\end{multicols}
I post here my question just in case is helpful for somebody else. My problem was that my colleague was connected to the same device and I was not able to connect to the same device.
Note: I had this problem with Amazon Fire TV connecting over Wifi.
There are 2 solutions:
Easy to "drop" his connection (sorry buddy :)
Restart the device
adb kill-server
adb start-server
adb connect device-ip
A bit more difficult but two clients can use the same device (use different TCP ports)
Please look at this answer
Session state is saved on the server, ViewState is saved in the page.
Session state is usually cleared after a period of inactivity from the user (no request happened containing the session id in the request cookies).
The view state is posted on subsequent post back in a hidden field.
sed supports in-place editing. From man sed
:
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied)
Example:
Let's say you have a file hello.txt
with the text:
hello world!
If you want to keep a backup of the old file, use:
sed -i.bak 's/hello/bonjour' hello.txt
You will end up with two files: hello.txt
with the content:
bonjour world!
and hello.txt.bak
with the old content.
If you don't want to keep a copy, just don't pass the extension parameter.
The basic answer is, yes it is undefined.
If you are seeing odd behavior because of this, it may depended on where it is declared. If within a function on the stack then the contents will more than likely be different every time the function gets called. If it is a static or module scope it is undefined but will not change.
Something like...
greetings = 'Hello {name}'.format(name = 'John')
Hello John
def all_anagrams(words: [str]) -> [str]:
word_dict = {}
for word in words:
sorted_word = "".join(sorted(word))
if sorted_word in word_dict:
word_dict[sorted_word].append(word)
else:
word_dict[sorted_word] = [word]
return list(word_dict.values())
If your table is only 2 columns across, you can easily reach the second td
with the adjacent sibling selector, which IE8 does support along with :first-child
:
.editor td:first-child
{
width: 150px;
}
.editor td:first-child + td input,
.editor td:first-child + td textarea
{
width: 500px;
padding: 3px 5px 5px 5px;
border: 1px solid #CCC;
}
Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td
, as suggested by James Allardice.
Change the backend to automatic:
Tools > preferences > IPython console > Graphics > Graphics backend > Backend: Automatic
Then close and open Spyder.
Actually MySQL provide a lot of easy to use function in daily life without more effort from user side-
NOW() it produce date and time both in current scenario whereas CURDATE() produce date only, CURTIME() display time only, we can use one of them according to our need with CAST or merge other calculation it, MySQL rich in these type of function.
NOTE:- You can see the difference using query select NOW() as NOWDATETIME, CURDATE() as NOWDATE, CURTIME() as NOWTIME ;
For the sake of completeness: the previous answers tell how to set the upstream branch, but not how to see it.
There are a few ways to do this:
git branch -vv
shows that info for all branches. (formatted in blue in most terminals)
cat .git/config
shows this also.
For reference:
Try using this library: https://github.com/jakiestfu/Blur.js-II
That should do it for ya.
When you want monitor specified process, usually it is done by scripting. Here is perl example. This put percents as the same way as top, scalling it to one CPU. Then when some process is active working with 2 threads, cpu usage can be more than 100%. Specially look how cpu cores are counted :D then let me show my example:
#!/usr/bin/perl
my $pid=1234; #insert here monitored process PID
#returns current process time counters or single undef if unavailable
#returns: 1. process counter , 2. system counter , 3. total system cpu cores
sub GetCurrentLoads {
my $pid=shift;
my $fh;
my $line;
open $fh,'<',"/proc/$pid/stat" or return undef;
$line=<$fh>;
close $fh;
return undef unless $line=~/^\d+ \([^)]+\) \S \d+ \d+ \d+ \d+ -?\d+ \d+ \d+ \d+ \d+ \d+ (\d+) (\d+)/;
my $TimeApp=$1+$2;
my $TimeSystem=0;
my $CpuCount=0;
open $fh,'<',"/proc/stat" or return undef;
while (defined($line=<$fh>)) {
if ($line=~/^cpu\s/) {
foreach my $nr ($line=~/\d+/g) { $TimeSystem+=$nr; };
next;
};
$CpuCount++ if $line=~/^cpu\d/;
}
close $fh;
return undef if $TimeSystem==0;
return $TimeApp,$TimeSystem,$CpuCount;
}
my ($currApp,$currSys,$lastApp,$lastSys,$cores);
while () {
($currApp,$currSys,$cores)=GetCurrentLoads($pid);
printf "Load is: %5.1f\%\n",($currApp-$lastApp)/($currSys-$lastSys)*$cores*100 if defined $currApp and defined $lastApp and defined $currSys and defined $lastSys;
($lastApp,$lastSys)=($currApp,$currSys);
sleep 1;
}
I hope it will help you in any monitoring. Of course you should use scanf or other C functions for converting any perl regexpes I've used to C source. Of course 1 second for sleeping is not mandatory. you can use any time. effect is, you will get averrage load on specfied time period. When you will use it for monitoring, of course last values you should put outside. It is needed, because monitoring usually calls scripts periodically, and script should finish his work asap.
I also found myself in a similar position a couple of weeks ago. You can also do this by creating a custom ElementLocatorFactory (or simply passing in divA into the DefaultElementLocatorFactory) to see if it's a child of the first div - you would then call the appropriate PageFactory initElements method.
In this case if you did the following:
PageFactory.initElements(new DefaultElementLocatorFactory(divA), pageObjectInstance));
// The Page Object instance would then need a WebElement
// annotated with something like the xpath above or @FindBy(tagName = "input")