Just like this worked for me on Github.
![Imgae Caption](ImageAddressOnGitHub.svg)
or
<img src="ImageAddressOnGitHub.svg">
I ran into this in IntelliJ and fixed it by adding the following to my pom:
<!-- logging dependencies -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<exclusions>
<exclusion>
<!-- Defined below -->
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
Check your project's properties. On the "Application" tab, select your Program
class as the Startup object:
What worked for me is moving the following code from page_load to page_prerender:
lstMain.DataBind();
Image img = (Image)lstMain.Items[0].FindControl("imgMain");
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
cs.RegisterStartupScript(cstype, csname1, "<script language=javascript> p=\"" + img.ClientID + "\"</script>");
}
If you want, you can deactivate this feature in your git core config using
git config core.autocrlf false
But it would be better to just get rid of the warnings using
git config core.autocrlf true
Try this code:
<input type="text" name="Phone Number" pattern="[7-9]{1}[0-9]{9}"
title="Phone number with 7-9 and remaing 9 digit with 0-9">
This code will inputs only in the following format:
9238726384 (starting with 9 or 8 or 7 and other 9 digit using any number)
8237373746
7383673874
Incorrect format:
2937389471(starting not with 9 or 8 or 7)
32796432796(more than 10 digit)
921543(less than 10 digit)
Using current browsers you can use it like this:
img {
-webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
filter: grayscale(100%);
}
and to remedy it:
img:hover{
-webkit-filter: grayscale(0%); /* Chrome, Safari, Opera */
filter: grayscale(0%);
}
worked with me and is much shorter. There is even more one can do within the CSS:
filter: none | blur() | brightness() | contrast() | drop-shadow() | grayscale() |
hue-rotate() | invert() | opacity() | saturate() | sepia() | url();
For more information and supporting browsers see this: http://www.w3schools.com/cssref/css3_pr_filter.asp
More methods in java 8:
EnumSet
with forEach
EnumSet.allOf(Direction.class).forEach(...);
Arrays.asList
with forEach
Arrays.asList(Direction.values()).forEach(...);
Swift 5.0 + , Simple and Short
example:
Style 1
func methodName(completionBlock: () -> Void) {
print("block_Completion")
completionBlock()
}
Style 2
func methodName(completionBlock: () -> ()) {
print("block_Completion")
completionBlock()
}
Use:
override func viewDidLoad() {
super.viewDidLoad()
methodName {
print("Doing something after Block_Completion!!")
}
}
Output
block_Completion
Doing something after Block_Completion!!
You need to specify the classpath. This should do it:
java -cp . Echo "hello"
This tells java to use .
(the current directory) as its classpath, i.e. the place where it looks for classes. Note than when you use packages, the classpath has to contain the root directory, not the package subdirectories. e.g. if your class is my.package.Echo
and the .class file is bin/my/package/Echo.class
, the correct classpath directory is bin
.
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
Use
const StartContainer = connect(null, mapDispatchToProps)(Start)
instead of
const StartContainer = connect(mapDispatchToProps)(Start)
In docker container phpmyadmin/phpmyadmin no php.ini file. But there are two files : php.ini-debug and php.ini-production
To solve the problem, simply rename one of the files to php.ini and restart docker container.
I will tell you steps how you can insert data in ajax using PHP
AJAX Code
<script type="text/javascript">
function insertData() {
var student_name=$("#student_name").val();
var student_roll_no=$("#student_roll_no").val();
var student_class=$("#student_class").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data.php",
data: {student_name:student_name,student_roll_no:student_roll_no,student_class:s
tudent_class},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
PHP Code:
<?php
include('db.php');
$student_name=$_POST['student_name'];
$student_roll_no=$_POST['student_roll_no'];
$student_class=$_POST['student_class'];
$stmt = $DBcon->prepare("INSERT INTO
student(student_name,student_roll_no,student_class)
VALUES(:student_name, :student_roll_no,:student_class)");
$stmt->bindparam(':student_name', $student_name);
$stmt->bindparam(':student_roll_no', $student_roll_no);
$stmt->bindparam(':student_class', $student_class);
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
?>
You can customize it according to your needs. you can also check complete steps of AJAX Insert Data PHP
foreach($images as $key=>$image)
{
if($image == 'http://i27.tinypic.com/29ykt1f.gif' ||
$image == 'http://img3.abload.de/img/10nxjl0fhco.gif' ||
$image == 'http://i42.tinypic.com/9pp2tx.gif')
{ unset($images[$key]); }
}
!!foreach($images as $key=>$image
cause $image is the value, so $images[$image] make no sense.
I suggest
if (checkbox.IsChecked == true)
{
//do something
}
Hope it's helpful ^^
Django's contributed humanize application does this:
{% load humanize %}
{{ my_num|intcomma }}
Be sure to add 'django.contrib.humanize'
to your INSTALLED_APPS
list in the settings.py
file.
%Matlab solution by Tim from Cody
function ans=distP2S(x0,y0,x1,y1,x2,y2)
% Point is x0,y0
z=complex(x0-x1,y0-y1);
complex(x2-x1,y2-y1);
abs(z-ans*min(1,max(0,real(z/ans))));
[I was going to post this as a comment on John Cromartie's post, but didn't realize you couldn't use formatting in a comment.]
I agree. Dropping it to a shell with os.execute() will definitely work but in general making shell calls is expensive. Wrapping some C code will be much quicker at run-time. In C/C++ on a Linux system, you could use:
static int lua_sleep(lua_State *L)
{
int m = static_cast<int> (luaL_checknumber(L,1));
usleep(m * 1000);
// usleep takes microseconds. This converts the parameter to milliseconds.
// Change this as necessary.
// Alternatively, use 'sleep()' to treat the parameter as whole seconds.
return 0;
}
Then, in main, do:
lua_pushcfunction(L, lua_sleep);
lua_setglobal(L, "sleep");
where "L" is your lua_State. Then, in your Lua script called from C/C++, you can use your function by calling:
sleep(1000) -- Sleeps for one second
Swift String
ranges and NSString
ranges are not "compatible".
For example, an emoji like counts as one Swift character, but as two NSString
characters (a so-called UTF-16 surrogate pair).
Therefore your suggested solution will produce unexpected results if the string contains such characters. Example:
let text = "Long paragraph saying!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
let start = distance(text.startIndex, substringRange.startIndex)
let length = distance(substringRange.startIndex, substringRange.endIndex)
let range = NSMakeRange(start, length)
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range)
}
})
println(attributedString)
Output:
Long paragra{ }ph say{ NSColor = "NSCalibratedRGBColorSpace 1 0 0 1"; }ing!{ }
As you see, "ph say" has been marked with the attribute, not "saying".
Since NS(Mutable)AttributedString
ultimately requires an NSString
and an NSRange
, it is actually
better to convert the given string to NSString
first. Then the substringRange
is an NSRange
and you don't have to convert the ranges anymore:
let text = "Long paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: nsText)
nsText.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
}
})
println(attributedString)
Output:
Long paragraph { }saying{ NSColor = "NSCalibratedRGBColorSpace 1 0 0 1"; }!{ }
Update for Swift 2:
let text = "Long paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: text)
nsText.enumerateSubstringsInRange(textRange, options: .ByWords, usingBlock: {
(substring, substringRange, _, _) in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
}
})
print(attributedString)
Update for Swift 3:
let text = "Long paragraph saying!"
let nsText = text as NSString
let textRange = NSMakeRange(0, nsText.length)
let attributedString = NSMutableAttributedString(string: text)
nsText.enumerateSubstrings(in: textRange, options: .byWords, using: {
(substring, substringRange, _, _) in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.red, range: substringRange)
}
})
print(attributedString)
Update for Swift 4:
As of Swift 4 (Xcode 9), the Swift standard library
provides method to convert between Range<String.Index>
and NSRange
.
Converting to NSString
is no longer necessary:
let text = "Long paragraph saying!"
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstrings(in: text.startIndex..<text.endIndex, options: .byWords) {
(substring, substringRange, _, _) in
if substring == "saying" {
attributedString.addAttribute(.foregroundColor, value: NSColor.red,
range: NSRange(substringRange, in: text))
}
}
print(attributedString)
Here substringRange
is a Range<String.Index>
, and that is converted to the
corresponding NSRange
with
NSRange(substringRange, in: text)
In my own experience, even though theoretically many JetBrains products share the same functionalities, the new features that get introduced in some apps don't get immediately introduced in the others. In particular, IntelliJ IDEA has a new version once per year, while WebStorm and PHPStorm get 2 to 3 per year I think. Keep that in mind when choosing an IDE. :)
i am use following construction to convert back nl2br
function br2nl( $input ) {
return preg_replace('/<br\s?\/?>/ius', "\n", str_replace("\n","",str_replace("\r","", htmlspecialchars_decode($input))));
}
here i replaced \n
and \r
symbols from $input because nl2br dosen't remove them and this causes wrong output with \n\n
or \r<br>
.
Being terminological, [[
operator extracts the element from a list whereas [
operator takes subset of a list.
The code project article Creating a Tasktray Application gives a very simple explanation and example of creating an application that only ever exists in the System Tray.
Basically change the Application.Run(new Form1());
line in Program.cs
to instead start up a class that inherits from ApplicationContext
, and have the constructor for that class initialize a NotifyIcon
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyCustomApplicationContext());
}
}
public class MyCustomApplicationContext : ApplicationContext
{
private NotifyIcon trayIcon;
public MyCustomApplicationContext ()
{
// Initialize Tray Icon
trayIcon = new NotifyIcon()
{
Icon = Resources.AppIcon,
ContextMenu = new ContextMenu(new MenuItem[] {
new MenuItem("Exit", Exit)
}),
Visible = true
};
}
void Exit(object sender, EventArgs e)
{
// Hide tray icon, otherwise it will remain shown until user mouses over it
trayIcon.Visible = false;
Application.Exit();
}
}
You can simplify the 5 through 21 part:
=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))
Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.
Here are some of its applications:
First you have to change values in php.ini file as per your requirements.
post_max_size = 1024M
upload_max_filesize = 1024M
max_execution_time = 3600
max_input_time = 3600
memory_limit = 1024M
Note - Change these values carefully. These values will impact for all of your projects of that server.
Now, If above solutions are not working, kindly check your phpmyadmin.conf file. If you are using WAMP so you can find the file in "C:\wamp64\alias".
You have to change below values.
Values already in file are -
php_admin_value upload_max_filesize 128M
php_admin_value post_max_size 128M
php_admin_value max_execution_time 360
php_admin_value max_input_time 360
Change above code to -
# php_admin_value upload_max_filesize 128M
# php_admin_value post_max_size 128M
# php_admin_value max_execution_time 360
# php_admin_value max_input_time 360
Now just restart your server, to work with changed values. :)
Yahoo uses a method called Sender ID, which can be configured at The SPF Setup Wizard and entered in to your DNS. Also one of the important ones for Exchange, Hotmail, AOL, Yahoo, and others is to have a Reverse DNS for your domain. Those will knock out most of the issues. However you can never prevent a person intentionally blocking your or custom rules.
In English:
ContentType
: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8
, which is fine for most cases.Accepts
: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType
.DataType
: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp
.Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const
type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.
str_replace(
array("search","items"),
array("replace", "items"),
$string
);
Typescript and Angular Implementation
directive
((): void=> {
"use strict";
angular.module("app").directive("busyindicator", busyIndicator);
function busyIndicator($http:ng.IHttpService): ng.IDirective {
var directive = <ng.IDirective>{
restrict: "A",
link(scope: Scope.IBusyIndicatorScope) {
scope.anyRequestInProgress = () => ($http.pendingRequests.length > 0);
scope.$watch(scope.anyRequestInProgress, x => {
if (x) {
scope.canShow = true;
} else {
scope.canShow = false;
}
});
}
};
return directive;
}
})();
Scope
module App.Scope {
export interface IBusyIndicatorScope extends angular.IScope {
anyRequestInProgress: any;
canShow: boolean;
}
}
Template
<div id="activityspinner" ng-show="canShow" class="show" data-busyindicator>
</div>
CSS
#activityspinner
{
display : none;
}
#activityspinner.show {
display : block;
position : fixed;
z-index: 100;
background-image : url('data:image/gif;base64,R0lGODlhNgA3APMAAPz8/GZmZqysrHV1dW1tbeXl5ZeXl+fn59nZ2ZCQkLa2tgAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAANgA3AAAEzBDISau9OOvNu/9gKI5kaZ4lkhBEgqCnws6EApMITb93uOqsRC8EpA1Bxdnx8wMKl51ckXcsGFiGAkamsy0LA9pAe1EFqRbBYCAYXXUGk4DWJhZN4dlAlMSLRW80cSVzM3UgB3ksAwcnamwkB28GjVCWl5iZmpucnZ4cj4eWoRqFLKJHpgSoFIoEe5ausBeyl7UYqqw9uaVrukOkn8LDxMXGx8ibwY6+JLxydCO3JdMg1dJ/Is+E0SPLcs3Jnt/F28XXw+jC5uXh4u89EQAh+QQJCgAAACwAAAAANgA3AAAEzhDISau9OOvNu/9gKI5kaZ5oqhYGQRiFWhaD6w6xLLa2a+iiXg8YEtqIIF7vh/QcarbB4YJIuBKIpuTAM0wtCqNiJBgMBCaE0ZUFCXpoknWdCEFvpfURdCcM8noEIW82cSNzRnWDZoYjamttWhphQmOSHFVXkZecnZ6foKFujJdlZxqELo1AqQSrFH1/TbEZtLM9shetrzK7qKSSpryixMXGx8jJyifCKc1kcMzRIrYl1Xy4J9cfvibdIs/MwMue4cffxtvE6qLoxubk8ScRACH5BAkKAAAALAAAAAA2ADcAAATOEMhJq7046827/2AojmRpnmiqrqwwDAJbCkRNxLI42MSQ6zzfD0Sz4YYfFwyZKxhqhgJJeSQVdraBNFSsVUVPHsEAzJrEtnJNSELXRN2bKcwjw19f0QG7PjA7B2EGfn+FhoeIiYoSCAk1CQiLFQpoChlUQwhuBJEWcXkpjm4JF3w9P5tvFqZsLKkEF58/omiksXiZm52SlGKWkhONj7vAxcbHyMkTmCjMcDygRNAjrCfVaqcm11zTJrIjzt64yojhxd/G28XqwOjG5uTxJhEAIfkECQoAAAAsAAAAADYANwAABM0QyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7/i8qmCoGQoacT8FZ4AXbFopfTwEBhhnQ4w2j0GRkgQYiEOLPI6ZUkgHZwd6EweLBqSlq6ytricICTUJCKwKkgojgiMIlwS1VEYlspcJIZAkvjXHlcnKIZokxJLG0KAlvZfAebeMuUi7FbGz2z/Rq8jozavn7Nev8CsRACH5BAkKAAAALAAAAAA2ADcAAATLEMhJq7046827/2AojmRpnmiqrqwwDAJbCkRNxLI42MSQ6zzfD0Sz4YYfFwzJNCmPzheUyJuKijVrZ2cTlrg1LwjcO5HFyeoJeyM9U++mfE6v2+/4PD6O5F/YWiqAGWdIhRiHP4kWg0ONGH4/kXqUlZaXmJlMBQY1BgVuUicFZ6AhjyOdPAQGQF0mqzauYbCxBFdqJao8rVeiGQgJNQkIFwdnB0MKsQrGqgbJPwi2BMV5wrYJetQ129x62LHaedO21nnLq82VwcPnIhEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7/g8Po7kX9haKoAZZ0iFGIc/iRaDQ40Yfj+RepSVlpeYAAgJNQkIlgo8NQqUCKI2nzNSIpynBAkzaiCuNl9BIbQ1tl0hraewbrIfpq6pbqsioaKkFwUGNQYFSJudxhUFZ9KUz6IGlbTfrpXcPN6UB2cHlgfcBuqZKBEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7yJEopZA4CsKPDUKfxIIgjZ+P3EWe4gECYtqFo82P2cXlTWXQReOiJE5bFqHj4qiUhmBgoSFho59rrKztLVMBQY1BgWzBWe8UUsiuYIGTpMglSaYIcpfnSHEPMYzyB8HZwdrqSMHxAbath2MsqO0zLLorua05OLvJxEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhfohELYHQuGBDgIJXU0Q5CKqtOXsdP0otITHjfTtiW2lnE37StXUwFNaSScXaGZvm4r0jU1RWV1hhTIWJiouMjVcFBjUGBY4WBWw1A5RDT3sTkVQGnGYYaUOYPaVip3MXoDyiP3k3GAeoAwdRnRoHoAa5lcHCw8TFxscduyjKIrOeRKRAbSe3I9Um1yHOJ9sjzCbfyInhwt3E2cPo5dHF5OLvJREAOwAAAAAAAAAAAA==')
-ms-opacity : 0.4;
opacity : 0.4;
background-repeat : no-repeat;
background-position : center;
left : 0;
bottom : 0;
right : 0;
top : 0;
}
You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.
db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );
or more compact:
db.T.find( { $where : "this.Grade1 > this.Grade2" } );
you can use $expr
as described in recent answer
Depending on your flavour of Linux and PHP version these may vary.
(sudo) yum install zip unzip php-zip
(sudo) apt install zip unzip php-zip
This is a very commonly asked question, you'll be able to find more useful info in the aether by searching <distro> php <version> zip extension
.
this is the query you need:
SELECT b.id, a.home,b.[datetime],b.player,a.resource FROM
(SELECT home,MAX(resource) AS resource FROM tbl_1 GROUP BY home) AS a
LEFT JOIN
(SELECT id,home,[datetime],player,resource FROM tbl_1) AS b
ON a.resource = b.resource WHERE a.home =b.home;
As I was using AppCompatActivity
above answers didn't worked for me. But the below solution worked:
In res/styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
</style>
PS: I've used colorPrimary
instead of android:colorPrimary
For the TypeScript users, here is a helper function:
// Typescript Type: Date Options
interface DateOptions {
day: 'numeric' | 'short' | 'long',
month: 'numeric',
year: 'numeric',
timeZone: 'UTC',
};
// Helper Function: Convert UTC Date To Local Date
export const convertUTCDateToLocalDate = (date: Date) => {
// Date Options
const dateOptions: DateOptions = {
day: 'numeric',
month: 'numeric',
year: 'numeric',
timeZone: 'UTC',
};
// Formatted Date (4/20/2020)
const formattedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000).toLocaleString('en-US', dateOptions);
return formattedDate;
};
For running it from other location you can use the composer program that come with the program. It is basically a bash script. If you don't have it you can create one by simply copying the following code into a text file
#!/bin/sh
dir=$(d=$(dirname "$0"); cd "$d" && pwd)
if command -v 'cygpath' >/dev/null 2>&1; then
dir=$(cygpath -m $dir);
fi
dir=$(echo $dir | sed 's/ /\ /g')
php "${dir}/composer.phar" $*
Then save the file inside your bin folder and name it composer without any file extension. Then add the bin folder to your environment variable f
You can try to change
for i in inp:
into
for i in range(1,inp):
Iteration doesn't work with a single int. Instead, you need provide a range for it to run.
Use this
$("input[name='nameOfYourRadioButton']").attr("checked", false);
The biggest difference between Task.Delay
and Thread.Sleep
is that Task.Delay
is intended to run asynchronously. It does not make sense to use Task.Delay
in synchronous code. It is a VERY bad idea to use Thread.Sleep
in asynchronous code.
Normally you will call Task.Delay()
with the await
keyword:
await Task.Delay(5000);
or, if you want to run some code before the delay:
var sw = new Stopwatch();
sw.Start();
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;
Guess what this will print? Running for 0.0070048 seconds.
If we move the await delay
above the Console.WriteLine
instead, it will print Running for 5.0020168 seconds.
Let's look at the difference with Thread.Sleep
:
class Program
{
static void Main(string[] args)
{
Task delay = asyncTask();
syncCode();
delay.Wait();
Console.ReadLine();
}
static async Task asyncTask()
{
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("async: Starting");
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
Console.WriteLine("async: Done");
}
static void syncCode()
{
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("sync: Starting");
Thread.Sleep(5000);
Console.WriteLine("sync: Running for {0} seconds", sw.Elapsed.TotalSeconds);
Console.WriteLine("sync: Done");
}
}
Try to predict what this will print...
async: Starting
async: Running for 0.0070048 seconds
sync: Starting
async: Running for 5.0119008 seconds
async: Done
sync: Running for 5.0020168 seconds
sync: Done
Also, it is interesting to notice that Thread.Sleep
is far more accurate, ms accuracy is not really a problem, while Task.Delay
can take 15-30ms minimal. The overhead on both functions is minimal compared to the ms accuracy they have (use Stopwatch
Class if you need something more accurate). Thread.Sleep
still ties up your Thread, Task.Delay
release it to do other work while you wait.
Only thing that worked for me is this function:
Sub DoTrim()
Dim cell As Range
Dim str As String
For Each cell In Selection.Cells
If cell.HasFormula = False Then
str = Left(cell.Value, 1) 'space
While str = " " Or str = Chr(160)
cell.Value = Right(cell.Value, Len(cell.Value) - 1)
str = Left(cell.Value, 1) 'space
Wend
str = Right(cell.Value, 1) 'space
While str = " " Or str = Chr(160)
cell.Value = Left(cell.Value, Len(cell.Value) - 1)
str = Right(cell.Value, 1) 'space
Wend
End If
Next cell
End Sub
Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.
I reccomend you to use the following tools for online base64 encoding/decoding:
Check the "Format as Data URL" option to format as a Data URL.
In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:
#include <stdio.h> #include <stdlib.h> void outchar(char ch); int main() { outchar('A'); outchar('B'); outchar('C'); return 0; } void outchar(char ch) { printf("%c", ch); }
Also, you should be specifying the return type of every function. I added that for you.
add following lines in gitignore, from all undesirable files
/target/
*/target/**
**/META-INF/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
Explanation of Serialize and Deserialize using Python
In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.
Serialization using pickle
import pickle
#the object to serialize
example_dic={1:"6",2:"2",3:"f"}
#where the bytes after serializing end up at, wb stands for write byte
pickle_out=open("dict.pickle","wb")
#Time to dump
pickle.dump(example_dic,pickle_out)
#whatever you open, you must close
pickle_out.close()
The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):
€}q (KX 6qKX 2qKX fqu.
Deserialization using pickle
import pickle
pickle_in=open("dict.pickle","rb")
get_deserialized_data_back=pickle.load(pickle_in)
print(get_deserialized_data_back)
Output:
{1: '6', 2: '2', 3: 'f'}
Like some people, I needed to combine multiple answers, and I also needed to set a proxy.
This should work for anyone. I have zero desire to run an EXE file or MSI file .. uninstall/ reinstall, or manually delete files and folders. That is so 1999 :P
Run this to update NPM:
Run PowerShell as administrator
npm i -g npm // This works
I am not thinking this code actually upgrades your npm version below
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade
(courtesy of "Robert" answer)
Run this to update Node.js:
wget https://nodejs.org/download/release/latest/win-x64/node.exe -OutFile 'C:\Program Files (x86)\nodejs\node.exe' (courtesy of BrunoLM answer)
If you get `wget : Could not find a part of the path .... "**, see below ...scroll down. Reading Web Response... It's at least punching through the firewall /proxy (if you have one or have already ran the code get through ...
Otherwise
You might need to set your proxy
npm config set proxy "http://proxy.yourcorp.com:811" (yes, use quotes)
2 possible errors
It cannot find path of the path solution "where.exe node" (courtesy of Lonnie Best Answer)
E.g. if Node.js is NOT living in "Program Files (x86)" perhaps with where.exe, it is living in 'C:\Program Files\nodejs\node.exe'.
wget https://nodejs.org/download/release/latest/win-x64/node.exe -OutFile 'C:\Program Files\nodejs\node.exe'
Now perhaps it tries to upgrade but you get another error, "node.exe is being used by another process."
npm -v (3.10.8)
node -v ( v6.6.0)
DONE. I'm at the version that I want.
I consider you can set the main content to viewport height, so if the content exceeds, the height of the main content will define the position of the footer
* {
margin: 0;
padding: 0;
width: 100%;
}
body {
display: flex;
flex-direction: column;
}
header {
height: 50px;
background: red;
}
main {
background: blue;
/* This is the most important part*/
height: 100vh;
}
footer{
background: black;
height: 50px;
bottom: 0;
}
_x000D_
<header></header>
<main></main>
<footer></footer>
_x000D_
I would probably use an integer as your primary key, and then just have your string (I assume it's some sort of ID) as a separate column.
create table sample (
sample_pk INT NOT NULL AUTO_INCREMENT,
sample_id VARCHAR(100) NOT NULL,
...
PRIMARY KEY(sample_pk)
);
You can always do queries and joins conditionally on the string (ID) column (where sample_id = ...).
The parameters to main
represent the command line parameters provided to the program when it was started. The argc
parameter represents the number of command line arguments, and char *argv[]
is an array of strings (character pointers) representing the individual arguments provided on the command line.
From Api level 1, you can use the public void setTextSize (float size)
method.
From the documentation:
Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.
Parameters: size -> float: The scaled pixel size.
So you can simple do:
textView.setTextSize(12); // your size in sp
Now, you can
#wrapper { display: flow-root; }
To grant a permission:
grant select on schema_name.sequence_name to user_or_role_name;
To check which permissions have been granted
select * from all_tab_privs where TABLE_NAME = 'sequence_name'
I've had the same requirement, but the solutions here didn't quite get me across the line, due to the source of data for the recyclerView.
I was extracting the RecyclerViews' LinearLayoutManager state in onPause()
private Parcelable state;
Public void onPause() {
state = mLinearLayoutManager.onSaveInstanceState();
}
Parcelable state
is saved in onSaveInstanceState(Bundle outState)
, and extracted again in onCreate(Bundle savedInstanceState)
, when savedInstanceState != null
.
However, the recyclerView adapter is populated and updated by a ViewModel LiveData object returned by a DAO call to a Room database.
mViewModel.getAllDataToDisplay(mSelectedData).observe(this, new Observer<List<String>>() {
@Override
public void onChanged(@Nullable final List<String> displayStrings) {
mAdapter.swapData(displayStrings);
mLinearLayoutManager.onRestoreInstanceState(state);
}
});
I eventually found that restoring the instance state directly after the data is set in the adapter would keep the scroll-state across rotations.
I suspect this either is because the LinearLayoutManager
state that I'd restored was being overwritten when the data was returned by the database call, or the restored state was meaningless against an 'empty' LinearLayoutManager.
If the adapter data is available directly (ie not contigent on a database call), then restoring the instance state on the LinearLayoutManager can be done after the adapter is set on the recyclerView.
The distinction between the two scenarios held me up for ages.
Here is another method, which may be easier than installing plugins or external tools in some situations:
select [whatever you need]
INTO temp.table_name
from [... etc ...]
.temp.table_name
in the "Choose Objects" screen, click Next.INSERT
statements appear in a new query window.[temp.table_name]
to [your_table_name]
.drop table [temp.table_name]
.Truncate drops the decimal point.
Extract the information from the database for the checkbox fields. Next change the above example line to:
(this code assumes that you've retrieved the information for the user into an associative array called dbvalue
and the DB field names match those on the HTML form)
<input type="checkbox" name="tag_1" id="tag_1" value="yes" <?php echo ($dbvalue['tag_1']==1 ? 'checked' : '');?>>
If you're looking for the code to do everything for you, you've come to the wrong place.
I tried a lot of methods, and the only one which worked was UpdateCellValue:
dataGridView.Rows[rowIndex].Cells[columnIndex].Value = "New Value";
dataGridView.UpdateCellValue(columnIndex, rowIndex);
I hope to have helped. =)
Worked for me using the parameter --user-install
running following command:
gem install name_of_gem --user-install
Then he started to fetch and install it.
Edit
There was one gem I still could not install (it required the Ruby.h headers of the Ruby development kit or something), then I tried the different version managers, but somehow that still did not really work as it was stated in the documentations how to just install and switch (it did just not switch the versions).
Then I removed all the installed version managers and installed afterwards with brew install ruby
the latest version and did set the PATH variable, too. (It will be mentioned after the installation of ruby from brew), which worked.
In my case - I had to double check the Backup path of the database from where I was restoring. I had previously restored it from a different path when I did it the first time. I fixed the Backup path to use the backup path I used the first time and it worked!
There is BashSupport plugin for IntelliJ IDEA which checks the syntax.
While some of the above solutions work, I thought I'd post our eventual solution - which defines a 'ready' method that will fire as soon as FB is initialized and ready to go. It has the advantage over other solutions that it's safe to call either before or after FB is ready.
It can be used like so:
f52.fb.ready(function() {
// safe to use FB here
});
Here's the source file (note that it's defined within a 'f52.fb' namespace).
if (typeof(f52) === 'undefined') { f52 = {}; }
f52.fb = (function () {
var fbAppId = f52.inputs.base.fbAppId,
fbApiInit = false;
var awaitingReady = [];
var notifyQ = function() {
var i = 0,
l = awaitingReady.length;
for(i = 0; i < l; i++) {
awaitingReady[i]();
}
};
var ready = function(cb) {
if (fbApiInit) {
cb();
} else {
awaitingReady.push(cb);
}
};
window.fbAsyncInit = function() {
FB.init({
appId: fbAppId,
xfbml: true,
version: 'v2.0'
});
FB.getLoginStatus(function(response){
fbApiInit = true;
notifyQ();
});
};
return {
/**
* Fires callback when FB is initialized and ready for api calls.
*/
'ready': ready
};
})();
In my case, I had an invalid package name. I wasn't able to pick up on the error code right away, because I didn't scroll up far enough, but the error was:
remote: $ NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client
remote: npm ERR! code EINVALIDPACKAGENAME // <-- this was hard to find
remote: npm ERR! Invalid package name "react-loader-spinne r": name can only contain URL-friendly characters
I know you asked how to do this, but the answer is you should not do this.
Instead, have a application.properties
, application-default.properties
application-dev.properties
etc., and switch profiles via args to the JVM: e.g. -Dspring.profiles.active=dev
You can also override some things at test time using @TestPropertySource
Ideally everything should be in source control so that there are no surprises e.g. How do you know what properties are sitting there in your server location, and which ones are missing? What happens if developers introduce new things?
Spring Boot is already giving you enough ways to do this right.
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
>>> x = "2342.34"
>>> float(x)
2342.3400000000001
There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).
I have a simpler and elegant solution that doesn't mess up with classes, styles, opacities and stuff.
For the draggable element - you add 'start' event which will execute every time you try to move the element somewhere. You will have a condition which move is not legal. For the moves that are illegal - prevent them with 'e.preventDefault();' like in the code below.
$(".disc").draggable({
revert: "invalid",
cursor: "move",
start: function(e, ui){
console.log("element is moving");
if(SOME_CONDITION_FOR_ILLEGAL_MOVE){
console.log("illegal move");
//This will prevent moving the element from it's position
e.preventDefault();
}
}
});
You are welcome :)
For ViewPager2,
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
}
})
where OnPageChangeCallback
is a static class with three methods:
onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position),
onPageScrollStateChanged(@ScrollState int state)
The module timeit
is useful for this and is included in the standard Python distribution.
Example:
import timeit
timeit.Timer('for i in xrange(10): oct(i)').timeit()
This should work.
if (rsData["usr.ursrdaystime"] != System.DBNull.Value))
{
strLevel = rsData["usr.ursrdaystime"].ToString();
}
also need to add using statement, like bellow:
using (var objConn = new SqlConnection(strConnection))
{
objConn.Open();
using (var objCmd = new SqlCommand(strSQL, objConn))
{
using (var rsData = objCmd.ExecuteReader())
{
while (rsData.Read())
{
if (rsData["usr.ursrdaystime"] != System.DBNull.Value)
{
strLevel = rsData["usr.ursrdaystime"].ToString();
}
}
}
}
}
this'll automaticly dispose (close) resources outside of block { .. }.
A project is not exactly the same thing as an executable jar file.
For starters, a project generally contains source code, while an executable jar file generally doesn't. Again, generally speaking, you need to export an Eclipse project to obtain a file suitable for importing.
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.
BTW: The correct way to do this is to use TryGetValue
obj item;
if(!dict.TryGetValue(name, out item))
return null;
return item;
This accesses the dictionary only once instead of twice.
If you really want to just return null
if the key doesn't exist, the above code can be simplified further:
obj item;
dict.TryGetValue(name, out item);
return item;
This works, because TryGetValue
sets item
to null
if no key with name
exists.
Try to add http://openstrategynetwork.com/sigin-facebook to Client OAuth Settings valid redirect URL along with your own redirect URL.
I had created a demo on my github which includes on swiping from right to left a delete button will appear and you can then delete your item from the ListView and update your ListView.
There's also a package called bit
that is specifically designed for fast boolean operations. It's especially useful if you have large vectors or need to do many boolean operations.
z <- sample(c(TRUE, FALSE), 1e8, rep = TRUE)
system.time({
sum(z) # 0.170s
})
system.time({
bit::sum.bit(z) # 0.021s, ~10x improvement in speed
})
You should favour range()
over xrange()
only when you need an actual list. For instance, when you want to modify the list returned by range()
, or when you wish to slice it. For iteration or even just normal indexing, xrange()
will work fine (and usually much more efficiently). There is a point where range()
is a bit faster than xrange()
for very small lists, but depending on your hardware and various other details, the break-even can be at a result of length 1 or 2; not something to worry about. Prefer xrange()
.
In Guava, this is easy:
Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');
Just notepad ~/.bashrc
from the git bash shell and save your file.That should be all.
NOTE: Please ensure that you need to restart your terminal for changes to be reflected.
Quick and easy forms.
Scala 2.10 and older:
import com.typesafe.scalalogging.slf4j.Logger
import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger("TheLoggerName"))
logger.debug("Useful message....")
And build.sbt:
libraryDependencies += "com.typesafe" %% "scalalogging-slf4j" % "1.1.0"
Scala 2.11+ and newer:
import import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger("TheLoggerName"))
logger.debug("Useful message....")
And build.sbt:
libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0"
Another approach to return a value from an asynchronous function, is to pass in an object that will store the result from the asynchronous function.
Here is an example of the same:
var async = require("async");
// This wires up result back to the caller
var result = {};
var asyncTasks = [];
asyncTasks.push(function(_callback){
// some asynchronous operation
$.ajax({
url: '...',
success: function(response) {
result.response = response;
_callback();
}
});
});
async.parallel(asyncTasks, function(){
// result is available after performing asynchronous operation
console.log(result)
console.log('Done');
});
I am using the result
object to store the value during the asynchronous operation. This allows the result be available even after the asynchronous job.
I use this approach a lot. I would be interested to know how well this approach works where wiring the result back through consecutive modules is involved.
I personally use a more generic function that works for any property of any array:
function lookup(array, prop, value) {
for (var i = 0, len = array.length; i < len; i++)
if (array[i] && array[i][prop] === value) return array[i];
}
You just call it like this:
lookup(purposeObjects, "purpose", "daily");
The syntax
def x():
print(20)
is basically the same as x = lambda: print(20)
(there are some differences under the hood, but for most pratical purposes, the results the same).
The syntax
def y(t):
return t**2
is basically the same as y= lambda t: t**2
. When you define a function, you're creating a variable that has the function as its value. In the first example, you're setting x
to be the function lambda: print(20)
. So x
now refers to that function. x()
is not the function, it's the call of the function. In python, functions are simply a type of variable, and can generally be used like any other variable. For example:
def power_function(power):
return lambda x : x**power
power_function(3)(2)
This returns 8. power_function
is a function that returns a function as output. When it's called on 3
, it returns a function that cubes the input, so when that function is called on the input 2
, it returns 8. You could do cube = power_function(3)
, and now cube(2)
would return 8.
You need to create an instance of the type that expose the Output
method:
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
var class1Type = DLL.GetType("DLL.Class1");
//Now you can use reflection or dynamic to call the method. I will show you the dynamic way
dynamic c = Activator.CreateInstance(class1Type);
c.Output(@"Hello");
Console.ReadLine();
}
This is my solution to create a fullscreen div, using pure css. It displays a full screen div that is persistent on scrolling. And if the page content fits on the screen, the page won't show a scroll-bar.
Tested in IE9+, Firefox 13+, Chrome 21+
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title> Fullscreen Div </title>_x000D_
<style>_x000D_
.overlay {_x000D_
position: fixed;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
left: 0;_x000D_
top: 0;_x000D_
background: rgba(51,51,51,0.7);_x000D_
z-index: 10;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class='overlay'>Selectable text</div>_x000D_
<p> This paragraph is located below the overlay, and cannot be selected because of that :)</p>_x000D_
</body>_x000D_
</html>
_x000D_
Here is my implementation, which is a bit more verbose than some of the previous answers
curl https://somewhere.com/somepath \
--silent \
--insecure \
--request POST \
--header "your-curl-may-want-a-header" \
--data @my.input.file \
--output site.output \
--write-out %{http_code} \
> http.response.code 2> error.messages
errorLevel=$?
httpResponse=$(cat http.response.code)
jq --raw-output 'keys | @csv' site.output | sed 's/"//g' > return.keys
hasErrors=`grep --quiet --invert errors return.keys;echo $?`
if [[ $errorLevel -gt 0 ]] || [[ $hasErrors -gt 0 ]] || [[ "$httpResponse" != "200" ]]; then
echo -e "Error POSTing https://somewhere.com/somepath with input my.input (errorLevel $errorLevel, http response code $httpResponse)" >> error.messages
send_exit_message # external function to send error.messages to whoever.
fi
I don't know if $var is a string and you want to find only those expressions but here it goes either way.
Try to use preg_match http://php.net/manual/en/function.preg-match.php
if(preg_match('abc', $val) || preg_match('def', $val) || ...)
echo "true"
Bitbucket uses CodeMirror for syntax highlighting. For Bash or shell you can use sh
, bash
, or zsh
. More information can be found at Configuring syntax highlighting for file extensions and Code mirror language modes.
use comma separated values in application.yml
ignoreFilenames: .DS_Store, .hg
java code for access
@Value("${ignoreFilenames}")
String[] ignoreFilenames
It is working ;)
try this
public static void main(String[] args) {
int[] series = {4,2};
series = addElement(series, 3);
series = addElement(series, 1);
}
static int[] addElement(int[] a, int e) {
a = Arrays.copyOf(a, a.length + 1);
a[a.length - 1] = e;
return a;
}
I know it has a lot of answers, but I want to write my version of split function like others and like string_split SQL Server 2016 native function.
create function [dbo].[Split]
(
@Value nvarchar(max),
@Delimiter nvarchar(50)
)
returns @tbl table
(
Seq int primary key identity(1, 1),
Value nvarchar(max)
)
as begin
declare @Xml xml = cast('<d>' + replace(@Value, @Delimiter, '</d><d>') + '</d>' as xml)
insert into @tbl
(Value)
select a.split.value('.', 'nvarchar(max)') as Value
from @Xml.nodes('/d') a(split)
return
end
Here's a answer to question.
CREATE TABLE Testdata
(
SomeID INT,
OtherID INT,
String VARCHAR(MAX)
)
INSERT Testdata SELECT 1, 9, '18,20,22'
INSERT Testdata SELECT 2, 8, '17,19'
INSERT Testdata SELECT 3, 7, '13,19,20'
INSERT Testdata SELECT 4, 6, ''
INSERT Testdata SELECT 9, 11, '1,2,3,4'
select t.SomeID, t.OtherID, s.Value
from Testdata t
cross apply dbo.Split(t.String, ',') s
--Output
SomeID OtherID Value
1 9 18
1 9 20
1 9 22
2 8 17
2 8 19
3 7 13
3 7 19
3 7 20
4 6
9 11 1
9 11 2
9 11 3
9 11 4
Joining Split with other split
declare @Names nvarchar(max) = 'a,b,c,d'
declare @Codes nvarchar(max) = '10,20,30,40'
select n.Seq, n.Value Name, c.Value Code
from dbo.Split(@Names, ',') n
inner join dbo.Split(@Codes, ',') c on n.Seq = c.Seq
--Output
Seq Name Code
1 a 10
2 b 20
3 c 30
4 d 40
Split two times
declare @NationLocSex nvarchar(max) = 'Korea,Seoul,1;Vietnam,Kiengiang,0;China,Xian,0'
; with rows as
(
select Value
from dbo.Split(@NationLocSex, ';')
)
select rw.Value r, cl.Value c
from rows rw
cross apply dbo.Split(rw.Value, ',') cl
--Output
r c
Korea,Seoul,1 Korea
Korea,Seoul,1 Seoul
Korea,Seoul,1 1
Vietnam,Kiengiang,0 Vietnam
Vietnam,Kiengiang,0 Kiengiang
Vietnam,Kiengiang,0 0
China,Xian,0 China
China,Xian,0 Xian
China,Xian,0 0
Split to columns
declare @Numbers nvarchar(50) = 'First,Second,Third'
; with t as
(
select case when Seq = 1 then Value end f1,
case when Seq = 2 then Value end f2,
case when Seq = 3 then Value end f3
from dbo.Split(@Numbers, ',')
)
select min(f1) f1, min(f2) f2, min(f3) f3
from t
--Output
f1 f2 f3
First Second Third
Generate rows by range
declare @Ranges nvarchar(50) = '1-2,4-6'
declare @Numbers table (Num int)
insert into @Numbers values (1),(2),(3),(4),(5),(6),(7),(8)
; with t as
(
select r.Seq, r.Value,
min(case when ft.Seq = 1 then ft.Value end) ValueFrom,
min(case when ft.Seq = 2 then ft.Value end) ValueTo
from dbo.Split(@Ranges, ',') r
cross apply dbo.Split(r.Value, '-') ft
group by r.Seq, r.Value
)
select t.Seq, t.Value, t.ValueFrom, t.ValueTo, n.Num
from t
inner join @Numbers n on n.Num between t.ValueFrom and t.ValueTo
--Output
Seq Value ValueFrom ValueTo Num
1 1-2 1 2 1
1 1-2 1 2 2
2 4-6 4 6 4
2 4-6 4 6 5
2 4-6 4 6 6
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
SELECT number, COUNT(*)
FROM YourTable
GROUP BY number
ORDER BY number
myString.replace(/<br ?\/?>/g, "\n")
<html>
<head>
<title>example</title>
<script>
$(function(){
$('#filename').load("htmlfile.html");
});
</script>
</head>
<body>
<div id="filename">
</div>
</body>
Lightweight example (with support for onSuccess and onTimeout). You need to pass callback name within URL if you need it.
var $jsonp = (function(){
var that = {};
that.send = function(src, options) {
var callback_name = options.callbackName || 'callback',
on_success = options.onSuccess || function(){},
on_timeout = options.onTimeout || function(){},
timeout = options.timeout || 10; // sec
var timeout_trigger = window.setTimeout(function(){
window[callback_name] = function(){};
on_timeout();
}, timeout * 1000);
window[callback_name] = function(data){
window.clearTimeout(timeout_trigger);
on_success(data);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
return that;
})();
Sample usage:
$jsonp.send('some_url?callback=handleStuff', {
callbackName: 'handleStuff',
onSuccess: function(json){
console.log('success!', json);
},
onTimeout: function(){
console.log('timeout!');
},
timeout: 5
});
At GitHub: https://github.com/sobstel/jsonp.js/blob/master/jsonp.js
Always keep in mind that 'size' is variable if not explicitly specified so if you declare
int i = 10;
On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).
In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across
typedef short INT16;
typedef int INT32;
typedef long INT64;
Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.
On a windows based system, you may see entries in stdin.h header file as
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.
in my case
@JsonInclude(Include.NON_EMPTY)
made it work.
One general procedure is laid out in the Wikipedia article on unsharp masking:
You use a Gaussian smoothing filter and subtract the smoothed version from the original image (in a weighted way so the values of a constant area remain constant).
To get a sharpened version of frame
into image
: (both cv::Mat
)
cv::GaussianBlur(frame, image, cv::Size(0, 0), 3);
cv::addWeighted(frame, 1.5, image, -0.5, 0, image);
The parameters there are something you need to adjust for yourself.
There's also Laplacian sharpening, you should find something on that when you google.
I was able to make this work with the
transform: scale(1.03);
Property applied on the image. For some reason, on Chrome, the other solutions provided wouldn't work if there was any relatively positioned parent element.
Check http://jsfiddle.net/ud5ya7jt/
This way the image will be slightly zoomed in by 3% and the edges will be cropped which shouldn't be a problem on a blurred image anyway. It worked well in my case because I was using a high res image as a background. Good luck!
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
Try setting the charset on your Content-Type:
httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );
You can use the form reference which exists on all inputs, this is much faster than .closest()
(5-10 times faster in Chrome and IE8). Works on IE6 & 7 too.
var input = $('input[type=submit]');
var form = input.length > 0 ? $(input[0].form) : $();
Logits is an overloaded term which can mean many different things:
In Math, Logit is a function that maps probabilities ([0, 1]
) to R ((-inf, inf)
)
Probability of 0.5 corresponds to a logit of 0. Negative logit correspond to probabilities less than 0.5, positive to > 0.5.
In ML, it can be
the vector of raw (non-normalized) predictions that a classification model generates, which is ordinarily then passed to a normalization function. If the model is solving a multi-class classification problem, logits typically become an input to the softmax function. The softmax function then generates a vector of (normalized) probabilities with one value for each possible class.
Logits also sometimes refer to the element-wise inverse of the sigmoid function.
The problem for me was a new server that System.Web.Routing was of version 3.5 while web.config requested version 4.0.0.0. The resolution was
%WINDIR%\Framework\v4.0.30319\aspnet_regiis -i
%WINDIR%\Framework64\v4.0.30319\aspnet_regiis -i
You can even make List of objects like this
var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
var feeType = {};
var $ID = $(this).find("input[id^=txtFeeType]").attr('id');
feeType["feeTypeID"] = $('#ddlTerm').val();
feeType["feeTypeName"] = $('#ddlProgram').val();
feeType["feeTypeDescription"] = $('#ddlBatch').val();
feeTypeList.push(feeType);
});
Using .filter()
also works, and is flexible for id, value, name:
$('input[name="cols"]').filter("[value='Site']").attr('checked', true);
(seen on this blog)
For targeting IE Users:
<!--[if IE]>
Place Content here for Users of Internet Explorer.
<![endif]-->
For targeting all others:
<![if !IE]>
Place Content here for Users of all other Browsers.
<![endif]>
The Conditional Comments can only be detected by Internet Explorer, all other Browsers thread it as normal Comments.
To target IE 6,7 etc.. You have to use "Greater Than Equal" or "Lesser Than (Equal)" in the If Statement. Like this.
Greater Than or Equal:
<!--[if gte IE 7]>
Place Content here for Users of Internet Explorer 7 or above.
<![endif]-->
Lesser Than:
<!--[if lt IE 6]>
Place Content here for Users of Internet Explorer 5 or lower.
<![endif]-->
You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:
<Grid>
<DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799" ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CanUserAddRows="False"> </Grid>
C#
Public Class Test
{
public string m_field1_Test{get;set;}
public string m_field2_Test { get; set; }
public Test()
{
m_field1_Test = "field1";
m_field2_Test = "field2";
}
public MainWindow()
{
listTest = new List<Test>();
for (int i = 0; i < 10; i++)
{
obj = new Test();
listTest.Add(obj);
}
this.MyDatagrid.ItemsSource = ListTest;
InitializeComponent();
}
I'm using a UIWebView
that isn't a subview (and thus isn't part of the window hierarchy) to determine the sizes of HTML content for UITableViewCells
. I found that the disconnected UIWebView
doesn't report its size properly with -[UIWebView sizeThatFits:]
. Additionally, as mentioned in https://stackoverflow.com/a/3937599/9636, you must set the UIWebView
's frame
height
to 1 in order to get the proper height at all.
If the UIWebView
's height is too big (i.e. you have it set to 1000, but the HTML content size is only 500):
UIWebView.scrollView.contentSize.height
-[UIWebView stringByEvaluatingJavaScriptFromString:@"document.height"]
-[UIWebView sizeThatFits:]
All return a height
of 1000.
To solve my problem in this case, I used https://stackoverflow.com/a/11770883/9636, which I dutifully voted up. However, I only use this solution when my UIWebView.frame.width
is the same as the -[UIWebView sizeThatFits:]
width
.
To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.
If you have image in the form of bitmap then use
imageview.setImageBitmap(bm);
If you have image in the form of drawable then use
imageview.setImageDrawable(drawable);
If you have image in your resource example if image is present in drawable folder then use
imageview.setImageResource(R.drawable.image);
If you have path of image then use
imageview.setImageURI(Uri.parse("pathofimage"));
I would go with linking the second object into a property of the first object. If the second object is the result of a function or method, use references. Ex:
//Not the result of a method
$obj1->extra = new Class2();
//The result of a method, for instance a factory class
$obj1->extra =& Factory::getInstance('Class2');
$('#mainn').text(function (_,txt) {
return txt.slice(0, -1);
});
demo -->
http://jsfiddle.net/d72ML/8/
Here's a little hack that switched from data-hover to data-toggle depending the screen width:
/**
* Bootstrap nav menu hack
*/
$(window).on('load', function () {
// On page load
if ($(window).width() < 768) {
$('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
}
// On window resize
$(window).resize(function () {
if ($(window).width() < 768) {
$('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
} else {
$('.navbar-nav > li > .dropdown-toggle').removeAttr('data-toggle').attr('data-hover', 'dropdown');
}
});
});
More Details Visit https://github.com/sapankumarmohanty/lamp/blob/master/Crate-XML-2-Array
//Convert XML to array and SOAP XML to array
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
{
if (!$contents) return array();
if (!function_exists('xml_parser_create')) {
// print "'xml_parser_create()' function not found!";
return array();
}
// Get the XML parser of PHP - PHP must have this module for the parser to work
$parser = xml_parser_create('');
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($contents) , $xml_values);
xml_parser_free($parser);
if (!$xml_values) return; //Hmm...
// Initializations
$xml_array = array();
$parents = array();
$opened_tags = array();
$arr = array();
$current = & $xml_array; //Refference
// Go through the tags.
$repeated_tag_index = array(); //Multiple tags with same name will be turned into an array
foreach($xml_values as $data) {
unset($attributes, $value); //Remove existing values, or there will be trouble
// This command will extract these variables into the foreach scope
// tag(string), type(string), level(int), attributes(array).
extract($data); //We could use the array by itself, but this cooler.
$result = array();
$attributes_data = array();
if (isset($value)) {
if ($priority == 'tag') $result = $value;
else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
}
// Set the attributes too.
if (isset($attributes) and $get_attributes) {
foreach($attributes as $attr => $val) {
if ( $attr == 'ResStatus' ) {
$current[$attr][] = $val;
}
if ($priority == 'tag') $attributes_data[$attr] = $val;
else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
}
}
// See tag status and do the needed.
//echo"<br/> Type:".$type;
if ($type == "open") { //The starting of the tag '<tag>'
$parent[$level - 1] = & $current;
if (!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
$current[$tag] = $result;
if ($attributes_data) $current[$tag . '_attr'] = $attributes_data;
//print_r($current[$tag . '_attr']);
$repeated_tag_index[$tag . '_' . $level] = 1;
$current = & $current[$tag];
}
else { //There was another element with the same tag name
if (isset($current[$tag][0])) { //If there is a 0th element it is already an array
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
$repeated_tag_index[$tag . '_' . $level]++;
}
else { //This section will make the value an array if multiple tags with the same name appear together
$current[$tag] = array(
$current[$tag],
$result
); //This will combine the existing item and the new item together to make an array
$repeated_tag_index[$tag . '_' . $level] = 2;
if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
}
$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
$current = & $current[$tag][$last_item_index];
}
}
elseif ($type == "complete") { //Tags that ends in 1 line '<tag />'
// See if the key is already taken.
if (!isset($current[$tag])) { //New Key
$current[$tag] = $result;
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $attributes_data) $current[$tag . '_attr'] = $attributes_data;
}
else { //If taken, put all things inside a list(array)
if (isset($current[$tag][0]) and is_array($current[$tag])) { //If it is already an array...
// ...push the new element into that array.
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
if ($priority == 'tag' and $get_attributes and $attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
$repeated_tag_index[$tag . '_' . $level]++;
}
else { //If it is not an array...
$current[$tag] = array(
$current[$tag],
$result
); //...Make it an array using using the existing value and the new value
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $get_attributes) {
if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
if ($attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
}
$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
}
}
}
elseif ($type == 'close') { //End of tag '</tag>'
$current = & $parent[$level - 1];
}
}
return ($xml_array);
}
// Let's call the this above function xml2array
xml2array($xmlContent, $get_attributes = 3, $priority = 'tag'); // it will work 100% if not ping me @skype: sapan.mohannty
// Enjoy coding
This worked for me: (notice that java 8 is required)
String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);
UserJsonParse is a class that shows gson how to parse the json formant.
class is like that:
public class UserJsonParser {
private String username;
private String name;
private String lastname;
private String mail;
private String pass1;
//then put setters and getters
}
the json string that is parsed is like that:
$jsonData: { "username": "testuser", "pass1": "clave1234" }
The rest of values (mail, lastname, name) are set to null
That can be done in short as:
Model::pluck('column')
where model is the Model such as User
model & column as column name like id
if you do
User::pluck('id') // [1,2,3, ...]
& of course you can have any other clauses like where
clause before pluck
If your matrix is given in row manner like below, where size is s*s here s=5
5
31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20
then you can use this
s=int(input())
b=list(map(int,input().split()))
arr=[[b[j+s*i] for j in range(s)]for i in range(s)]
your matrix will be 'arr'
I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html
Specifically:
Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.
I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.
Here's one that accounts for ties.
Name Salary
Jim 6
Foo 5
Bar 5
Steve 4
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees))
Result --> Bar 5, Foo 5
EDIT: I took Manoj's second post, tweaked it, and made it a little more human readable. To me n-1 is not intuitive; however, using the value I want, 2=2nd, 3=3rd, etc. is.
/* looking for 2nd highest salary -- notice the '=2' */
SELECT name,salary FROM employees
WHERE salary = (SELECT DISTINCT(salary) FROM employees as e1
WHERE (SELECT COUNT(DISTINCT(salary))=2 FROM employees as e2
WHERE e1.salary <= e2.salary)) ORDER BY name
Result --> Bar 5, Foo 5
You can use this
lblTime.Text = DateTime.Now.TimeOfDay.ToString();
It is realtime with milliseconds value and it sets to time only.
To ensure success with a full path use recurse=yes
- name: ensure custom facts directory exists
file: >
path=/etc/ansible/facts.d
recurse=yes
state=directory
window.location.assign(url)
this fixs the window.open(url)
issue in ios devices
Fixed by moving the view modifiers to onPostExecute so the fixed code is :
public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;
//private MyProgressDialog dialog;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.sorties);
tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");
new ProgressTask(Soirees.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
@Vladimir, thx your code was very helpful.
import java.io.FileWriter;
...
FileWriter writer = new FileWriter("output.txt");
for(String str: arr) {
writer.write(str + System.lineSeparator());
}
writer.close();
It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg
. FigureCanvasQTAgg
and NavigationToolbar2QT
are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure
, Navigation
and a single button that draws some random data. I've added comments to explain things.
import sys
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import random
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = Figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QtGui.QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
ax.clear()
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
Edit:
Updated to reflect comments and API changes.
NavigationToolbar2QTAgg
changed with NavigationToolbar2QT
Figure
instead of pyplot
ax.hold(False)
with ax.clear()
Django 1.10 no longer allows you to specify views as a string (e.g. 'myapp.views.home'
) in your URL patterns.
The solution is to update your urls.py
to include the view callable. This means that you have to import the view in your urls.py
. If your URL patterns don't have names, then now is a good time to add one, because reversing with the dotted python path no longer works.
from django.conf.urls import include, url
from django.contrib.auth.views import login
from myapp.views import home, contact
urlpatterns = [
url(r'^$', home, name='home'),
url(r'^contact/$', contact, name='contact'),
url(r'^login/$', login, name='login'),
]
If there are many views, then importing them individually can be inconvenient. An alternative is to import the views module from your app.
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from myapp import views as myapp_views
urlpatterns = [
url(r'^$', myapp_views.home, name='home'),
url(r'^contact/$', myapp_views.contact, name='contact'),
url(r'^login/$', auth_views.login, name='login'),
]
Note that we have used as myapp_views
and as auth_views
, which allows us to import the views.py
from multiple apps without them clashing.
See the Django URL dispatcher docs for more information about urlpatterns
.
If after importing import 'rxjs/add/operator/map' or import 'rxjs/Rx' too you are getting the same error then restart your visual studio code editor, the error will be resolved.
http://swftools.org/ these guys have a pdf2swf component. They are also able to show tables. They are also giving the source. So you could possibly check it out.
For those, who wonder how it goes in VS.
MSVC 2015 Update 1, cl.exe version 19.00.24215.1:
#include <iostream>
template<typename X, typename Y>
struct A
{
template<typename Z>
static void f()
{
std::cout << "from A::f():" << std::endl
<< __FUNCTION__ << std::endl
<< __func__ << std::endl
<< __FUNCSIG__ << std::endl;
}
};
void main()
{
std::cout << "from main():" << std::endl
<< __FUNCTION__ << std::endl
<< __func__ << std::endl
<< __FUNCSIG__ << std::endl << std::endl;
A<int, float>::f<bool>();
}
output:
from main(): main main int __cdecl main(void) from A::f(): A<int,float>::f f void __cdecl A<int,float>::f<bool>(void)
Using of __PRETTY_FUNCTION__
triggers undeclared identifier error, as expected.
Inspired by Michal B. answer. If you use bootstrap..
label.btn {_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
label.btn input {_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
label.btn span {_x000D_
text-align: center;_x000D_
padding: 6px 12px;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
label.btn input:checked+span {_x000D_
background-color: rgb(80, 110, 228);_x000D_
color: #fff;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<div>_x000D_
<label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>One</span></label>_x000D_
<label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Two</span></label>_x000D_
<label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Three</span></label>_x000D_
</div>
_x000D_
private static final int[] CDRIVES = new int[] {0xe0, 0xf4, ...};
and after access convert to byte.
check both tables has same schema InnoDB MyISAM. I made them all the same in my case InnoDB and worked
The top answer is not clear enough. here is what worked for me: The correct format should look like this if you want to point to the actual file:
<a href="./page.html">
This will have you point to that file within the same folder if you are on the page http://example.com/folder/index.html
It seems strange, but nonetheless HTML5 supports drawing lines, circles, rectangles and many other basic shapes, it does not have anything suitable for drawing the basic point. The only way to do so is to simulate a point with whatever you have.
So basically there are 3 possible solutions:
Each of them has their drawbacks.
Line
function point(x, y, canvas){
canvas.beginPath();
canvas.moveTo(x, y);
canvas.lineTo(x+1, y+1);
canvas.stroke();
}
Keep in mind that we are drawing to South-East direction, and if this is the edge, there can be a problem. But you can also draw in any other direction.
Rectangle
function point(x, y, canvas){
canvas.strokeRect(x,y,1,1);
}
or in a faster way using fillRect because render engine will just fill one pixel.
function point(x, y, canvas){
canvas.fillRect(x,y,1,1);
}
Circle
One of the problems with circles is that it is harder for an engine to render them
function point(x, y, canvas){
canvas.beginPath();
canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
canvas.stroke();
}
the same idea as with rectangle you can achieve with fill.
function point(x, y, canvas){
canvas.beginPath();
canvas.arc(x, y, 1, 0, 2 * Math.PI, true);
canvas.fill();
}
Problems with all these solutions:
If you are wondering, what is the best way to draw a point, I would go with filled rectangle. You can see my jsperf here with comparison tests
Note: if you choose to hide the badge, please use
.grecaptcha-badge { visibility: hidden; }
You are allowed to hide the badge as long as you include the reCAPTCHA branding visibly in the user flow. Please include the following text:
This site is protected by reCAPTCHA and the Google
<a href="https://policies.google.com/privacy">Privacy Policy</a> and
<a href="https://policies.google.com/terms">Terms of Service</a> apply.
more details here reCaptacha
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
You can use numpy:
import numpy as np
Example from Empty Array:
np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]])
I got the same error for pandas latest version. Then saw this warning
FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.
This shall work for you.
Using just awk you could do (I also shortened some of your piping):
strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'
I can't verify it for you because I don't know your exact input, but the following works:
echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'
See also this question on removing single quotes.
If you can't make DNode serializable a good solution would be to add "transient" to the variable.
Example:
public static transient DNode dNode = null;
This will ignore the variable when using Intent.putExtra(...).
Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:
$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl
First method you can try this
$department->department_name = $request->department_name;
$department->status = $request->status;
$department->save();
Another way to insert records into the database with create function
$department = new Department;
// Another Way to insert records
$department->create($request->all());
return redirect('admin/departments');
You need to set the filledby in Department model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $fillable = ['department_name','status'];
}
To really be universal, I'm using this:
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'
|| $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
header('Location: '.$protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
I like $_SERVER['REQUEST_URI']
because it respects mod_rewrite and/or any GET variables.
https detection from https://stackoverflow.com/a/2886224/947370
Check out Lists.partition(java.util.List, int)
from Google Guava:
Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing
[a, b, c, d, e]
with a partition size of 3 yields[[a, b, c]
,[d, e]]
-- an outer list containing two inner lists of three and two elements, all in the original order.
R interpreter has a duck-typing memory allocation system. There is no builtin method to tell you the datatype of your pointer to memory. Duck typing is done for speed, but turned out to be a bad idea because now statements such as: print(is.integer(5))
returns FALSE and is.integer(as.integer(5))
returns TRUE. Go figure.
The R-manual on basic types: https://cran.r-project.org/doc/manuals/R-lang.html#Basic-types
The best you can hope for is to write your own function to probe your pointer to memory, then use process of elimination to decide if it is suitable for your needs.
Your object()
needs to be penetrated with get(...)
before you can see inside. Example:
a <- 10
myGlobals <- objects()
for(i in myGlobals){
typeof(i) #prints character
typeof(get(i)) #prints integer
}
The R function typeof
has a bias to give you the type at maximum depth, for example.
library(tibble)
#expression notes type
#----------------------- -------------------------------------- ----------
typeof(TRUE) #a single boolean: logical
typeof(1L) #a single numeric with L postfixed: integer
typeof("foobar") #A single string in double quotes: character
typeof(1) #a single numeric: double
typeof(list(5,6,7)) #a list of numeric: list
typeof(2i) #an imaginary number complex
typeof(5 + 5L) #double + integer is coerced: double
typeof(c()) #an empty vector has no type: NULL
typeof(!5) #a bang before a double: logical
typeof(Inf) #infinity has a type: double
typeof(c(5,6,7)) #a vector containing only doubles: double
typeof(c(c(TRUE))) #a vector of vector of logicals: logical
typeof(matrix(1:10)) #a matrix of doubles has a type: list
typeof(substr("abc",2,2))#a string at index 2 which is 'b' is: character
typeof(c(5L,6L,7L)) #a vector containing only integers: integer
typeof(c(NA,NA,NA)) #a vector containing only NA: logical
typeof(data.frame()) #a data.frame with nothing in it: list
typeof(data.frame(c(3))) #a data.frame with a double in it: list
typeof(c("foobar")) #a vector containing only strings: character
typeof(pi) #builtin expression for pi: double
typeof(1.66) #a single numeric with mantissa: double
typeof(1.66L) #a double with L postfixed double
typeof(c("foobar")) #a vector containing only strings: character
typeof(c(5L, 6L)) #a vector containing only integers: integer
typeof(c(1.5, 2.5)) #a vector containing only doubles: double
typeof(c(1.5, 2.5)) #a vector containing only doubles: double
typeof(c(TRUE, FALSE)) #a vector containing only logicals: logical
typeof(factor()) #an empty factor has default type: integer
typeof(factor(3.14)) #a factor containing doubles: integer
typeof(factor(T, F)) #a factor containing logicals: integer
typeof(Sys.Date()) #builtin R dates: double
typeof(hms::hms(3600)) #hour minute second timestamp double
typeof(c(T, F)) #T and F are builtins: logical
typeof(1:10) #a builtin sequence of numerics: integer
typeof(NA) #The builtin value not available: logical
typeof(c(list(T))) #a vector of lists of logical: list
typeof(list(c(T))) #a list of vectors of logical: list
typeof(c(T, 3.14)) #a vector of logicals and doubles: double
typeof(c(3.14, "foo")) #a vector of doubles and characters: character
typeof(c("foo",list(T))) #a vector of strings and lists: list
typeof(list("foo",c(T))) #a list of strings and vectors: list
typeof(TRUE + 5L) #a logical plus an integer: integer
typeof(c(TRUE, 5L)[1]) #The true is coerced to 1 integer
typeof(c(c(2i), TRUE)[1])#logical coerced to complex: complex
typeof(c(NaN, 'batman')) #NaN's in a vector don't dominate: character
typeof(5 && 4) #doubles are coerced by order of && logical
typeof(8 < 'foobar') #string and double is coerced logical
typeof(list(4, T)[[1]]) #a list retains type at every index: double
typeof(list(4, T)[[2]]) #a list retains type at every index: logical
typeof(2 ** 5) #result of exponentiation double
typeof(0E0) #exponential lol notation double
typeof(0x3fade) #hexidecimal double
typeof(paste(3, '3')) #paste promotes types to string character
typeof(3 + ?) #R pukes on unicode error
typeof(iconv("a", "latin1", "UTF-8")) #UTF-8 characters character
typeof(5 == 5) #result of a comparison: logical
The R function class
has a bias to give you the type of container or structure encapsulating your types, for example.
library(tibble)
#expression notes class
#--------------------- ---------------------------------------- ---------
class(matrix(1:10)) #a matrix of doubles has a class: matrix
class(factor("hi")) #factor of items is: factor
class(TRUE) #a single boolean: logical
class(1L) #a single numeric with L postfixed: integer
class("foobar") #A single string in double quotes: character
class(1) #a single numeric: numeric
class(list(5,6,7)) #a list of numeric: list
class(2i) #an imaginary complex
class(data.frame()) #a data.frame with nothing in it: data.frame
class(Sys.Date()) #builtin R dates: Date
class(sapply) #a function is function
class(charToRaw("hi")) #convert string to raw: raw
class(array("hi")) #array of items is: array
class(5 + 5L) #double + integer is coerced: numeric
class(c()) #an empty vector has no class: NULL
class(!5) #a bang before a double: logical
class(Inf) #infinity has a class: numeric
class(c(5,6,7)) #a vector containing only doubles: numeric
class(c(c(TRUE))) #a vector of vector of logicals: logical
class(substr("abc",2,2))#a string at index 2 which is 'b' is: character
class(c(5L,6L,7L)) #a vector containing only integers: integer
class(c(NA,NA,NA)) #a vector containing only NA: logical
class(data.frame(c(3))) #a data.frame with a double in it: data.frame
class(c("foobar")) #a vector containing only strings: character
class(pi) #builtin expression for pi: numeric
class(1.66) #a single numeric with mantissa: numeric
class(1.66L) #a double with L postfixed numeric
class(c("foobar")) #a vector containing only strings: character
class(c(5L, 6L)) #a vector containing only integers: integer
class(c(1.5, 2.5)) #a vector containing only doubles: numeric
class(c(TRUE, FALSE)) #a vector containing only logicals: logical
class(factor()) #an empty factor has default class: factor
class(factor(3.14)) #a factor containing doubles: factor
class(factor(T, F)) #a factor containing logicals: factor
class(hms::hms(3600)) #hour minute second timestamp hms difftime
class(c(T, F)) #T and F are builtins: logical
class(1:10) #a builtin sequence of numerics: integer
class(NA) #The builtin value not available: logical
class(c(list(T))) #a vector of lists of logical: list
class(list(c(T))) #a list of vectors of logical: list
class(c(T, 3.14)) #a vector of logicals and doubles: numeric
class(c(3.14, "foo")) #a vector of doubles and characters: character
class(c("foo",list(T))) #a vector of strings and lists: list
class(list("foo",c(T))) #a list of strings and vectors: list
class(TRUE + 5L) #a logical plus an integer: integer
class(c(TRUE, 5L)[1]) #The true is coerced to 1 integer
class(c(c(2i), TRUE)[1])#logical coerced to complex: complex
class(c(NaN, 'batman')) #NaN's in a vector don't dominate: character
class(5 && 4) #doubles are coerced by order of && logical
class(8 < 'foobar') #string and double is coerced logical
class(list(4, T)[[1]]) #a list retains class at every index: numeric
class(list(4, T)[[2]]) #a list retains class at every index: logical
class(2 ** 5) #result of exponentiation numeric
class(0E0) #exponential lol notation numeric
class(0x3fade) #hexidecimal numeric
class(paste(3, '3')) #paste promotes class to string character
class(3 + ?) #R pukes on unicode error
class(iconv("a", "latin1", "UTF-8")) #UTF-8 characters character
class(5 == 5) #result of a comparison: logical
storage.mode
of your variable:When an R variable is written to disk, the data layout changes again, and is called the data's storage.mode
. The function storage.mode(...)
reveals this low level information: see Mode, Class, and Type of R objects. You shouldn't need to worry about R's storage.mode unless you are trying to understand delays caused by round trip casts/coercions that occur when assigning and reading data to and from disk.
gettype(your_variable)
:Run this R code then adapt it for your purposes, it'll make a pretty good guess as to what type it is.
get_type <- function(variable){
sz <- as.integer(length(variable)) #length of your variable
tof <- typeof(variable) #typeof your variable
cls <- class(variable) #class of your variable
isc <- is.character(variable) #what is.character() has to say about it.
d <- dim(variable) #dimensions of your variable
isv <- is.vector(variable)
if (is.matrix(variable)){
d <- dim(t(variable)) #dimensions of your matrix
}
#observations ----> datatype
if (sz>=1 && tof == "logical" && cls == "logical" && isv == TRUE){ return("vector of logical") }
if (sz>=1 && tof == "integer" && cls == "integer" ){ return("vector of integer") }
if (sz==1 && tof == "double" && cls == "Date" ){ return("Date") }
if (sz>=1 && tof == "raw" && cls == "raw" ){ return("vector of raw") }
if (sz>=1 && tof == "double" && cls == "numeric" ){ return("vector of double") }
if (sz>=1 && tof == "double" && cls == "array" ){ return("vector of array of double") }
if (sz>=1 && tof == "character" && cls == "array" ){ return("vector of array of character") }
if (sz>=0 && tof == "list" && cls == "data.frame" ){ return("data.frame") }
if (sz>=1 && isc == TRUE && isv == TRUE){ return("vector of character") }
if (sz>=1 && tof == "complex" && cls == "complex" ){ return("vector of complex") }
if (sz==0 && tof == "NULL" && cls == "NULL" ){ return("NULL") }
if (sz>=0 && tof == "integer" && cls == "factor" ){ return("factor") }
if (sz>=1 && tof == "double" && cls == "numeric" && isv == TRUE){ return("vector of double") }
if (sz>=1 && tof == "double" && cls == "matrix"){ return("matrix of double") }
if (sz>=1 && tof == "character" && cls == "matrix"){ return("matrix of character") }
if (sz>=1 && tof == "list" && cls == "list" && isv == TRUE){ return("vector of list") }
if (sz>=1 && tof == "closure" && cls == "function" && isv == FALSE){ return("closure/function") }
return("it's pointer to memory, bruh")
}
assert <- function(a, b){
if (a == b){
cat("P")
}
else{
cat("\nFAIL!!! Sniff test:\n")
sz <- as.integer(length(variable)) #length of your variable
tof <- typeof(variable) #typeof your variable
cls <- class(variable) #class of your variable
isc <- is.character(variable) #what is.character() has to say about it.
d <- dim(variable) #dimensions of your variable
isv <- is.vector(variable)
if (is.matrix(variable)){
d <- dim(t(variable)) #dimensions of your variable
}
if (!is.function(variable)){
print(paste("value: '", variable, "'"))
}
print(paste("get_type said: '", a, "'"))
print(paste("supposed to be: '", b, "'"))
cat("\nYour pointer to memory has properties:\n")
print(paste("sz: '", sz, "'"))
print(paste("tof: '", tof, "'"))
print(paste("cls: '", cls, "'"))
print(paste("d: '", d, "'"))
print(paste("isc: '", isc, "'"))
print(paste("isv: '", isv, "'"))
quit()
}
}
#these asserts give a sample for exercising the code.
assert(get_type(TRUE), "vector of logical") #everything is a vector in R by default.
assert(get_type(c(TRUE)), "vector of logical") #c() just casts to vector
assert(get_type(c(c(TRUE))),"vector of logical") #casting vector multiple times does nothing
assert(get_type(!5), "vector of logical") #bang inflicts 'not truth-like'
assert(get_type(1L), "vector of integer") #naked integers are still vectors of 1
assert(get_type(c(1L, 2L)), "vector of integer") #Longs are not doubles
assert(get_type(c(1L, c(2L, 3L))),"vector of integer") #nested vectors of integers
assert(get_type(c(1L, c(TRUE))), "vector of integer") #logicals coerced to integer
assert(get_type(c(FALSE, c(1L))), "vector of integer") #logicals coerced to integer
assert(get_type("foobar"), "vector of character") #character here means 'string'
assert(get_type(c(1L, "foobar")), "vector of character") #integers are coerced to string
assert(get_type(5), "vector of double")
assert(get_type(5 + 5L), "vector of double")
assert(get_type(Inf), "vector of double")
assert(get_type(c(5,6,7)), "vector of double")
assert(get_type(NaN), "vector of double")
assert(get_type(list(5)), "vector of list") #your list is in a vector.
assert(get_type(list(5,6,7)), "vector of list")
assert(get_type(c(list(5,6,7))),"vector of list")
assert(get_type(list(c(5,6),T)),"vector of list") #vector of list of vector and logical
assert(get_type(list(5,6,7)), "vector of list")
assert(get_type(2i), "vector of complex")
assert(get_type(c(2i, 3i, 4i)), "vector of complex")
assert(get_type(c()), "NULL")
assert(get_type(data.frame()), "data.frame")
assert(get_type(data.frame(4,5)),"data.frame")
assert(get_type(Sys.Date()), "Date")
assert(get_type(sapply), "closure/function")
assert(get_type(charToRaw("hi")),"vector of raw")
assert(get_type(c(charToRaw("a"), charToRaw("b"))), "vector of raw")
assert(get_type(array(4)), "vector of array of double")
assert(get_type(array(4,5)), "vector of array of double")
assert(get_type(array("hi")), "vector of array of character")
assert(get_type(factor()), "factor")
assert(get_type(factor(3.14)), "factor")
assert(get_type(factor(TRUE)), "factor")
assert(get_type(matrix(3,4,5)), "matrix of double")
assert(get_type(as.matrix(5)), "matrix of double")
assert(get_type(matrix("yatta")),"matrix of character")
I put in a C++/Java/Python ideology here that gives me the scoop of what the memory most looks like. R triad typing system is like trying to nail spaghetti to the wall, <-
and <<-
will package your matrix to a list when you least suspect. As the old duck-typing saying goes: If it waddles like a duck and if it quacks like a duck and if it has feathers, then it's a duck.
var a = [1,2,3,4,5,6];
console.log(a.reverse().slice(1).reverse());
//Array(5) [ 1, 2, 3, 4, 5 ]
Abstract methods means there is no default implementation for it and an implementing class will provide the details.
Essentially, you would have
abstract class AbstractObject {
public abstract void method();
}
class ImplementingObject extends AbstractObject {
public void method() {
doSomething();
}
}
So, it's exactly as the error states: your abstract method can not have a body.
There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.
A very simple example would be shapes:
You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.
(This is taken from the site I linked above)
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
Of these two, the first one is a type mistake: '\0' is a character, not a pointer. The compiler still accepts it because it can convert it to a pointer.
The second one "works" only by coincidence. "\0" is a string literal of two characters. If those occur in multiple places in the source file, the compiler may, but need not, make them identical.
So the proper way to write the first one is
char* array[] = { "abc", "def", NULL };
and you test for array[index]==NULL
. The proper way to test for the second one is
array[index][0]=='\0'
; you may also drop the '\0' in the string (i.e. spell it as ""
) since that will already include a null byte.
Are you using Webfonts from Google, Typekit, etc? There are multiple ways you could use Webfonts like @font-face or CSS3 methods, some browsers like Firefox & IE may refuse to embed the font when it’s coming from some non-standard 3rd party URL (like your blog) for same security reason.
In order to fix an issue for your WordPress blog, just put below into your .htaccess file.
<IfModule mod_headers.c>
<FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css|css|js)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
getClass().getResource(path)
loads resources from the classpath, not from a filesystem path.
This one worked for me.
window.open("data:application/octet-stream;charset=utf-16le;base64,"+data64);
This one worked too
let a = document.createElement("a");
a.href = "data:application/octet-stream;base64,"+data64;
a.download = "documentName.pdf"
a.click();
UPDATE mytable SET spares = CONCAT(spares, ',', '818') WHERE id = 1
not working for me.
spares is NULL
by default but its varchar
If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.
I was also having above doubt, what worked for me is
ALTER TABLE `your_table` CHANGE `property` `property`
VARCHAR(whatever_you_want) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$("#btn1").click(function()
{
person = new Object();
person.name = "vishal";
person.age =20;
$("div").data(person);
});
$("#btn2").click(function()
{
alert($("div").data("name"));
});
});
</script>
<body>
<button id="btn1">Attach data to div element</button><br>
<button id="btn2">Get data attached to div element</button>
<div></div>
</body>
</html>
Anser:-Attach data to selected elements using an object with name/value pairs.
GET value using object propetis like name,age etc...
Instead of adding File, add class. File
->New
->Class
. That fixed my issue.
The keyword super
doesn't "stick". Every method call is handled individually, so even if you got to SuperClass.method1()
by calling super
, that doesn't influence any other method call that you might make in the future.
That means there is no direct way to call SuperClass.method2()
from SuperClass.method1()
without going though SubClass.method2()
unless you're working with an actual instance of SuperClass
.
You can't even achieve the desired effect using Reflection (see the documentation of java.lang.reflect.Method.invoke(Object, Object...)
).
[EDIT] There still seems to be some confusion. Let me try a different explanation.
When you invoke foo()
, you actually invoke this.foo()
. Java simply lets you omit the this
. In the example in the question, the type of this
is SubClass
.
So when Java executes the code in SuperClass.method1()
, it eventually arrives at this.method2();
Using super
doesn't change the instance pointed to by this
. So the call goes to SubClass.method2()
since this
is of type SubClass
.
Maybe it's easier to understand when you imagine that Java passes this
as a hidden first parameter:
public class SuperClass
{
public void method1(SuperClass this)
{
System.out.println("superclass method1");
this.method2(this); // <--- this == mSubClass
}
public void method2(SuperClass this)
{
System.out.println("superclass method2");
}
}
public class SubClass extends SuperClass
{
@Override
public void method1(SubClass this)
{
System.out.println("subclass method1");
super.method1(this);
}
@Override
public void method2(SubClass this)
{
System.out.println("subclass method2");
}
}
public class Demo
{
public static void main(String[] args)
{
SubClass mSubClass = new SubClass();
mSubClass.method1(mSubClass);
}
}
If you follow the call stack, you can see that this
never changes, it's always the instance created in main()
.
Since ES6 you can do this
let newCodes = function() {
const dCodes = fg.codecsCodes.rs
const dCodes2 = fg.codecsCodes2.rs
return {dCodes, dCodes2}
};
let {dCodes, dCodes2} = newCodes()
Return expression {dCodes, dCodes2}
is property value shorthand and is equivalent to this {dCodes: dCodes, dCodes2: dCodes2}
.
This assignment on last line is called object destructing assignment. It extracts property value of an object and assigns it to variable of same name. If you'd like to assign return values to variables of different name you could do it like this let {dCodes: x, dCodes2: y} = newCodes()
I don't know if leaving hibernate
off the front makes a difference.
The reference suggests it should be hibernate.hbm2ddl.auto
A value of create
will create your tables at sessionFactory creation, and leave them intact.
A value of create-drop
will create your tables, and then drop them when you close the sessionFactory.
Perhaps you should set the javax.persistence.Table
annotation explicitly?
Hope this helps.
As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.
This is some pseudocodish JavaScript:
Client:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
Server:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
This should work:
Nullable<T> a = new Nullable<T>().GetValueOrDefault();
The syntax of ng-style
is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:
<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>
And then in your controller:
$scope.width = '900px';
$scope.bgColor = 'red';
This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.
This is as simple an answer as I could come up with. Worked well with my data. If you want to exclude certain values just add a where clause to the inner select.
SELECT TOP 1
ValueField AS MedianValue
FROM
(SELECT TOP(SELECT COUNT(1)/2 FROM tTABLE)
ValueField
FROM
tTABLE
ORDER BY
ValueField) A
ORDER BY
ValueField DESC
if the variable is :
int foo;
in the 2nd C file you declare:
extern int foo;
unset
doesn't change the index, but array_splice
does:
$arrayName = array('1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
500 => 'somevalue500',
);
echo $arrayName['500'];
//somevalue500
array_splice($arrayName, 1, 2);
print_r($arrayName);
//Array ( [0] => somevalue [1] => somevalue500 )
$arrayName = array( '1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
500 => 'somevalue500',
);
echo $arrayName['500'];
//somevalue500
unset($arrayName[1]);
print_r($arrayName);
//Array ( [0] => somevalue [1] => somevalue500 )
Use queue.rear+1
to get the length of the queue
ps -ef | grep KEYWORD | grep -v grep | awk '{print $2}'
-Ldir
Add directory dir to the list of directories to be searched for -l.
In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:
<table id="elitable" border="1" cellspacing="0" width="100%">
<tr>
<td>100</td><td>AAA</td><td>aaa</td>
</tr>
<tr>
<td>200</td><td>BBB</td><td>bbb</td>
</tr>
<tr>
<td>300</td><td>CCC</td><td>ccc</td>
</tr>
</table>
<script>
$(function(){
$("#elitable tr").click(function(){
alert (this.rowIndex);
});
});
</script>
You can also use std::list
instead of std::vector
. list
has a built-in function list::reverse for reversing elements.
You should not expose this info. in public, specially api keys. It may lead to a privacy leak.
Before making the website public you should hide it. You can do it in 2 or more ways
Using Java 7
:
public static void writeToFile(String text, String targetFilePath) throws IOException
{
Path targetPath = Paths.get(targetFilePath);
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}
import re
sentence = ' hello apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub(' ',' ',sentence) #hello world (remove double spaces)
For me, I have to Revoke USB debugging authorizations
in Developer Options. Here is the steps:
USB Debugging
,USB Debugging
What are the differences between the assignment operators
=
and<-
in R?
As your example shows, =
and <-
have slightly different operator precedence (which determines the order of evaluation when they are mixed in the same expression). In fact, ?Syntax
in R gives the following operator precedence table, from highest to lowest:
… ‘-> ->>’ rightwards assignment ‘<- <<-’ assignment (right to left) ‘=’ assignment (right to left) …
But is this the only difference?
Since you were asking about the assignment operators: yes, that is the only difference. However, you would be forgiven for believing otherwise. Even the R documentation of ?assignOps
claims that there are more differences:
The operator
<-
can be used anywhere, whereas the operator=
is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.
Let’s not put too fine a point on it: the R documentation is wrong. This is easy to show: we just need to find a counter-example of the =
operator that isn’t (a) at the top level, nor (b) a subexpression in a braced list of expressions (i.e. {…; …}
). — Without further ado:
x
# Error: object 'x' not found
sum((x = 1), 2)
# [1] 3
x
# [1] 1
Clearly we’ve performed an assignment, using =
, outside of contexts (a) and (b). So, why has the documentation of a core R language feature been wrong for decades?
It’s because in R’s syntax the symbol =
has two distinct meanings that get routinely conflated (even by experts, including in the documentation cited above):
=
operator it performs no action at runtime, it merely changes the way an expression is parsed.So how does R decide whether a given usage of =
refers to the operator or to named argument passing? Let’s see.
In any piece of code of the general form …
‹function_name›(‹argname› = ‹value›, …)
‹function_name›(‹args›, ‹argname› = ‹value›, …)
… the =
is the token that defines named argument passing: it is not the assignment operator. Furthermore, =
is entirely forbidden in some syntactic contexts:
if (‹var› = ‹value›) …
while (‹var› = ‹value›) …
for (‹var› = ‹value› in ‹value2›) …
for (‹var1› in ‹var2› = ‹value›) …
Any of these will raise an error “unexpected '=' in ‹bla›”.
In any other context, =
refers to the assignment operator call. In particular, merely putting parentheses around the subexpression makes any of the above (a) valid, and (b) an assignment. For instance, the following performs assignment:
median((x = 1 : 10))
But also:
if (! (nf = length(from))) return()
Now you might object that such code is atrocious (and you may be right). But I took this code from the base::file.copy
function (replacing <-
with =
) — it’s a pervasive pattern in much of the core R codebase.
The original explanation by John Chambers, which the the R documentation is probably based on, actually explains this correctly:
[
=
assignment is] allowed in only two places in the grammar: at the top level (as a complete program or user-typed expression); and when isolated from surrounding logical structure, by braces or an extra pair of parentheses.
In sum, by default the operators <-
and =
do the same thing. But either of them can be overridden separately to change its behaviour. By contrast, <-
and ->
(left-to-right assignment), though syntactically distinct, always call the same function. Overriding one also overrides the other. Knowing this is rarely practical but it can be used for some fun shenanigans.
z-index only works within a particular context i.e. relative
, fixed
or absolute
position.
z-index for a relative div has nothing to do with the z-index
of an absolutely or fixed div.
EDIT This is an incomplete answer. This answer provides false information. Please review @Dansingerman's comment and example below.
I was getting this issue on our TeamCity build server. I tried updating NuGet on the build server (via TC) but that didn't work. I finally resolved the problem by changing the "Update Mode" of the Nuget Installer build step from solution file to packages.config
.
$ vim /etc/profile.d/nodejs.sh
NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript
export NODE_PATH="$NODE_PATH"
This doesn't have anything to do with jQuery. You can use the JavaScript replace
function for this:
var str = "data-123";
str = str.replace("data-", "");
You can also pass a regex to this function. In the following example, it would replace everything except numerics:
str = str.replace(/[^0-9\.]+/g, "");
You have to put a g
at the end, it stands for "global":
echo dog dog dos | sed -r 's:dog:log:g'
^
I did some mock testing to record the difference between save()
and persist()
.
Sounds like both these methods behaves same when dealing with Transient Entity but differ when dealing with Detached Entity.
For the below example, take EmployeeVehicle as an Entity with PK as vehicleId
which is a generated value and vehicleName
as one of its properties.
Example 1 : Dealing with Transient Object
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = new EmployeeVehicle();
entity.setVehicleName("Honda");
session.save(entity);
// session.persist(entity);
session.getTransaction().commit();
session.close();
Result:
select nextval ('hibernate_sequence') // This is for vehicle Id generated : 36
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Honda, 36)
Note the result is same when you get an already persisted object and save it
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
entity.setVehicleName("Toyota");
session.save(entity); -------> **instead of session.update(entity);**
// session.persist(entity);
Repeat the same using persist(entity)
and will result the same with new Id ( say 37 , honda ) ;
Example 2 : Dealing with Detached Object
// Session 1
// Get the previously saved Vehicle Entity
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();
// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it
// (i) Using Save() to persist a detached object
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.save(entity);
session2.getTransaction().commit();
session2.close();
Result : You might be expecting the Vehicle with id : 36 obtained in previous session is updated with name as "Toyota" . But what happens is that a new entity is saved in the DB with new Id generated for and Name as "Toyota"
select nextval ('hibernate_sequence')
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Toyota, 39)
Using persist to persist detached entity
// (ii) Using Persist() to persist a detached
// Session 1
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();
// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it
// (i) Using Save() to persist a detached
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.persist(entity);
session2.getTransaction().commit();
session2.close();
Result:
Exception being thrown : detached entity passed to persist
So, it is always better to use Persist() rather than Save() as save has to be carefully used when dealing with Transient object .
Important Note : In the above example , the pk of vehicle entity is a generated value , so when using save() to persist a detached entity , hibernate generates a new id to persist . However if this pk is not a generated value than it is result in a exception stating key violated.
http://stevenlevithan.com/assets/misc/date.format.js
var date = eval(data.Data.Entity.Slrq.replace(/\/Date\((\d )\)\//gi, "new Date($1)"));
alert(date.format("yyyy-MM-dd HH:mm:ss"));
alert(dateFormat(date, "yyyy-MM-dd HH:mm:ss"));
This is the bit of code you need at the top of your JavaScript file:
<?php
header('Content-Type: text/javascript; charset=UTF-8');
?>
(function() {
alert("hello world");
}) ();
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
connection = DriverManager.getConnection("jdbc:oracle:thin:@machinename:portnum:schemaname","userid","password");
Cong Ma does a good job of explaining what __getitem__
is used for - but I want to give you an example which might be useful.
Imagine a class which models a building. Within the data for the building it includes a number of attributes, including descriptions of the companies that occupy each floor :
Without using __getitem__
we would have a class like this :
class Building(object):
def __init__(self, floors):
self._floors = [None]*floors
def occupy(self, floor_number, data):
self._floors[floor_number] = data
def get_floor_data(self, floor_number):
return self._floors[floor_number]
building1 = Building(4) # Construct a building with 4 floors
building1.occupy(0, 'Reception')
building1.occupy(1, 'ABC Corp')
building1.occupy(2, 'DEF Inc')
print( building1.get_floor_data(2) )
We could however use __getitem__
(and its counterpart __setitem__
) to make the usage of the Building class 'nicer'.
class Building(object):
def __init__(self, floors):
self._floors = [None]*floors
def __setitem__(self, floor_number, data):
self._floors[floor_number] = data
def __getitem__(self, floor_number):
return self._floors[floor_number]
building1 = Building(4) # Construct a building with 4 floors
building1[0] = 'Reception'
building1[1] = 'ABC Corp'
building1[2] = 'DEF Inc'
print( building1[2] )
Whether you use __setitem__
like this really depends on how you plan to abstract your data - in this case we have decided to treat a building as a container of floors (and you could also implement an iterator for the Building, and maybe even the ability to slice - i.e. get more than one floor's data at a time - it depends on what you need.
It may be a little late but for this you can do:
HTML
<!-- html -->
<div class="images-wrapper">
<img src="images/1" alt="image 1" />
<img src="images/2" alt="image 2" />
<img src="images/3" alt="image 3" />
<img src="images/4" alt="image 4" />
</div>
SASS
// In _extra.scss
$maxImagesNumber: 5;
.images-wrapper {
img {
position: absolute;
padding: 5px;
border: solid black 1px;
}
@for $i from $maxImagesNumber through 1 {
:nth-child(#{ $i }) {
z-index: #{ $maxImagesNumber - ($i - 1) };
left: #{ ($i - 1) * 30 }px;
}
}
}
You want to use regexp_substr()
for this. This should work for your example:
select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
Here, by the way, is the SQL Fiddle.
Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace()
for the first part:
select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
And here is this corresponding SQL Fiddle.
I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.
Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition
SELECT * FROM test WHERE REGEXP_LIKE(sampletext, '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );
Just as an FYI - "best" questions aren't the norm at SO, but I will give you a list of options, just as a service.
OK then. These two are the ones I used:
and then there is always Eclipse.
*UPDATE 20 March 2013 *
Well, Sublime Text 2 is the one to heavily consider. Heavily.
In my case I use this
var key=dict.FirstOrDefault(m => m.Value == s).Key;
dict.Remove(key);
Typing the SET PATH
command into the command shell every time you fire it up could get old for you pretty fast. Three alternatives:
.CMD
) file. Then you can just put the SET PATH
into that file before your javac
execution. Or you could do without the SET PATH
if you simply code the explicit path to javac.exe
PATH
in the "environment variables" configuration of your system.PATH
first, which brings us back to (1) and (2).IE11 does implement String.prototype.includes so why not using the official Polyfill?
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
Source: polyfill source
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
Here's a basic code that will help serializing the C# objects into xml:
using System;
public class clsPerson
{
public string FirstName;
public string MI;
public string LastName;
}
class class1
{
static void Main(string[] args)
{
clsPerson p=new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}
I had this problem as well.
I got it working with this:
.ui-dialog{
display:inline-block;
}
You could try:
<html>
<head>
<style>
#main {
width: 500; /*Set to whatever*/
height: 500;/*Set to whatever*/
}
</style>
</head>
<body id="main">
</body>
</html>
On Windows (msys) using Docker Toolbox/Machine, I had to add an extra /
before /bin/bash
to indicate that it was a *nix filepath.
So,
docker run --rm -it <image>:latest //bin/bash