1) To redirect to the login page / from the login page, don't use the Redirect() methods. Use FormsAuthentication.RedirectToLoginPage()
and FormsAuthentication.RedirectFromLoginPage()
!
2) You should just use RedirectToAction("action", "controller") in regular scenarios..
You want to redirect in side the Initialize method? Why? I don't see why would you ever want to do this, and in most cases you should review your approach imo.. If you want to do this for authentication this is DEFINITELY the wrong way (with very little chances foe an exception)
Use the [Authorize]
attribute on your controller or method instead :)
UPD: if you have some security checks in the Initialise method, and the user doesn't have access to this method, you can do a couple of things: a)
Response.StatusCode = 403;
Response.End();
This will send the user back to the login page. If you want to send him to a custom location, you can do something like this (cautios: pseudocode)
Response.Redirect(Url.Action("action", "controller"));
No need to specify the full url. This should be enough. If you completely insist on the full url:
Response.Redirect(new Uri(Request.Url, Url.Action("action", "controller")).ToString());
There are multiple nuget packages read in the following order:
NuGetDefaults.Config file
. You will find this in %ProgramFiles(x86)%\NuGet\Config
.%APPDATA%\NuGet\nuget.config
.nuget.config
beginning from the root of your drive up to the directory where nuget.exe is called.You can find more information here.
window.location
always refers to the location of the current window. Changing it will affect only the current window.
One thing that can be done is forcing a click on the link after setting its target
attribute to _blank
:
Check this: http://www.techfoobar.com/2012/jquery-programmatically-clicking-a-link-and-forcing-the-default-action
Disclaimer: Its my blog.
Try this simple function to add an dictionary item if it does not exist or update when it exists:
public void AddOrUpdateDictionaryEntry(string key, int value)
{
if (dict.ContainsKey(key))
{
dict[key] = value;
}
else
{
dict.Add(key, value);
}
}
This is the same as dict[key] = value.
int fun(int n_args, ...) {
int *p = &n_args;
int s = sizeof(int);
p += s + s - 1;
for(int i = 0; i < n_args; i++) {
printf("A1 %d!\n", *p);
p += 2;
}
}
Plain version
You are missing the event parameter on your function.
$(document).on("click",".appDetails", function (event) {
alert(event.target.id);
});
I had the same problem. I changed the order of the scripts in the head part, and it worked for me. Every script the plugin needs - needs to stay close.
For example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#slider').cycle({
fx: 'fade'
});
});
</script>
The finite repetition syntax uses {m,n}
in place of star/plus/question mark.
From java.util.regex.Pattern
:
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
All repetition metacharacter have the same precedence, so just like you may need grouping for *
, +
, and ?
, you may also for {n,m}
.
ha*
matches e.g. "haaaaaaaa"
ha{3}
matches only "haaa"
(ha)*
matches e.g. "hahahahaha"
(ha){3}
matches only "hahaha"
Also, just like *
, +
, and ?
, you can add the ?
and +
reluctant and possessive repetition modifiers respectively.
System.out.println(
"xxxxx".replaceAll("x{2,3}", "[x]")
); "[x][x]"
System.out.println(
"xxxxx".replaceAll("x{2,3}?", "[x]")
); "[x][x]x"
Essentially anywhere a *
is a repetition metacharacter for "zero-or-more", you can use {...}
repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use *
because Java doesn't officially support infinite-length lookbehind.
.*
and .*?
for regexregex{n,}?
== regex{n}
?a{1}b{0,1}
instead of ab?
There's also str_pad
<?php
$input = "Alien";
echo str_pad($input, 10); // produces "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // produces "__Alien___"
echo str_pad($input, 6 , "___"); // produces "Alien_"
?>
It should be noted that you can export a variable and later change the value. The variable's changed value will be available to child processes. Once export has been set for a variable you must do export -n <var>
to remove the property.
$ K=1
$ export K
$ K=2
$ bash -c 'echo ${K-unset}'
2
$ export -n K
$ bash -c 'echo ${K-unset}'
unset
As of today, you can read some values from HTML5 data
attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data
properties for setting the content
.
Unfortunately it is not working for the width
and height
(tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).
But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width
and data-height
. You can find the GitHub repo to it here: cssattr.js.
I haven’t actually done anything with font-face
, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.
The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.
Does Firefox download the font when you actually use it in a font
declaration? (e.g. h1 { font: 'DejaVu Serif';
)?
Adding one more answer on this question. For Linux Debian Stretch release you would need to install the following dependencies:
apt-get update
apt-get install g++
apt-get install unixodbc-dev
pip install pyodbc
Swift 3
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .normal, title: "Edit") { (rowAction, indexPath) in
//TODO: edit the row at indexPath here
}
editAction.backgroundColor = .blue
let deleteAction = UITableViewRowAction(style: .normal, title: "Delete") { (rowAction, indexPath) in
//TODO: Delete the row at indexPath here
}
deleteAction.backgroundColor = .red
return [editAction,deleteAction]
}
Swift 2.1
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .Normal, title: "Edit") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
//TODO: edit the row at indexPath here
}
editAction.backgroundColor = UIColor.blueColor()
let deleteAction = UITableViewRowAction(style: .Normal, title: "Delete") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
//TODO: Delete the row at indexPath here
}
deleteAction.backgroundColor = UIColor.redColor()
return [editAction,deleteAction]
}
Note: for iOS 8 onwards
List<Integer> x = new ArrayList<>(Arrays.asList(7, 9, 13));
int[] n = new int[x.size()];
Arrays.setAll(n, x::get);
System.out.println("Array of primitive ints: " + Arrays.toString(n));
Output:
Array of primitive ints: [7, 9, 13]
The same works for an array of long
or double
, but not for arrays of boolean
, char
, byte
, short
or float
. If you’ve got a really huge list, there’s even a parallelSetAll
method that you may use instead.
To me this is good and elgant enough that I wouldn’t want to get an external library nor use streams for it.
Documentation link: Arrays.setAll(int[], IntUnaryOperator)
MacOS Big Sur seemed to renamed the Application\ Support
folder to ApplicationSupport
. So the updated Path would be:
/Users/<USERNAME>/Library/ApplicationSupport/Postgres/var-10
(or "/var-<YOUR PG VERSION>")
<div style="cursor:pointer;" onclick="document.location='http://www.google.com'">Foo</div>
$('#btnSubmit').click(function(event){
alert("Button Clicked");
});
or as you are using submit button so you can write your code in form's validate event like
$('#myForm').validate(function(){
alert("Hello World!!");
});
No, they are not always.
It depends on whether you allow user input to be placed within the query itself. For example:
$dbh = new PDO("blahblah");
$tableToUse = $_GET['userTable'];
$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
would be vulnerable to SQL injections and using prepared statements in this example won't work, because the user input is used as an identifier, not as data. The right answer here would be to use some sort of filtering/validation like:
$dbh = new PDO("blahblah");
$tableToUse = $_GET['userTable'];
$allowedTables = array('users','admins','moderators');
if (!in_array($tableToUse,$allowedTables))
$tableToUse = 'users';
$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
Note: you can't use PDO to bind data that goes outside of DDL (Data Definition Language), i.e. this does not work:
$stmt = $dbh->prepare('SELECT * FROM foo ORDER BY :userSuppliedData');
The reason why the above does not work is because DESC
and ASC
are not data. PDO can only escape for data. Secondly, you can't even put '
quotes around it. The only way to allow user chosen sorting is to manually filter and check that it's either DESC
or ASC
.
So for this task First Sort your data in order from A to Z or Z to A then you can just use one simple formula as stated below:
=IF(A2=A3, "Duplicate", "Not Duplicate")
The above formula states that if column A2 data ( A is column and 2 is row number) is similar to A3 (A is Column and 3 is Row number) then it will print Duplicate else will print Not Duplicate.
Lets consider an example, Column A consists Email address in which some are duplicate, so in Column 2, I used the above stated formula which in results displayed me the 2 duplicates cells one is Row 2 and Row 6.
One you got the duplicate data just put filter on your sheet and make visible only the duplicate data and delete all the unnecessary data.
It's not a format suitable for blindly copying to another machine, but users who wish to work out whether they've added a repository yet or not (like I did), you can just do:
sudo apt update
When apt
is updating, it outputs a list of repositories it fetches. It seems obvious, but I've just realised what the GET
URLs are that it spits out.
The following awk
-based expression could be used to generate a sources.list file:
cat /tmp/apt-update.txt | awk '/http/ { gsub("/", " ", $3); gsub("^\s\*$", "main", $3); printf("deb "); if($4 ~ "^[a-z0-9]$") printf("[arch=" $4 "] "); print($2 " " $3) }' | sort | uniq
Alternatively, as other answers suggest, you could just cat
all the pre-existing sources like this:
cat /etc/apt/sources.list /etc/apt/sources.list.d/*
Since the disabled repositories are commented out with hash, this should work as intended.
I just gave this a whirl in both Chrome and Firefox and IE10.
As mentioned above - make sure that you have marked up with type = "button", "reset", "submit" etc to ensure that it correctly cascades and chooses the correct button.
Perhaps also setting all of them to have the same form (ie all as that worked for me)
You need to change your Ajax call to
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
contentType: "json",
processData: false,
success:function(data) {
$('#save_message').html(data.message);
}
});
change the dataType
to contentType
and add the processData
option.
To retrieve the JSON payload from your controller, use:
dd(json_decode($request->getContent(), true));
instead of
dd($request->all());
You can user either
.your-class{
position:absolute;
-moz-transform: scaleX(-1);
-o-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
filter: FlipH;
}
or
.your-class{
position:absolute;
transform: rotate(360deg) scaleX(-1);
}
Notice that setting position
to absolute
is very important! If you won't set it, you will need to set display: inline-block;
Adding pause
in (Windows 7) to the end did not work for me
but adding the cmd /k
in front of my command did work.
Example :
cmd /k gradlew cleanEclipse
If you wish to clear your entire database.
Because of the foreign-key constraints it matters which sequence the tables are truncated. This is a way to bruteforce this sequence.
public static void ClearDatabase<T>() where T : DbContext, new()
{
using (var context = new T())
{
var tableNames = context.Database.SqlQuery<string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT LIKE '%Migration%'").ToList();
foreach (var tableName in tableNames)
{
foreach (var t in tableNames)
{
try
{
if (context.Database.ExecuteSqlCommand(string.Format("TRUNCATE TABLE [{0}]", tableName)) == 1)
break;
}
catch (Exception ex)
{
}
}
}
context.SaveChanges();
}
}
usage:
ClearDatabase<ApplicationDbContext>();
remember to reinstantiate your DbContext after this.
When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.
@
string literal, pass string value, one way binding.=
string literal, pass object, 2 ways binding.&
string literal, calls external function, can pass data from directive to controller.Try this code. You can change the height and width percentages with app:layout_constraintHeight_percent and app:layout_constraintWidth_percent.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#FF00FF"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHeight_percent=".6"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent=".4"></LinearLayout>
</android.support.constraint.ConstraintLayout>
Gradle:
dependencies {
...
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
The best way for me was to put it in a hidden div in php blade
<div hidden id="token">{{$token}}</div>
then call it in javascript as a constant to avoid undefined var errors
const token = document.querySelector('div[id=token]').textContent
// console.log(token)
// eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5MjNlOTcyMi02N2NmLTQ4M2UtYTk4Mi01YmE5YTI0Y2M2MzMiLCJqdGkiOiI2Y2I1ZGRhNzRhZjNhYTkwNzA3ZjMzMDFiYjBiZDUzNTZjNjYxMGUyZWJlNmYzOTI5NzBmMjNjNDdiNjhjY2FiYjI0ZWVmMzYwZmNiZDBmNyIsImlhdCI6IjE2MDgwODMyNTYuNTE2NjE4IiwibmJmIjoiMTYwODA4MzI1Ni41MTY2MjUiLCJleHAiOiIxNjIzODA4MDU2LjMxMTg5NSIsInN1YiI6IjUiLCJzY29wZXMiOlsiYWRtaW4iXX0.GbKZ8CIjt3otzFyE5aZEkNBCtn75ApIfS6QbnD6z0nxDjycknQaQYz2EGems9Z3Qjabe5PA9zL1mVnycCieeQfpLvWL9xDu9hKkIMs006Sznrp8gWy6JK8qX4Xx3GkzWEx8Z7ZZmhsKUgEyRkqnKJ-1BqC2tTiTBqBAO6pK_Pz7H74gV95dsMiys9afPKP5ztW93kwaC-pj4h-vv-GftXXc6XDnUhTppT4qxn1r2Hf7k-NXE_IHq4ZPb20LRXboH0RnbJgq2JA1E3WFX5_a6FeWJvLlLnGGNOT0ocdNZq7nTGWwfocHlv6pH0NFaKa3hLoRh79d5KO_nysPVCDt7jYOMnpiq8ybIbe3oYjlWyk_rdQ9067bnsfxyexQwLC3IJpAH27Az8FQuOQMZg2HJhK8WtWUph5bsYUU0O2uPG8HY9922yTGYwzeMEdAqBss85jdpMNuECtlIFM1Pc4S-0nrCtBE_tNXn8ATDrm6FecdSK8KnnrCOSsZhR04MvTyznqCMAnKtN_vMDpmIAmPd181UanjO_kxR7QIlsEmT_UhM1MBmyfdIEvHkgLgUdUouonjQNvOKwCrrgDkP0hkZQff-iuHPwpL-CUjw7GPa70lp-TIDhfei8T90RkAXte1XKv7ku3sgENHTwPrL9QSrNtdc5MfB9AbUV-tFMJn9T7k
Your code doesn't work, because what it does is:
Create variable `funcs` and assign it an empty array;
Loop from 0 up until it is less than 3 and assign it to variable `i`;
Push to variable `funcs` next function:
// Only push (save), but don't execute
**Write to console current value of variable `i`;**
// First loop has ended, i = 3;
Loop from 0 up until it is less than 3 and assign it to variable `j`;
Call `j`-th function from variable `funcs`:
**Write to console current value of variable `i`;**
// Ask yourself NOW! What is the value of i?
Now the question is, what is the value of variable i
when the function is called? Because the first loop is created with the condition of i < 3
, it stops immediately when the condition is false, so it is i = 3
.
You need to understand that, in time when your functions are created, none of their code is executed, it is only saved for later. And so when they are called later, the interpreter executes them and asks: "What is the current value of i
?"
So, your goal is to first save the value of i
to function and only after that save the function to funcs
. This could be done for example this way:
var funcs = [];
for (var i = 0; i < 3; i++) { // let's create 3 functions
funcs[i] = function(x) { // and store them in funcs
console.log("My value: " + x); // each should log its value.
}.bind(null, i);
}
for (var j = 0; j < 3; j++) {
funcs[j](); // and now let's run each one to see
}
This way, each function will have it's own variable x
and we set this x
to the value of i
in each iteration.
This is only one of the multiple ways to solve this problem.
controller_name
holds the name of the controller used to serve the current view.
Since Python 3.5 you can use math.inf
:
>>> import math
>>> math.inf
inf
This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.
<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com
SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"
VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"
DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
SqlConnection con = new SqlConnection(@"Some Connection String");
SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
I think it would be a lot more productive to use a TextWriter
, in this case a StreamWriter to write to the MemoryStream. After that, as other have said, you need to "rewind" the MemoryStream using something like stringAsStream.Position = 0L;
.
stringAsStream = new MemoryStream();
// create stream writer with UTF-16 (Unicode) encoding to write to the memory stream
using(StreamWriter sWriter = new StreamWriter(stringAsStream, UnicodeEncoding.Unicode))
{
sWriter.Write("Lorem ipsum.");
}
stringAsStream.Position = 0L; // rewind
Note that:
StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. This instance of UTF8Encoding is constructed without a byte order mark (BOM)
Also, you don't have to create a new UnicodeEncoding()
usually, since there's already one as a static member of the class for you to use in convenient utf-8, utf-16, and utf-32 flavors.
And then, finally (as others have said) you're trying to convert the byte
s directly to char
s, which they are not. If I had a memory stream and knew it was a string, I'd use a TextReader
to get the string back from the bytes. It seems "dangerous" to me to mess around with the raw bytes.
Edit:
use jquery plugin: jquery.sizes.js
$('img').margin() or $('img').padding()
return:
{bottom: 10 ,left: 4 ,top: 0 ,right: 5}
get value:
$('img').margin().top
It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.
I had the same problem. I solved it by switching to <a>
and add onclick="return false;"
(so that clicking on it won't add a new entry to browser history).
You can get the bounding box of any element by calling getBoundingClientRect
var rect = document.getElementById("myElement").getBoundingClientRect();
That will return an object with left, top, width and height fields.
Programmatically in Java - At least API v14+
exampleEditText.setHintTextColor(getResources().getColor(R.color.your_color));
I found that if it's a presented view controller, you can override preferredInterfaceOrientationForPresentation
Swift:
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Landscape.rawValue)
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
return UIInterfaceOrientation.LandscapeLeft
}
override func shouldAutorotate() -> Bool {
return false
}
If you need to insert node/element in some specific place , you can to do next steps
It is simple algorithm but should works...
You can use a CSS3 transition
for this. Have a look at this example:
Here is the main code:
#box {
position : relative;
width : 100px;
height : 100px;
background-color : gray;
border : 5px solid black;
-webkit-transition : border 500ms ease-out;
-moz-transition : border 500ms ease-out;
-o-transition : border 500ms ease-out;
transition : border 500ms ease-out;
}
#box:hover {
border : 10px solid red;
}
Another way to use Linq, but without having to return everything and filter on that in memory.
var files = Directory.GetFiles("C:\\path", "*.mp3", SearchOption.AllDirectories).Union(Directory.GetFiles("C:\\path", "*.jpg", SearchOption.AllDirectories));
It's actually 2 calls to GetFiles()
, but I think it's consistent with the spirit of the question and returns them in one enumerable.
For myself I use following extension functions:
fun T?.or<T>(default: T): T = if (this == null) default else this
fun T?.or<T>(compute: () -> T): T = if (this == null) compute() else this
First one will return provided default value in case object equals null. Second will evaluate expression provided in lambda in the same case.
Usage:
1) e?.getMessage().or("unknown")
2) obj?.lastMessage?.timestamp.or { Date() }
Personally for me code above more readable than if
construction inlining
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
The link below provides a pure HTML / CSS solution to this problem.
Browser support - as stated in the article:
So far we have tested on Safari 5.0, IE 9 (must be in standards mode), Opera 12 and Firefox 15.
Older browsers will still work quite well, as the meat of the layout is in normal positioning, margin and padding properties. if your platform is older (e.g. Firefox 3.6, IE 8), you can use the method but redo the gradient as a standalone PNG image or DirectX filter.
http://www.mobify.com/dev/multiline-ellipsis-in-pure-css
p { margin: 0; padding: 0; font-family: sans-serif;}
.ellipsis {
overflow: hidden;
height: 200px;
line-height: 25px;
margin: 20px;
border: 5px solid #AAA; }
.ellipsis:before {
content:"";
float: left;
width: 5px; height: 200px; }
.ellipsis > *:first-child {
float: right;
width: 100%;
margin-left: -5px; }
.ellipsis:after {
content: "\02026";
box-sizing: content-box;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
float: right; position: relative;
top: -25px; left: 100%;
width: 3em; margin-left: -3em;
padding-right: 5px;
text-align: right;
background: -webkit-gradient(linear, left top, right top,
from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); }
<div class="ellipsis">
<div>
<p>Call me Ishmael. Some years ago – never mind how long precisely – having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen, and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off – then, I account it high time to get to sea as soon as I can.</p>
</div>
</div>
(resize browser's window for testing)
You can use any of these tools:
adb logcat
adb logcat > logs.txt (you can use editors to open and search errors.)
eclipse logcat (If not visible in eclipse, Go to Windows->Show View->Others->Android->LogCat)
Android Debug Monitor or Android Device Monitor(type command monitor or open through UI)
- Android Studio
I suggest to use Android Debug Monitor, it is good. Because eclipse hangs when too many logs are there, and through adb logcat filter and all difficult.
I use oneliner @ the very beginning of script:
#!/bin/bash
if [[ $(pgrep -afc "$(basename "$0")") -gt "1" ]]; then echo "Another instance of "$0" has already been started!" && exit; fi
.
the_beginning_of_actual_script
It is good to see the presence of process in the memory (no matter what the status of process is); but it does the job for me.
Most of the solutions I have seen either expects us to design a loading overlay, keep it hidden and then unhide it when required, or, show a gif or image etc.
I wanted to develop a robust plugin, where with a simply jQuery call I can display the loading screen and tear it down when the task is completed.
Below is the code. It depends on Font awesome and jQuery:
/**
* Raj: Used basic sources from here: http://jsfiddle.net/eys3d/741/
**/
(function($){
// Retain count concept: http://stackoverflow.com/a/2420247/260665
// Callers should make sure that for every invocation of loadingSpinner method there has to be an equivalent invocation of removeLoadingSpinner
var retainCount = 0;
// http://stackoverflow.com/a/13992290/260665 difference between $.fn.extend and $.extend
$.extend({
loadingSpinner: function() {
// add the overlay with loading image to the page
var over = '<div id="custom-loading-overlay">' +
'<i id="custom-loading" class="fa fa-spinner fa-spin fa-3x fa-fw" style="font-size:48px; color: #470A68;"></i>'+
'</div>';
if (0===retainCount) {
$(over).appendTo('body');
}
retainCount++;
},
removeLoadingSpinner: function() {
retainCount--;
if (retainCount<=0) {
$('#custom-loading-overlay').remove();
retainCount = 0;
}
}
});
}(jQuery));
Just put the above in a js file and include it throughout the project.
CSS addition:
#custom-loading-overlay {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: #000;
opacity: 0.8;
filter: alpha(opacity=80);
}
#custom-loading {
width: 50px;
height: 57px;
position: absolute;
top: 50%;
left: 50%;
margin: -28px 0 0 -25px;
}
Invocation:
$.loadingSpinner();
$.removeLoadingSpinner();
The imshow()
function with parameters interpolation='nearest'
and cmap='hot'
should do what you want.
import matplotlib.pyplot as plt
import numpy as np
a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()
This is how I write my AsyncTask
the key point is add Thread.sleep(1);
@Override protected Integer doInBackground(String... params) {
Log.d(TAG, PRE + "url:" + params[0]);
Log.d(TAG, PRE + "file name:" + params[1]);
downloadPath = params[1];
int returnCode = SUCCESS;
FileOutputStream fos = null;
try {
URL url = new URL(params[0]);
File file = new File(params[1]);
fos = new FileOutputStream(file);
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
byte[] data = new byte[10240];
int nFinishSize = 0;
while( bis.read(data, 0, 10240) != -1){
fos.write(data, 0, 10240);
nFinishSize += 10240;
**Thread.sleep( 1 ); // this make cancel method work**
this.publishProgress(nFinishSize);
}
data = null;
Log.d(TAG, "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
returnCode = FAIL;
} catch (Exception e){
e.printStackTrace();
} finally{
try {
if(fos != null)
fos.close();
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
e.printStackTrace();
}
}
return returnCode;
}
If you still cannot solve the problem after you turn on the less secure apps
.
The other possible reason which might cause this error is you are not using gmail account.
- : user_name => '[email protected]' , # It can not be used since it is not a gmail address
+ : user_name => '[email protected]' , # since it's a gmail address
Refer to here.
Also, bear in mind that it might take some times to enable the less secure apps
. I have to do it several times (before it works, every time I access the link it will shows that it is off
) and wait for a while until it really work.
Error message suggests that the client has closed the connection while the server is still trying to write out a response.
Refer to this link for more details:
This answer is going to briefly explain how the native files are handled on the latest launcher.
As of 4/29/2017 the Minecraft launcher for Windows extracts all native files and places them info %APPDATA%\Local\Temp{random folder}. That folder is temporary and is deleted once the javaw.exe process finishes (when Minecraft is closed). The location of that temporary folder must be provided in the launch arguments as the value of
-Djava.library.path=
Also, the latest launcher (2.0.847) does not show you the launch arguments so if you need to check them yourself you can do so under the Task Manager (simply enable the Command Line tab and expand it) or by using the WMIC
utility as explained here.
Hope this helps some people who are still interested in doing this in 2017.
As per macOS 10.14.5, below are the details:
Go to
system preferences > sharing > remote login.
If the culture of the result doesn't matters or we're only talking of integer values, CONVERT
or CAST
will be fine.
However, if the result must match a specific culture, FORMAT
might be the function to go:
DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value) --> 1505.5698
SELECT FORMAT(@value, 'N2', 'en-us') --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de') --> 1.505,57
For more information on FORMAT
see here.
Of course, formatting the result should be a matter of the UI layer of the software.
something like this would probably work
class MyClass:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
def __iter__(self): #overridding this to return tuples of (key,value)
return iter([('x',self.x),('y',self.y),('z',self.z)])
dict(MyClass(5,6,7)) # because dict knows how to deal with tuples of (key,value)
And if you want to search and replace based on the value of another field you could do a CONCAT:
update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));
Just to have this one here so that others will find it at once.
So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:
These options work great with me and I can start apache service without errors.
The other option is to change apache listen port from httpd.conf and set another port number.
Hope this solution helps anyone who face the same problem again.
Here's a more complete and flexible example that doesn't omit necessary includes to generate compilation errors:
#include <iostream>
#include <unordered_map>
class Hashtable {
std::unordered_map<const void *, const void *> htmap;
public:
void put(const void *key, const void *value) {
htmap[key] = value;
}
const void *get(const void *key) {
return htmap[key];
}
};
int main() {
Hashtable ht;
ht.put("Bob", "Dylan");
int one = 1;
ht.put("one", &one);
std::cout << (char *)ht.get("Bob") << "; " << *(int *)ht.get("one");
}
Still not particularly useful for keys, unless they are predefined as pointers, because a matching value won't do! (However, since I normally use strings for keys, substituting "string" for "const void *" in the declaration of the key should resolve this problem.)
I think when you define a function with "var foo = function() {...};
", the function is only defined after that line. In other words, try this:
var replaceHtmlEntites = (function() {
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {
"nbsp": " ",
"amp" : "&",
"quot": "\"",
"lt" : "<",
"gt" : ">"
};
return function(s) {
return ( s.replace(translate_re, function(match, entity) {
return translate[entity];
}) );
}
})();
var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
cleanText = replaceHtmlEntities(text);
Edit: Also, only use "var
" the first time you declare a variable (you're using it twice on the cleanText
variable).
Edit 2: The problem is the spelling of the function name. You have "var replaceHtmlEntites =". It should be "var replaceHtmlEntities ="
If you didn't commit it to the master branch yet, its easy:
git checkout -b oops/fluke/dang
)git add -u; git commit;
)git checkout master
)Your changes will be saved in branch oops/fluke/dang; master will be as it was.
There is a read_pickle function as part of pandas 0.22+
import pandas as pd
object = pd.read_pickle(r'filepath')
Here’s how:
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const int SW_SHOW = 5;
var handle = GetConsoleWindow();
// Hide
ShowWindow(handle, SW_HIDE);
// Show
ShowWindow(handle, SW_SHOW);
When in doubt, be explicit about the data type conversion using CAST/CONVERT:
UPDATE TABLE
SET EndDate = CAST('2009-05-25' AS DATETIME)
WHERE Id = 1
Thread
is a lower-level concept: if you're directly starting a thread, you know it will be a separate thread, rather than executing on the thread pool etc.
Task
is more than just an abstraction of "where to run some code" though - it's really just "the promise of a result in the future". So as some different examples:
Task.Delay
doesn't need any actual CPU time; it's just like setting a timer to go off in the futureWebClient.DownloadStringTaskAsync
won't take much CPU time locally; it's representing a result which is likely to spend most of its time in network latency or remote work (at the web server)Task.Run()
really is saying "I want you to execute this code separately"; the exact thread on which that code executes depends on a number of factors.Note that the Task<T>
abstraction is pivotal to the async support in C# 5.
In general, I'd recommend that you use the higher level abstraction wherever you can: in modern C# code you should rarely need to explicitly start your own thread.
The SQL in your SP is wrong. You probably want
Select @code = RecItemCode from Receipt where RecTransaction = @id
In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException
when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.
The other issue is that your SQL statement if rewritten as
Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id
It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id
If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements
Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id
This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.
If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery();
and then read the output parameter value.
Another issue with your SP and code. In your SP, you have declared @code as varchar
. In your code, you specify the parameter type as Int
. Either change your SP or your code to make the types consistent.
Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write
Select RecItemCode from Receipt where RecTransaction = @id
And then use object obj = cmd.ExecuteScalar();
to get the result, no need for an output parameter in the SP or in your code.
Element node = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream("<node>value</node>".getBytes()))
.getDocumentElement();
See the documentation for jQuery Event Target. Using the target property of the event object, you can detect where the click originated within the #menu_content
element and, if so, terminate the click handler early. You will have to use .closest()
to handle cases where the click originated in a descendant of #menu_content
.
$(document).click(function(e){
// Check if click was triggered on or within #menu_content
if( $(e.target).closest("#menu_content").length > 0 ) {
return false;
}
// Otherwise
// trigger your click function
});
Wizard
Have you tried setting the height and width of the extra div, I know that on a project I am working on JS won't put anything in the div unless I have the height and width already set.
I used your code and hard coded the height and width and it shows up for me and without it doesn't show.
<body>
<div style="height:500px; width:500px;"> <!-- ommiting the height and width will not show the map -->
<div id="map-canvas"></div>
</div>
</body>
I would recommend either hard coding it in or assigning the div an ID and then add it to your CSS file.
Using a Service Account might work for you.
window.dispatchEvent(new Event('resize'));
If I'm understanding correctly:
var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
var tup = property.split(':');
obj[tup[0]] = tup[1];
});
I'm assuming that the property name is to the left of the colon and the string value that it takes on is to the right.
Note that Array.forEach
is JavaScript 1.6 -- you may want to use a toolkit for maximum compatibility.
If you have MFA enabled on GitLab you should go to Repository Settings/Repository ->Deploy Keys and create one, then use it as login while importing repo on GitHub
So you cant have the behavior that you want but you can do something that feels like it. You want to be able to do Choice.first.question
what I have done in the past is something like this
class Choice
belongs_to :user
belongs_to :answer
validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
...
def question
answer.question
end
end
this way the you can now call question on Choice
<ImageBackground
source={require("../assests/background_image.jpg")}
style={styles.container}
>
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center"
}}
>
<Button
onPress={() => this.props.showImagePickerComponent(this.props.navigation)}
title="START"
color="#841584"
accessibilityLabel="Increase Count"
/>
</View>
</ImageBackground>
Please use this code for set background image in react native
As per my Answer here: https://stackoverflow.com/questions/6313126/how-to-remove-a-directory-in-my-github-repository
Steps to remove directory
git rm -r --cached File-or-FolderName
git commit -m "Removed folder from repository"
git push origin master
Steps to ignore that folder in next commits
To ignore that folder from next commits make one file in root named .gitignore and put that folders name into it. You can put as many as you want
.gitignore file will be look like this
/FolderName
check two things
pip2 --version
and
pip3 --version
because the default pip may be anyone of this so it is always better to check both.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
Just return object: it will be parser to JSON.
public Object Get(string id)
{
return new { id = 1234 };
}
I use
SHOW CREATE TABLE mytable;
This shows you the SQL statement necessary to receate mytable
in its current form. You can see all the columns and their types (like DESC
) but it also shows you constraint information (and table type, charset, etc.).
You can add this in your css file:
[data-role=page]{height: 100% !important; position:relative !important;}
[data-role=footer]{bottom:0; position:absolute !important; top: auto !important; width:100%;}
So the page data-role now have 100% height, and footer is in absolute position.
Also Yappo have wrote an excellent plugin that you can find here: jQuery Mobile in a iScroll plugin http://yappo.github.com/projects/jquery.mobile.iscroll/livedemo.html
hope you found the answer!
An answer update
You can now use the data-position="fixed"
attribute to keep your footer element on the bottom.
Docs and demos: http://view.jquerymobile.com/master/demos/toolbar-fixed/
On success, atof() function returns the converted floating point number as a double value. If no valid conversion could be performed, the function returns zero (0.0). If the converted value would be out of the range of representable values by a double, it causes undefined behavior.
Refrence:http://www.cplusplus.com/reference/cstdlib/atof/
Try this code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char s[100] = "4.0800";
printf("Float value : %4.8f\n",strtod(s,NULL));
return 0;
}
You will get the following output:
Float value : 4.08000000
Write this code
<?php
if(isset($_POST['submit'])){
echo 'Hello World';
}
?>
<html>
<body>
<form method="post">
<input type="text" name="studentname">
<input type="submit" name="submit" value="click">
</form>
</body>
</html>
In ES6 you can use array destructuring to catch your groups:
let text = '27 months';
let regex = /(\d+)\s*(days?|months?|years?)/;
let [, count, unit] = regex.exec(text) || [];
// count === '27'
// unit === 'months'
Notice:
let
skips the first value of the resulting array, which is the whole matched string|| []
after .exec()
will prevent a destructuring error when there are no matches (because .exec()
will return null
)This is also known as the "inline if", or as above the ternary operator. https://en.wikipedia.org/wiki/%3F:
It's used to reduce code, though it's not recommended to use a lot of these on a single line as it may make maintaining code quite difficult. Imagine:
a = b?c:(d?e:(f?g:h));
and you could go on a while.
It ends up basically the same as writing:
if(b)
a = c;
else if(d)
a = e;
else if(f)
a = g;
else
a = h;
In your case, "string requestUri = _apiURL + "?e=" + OperationURL[0] + ((OperationURL[1] == "GET") ? GetRequestSignature() : "");"
Can also be written as: (omitting the else, since it's an empty string)
string requestUri = _apiURL + "?e=" + OperationURL[0];
if((OperationURL[1] == "GET")
requestUri = requestUri + GetRequestSignature();
or like this:
string requestUri;
if((OperationURL[1] == "GET")
requestUri = _apiURL + "?e=" + OperationURL[0] + GetRequestSignature();
else
requestUri = _apiURL + "?e=" + OperationURL[0];
Depending on your preference / the code style your boss tells you to use.
I have created an Object.filter()
which does not only filter by a function, but also accepts an array of keys to include. The optional third parameter will allow you to invert the filter.
var foo = {
x: 1,
y: 0,
z: -1,
a: 'Hello',
b: 'World'
}
Object.filter(foo, ['z', 'a', 'b'], true);
Object.filter(foo, function (key, value) {
return Ext.isString(value);
});
Disclaimer: I chose to use Ext JS core for brevity. Did not feel it was necessary to write type checkers for object types as it was not part of the question.
// Helper function_x000D_
function print(obj) {_x000D_
document.getElementById('disp').innerHTML += JSON.stringify(obj, undefined, ' ') + '<br />';_x000D_
console.log(obj);_x000D_
}_x000D_
_x000D_
Object.filter = function (obj, ignore, invert) {_x000D_
let result = {}; // Returns a filtered copy of the original list_x000D_
if (ignore === undefined) {_x000D_
return obj; _x000D_
}_x000D_
invert = invert || false;_x000D_
let not = function(condition, yes) { return yes ? !condition : condition; };_x000D_
let isArray = Ext.isArray(ignore);_x000D_
for (var key in obj) {_x000D_
if (obj.hasOwnProperty(key) &&_x000D_
!(isArray && not(!Ext.Array.contains(ignore, key), invert)) &&_x000D_
!(!isArray && not(!ignore.call(undefined, key, obj[key]), invert))) {_x000D_
result[key] = obj[key];_x000D_
}_x000D_
}_x000D_
return result;_x000D_
};_x000D_
_x000D_
let foo = {_x000D_
x: 1,_x000D_
y: 0,_x000D_
z: -1,_x000D_
a: 'Hello',_x000D_
b: 'World'_x000D_
};_x000D_
_x000D_
print(Object.filter(foo, ['z', 'a', 'b'], true));_x000D_
print(Object.filter(foo, (key, value) => Ext.isString(value)));
_x000D_
#disp {_x000D_
white-space: pre;_x000D_
font-family: monospace_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/4.2.1/builds/ext-core.min.js"></script>_x000D_
<div id="disp"></div>
_x000D_
I do not recommend using the answer that has been marked as correct here. It is a huge blob of CSS which tries to cover everything.
I would suggest that you evaluate how to remove the style from an element on a per case basis.
Lets say for SEO purposes you need to include an H1 on a page which has no actual heading in the design. You might want to make the nav link of that page an H1 but ofcourse you do not want that navigation link to display as a giant H1 on the page.
What you should do is wrap that element in an h1 tag and inspect it. See what CSS styles are being applied specifically to the h1 element.
Lets say I see the following styles applied to the element.
//bootstrap.min.css:1
h1 {
font-size: 65px;
font-family: 'rubikbold'!important;
font-weight: normal;
font-style: normal;
text-transform: uppercase;
}
//bootstrap.min.css:1
h1, .h1 {
font-size: 36px;
}
//bootstrap.min.css:1
h1, .h1, h2, .h2, h3, .h3 {
margin-top: 20px;
margin-bottom: 10px;
}
//bootstrap.min.css:1
h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
//bootstrap.min.css:1
h1 {
margin: .67em 0;
font-size: 2em;
}
//user agent stylesheet
h1 {
display: block;
font-size: 2em;
-webkit-margin-before: 0.67em;
-webkit-margin-after: 0.67em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
font-weight: bold;
}
Now you need to pin point the exact style which are applied to the H1 and unset them in a css class. This would look something like the following:
.no-style-h1 {
font-size: unset !important;
font-family: unset !important;
font-weight: unset !important;
font-style: unset !important;
text-transform: unset !important;
margin-top: unset !important;
margin-bottom: unset !important;
line-height: unset !important;
color: unset !important;
margin: unset !important;
display: unset !important;
-webkit-margin-before: unset !important;
-webkit-margin-after: unset !important;
-webkit-margin-start: unset !important;
-webkit-margin-end: unset !important;
}
This is much cleaner and does not just dump a random blob of code into your css which you don't know what it's actually doing.
Now you can add this class to your h1
<h1 class="no-style-h1">
Title
</h1>
java.util.UUID.randomUUID();
Model1.belongsTo(Model2, { as: 'alias' })
Model1.findAll({include: [{model: Model2 , as: 'alias' }]},{raw: true}).success(onSuccess).error(onError);
As rightly said by previous posts, one of way is to implement a custom basic authentication middleware. I found the best working code with explanation in this blog: Basic Auth with custom middleware
I referred the same blog but had to do 2 adaptations:
While reading the username, password from appsettings.json file, add static read only property in Startup file. Then read from appsettings.json. Finally, read the values from anywhere in the project. Example:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public static string UserNameFromAppSettings { get; private set; }
public static string PasswordFromAppSettings { get; private set; }
//set username and password from appsettings.json
UserNameFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("UserName").Value;
PasswordFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("Password").Value;
}
I haven't tried specifically getting the VM settings, but there is a wealth of information in the JMX utilities specifically the MXBean utilities. This would be where I would start. Hopefully you find something there to help you.
The sun website has a bunch on the technology:
http://java.sun.com/javase/6/docs/technotes/guides/management/mxbeans.html
I had this info message "No Spring WebApplicationInitializer types detected on classpath" while deploying a WAR with spring integration beans in WebLogic server. Actually, I could observe that the servlet URL returned 404 Not Found and beside that info message with a negative tone "No Spring ...etc" in Server logs, nothing else was seemingly in error in my spring config; no build or deployment errors, no complaints. Indeed, I suspected that the beans.xml (spring context XML) was actually not picked up at all and that was bound to the very specific organizing of artefacts in Oracle's jDeveloper. The solution is to play carefully with the 'contributors' and 'filters' for the WEB-INF/classes category when you edit your deployment profile under the 'deployment' topic in project properties.
Precisely, I would advise to name your spring context by the jDeveloper default "beans.xml" and place it side by side to the WEB-INF subdirectory itself (under your web Apllication source path, e.g. like <...your project path>/public_html/). Then in the WEB-INF/classes category (when editing the deployment profile) your can check the Project HTML root directory in the 'contributor' list, and then select the beans.xml in filters, and then ensure your web.xml features a context-param value like classpath:beans.xml.
Once that was fixed, I was able to progress and after some more bean config changes and implementations, the message "No Spring WebApplicationInitializer types detected on classpath" came back! Actually, I did not notice when and why exactly it came back. This second time, I added a
public class HttpGatewayInit implements WebApplicationInitializer { ... }
which implements empty inherited methods, and the whole application works fine!
...If you feel that java EE development has been getting a bit too crazy with cascades of XML configuration files (some edited manually, others through wizards) intepreted by cascades of variant initializers, let me insist that I fully share your point.
Agree with the Money pattern: Handling currencies is just too cumbersome when you use decimals.
If you create a Currency-class, you can then put all the logic relating to money there, including a correct ToString()-method, more control of parsing values and better control of divisions.
Also, with a Currency class, there is no chance of unintentionally mixing money up with other data.
Here is a function that I have in my PowerShell profile for loading SQL snapins:
function Load-SQL-Server-Snap-Ins
{
try
{
$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"
if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
{
throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
}
$item = Get-ItemProperty $sqlpsreg
$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
$assemblyList = @(
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.SmoExtended",
"Microsoft.SqlServer.Dmf",
"Microsoft.SqlServer.WmiEnum",
"Microsoft.SqlServer.SqlWmiManagement",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.Management.RegisteredServers",
"Microsoft.SqlServer.Management.Sdk.Sfc",
"Microsoft.SqlServer.SqlEnum",
"Microsoft.SqlServer.RegSvrEnum",
"Microsoft.SqlServer.ServiceBrokerEnum",
"Microsoft.SqlServer.ConnectionInfoExtended",
"Microsoft.SqlServer.Management.Collector",
"Microsoft.SqlServer.Management.CollectorEnum"
)
foreach ($assembly in $assemblyList)
{
$assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly)
if ($assembly -eq $null)
{ Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
}
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000
Push-Location
if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null)
{
cd $sqlpsPath
Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
Update-FormatData -PrependPath SQLProvider.Format.ps1xml
}
}
catch
{
Write-Host "`t`t$($MyInvocation.InvocationName): $_"
}
finally
{
Pop-Location
}
}
I have these two functions in my .zshrc
file:
function gitstash() {
git stash push -m "zsh_stash_name_$1"
}
function gitstashapply() {
git stash apply $(git stash list | grep "zsh_stash_name_$1" | cut -d: -f1)
}
Using them this way:
gitstash nice
gitstashapply nice
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
Hope it helps
Ensure position
is on your element and set the z-index
to a value higher than the elements you want to cover.
element {
position: fixed;
z-index: 999;
}
div {
position: relative;
z-index: 99;
}
It will probably require some more work than that but it's a start since you didn't post any code.
Make children divs inline-block
and they will position side by side:
#content {
width: 500px;
height: 500px;
}
#left, #right {
display: inline-block;
width: 45%;
height: 100%;
}
See Demo
For django forms you can do this;
form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))
It seems to me that the simplest answer is to use the sprintf
function:
sprintf(outString,"%s%d",name,age);
Here's some sample code. This worked for me.
<LinearLayout
android:gravity="center"
>
<TextView
android:layout_gravity="center"
/>
<Button
android:layout_gravity="center"
/>
</LinearLayout>
So you're designing the Linear Layout to place all its contents (TextView and Button) in its center, and then the TextView and Button are placed relative to the center of the Linear Layout.
I hope this example will be helpful for you)
print(type(None)) # NoneType
So, you can check type of the variable name
# Example
name = 12 # name = None
if type(name) is type(None):
print("Can't find name")
else:
print(name)
According to the website, sizeof()
is an alias of count()
, so they should be running the same code. Perhaps sizeof()
has a little bit of overhead because it needs to resolve it to count()
? It should be very minimal though.
You don't need --header "Content-Length: $LENGTH".
curl --request POST --data-binary "@template_entry.xml" $URL
Note that GET request does not support content body widely.
Also remember that POST request have 2 different coding schema. This is first form:
$ nc -l -p 6666 & $ curl --request POST --data-binary "@README" http://localhost:6666 POST / HTTP/1.1 User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6 Host: localhost:6666 Accept: */* Content-Length: 9309 Content-Type: application/x-www-form-urlencoded Expect: 100-continue .. -*- mode: rst; coding: cp1251; fill-column: 80 -*- .. rst2html.py README README.html .. contents::
You probably request this:
-F/--form name=content (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content- Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
Swift 4.2 and Xcode 10.1
//For mobile number validation
func isValidPhone(phone: String) -> Bool {
let phoneRegex = "^((0091)|(\\+91)|0?)[6789]{1}\\d{9}$";
let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
return valid
}
//For email validation
func isValidEmail(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
if valid {
valid = !candidate.contains("..")
}
return valid
}
Use like this
//Button Action
@IBAction func onClickRegrBtn(_ sender: UIButton) {
//Check net connection here
let networkReachability = Reachability.forInternetConnection()
let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
if networkStatus == NotReachable.rawValue {
let msg = SharedClass.sharedInstance.noNetMsg
SharedClass.sharedInstance.alert(view: self, title: "", message: msg)//Display alert message
} else {
let mobileTrimmedString = mobileNoTF.text?.trimmingCharacters(in: .whitespaces) //Trim white spaces
if mobileTrimmedString != "" {
if isValidPhone(phone: mobileTrimmedString!) == false {
SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter valid mobile number")
} else {
UserDefaults.standard.set(mobileTrimmedString, forKey: "mobile") //setObject
sendMobileNumber()//Call function...
}
} else {
mobileNoTF.text = ""
//Call alert function
SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter mobile number")
}
}
}
@ostrokach answer is best. Most likely you would want to keep that throughout any references to the dataframe, thus would benefit from inplace = True.
df.rename(columns=df.iloc[0], inplace = True)
df.drop([0], inplace = True)
THE 2019 ANSWER for macOS Sierra & High Sierra & Catalina:
PS: most of the other answers will have you to create a new ssh key ... but you don't need to do that :)
As described in detail on https://openradar.appspot.com/27348363, macOS/OS X till Yosemite used to remember SSH keys added by command ssh-add -K <key>
So here are the 4 steps i had to take in order for it to work:
1: ssh-add ~/.ssh/PATH_TO_YOUR_SSH_PRIVATE_KEY (e.g. ~/.ssh/id_rsa)
2: Add the following in ~/.ssh/config
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile PATH_TO_YOUR_SSH_PRIVATE_KEY (e.g. ~/.ssh/id_rsa)
3: make sure to remove any gitconfig entry that use osxkeychain helper:
https://github.com/gregory/dotfiles/commit/e38000527fb1a82b577f2dcf685aeefd3b78a609#diff-6cb0f77b38346e0fed47293bdc6430c6L48
4: restart your terminal for it to take effect.
one discuss found here
quote from Thomas Mueller:
http://www.dbsolo.com/
http://www.minq.se/products/dbvis/
http://executequery.org/index.jsp
http://sqldeveloper.solyp.com/index.html
http://sql-workbench.net/index.html
http://www.squirrelsql.org/
You could say defaultdict
is useful for settings defaults before filling the dict and setdefault
is useful for setting defaults while or after filling the dict.
Probably the most common use case: Grouping items (in unsorted data, else use itertools.groupby
)
# really verbose
new = {}
for (key, value) in data:
if key in new:
new[key].append( value )
else:
new[key] = [value]
# easy with setdefault
new = {}
for (key, value) in data:
group = new.setdefault(key, []) # key might exist already
group.append( value )
# even simpler with defaultdict
from collections import defaultdict
new = defaultdict(list)
for (key, value) in data:
new[key].append( value ) # all keys have a default already
Sometimes you want to make sure that specific keys exist after creating a dict. defaultdict
doesn't work in this case, because it only creates keys on explicit access. Think you use something HTTP-ish with many headers -- some are optional, but you want defaults for them:
headers = parse_headers( msg ) # parse the message, get a dict
# now add all the optional headers
for headername, defaultvalue in optional_headers:
headers.setdefault( headername, defaultvalue )
Assuming userInfoList
is a List<UserInfo>
:
var groups = userInfoList
.GroupBy(n => n.metric)
.Select(n => new
{
MetricName = n.Key,
MetricCount = n.Count()
}
)
.OrderBy(n => n.MetricName);
The lambda function for GroupBy()
, n => n.metric
means that it will get field metric
from every UserInfo
object encountered. The type of n
is depending on the context, in the first occurrence it's of type UserInfo
, because the list contains UserInfo
objects. In the second occurrence n
is of type Grouping
, because now it's a list of Grouping
objects.
Grouping
s have extension methods like .Count()
, .Key()
and pretty much anything else you would expect. Just as you would check .Lenght
on a string
, you can check .Count()
on a group.
I had an array of strings, not objects and i used this approach:
ng-repeat="name in names | unique"
with this filter:
angular.module('app').filter('unique', unique);
function unique(){
return function(arry){
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
};
if(arry === undefined || arry.length === 0){
return '';
}
else {
return arry.getUnique();
}
};
}
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
Windows environment, local machine. I had an error
[js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException:
Error connecting to 127.0.0.1:27017 :: caused by ::
No connection could be made because the target machine actively refused it. :
After some back and forth attempts I decided
The upcoming version v3.3.0 of ggplot2
will have an option n.breaks
to automatically generate breaks for scale_x_continuous
and scale_y_continuous
devtools::install_github("tidyverse/ggplot2")
library(ggplot2)
plt <- ggplot(mtcars, aes(x = mpg, y = disp)) +
geom_point()
plt +
scale_x_continuous(n.breaks = 5)
plt +
scale_x_continuous(n.breaks = 10) +
scale_y_continuous(n.breaks = 10)
Here is a working solution - http://jsfiddle.net/STTaf/
I used simple jQuery:
$(function() {
$('li').css('cursor', 'pointer')
.click(function() {
window.location = $('a', this).attr('href');
return false;
});
});
You can try using Putty (freeware). It is mainly known as a SSH client, but you can use for Telnet login as well
Unless I'm mistaken, I'd say it's to write your own function.
function findIndexOfGreatest(array) {
var greatest;
var indexOfGreatest;
for (var i = 0; i < array.length; i++) {
if (!greatest || array[i] > greatest) {
greatest = array[i];
indexOfGreatest = i;
}
}
return indexOfGreatest;
}
This script helps to change the image on click the text:
<script>
$(document).ready(function(){
$('li').click(function(){
var imgpath = $(this).attr('dir');
$('#image').html('<img src='+imgpath+'>');
});
$('.btn').click(function(){
$('#thumbs').fadeIn(500);
$('#image').animate({marginTop:'10px'},200);
$(this).hide();
$('#hide').fadeIn('slow');
});
$('#hide').click(function(){
$('#thumbs').fadeOut(500,function (){
$('#image').animate({marginTop:'50px'},200);
});
$(this).hide();
$('#show').fadeIn('slow');
});
});
</script>
<div class="sandiv">
<h1 style="text-align:center;">The Human Body Parts :</h1>
<div id="thumbs">
<div class="sanl">
<ul>
<li dir="5.png">Human-body-organ-diag-1</li>
<li dir="4.png">Human-body-organ-diag-2</li>
<li dir="3.png">Human-body-organ-diag-3</li>
<li dir="2.png">Human-body-organ-diag-4</li>
<li dir="1.png">Human-body-organ-diag-5</li>
</ul>
</div>
</div>
<div class="man">
<div id="image">
<img src="2.png" width="348" height="375"></div>
</div>
<div id="thumbs">
<div class="sanr" >
<ul>
<li dir="5.png">Human-body-organ-diag-6</li>
<li dir="4.png">Human-body-organ-diag-7</li>
<li dir="3.png">Human-body-organ-diag-8</li>
<li dir="2.png">Human-body-organ-diag-9</li>
<li dir="1.png">Human-body-organ-diag-10</li>
</ul>
</div>
</div>
<h2><a style="color:#333;" href="http://www.sanwebcorner.com/">sanwebcorner.com</a></h2>
</div>
see the demo here
Using Flexbox:
<style>
.container {
display: flex;
align-items: center; /* Vertical align */
justify-content: center; /* Horizontal align */
}
</style>
<div class="container">
<div class="block"></div>
</div>
Centers block
inside container
vertically (and horizontally).
Browser support: http://caniuse.com/flexbox
I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:
curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"
The basic idea is that each part (split by string in boundary
with --
) has it's own headers (Content-Type
in the second part, for example.) The FormData
object manages all this for you, so it's a better way to accomplish our goals.
This translates to fetch API like this:
const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')
fetch('http://localhost:5001/api/v0/add', {
method: 'POST',
body: formData
})
.then(r => r.json())
.then(data => {
console.log(data)
})
This is a bit high-level answer for applications which want to seamlessly fit into the Windows environment. Technical details of playing particular sound were provided in other answers. Besides that, always note these two points:
Use five standard system sounds in typical scenarios, i.e.
Asterisk - play when you want to highlight current event
Question - play with questions (system message box window plays this one)
Exclamation - play with excalamation icon (system message box window plays this one)
Beep (default system sound)
Critical stop ("Hand") - play with error (system message box window plays this one)
Methods of class System.Media.SystemSounds
will play them for you.
Implement any other sounds as customizable by your users in Sound control panel
Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. my Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time. Google must provide a way to deal with such a situation. As it renders many SD card aware apps (i.e card backup) failing miserably on these phones.
if you have existing project and you would like to add remote repository url then you need to do following command
git init
if you would like to add readme.md file then you can create it and add it using below command.
git add README.md
make your first commit using below command
git commit -m "first commit"
Now you completed all local repository process, now how you add remote repository url ? check below command this is for ssh url, you can change it for https.
git remote add origin [email protected]:user-name/repository-name.git
How you push your first commit see below command :
git push -u origin master
Look /etc/php5/cli/conf.d/ and delete corresponding *.ini files. This error happens when you remove some php packages not so cleanly.
You can use offsetWidth
. Refer to this post and question for more.
console.log("width:" + document.getElementsByTagName("div")[0].offsetWidth + "px");
_x000D_
div {border: 1px solid #F00;}
_x000D_
<div style="width: 100%; height: 10px;"></div>
_x000D_
In my case adding Microsoft.AspNet.WebApi.Owin reference via nuget did the trick.
You can use the below code inside your code when you get any web browser pop-up alert message box.
// Accepts (Click on OK) Chrome Alert Browser for RESET button.
Alert alertOK = driver.switchTo().alert();
alertOK.accept();
//Rejects (Click on Cancel) Chrome Browser Alert for RESET button.
Alert alertCancel = driver.switchTo().alert();
alertCancel.dismiss();
Not an exact answer because you're using xml data and there is currently no pd.read_xml()
function (as of v0.23.4), but pandas (starting with v0.21.0) can uncompress the file for you! Thanks Wes!
import pandas as pd
import os
fn = '../data/file_to_load.json.gz'
print(os.path.isfile(fn))
df = pd.read_json(fn, lines=True, compression='gzip')
df.tail()
In my case there was a mismatch between the build path JRE and installed JRE on execution environment. I moved into Project > Properties > Java compiler. There was a warning message at the bottom.
I clicked on the links 'Installed JRE', 'Execution environment', 'Java build path' and changed the JDK version to 1.7 and the warning disappeared.
The crawlers do not need a rich featured pretty styled gui, they only want to see the content, so you do not need to give them a snapshot of a page that has been built for humans.
My solution: to give the crawler what the crawler wants:
You must think of what do the crawler want, and give him only that.
TIP don't mess with the back. Just add a little server-sided frontview using the same API
The following query will get the current datetime and convert into string. with the following format yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar(25), getdate(), 120)
For the selected value: $(this).val()
If you need the selected option element, $("option:selected", this)
default_scope
This works for Rails 4+:
class Book < ActiveRecord::Base
default_scope { order(created_at: :desc) }
end
For Rails 2.3, 3, you need this instead:
default_scope order('created_at DESC')
For Rails 2.x:
default_scope :order => 'created_at DESC'
Where created_at
is the field you want the default sorting to be done on.
Note: ASC is the code to use for Ascending and DESC is for descending (desc
, NOT dsc
!).
scope
Once you're used to that you can also use scope
:
class Book < ActiveRecord::Base
scope :confirmed, :conditions => { :confirmed => true }
scope :published, :conditions => { :published => true }
end
For Rails 2 you need named_scope
.
:published
scope gives you Book.published
instead of
Book.find(:published => true)
.
Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed
.
With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.
You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:
scope :recent_books, lambda
{ |since_when| where("created_at >= ?", since_when) }
# Note the `where` is making use of AREL syntax added in Rails 3.
Finally you can disable default scope with:
Book.with_exclusive_scope { find(:all) }
or even better:
Book.unscoped.all
which will disable any filter (conditions) or sort (order by).
Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+
So
... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end
but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!
In fact they are Class level methods as they operate on the 1 set of 'all' records.
Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }
.
As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where
's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where
selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published
where published
is a named scope.
In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.
Followed Mark's advise and did this to set the default number formatting to text in the whole workbook:
$objPHPExcel = new PHPExcel();
$objPHPExcel->getDefaultStyle()
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
And it works flawlessly. Thank you, Mark Baker.
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
Surprisingly array_keys_exist
doesn't exist?! In the interim that leaves some space to figure out a single line expression for this common task. I'm thinking of a shell script or another small program.
Note: each of the following solutions use concise […]
array declaration syntax available in php 5.4+
if (0 === count(array_diff(['story', 'message', '…'], array_keys($source)))) {
// all keys found
} else {
// not all
}
(hat tip to Kim Stacks)
This approach is the most brief I've found. array_diff()
returns an array of items present in argument 1 not present in argument2. Therefore an empty array indicates all keys were found. In php 5.5 you could simplify 0 === count(…)
to be simply empty(…)
.
if (0 === count(array_reduce(array_keys($source),
function($in, $key){ unset($in[array_search($key, $in)]); return $in; },
['story', 'message', '…'])))
{
// all keys found
} else {
// not all
}
Harder to read, easy to change. array_reduce()
uses a callback to iterate over an array to arrive at a value. By feeding the keys we're interested in the $initial
value of $in
and then removing keys found in source we can expect to end with 0 elements if all keys were found.
The construction is easy to modify since the keys we're interested in fit nicely on the bottom line.
if (2 === count(array_filter(array_keys($source), function($key) {
return in_array($key, ['story', 'message']); }
)))
{
// all keys found
} else {
// not all
}
Simpler to write than the array_reduce
solution but slightly tricker to edit. array_filter
is also an iterative callback that allows you to create a filtered array by returning true (copy item to new array) or false (don't copy) in the callback. The gotchya is that you must change 2
to the number of items you expect.
This can be made more durable but verge's on preposterous readability:
$find = ['story', 'message'];
if (count($find) === count(array_filter(array_keys($source), function($key) use ($find) { return in_array($key, $find); })))
{
// all keys found
} else {
// not all
}
For what you want I would've used
app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
const name = request.params.fruitName
const color = request.params.fruitColor
});
or better yet
app.get('/fruit/:fruit', function(request, response) {
const fruit = request.params.fruit
console.log(fruit)
});
where fruit is a object. So in the client app you just call
https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}
and as a response you should see:
// client side response
// { name: My fruit name, color:The color of the fruit}
Start off by opening a cmd.exe session, changing directory to the "program files" directory that has the javac.exe executable and running .\javac.exe.
If that doesn't work, reinstall java. If that works, odds are you will find (in doing that task) that you've installed a 64 bit javac.exe
, or a slightly different release number of javac.exe
, or in a different drive, etc. and selecting the right entry in your path will become child's play.
Only use the semicolon between directories in the PATH environment variable, and remember that in some systems, you need to log out and log back in before the new environment variable is accessible to all environments.
You can use an inline if inside your ngStyle:
[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"
A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:
[style.background-color]="myColorVaraible"
If the file is really an old .xls, this works for me on python3 just using base open() and pandas:
df = pandas.read_csv(open(f, encoding = 'UTF-8'), sep='\t')
Note that the file I'm using is tab delimited. less or a text editor should be able to read .xls so that you can sniff out the delimiter.
I did not have a lot of luck with xlrd because of – I think – UTF-8 issues.
For small files:
dd if=/dev/zero of=upload_test bs=file_size count=1
Where file_size
is the size of your test file in bytes.
For big files:
dd if=/dev/zero of=upload_test bs=1M count=size_in_megabytes
I have used this in the past:
html
January<span class="right">2014</span>
Css
.right {
margin-left:100%;
}
From a little search on google the first thing I tried was this
npm config set registry http://registry.npmjs.org/
npm config set proxy "your proxy"
npm config set https-proxy "your proxy"
But still npm seemed to lose connection when trying to do "npm install"s. then I ran this line in command prompt and now I can use npm install
set NODE_TLS_REJECT_UNAUTHORIZED=0
remap
is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:
:map
and :noremap
are recursive and non-recursive versions of the various mapping commands. For example, if we run:
:map j gg (moves cursor to first line)
:map Q j (moves cursor to first line)
:noremap W j (moves cursor down one line)
Then:
j
will be mapped to gg
.Q
will also be mapped to gg
, because j
will be expanded for the recursive mapping.W
will be mapped to j
(and not to gg
) because j
will not be expanded for the non-recursive mapping.Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.
For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map
and :noremap
), one that works in normal mode (:nmap
and :nnoremap
), one in visual mode (:vmap
and :vnoremap
) and so on.
For more guidance on this, see:
:help :map
:help :noremap
:help recursive_mapping
:help :map-modes
var swap = function () {
var divs = document.getElementsByTagName('div');
var div1 = divs[0];
var div2 = divs[1];
var div3 = divs[2];
div3.parentNode.insertBefore(div1, div3);
div1.parentNode.insertBefore(div3, div2);
};
This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.
What standards peculiarities does it rely on?
insertBefore Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.
really this belongs as a comment to Nathan's answer, but I'm not allowed to do that yet...
I wanted to maintain the aspect ratio, even if there is too much stuff to fit in the box. His example expands the height, changing the aspect ratio. I found adding
overflow: hidden;
overflow-x: auto;
overflow-y: auto;
to the .element helped. See http://jsfiddle.net/B8FU8/3111/
Well, in addition to all the answers, I am just adding an example.
As others said API stands for Application Programming Interface
through which softwares can interact with each other
. Note, not a human interaction.
Where it is used
An example: You are buying an item online through your credit card. You will provide credit card details and press 'continue' button. It will tell you whether your information is correct or not. To provide these results, there are lot of things in the background.
The application will send your credit card details to a remote application which will validate your information and send the result back to your application. API is used in this scenario.
I hope it helps for the beginners who don't understand really what API is.
ANOTHER EXAMPLE
Weather application
Without API - Weather application must open weather.com site and read the details as a human does.
With API - Weather application will send a message to weather.com and receive the result and then display it.
SOURCE - Various online resources
The Instant
class doesn't contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC.
So, formatter can't print a date because date always printed for concrete time zone.
You should set time zone to formatter and all will be fine, like this :
Instant instant = Instant.ofEpochMilli(92554380000L);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);
assert formatter.format(instant).equals("07/12/72 05:33");
assert instant.toString().equals("1972-12-07T05:33:00Z");
It seems the answers here do not support an enterprise use case where a Nexus server has multiple users and has project-based isolation (protection) based on user id ALONG with using an automated build (CI) system like Jenkins. You would not be able to create a settings.xml file to satisfy the different user ids needed for different projects. I am not sure how to solve this, except by opening Nexus up to anonymous access for reading repositories, unless the projects could store a project-specific generic user id in their pom.xml.
this works for me
String body = json.encode(data);
http.Response response = await http.post(
url: 'https://example.com',
headers: {"Content-Type": "application/json"},
body: body,
);
my form:
<form method="post" action="radio.php">
select your gender:
<input type="radio" name="radioGender" value="female">
<input type="radio" name="radioGender" value="male">
<input type="submit" name="btnSubmit" value="submit">
</form>
my php:
<?php
if (isset($_POST["btnSubmit"])) {
if (isset($_POST["radioGender"])) {
$answer = $_POST['radioGender'];
if ($answer == "female") {
echo "female";
} else {
echo "male";
}
}else{
echo "please select your gender";
}
}
?>
An example of an IF Statement that can be used to add a calculation into the cell you wish to hide if value = 0 but displayed upon another cell value reference.
=IF(/Your reference cell/=0,"",SUM(/Here you put your SUM/))
You can simply use background
CSS property as follows:
tr:hover{
background: #F1F1F2;
}
This is an improved version of the recursive GetAllControls() that actually works on private vars:
private void Test()
{
List<Control> allTextboxes = GetAllControls(this);
}
private List<Control> GetAllControls(Control container, List<Control> list)
{
foreach (Control c in container.Controls)
{
if (c is TextBox) list.Add(c);
if (c.Controls.Count > 0)
list = GetAllControls(c, list);
}
return list;
}
private List<Control> GetAllControls(Control container)
{
return GetAllControls(container, new List<Control>());
}
the easiest way to do that in angular or angularjs without external modules or directives is using list and datalist HTML5. You just get a json and use ng-repeat for feeding the options in datalist. The json you can fetch it from ajax.
in this example:
then you can add filters and orderby in the ng-reapet
!! list and datalist id must have the same name !!
<input type="text" list="autocompleList" ng-model="ctrl.query" placeholder={{ctrl.msg}}>
<datalist id="autocompleList">
<option ng-repeat="Ids in ctrl.dataList value={{Ids}} >
</datalist>
UPDATE : is native HTML5 but be carreful with the type browser and version. check it out : https://caniuse.com/#search=datalist.
The function is max
. To obtain the first maximum value you should do
[val, idx] = max(a);
val
is the maximum value and idx
is its index.
This link should get you started. Long story short, a div that has been styled to look like a scrollbar is used to catch click-and-drag events. Wired up to these events are methods that scroll the contents of another div which is set to an arbitrary height and typically has a css rule of overflow:scroll (there are variants on the css rules but you get the idea).
I'm all about the learning experience -- but after you've learned how it works, I recommend using a library (of which there are many) to do it. It's one of those "don't reinvent" things...
The following also worked for me. ISO 8859-1 is going to save a lot, hahaha - mainly if using Speech Recognition APIs.
Example:
file = open('../Resources/' + filename, 'r', encoding="ISO-8859-1");
A file with associated buffering is called a stream and is declared to be a pointer to a defined type FILE. The fopen() function creates certain descriptive data for a stream and returns a pointer to designate the stream in all further transactions. Normally there are three open streams with constant pointers declared in the header and associated with the standard open files. At program startup three streams are predefined and need not be opened explicitly: standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). When opened the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device
Using name on a select option is not valid.
Other have suggested the data- attribute, an alternative is a lookup table
Here the "this" refers to the select so no need to "find" the option
var names = ["", "acoustic", "jazz", "acoustic_jazz", "party", "acoustic_party", "jazz_party", "acoustic_jazz_party"];_x000D_
_x000D_
$(function() {_x000D_
$('#band_type_choices').on('change', function() {_x000D_
$('.checkboxlist').hide();_x000D_
var idx = this.selectedIndex;_x000D_
if (idx > 0) $('#checkboxlist_' + names[idx]).show();_x000D_
});_x000D_
});
_x000D_
.checkboxlist { display:none }
_x000D_
Choose acoustic to see the corresponding div_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="band_type_choices">_x000D_
<option vlaue="0"></option>_x000D_
<option value="100" name="acoustic">Acoustic</option>_x000D_
<option value="0" name="jazz">Jazz/Easy Listening</option>_x000D_
<option value="0" name="acoustic_jazz">Acoustic + Jazz/Easy Listening</option>_x000D_
<option value="0" name="party">Party</option>_x000D_
<option value="0" name="acoustic_party">Acoustic + Party</option>_x000D_
<option value="0" name="jazz_party">Jazz/Easy Listening + Party</option>_x000D_
<option value="0" name="acoustic_jazz_party">Acoustic + Jazz/Easy Listening + Party</option>_x000D_
</select>_x000D_
<div class="checkboxlist" id="checkboxlist_acoustic">_x000D_
<input type="checkbox" class="checkbox keys" name="keys" value="100" />Keys<br>_x000D_
<input type="checkbox" class="checkbox acou_guit" name="acou_guit" value="100" />Acoustic Guitar<br>_x000D_
<input type="checkbox" class="checkbox drums" name="drums" value="100" />Drums<br>_x000D_
<input type="checkbox" class="checkbox alt_sax" name="alt_sax" value="100" />Alto Sax<br>_x000D_
<input type="checkbox" class="checkbox ten_sax" name="ten_sax" value="100" />Tenor Sax<br>_x000D_
<input type="checkbox" class="checkbox clarinet" name="clarinet" value="100" />Clarinet<br>_x000D_
<input type="checkbox" class="checkbox trombone" name="trombone" value="100" />Trombone<br>_x000D_
<input type="checkbox" class="checkbox trumpet" name="trumpet" value="100" />Trumpet<br>_x000D_
<input type="checkbox" class="checkbox flute" name="flute" value="100" />Flute<br>_x000D_
<input type="checkbox" class="checkbox cello" name="cello" value="100" />Cello<br>_x000D_
<input type="checkbox" class="checkbox violin" name="violin" value="100" />Violin<br>_x000D_
</div>
_x000D_
I often load the dict into a pandas DataFrame then use the plot function of the DataFrame.
Here is the one-liner:
pandas.DataFrame(D, index=['quantity']).plot(kind='bar')
myfun <- function(x, arg1) {
# doing something here with x and arg1
}
x
is a vector or a list and myfun
in lapply(x, myfun)
is called for each element of x
separately.
Option 1
If you'd like to use whole arg1
in each myfun
call (myfun(x[1], arg1)
, myfun(x[2], arg1)
etc.), use lapply(x, myfun, arg1)
(as stated above).
Option 2
If you'd however like to call myfun
to each element of arg1
separately alongside elements of x
(myfun(x[1], arg1[1])
, myfun(x[2], arg1[2])
etc.), it's not possible to use lapply
. Instead, use mapply(myfun, x, arg1)
(as stated above) or apply
:
apply(cbind(x,arg1), 1, myfun)
or
apply(rbind(x,arg1), 2, myfun).
These are several ways to apply style to an element. Try any one of the examples below:
1. document.getElementById('div_register').className = 'wide';
/* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';
If you do not need the SSL security then you might want to switch it off.
/**
* disable SSL
*/
private void disableSslVerification() {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
}
} };
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
Try:
select concat(first_name,last_name) as "Name" from test.student
or, better:
select concat(first_name," ",last_name) as "Name" from test.student
StartsWith
a) left(@edition, 15) = 'Express Edition'
b) charindex('Express Edition', @edition) = 1
Contains
charindex('Express Edition', @edition) >= 1
Examples
left
function
set @isExpress = case when left(@edition, 15) = 'Express Edition' then 1 else 0 end
iif
function (starting with SQL Server 2012)
set @isExpress = iif(left(@edition, 15) = 'Express Edition', 1, 0);
charindex
function
set @isExpress = iif(charindex('Express Edition', @edition) = 1, 1, 0);
The way /* B */
is fine in C++ also the C++0x is going to extend the syntax so it is useful for C++ containers too. I do not understand why you call it bad style?
If you want to indicate parameters with names then you can use boost parameter library, but it may confuse someone unfamiliar with it.
Reordering struct members is like reordering function parameters, such refactoring may cause problems if you don't do it very carefully.
I think this is what you're looking for:
Follow this one
$teacher_id = '';
for ($i = 0; $i < count($data['teacher_id']); $i++) {
$teacher_id .= $data['teacher_id'][$i].',';
}
$teacher_id = rtrim($teacher_id, ',');
echo $teacher_id; exit;
No it doesn't. I would expect this in a future api release, but for now we are stuck with EditText. Another option is this library:
https://github.com/marvinlabs/android-floatinglabel-widgets
Deleting the entire local m2 repo may not be advisable. As in my case I have hundreds and hundreds of jars in my local, I don't want to re-download them all just for one jar. Most of the above answers didn't work for me, here is what I did.
STEP:1: Ensure if you are downloading from the correct Maven repo in you settings.xml. In my case it was referring to http://central.maven.org/maven2/ as https://repo1.maven.org/maven2/. So it was getting corrupted or going otherwise?
STEP:2: Delete the folder containing the artifact and other details in your local machine.This will force it download it again upon next build
STEP:3: mvn clean install :).
Hope it helps.
require('url').parse('/status?name=ryan', {parseQueryString: true}).query
returns
{ name: 'ryan' }
I've tried everything, my problem was that the image picker for the camera and photo library disappeared right after they showed. I solved it with the following line (swift)
imagePicker.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
I ran into a case where I got that error message and had
Foo foo(Bar());
and was basically trying to pass in a temporary Bar object to the Foo constructor. Turns out the compiler was translating this to
Foo foo(Bar(*)());
that is, a function declaration whose name is foo that returns a Foo that takes in an argument -- a function pointer returning a Bar with 0 arguments. When passing in temporaries like this, better to use Bar{}
instead of Bar()
to eliminate ambiguity.
All objects in java are passed to functions by reference copy except primitives.
In effect, this means that you are sending a copy of the pointer to the original object rather than a copy of the object itself.
Please leave a comment if you want an example to understand this.
use a trigges it will work:-
->CREATE TRIGGER trigger_name BEFORE INSERT ON table_name
FOR EACH ROW SET NEW.column_name3 = NEW.column_name1 + NEW.column_name2;
this will only work only when you will insert a row in table not when you will be updating your table for such a pupose create another trigger of different name and use UPDATE on the place of INSERT in the above syntax
os.path.commonprefix() and os.path.relpath() are your friends:
>>> print os.path.commonprefix(['/usr/var/log', '/usr/var/security'])
'/usr/var'
>>> print os.path.commonprefix(['/tmp', '/usr/var']) # No common prefix: the root is the common prefix
'/'
You can thus test whether the common prefix is one of the paths, i.e. if one of the paths is a common ancestor:
paths = […, …, …]
common_prefix = os.path.commonprefix(list_of_paths)
if common_prefix in paths:
…
You can then find the relative paths:
relative_paths = [os.path.relpath(path, common_prefix) for path in paths]
You can even handle more than two paths, with this method, and test whether all the paths are all below one of them.
PS: depending on how your paths look like, you might want to perform some normalization first (this is useful in situations where one does not know whether they always end with '/' or not, or if some of the paths are relative). Relevant functions include os.path.abspath() and os.path.normpath().
PPS: as Peter Briggs mentioned in the comments, the simple approach described above can fail:
>>> os.path.commonprefix(['/usr/var', '/usr/var2/log'])
'/usr/var'
even though /usr/var
is not a common prefix of the paths. Forcing all paths to end with '/' before calling commonprefix()
solves this (specific) problem.
PPPS: as bluenote10 mentioned, adding a slash does not solve the general problem. Here is his followup question: How to circumvent the fallacy of Python's os.path.commonprefix?
PPPPS: starting with Python 3.4, we have pathlib, a module that provides a saner path manipulation environment. I guess that the common prefix of a set of paths can be obtained by getting all the prefixes of each path (with PurePath.parents()
), taking the intersection of all these parent sets, and selecting the longest common prefix.
PPPPPS: Python 3.5 introduced a proper solution to this question: os.path.commonpath()
, which returns a valid path.
You can use the function getBBox() to get the bounding box for the path. This will give you the position and size of the tightest rectangle that could contain the rendered path.
An advantage of using this method over reading the x and y values is that it will work with all graphical objects. There are more objects than paths that do not have x and y, for example circles that have cx and cy instead.
HTML5 File input has accept attribute and also multiple attribute. By using multiple attribute you can upload multiple images in an instance.
<input type="file" multiple accept="image/*">
You can also limit multiple mime types.
<input type="file" multiple accept="image/*,audio/*,video/*">
and another way of checking mime type using file object.
file object gives you name,size and type.
var files=e.target.files;
var mimeType=files[0].type; // You can get the mime type
You can also restrict the user for some file types to upload by the above code.
In order to reload/re-render/refresh component, stop the long codings. There is a Vue.JS way of doing that.
Just use :key
attribute.
For example:
<my-component :key="unique" />
I am using that one in BS Vue Table Slot. Telling that I will do something for this component so make it unique.
\sf
function_name in psql yields editable source code of a single function.
From https://www.postgresql.org/docs/9.6/static/app-psql.html:
\sf[+] function_description This command fetches and shows the definition of the named function, in the form of a CREATE OR REPLACE FUNCTION command.
If + is appended to the command name, then the output lines are numbered, with the first line of the function body being line 1.
A similar issue happened to me after I a completely reinstalled Python. Opening the settings.json
by Ctrl+ ? Shift+P:
and I saw that I had set the default linter to
"python.linting.pylintPath": "pylint_django"
so opening a terminal (e.g., Ctrl + ?Shift + ~) and the installing
pip install pylint_django
solved the problem.
The each
function iterates over an array, calling the supplied function once per element, and setting this
to the active element. This:
function countdown() {
alert(this + "..");
}
$([5, 4, 3, 2, 1]).each(countdown);
will alert 5..
then 4..
then 3..
then 2..
then 1..
Map on the other hand takes an array, and returns a new array with each element changed by the function. This:
function squared() {
return this * this;
}
var s = $([5, 4, 3, 2, 1]).map(squared);
would result in s being [25, 16, 9, 4, 1]
.
Try redirecting the output like this:
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1
I had this same problem on Ubuntu 19.10 LTS.
To solve this I ran the following command:
$ sudo apt install node-typescript
After that, I was able to use tsc
.
var d = new DirectoryInfo(@"C:\logs");
var list = d.GetFiles("*.txt").Select(m => m.Name).ToList();
In one line:
text if not text.endswith(suffix) or len(suffix) == 0 else text[:-len(suffix)]
Here is my code without using eval
. Its easy to understand too.
function value(obj, props) {
if (!props) return obj;
var propsArr = props.split('.');
var prop = propsArr.splice(0, 1);
return value(obj[prop], propsArr.join('.'));
}
var obj = { a: { b: '1', c: '2', d:{a:{b:'blah'}}}};
console.log(value(obj, 'a.d.a.b')); //returns blah
I found a solution to this. It's bloody witchcraft, but it works.
When you install the client, open Control Panel > Network Connections.
You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).
Right Click it, click Enable.
The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.
Here is a solution for the single column search using PATINDEX.
It also displays the StartPosition, InvalidCharacter and ASCII code.
select line,
patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line) as [Position],
substring(line,patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line),1) as [InvalidCharacter],
ascii(substring(line,patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line),1)) as [ASCIICode]
from staging.APARMRE1
where patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line) >0
Most commands allow args to come in any order. Just move the commented flags to the end of the line:
ls -l -a /etc # -F is turned off
Then to turn it back on, just uncomment and remove the text:
ls -l -a /etc -F
Well, this question was asked and answered way back in 2011, but there is nullptr
in C++11. That's all I'm using currently.
You can read more from Stack Overflow and also from this article.
Try:
AssetFileDescriptor afd = getAssets().openFd(fileName);
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(), afd.getLength());
Update 2018
Since the original answer HTML5 validation is now supported in all modern browsers. Now the easiest way to make a field required is simply using the required attibute.
<input type="email" class="form-control" id="exampleInputEmail1" required>
or in compliant HTML5:
<input type="email" class="form-control" id="exampleInputEmail1" required="true">
Read more on Bootstrap 4 validation
In Bootstrap 3, you can apply a "validation state" class to the parent element: http://getbootstrap.com/css/#forms-control-validation
For example has-error
will show a red border around the input. However, this will have no impact on the actual validation of the field. You'd need to add some additional client (javascript) or server logic to make the field required.
Demo: http://bootply.com/90564
Just to confirm though you probably did...
Did you include the
<!-- tell spring to use annotation based congfigurations -->
<context:annotation-config />
<!-- tell spring where to find the beans -->
<context:component-scan base-package="zz.yy.abcd" />
bits in your application context.xml?
Also I'm not so sure you'd be able to use a jta transaction type with this kind of setup? Wouldn't that require a data source managed connection pool? So try RESOURCE_LOCAL instead.
For parsing command line arguments on posix systems, the standard is to use the getopt()
family of library routines to handle command line arguments.
A good reference is the GNU getopt manual
Try using download manager, which can help you download everything you want and save you time.
Check those to options:
Option 1 ->
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
Option 2 ->
if(mWebview.getUrl().contains(".mp3") {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
// You can change the name of the downloads, by changing "download" to everything you want, such as the mWebview title...
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
You can use JS as below:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('elementid').focus();");
I solve this in my VB app with a simple tiny function (one line). Code taken out of a production app. The function looks like this:
Public Function MySQLDateTimeVar(inDate As Date, inTime As String) As String Return "'" & inDate.ToString(format:="yyyy'-'MM'-'dd") & " " & inTime & "'" End Function
Usage: Let's say I have DateTimePicker1 and DateTimePicker2 and the user must define a start date and an end date. No matter if the dates are the same. I need to query a DATETIME field using only the DATE. My query string is easily built like this:
Dim QueryString As String = "Select * From SOMETABLE Where SOMEDATETIMEFIELD BETWEEN " & MySQLDateTimeVar(DateTimePicker1.Value,"00:00:00") & " AND " & MySQLDateTimeVar(DateTimePicker2.Value,"23:59:59")
The function generates the correct MySQL DATETIME syntax for DATETIME fields in the query and the query returns all records on that DATE (or BETWEEN the DATES) correctly.