I stopped the rails server, ran rake db:migrate
and started my rails s
.
I'm not amazing at PHP, but I think this is what you do:
$password = md5($password)
and $password
would be the $_POST['password']
or whatever
Just to offer some variety, the comma operator can be used too but some might say "noooooo!", but it works:
<input type="button" onclick="one(), two(), three(), four()"/>
For workdays, Monday to Friday, you can do it with a single SELECT, like this:
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2008/10/01'
SET @EndDate = '2008/10/31'
SELECT
(DATEDIFF(dd, @StartDate, @EndDate) + 1)
-(DATEDIFF(wk, @StartDate, @EndDate) * 2)
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
If you want to include holidays, you have to work it out a bit...
It's all about editing the cell, the problem that is the cell didn't edited actually, so you need to save The changes of the cell or the row to get the event when you click the check box so you can use this function:
datagridview.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange)
with this you can use it even with a different event.
You need to make sure the frame is fully loaded the best way to do it is to use onload:
<iframe id="nesgt" src="" onload="custom()"></iframe>
function custom(){
document.getElementById("nesgt").contentWindow.document;
}
this function will run automatically when the iframe is fully loaded.
it could be done with setTimeout but we can't get the exact time of the frame load.
hope this helps someone.
If your array is actually a set of JQuery objects, what about simply using the .filter() method ?
purposeObjects.filter('[purpose="daily"]')
Try this (I'm using SASS):
.carousel {
max-height: 700px;
overflow: hidden;
.item img {
width: 100%;
height: auto;
}
}
You can wrap the .carousel
into a .container
if you wish.
If you have the product's ID you can use that to create a product object:
$_product = wc_get_product( $product_id );
Then from the object you can run any of WooCommerce's product methods.
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
Update
Please review the Codex article on how to write your own shortcode.
Integrating the WooCommerce product data might look something like this:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = "price = " . $_product->get_price();
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
Your shortcode would then look like [woocommerce_price id="99"]
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
Those commands use different output streams. By default both messages will be printed on console but it's possible for example to redirect one or both of these to a file.
java MyApp 2>errors.txt
This will redirect System.err
to errors.txt
file.
I have once written a little SQL*Plus script that uses dbms_sql
and dbms_output
to create a csv (actually an ssv). You can find it on my githup repository.
If they are .NET created services you can use the installutil.exe with the /u switch its in the .net framework folder like C:\Windows\Microsoft.NET\Framework64\v2.0.50727
In C, a void *
can be converted to a pointer to an object of a different type without an explicit cast:
void abc(void *a, int b)
{
int *test = a;
/* ... */
This doesn't help with writing your function in a more generic way, though.
You can't dereference a void *
with converting it to a different pointer type as dereferencing a pointer is obtaining the value of the pointed-to object. A naked void
is not a valid type so derefencing a void *
is not possible.
Pointer arithmetic is about changing pointer values by multiples of the sizeof
the pointed-to objects. Again, because void
is not a true type, sizeof(void)
has no meaning so pointer arithmetic is not valid on void *
. (Some implementations allow it, using the equivalent pointer arithmetic for char *
.)
I used the code of @Spajus and wrote a more extended jQuery plugin.
I wrote these four jQuery functions:
upperFirstAll()
to capitalize ALL words in an inputfieldupperFirst()
to capitalize only the FIRST wordupperCase()
to convert the hole text to upper caselowerCase()
to convert the hole text to lower caseYou can use and chain them like any other jQuery function:
$('#firstname').upperFirstAll()
My complete jQuery plugin:
(function ($) {
$.fn.extend({
// With every keystroke capitalize first letter of ALL words in the text
upperFirstAll: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// With every keystroke capitalize first letter of the FIRST word in the text
upperFirst: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to lowercase
lowerCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase());
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to uppercase
upperCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toUpperCase());
box.setSelectionRange(start, end);
});
return this;
}
});
}(jQuery));
Groetjes :)
So, you may use
Yii::app()->getBaseUrl(true)
to get an Absolute webroot url, and strip the http[s]://
jQuery's CSS manipulation isn't queued, but you can make it executed inside the 'fx' queue by doing:
$('#div').delay(1000).queue('fx', function() { $(this).removeClass('error'); });
Quite same thing as calling setTimeout but uses jQuery's queue mecanism instead.
I have tried to compile everything that needs to be done for self-hosting icons in my answer. You need to follow these 4 simple steps.
Open the iconfont folder of the materialize repository
link- https://github.com/google/material-design-icons/tree/master/iconfont
Download these three icons files ->
MaterialIcons-Regular.woff2 - format('woff2')
MaterialIcons-Regular.woff - format('woff')
MaterialIcons-Regular.ttf - format('truetype');
Note- After Download you can rename it to whatever you like.
Now, go to your CSS and add this code
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: url(MaterialIcons-Regular.eot); /* For IE6-8 */
src: local('Material Icons'),
local('MaterialIcons-Regular'),
url(MaterialIcons-Regular.woff2) format('woff2'),
url(MaterialIcons-Regular.woff) format('woff'),
url(MaterialIcons-Regular.ttf) format('truetype');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px; /* Preferred icon size */
display: inline-block;
line-height: 1;
text-transform: none;
letter-spacing: normal;
word-wrap: normal;
white-space: nowrap;
direction: ltr;
/* Support for all WebKit browsers. */
-webkit-font-smoothing: antialiased;
/* Support for Safari and Chrome. */
text-rendering: optimizeLegibility;
/* Support for Firefox. */
-moz-osx-font-smoothing: grayscale;
/* Support for IE. */
font-feature-settings: 'liga';
}
_x000D_
Note : The address provided in src:url(...) should be with respect to the 'CSS File' and not the index.html file. For example it can be src : url(../myicons/MaterialIcons-Regular.woff2)
<i class="material-icons">face</i>
_x000D_
Click here to see all the icons that can be used.
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
You want the CASE statement
WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber)=1 THEN @OrderNumber ELSE '%' + @OrderNumber END
In our case, the problem was a clone that wrote a .git/config
file which contained a url entry that was a read only access method. Changing the url from the ://
method to the @
method fixed the problem.
Running git remote -v
illuminated the issue some.
As found on this website So Let’s begin by installing jEnv
Run this in the terminal
brew install https://raw.github.com/gcuisinier/jenv/homebrew/jenv.rb
Add jEnv to the bash profile
if which jenv > /dev/null; then eval "$(jenv init -)"; fi
When you first install jEnv will not have any JDK associated with it.
For example, I just installed JDK 8 but jEnv does not know about it. To check Java versions on jEnv
At the moment it only found Java version(jre) on the system. The *
shows the version currently selected. Unlike rvm and rbenv, jEnv cannot install JDK for you. You need to install JDK manually from Oracle website.
Install JDK 6 from Apple website. This will install Java in /System/Library/Java/JavaVirtualMachines/
. The reason we are installing Java 6 from Apple website is that SUN did not come up with JDK 6 for MAC, so Apple created/modified its own deployment version.
Similarly install JDK7 and JDK8.
Add JDKs to jEnv.
JDK 6:
Check the java versions installed using jenv
So now we have 3 versions of Java on our system. To set a default version use the command
jenv local <jenv version>
Ex – I wanted Jdk 1.6 to start IntelliJ
jenv local oracle64-1.6.0.65
check the java version
That’s it. We now have multiple versions of java and we can switch between them easily. jEnv also has some other features, such as wrappers for Gradle, Ant, Maven, etc, and the ability to set JVM options globally or locally. Check out the documentation for more information.
Addendum: No one mentioned "Populate" --- it is very much worth your time and money looking at Mongooses Populate Method : Also explains cross documents referencing
For the following statement shared by Alex Booker in their answer
When the compiler encounters an expression-bodied property member, it essentially converts it to a getter like this:
Please see the following screenshot, it shows how this statement (using SharpLab link)
public string APIBasePath => Configuration.ToolsAPIBasePath;
converts to
public string APIBasePath
{
get
{
return Configuration.ToolsAPIBasePath;
}
}
The only viable solution in my opinion is to use
ID INT IDENTITY(1,1)
column to get SQL Server to handle the automatic increment of your numeric valueSo try this:
CREATE TABLE dbo.tblUsers
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblUsers
without specifying values for ID
or UserID
:
INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID
value, and UserID
will contain values like UID00000001
, UID00000002
,...... and so on - automatically, safely, reliably, no duplicates.
Update: the column UserID
is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:
Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.
<object data="html/stuff_to_include.html">
Your browser doesn’t support the object tag.
</object>
more info at http://www.w3schools.com/tags/tag_object.asp
If you were trying to do what I imagine you were trying to do, then you only have to treat scope like a regular JS object.
This is what I use for an API success response for JSON data array...
function(data){
$scope.subjects = [];
$.each(data, function(i,subject){
//Store array of data types
$scope.subjects.push(subject.name);
//Split data in to arrays
$scope[subject.name] = subject.data;
});
}
Now {{subjects}} will return an array of data subject names, and in my example there would be a scope attribute for {{jobs}}, {{customers}}, {{staff}}, etc. from $scope.jobs, $scope.customers, $scope.staff
Use that piece of code, that will give you all the color and zooming control of google map. (scaleControl: false and scrollwheel: false will prevent the mousewheel from zoom up or down)
function initMap() {_x000D_
// Styles a map in night mode._x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
center: {lat: 23.684994, lng: 90.356331},_x000D_
zoom: 8,_x000D_
scaleControl: false,_x000D_
scrollwheel: false,_x000D_
styles: [_x000D_
{elementType: 'geometry', stylers: [{color: 'F1F2EC'}]},_x000D_
{elementType: 'labels.text.stroke', stylers: [{color: '877F74'}]},_x000D_
{elementType: 'labels.text.fill', stylers: [{color: '877F74'}]},_x000D_
{_x000D_
featureType: 'administrative.locality',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#d59563'}]_x000D_
},_x000D_
{_x000D_
featureType: 'poi',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#d59563'}]_x000D_
},_x000D_
{_x000D_
featureType: 'poi.park',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: '#263c3f'}]_x000D_
},_x000D_
{_x000D_
featureType: 'poi.park',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#f77c2b'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: 'F5DAA6'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road',_x000D_
elementType: 'geometry.stroke',_x000D_
stylers: [{color: '#212a37'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#f77c2b'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road.highway',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: '#746855'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road.highway',_x000D_
elementType: 'geometry.stroke',_x000D_
stylers: [{color: 'F5DAA6'}]_x000D_
},_x000D_
{_x000D_
featureType: 'road.highway',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: 'F5DAA6'}]_x000D_
},_x000D_
{_x000D_
featureType: 'transit',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: '#2f3948'}]_x000D_
},_x000D_
{_x000D_
featureType: 'transit.station',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#f77c2b3'}]_x000D_
},_x000D_
{_x000D_
featureType: 'water',_x000D_
elementType: 'geometry',_x000D_
stylers: [{color: '#0676b6'}]_x000D_
},_x000D_
{_x000D_
featureType: 'water',_x000D_
elementType: 'labels.text.fill',_x000D_
stylers: [{color: '#515c6d'}]_x000D_
},_x000D_
{_x000D_
featureType: 'water',_x000D_
elementType: 'labels.text.stroke',_x000D_
stylers: [{color: '#17263c'}]_x000D_
}_x000D_
]_x000D_
});_x000D_
_x000D_
var marker = new google.maps.Marker({_x000D_
position: {lat: 23.684994, lng: 90.356331},_x000D_
map: map,_x000D_
title: 'BANGLADESH'_x000D_
});_x000D_
}
_x000D_
Though both the sorts are O(N^2).The hidden constants are much smaller in Insertion sort.Hidden constants refer to the actual number of primitive operations carried out.
When insertion sort has better running time?
Notice that insertion sort is not always better than bubble sort.To get the best of both worlds, you can use insertion sort if array is of small size, and probably merge sort(or quicksort) for larger arrays.
If none of the answers worked for you. You might be in the wrong "Window". I was in "Package explorer" and switching to "Project Explorer" showed me the folders.
if you are using Mac OS X here is a fix: Open terminal and run this command
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log restart
and for other OS just restart your Postgresql server, it will solve
Then start pgAdmin4, it will start as normal
Share or comment if saved someone
I simply do this:
UIWebView *webView = [[[UIWebView alloc] init] autorelease];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
Where "index.html" relatively references images, CSS, javascript, etc.
Wood-eye be careful. After seeing the consequences after applying the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:
Let's start with the shortest, but very strict way:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
var parseBool = function(str)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
return false;
if (typeof str === 'boolean')
{
return (str === true);
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq: if seq: No: if len(seq): if not len(seq):
You need to specify the append open mode like
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}
Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .
using (var client = new System.Net.Http.HttpClient())
{
return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}
I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.
However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
This post will go through the following topics:
merge
, join
, concat
There are a few options, some simpler than others depending on the use case.
DataFrame.merge
withleft_index
andright_index
(orleft_on
andright_on
using names indexes)
- supports inner/left/right/full
- can only join two at a time
- supports column-column, index-column, index-index joins
DataFrame.join
(join on index)
- supports inner/left (default)/right/full
- can join multiple DataFrames at a time
- supports index-index joins
pd.concat
(joins on index)
- supports inner/full (default)
- can join multiple DataFrames at a time
- supports index-index joins
Setup & Basics
import pandas as pd
import numpy as np
np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)},
index=['A', 'B', 'C', 'D'])
right = pd.DataFrame(data={'value': np.random.randn(4)},
index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'
left
value
idxkey
A -0.602923
B -0.402655
C 0.302329
D -0.524349
right
value
idxkey
B 0.543843
D 0.013135
E -0.326498
F 1.385076
Typically, an inner join on index would look like this:
left.merge(right, left_index=True, right_index=True)
value_x value_y
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
Other joins follow similar syntax.
Notable Alternatives
DataFrame.join
defaults to joins on the index. DataFrame.join
does a LEFT OUTER JOIN by default, so how='inner'
is necessary here.
left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
value_x value_y
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
Note that I needed to specify the lsuffix
and rsuffix
arguments since join
would otherwise error out:
left.join(right)
ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
Since the column names are the same. This would not be a problem if they were differently named.
left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
leftvalue value
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
pd.concat
joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner'
is required here..
pd.concat([left, right], axis=1, sort=False, join='inner')
value value
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
For more information on concat
, see this post.
To perform an inner join using index of left, column of right, you will use DataFrame.merge
a combination of left_index=True
and right_on=...
.
right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
colkey value
0 B 0.543843
1 D 0.013135
2 E -0.326498
3 F 1.385076
left.merge(right2, left_index=True, right_on='colkey')
value_x colkey value_y
0 -0.402655 B 0.543843
1 -0.524349 D 0.013135
Other joins follow a similar structure. Note that only merge
can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.
join
and concat
are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index
.
If your index is named, then from pandas >= 0.23, DataFrame.merge
allows you to specify the index name to on
(or left_on
and right_on
as necessary).
left.merge(right, on='idxkey')
value_x value_y
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
For the previous example of merging with the index of left, column of right, you can use left_on
with the index name of left:
left.merge(right2, left_on='idxkey', right_on='colkey')
value_x colkey value_y
0 -0.402655 B 0.543843
1 -0.524349 D 0.013135
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
ElementTree is a good module for reading xml and writing too e.g.
from xml.etree.ElementTree import Element, SubElement, tostring
root = Element('root')
child = SubElement(root, "child")
child.text = "I am a child"
print(tostring(root))
Output:
<root><child>I am a child</child></root>
See this tutorial for more details and how to pretty print.
Alternatively if your XML is simple, do not underestimate the power of string formatting :)
xmlTemplate = """<root>
<person>
<name>%(name)s</name>
<address>%(address)s</address>
</person>
</root>"""
data = {'name':'anurag', 'address':'Pune, india'}
print xmlTemplate%data
Output:
<root>
<person>
<name>anurag</name>
<address>Pune, india</address>
</person>
</root>
You can use string.Template or some template engine too, for complex formatting.
For this kind of issue, I ended up in putting @Service
annotation on the newly created service class then the autowire was picked up.
So, try to check those classes which are not getting autowired, if they need the corresponding required annotations(like @Controller
, @Service
, etc.) applied to them and then try to build the project again.
I created a very simple solution without using any frameworks or APIs. This looks more elegant and understandable. The class is called TimeoutBlock.
public class TimeoutBlock {
private final long timeoutMilliSeconds;
private long timeoutInteval=100;
public TimeoutBlock(long timeoutMilliSeconds){
this.timeoutMilliSeconds=timeoutMilliSeconds;
}
public void addBlock(Runnable runnable) throws Throwable{
long collectIntervals=0;
Thread timeoutWorker=new Thread(runnable);
timeoutWorker.start();
do{
if(collectIntervals>=this.timeoutMilliSeconds){
timeoutWorker.stop();
throw new Exception("<<<<<<<<<<****>>>>>>>>>>> Timeout Block Execution Time Exceeded In "+timeoutMilliSeconds+" Milli Seconds. Thread Block Terminated.");
}
collectIntervals+=timeoutInteval;
Thread.sleep(timeoutInteval);
}while(timeoutWorker.isAlive());
System.out.println("<<<<<<<<<<####>>>>>>>>>>> Timeout Block Executed Within "+collectIntervals+" Milli Seconds.");
}
/**
* @return the timeoutInteval
*/
public long getTimeoutInteval() {
return timeoutInteval;
}
/**
* @param timeoutInteval the timeoutInteval to set
*/
public void setTimeoutInteval(long timeoutInteval) {
this.timeoutInteval = timeoutInteval;
}
}
example :
try {
TimeoutBlock timeoutBlock = new TimeoutBlock(10 * 60 * 1000);//set timeout in milliseconds
Runnable block=new Runnable() {
@Override
public void run() {
//TO DO write block of code to execute
}
};
timeoutBlock.addBlock(block);// execute the runnable block
} catch (Throwable e) {
//catch the exception here . Which is block didn't execute within the time limit
}
This was so much useful for me when i had to connect to a FTP account. Then download and upload stuff. sometimes FTP connection hangs or totally breaks. This caused whole system to go down. and i needed a way to detect it and prevent it from happening . So i created this and used it. Works pretty well.
Please see the below code to enable or disable Submit button
If Name and City fields has value then only Submit button will be enabled.
<script>_x000D_
$(document).ready(function() {_x000D_
$(':input[type="submit"]').prop('disabled', true);_x000D_
_x000D_
$('#Name').keyup(function() {_x000D_
ToggleButton();_x000D_
});_x000D_
$('#City').keyup(function() {_x000D_
ToggleButton();_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
function ToggleButton() {_x000D_
if (($('#Name').val() != '') && ($('#City').val() != '')) {_x000D_
$(':input[type="submit"]').prop('disabled', false);_x000D_
return true;_x000D_
} else {_x000D_
$(':input[type="submit"]').prop('disabled', true);_x000D_
return false;_x000D_
}_x000D_
} </script>
_x000D_
<form method="post">_x000D_
_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<h2>Getting started</h2>_x000D_
<fieldset>_x000D_
<label class="control-label text-danger">Name</label>_x000D_
<input type="text" id="Name" name="Name" class="form-control" />_x000D_
<label class="control-label">Address</label>_x000D_
<input type="text" id="Address" name="Address" class="form-control" />_x000D_
<label class="control-label text-danger">City</label>_x000D_
<input type="text" id="City" name="City" class="form-control" />_x000D_
<label class="control-label">Pin</label>_x000D_
<input type="text" id="Pin" name="Pin" class="form-control" />_x000D_
<input type="submit" value="send" class="btn btn-success" />_x000D_
</fieldset>_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
Using Bash Parameter Expansion:
orig="AxxBCyyyDEFzzLMN"
mod=${orig//[xyz]/_}
The real problem isn't the error you're getting; it's that the application isn't cleaning up after itself.
It's either holding on to references, not freeing resources, or something else that's causing the process to not end when it's being told to close. Fix up that issue and this problem will resolve itself. We can't really help you with that unless you post your code (and at this point, if you need help with that, you should start a new question).
Given Array:
int[] givenArray = {2,2,3,3,4,5};
Converting integer array to Integer List
One way: boxed() -> returns the IntStream
List<Integer> givenIntArray1 = Arrays.stream(givenArray)
.boxed()
.collect(Collectors.toList());
Second Way: map each element of the stream to Integer and then collect
NOTE: Using mapToObj you can covert each int element into string stream, char stream etc by casing i to (char)i
List<Integer> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->i)
.collect(Collectors.toList());
Converting One array Type to Another Type Example:
List<Character> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->(char)i)
.collect(Collectors.toList());
you can do it as follow:
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
refer live demo http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/
This is the best and easiest code:
public class test
{
public static void main(String str[])
{
String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("rcv"));
System.out.println(jsonObject.getJSONArray("argv"));
}
}
The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.
You can download the zip. And then create a package
in your project with org.json as name. and paste all the downloaded codes there, and have fun.
I feel this to be the best and the most easiest JSON Decoding.
If you don't want to keep strings out of it, this works as well (Put it into a function):
DECLARE @Day int, @Month int, @Year int
SELECT @Day = 1, @Month = 2, @Year = 2008
SELECT DateAdd(dd, @Day-1, DateAdd(mm, @Month -1, DateAdd(yy, @Year - 2000, '20000101')))
If you only want to verify that issuer of UserCert.pem
is actually Intermediate.pem
do the following (example uses: OpenSSL 1.1.1
):
openssl verify -no-CAfile -no-CApath -partial_chain -trusted Intermediate.pem UserCert.pem
and you will get:
UserCert.pem: OK
or
UserCert.pem: verification failed
You can use the path
module to join the path of the directory in which helper1.js
lives to the relative path of foobar.json
. This will give you the absolute path to foobar.json
.
var fs = require('fs');
var path = require('path');
var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');
This should work on Linux, OSX, and Windows assuming a UTF8 encoding.
sa
is enabledI don't know much about git on Windows, but...
Appears to me that git is converting the return format to match that of the running platform (Windows). CRLF is the default return format in Windows, while LF is the default return format for most other OSes.
Chances are, the return format will be adjusted properly when the code is moved to another system. I also reckon git is smart enough to keep binary files intact rather than trying to convert LFs to CRLFs in, say, JPEGs.
In summary, you probably don't need to fret too much over this conversion. However, if you go to archive your project as a tarball, fellow coders would probably appreciate having LF line terminators rather than CRLF. Depending on how much you care (and depending on you not using Notepad), you might want to set git to use LF returns if you can :)
Appendix: CR is ASCII code 13, LF is ASCII code 10. Thus, CRLF is two bytes, while LF is one.
Here's an updated example that is using NSURLConnection +sendAsynchronousRequest: (10.7+, iOS 5+), The "Post" request remains the same as with the accepted answer and is omitted here for the sake of clarity:
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:@"http://www.myserver.com/api/api.php?request=%@", @"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(@"%@", responseString);
}
}
}];
LivingRoom.objects.create()
calls LivingRoom.__init__()
- as you might have noticed if you had read the traceback - passing it the same arguments. To make a long story short, a Django models.Model
subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields. The correct way to provide default values for fields is in the field constructor using the default
keyword as explained in the FineManual.
Published by Microsoft in Standard Date and Time Format Strings:
dataGrid.Columns[2].DefaultCellStyle.Format = "d"; // Short date
That should format the date according to the person's location settings.
This is part of Microsoft's larger collection of Formatting Types in .NET.
Below is a re-write of a previously posted function:
def addBinary(a, b): # Example: a = '11' + b =' 100' returns as '111'.
for ch in a: assert ch in {'0','1'}, 'bad digit: ' + ch
for ch in b: assert ch in {'0','1'}, 'bad digit: ' + ch
sumx = int(a, 2) + int(b, 2)
return bin(sumx)[2:]
for ($s=65; $s<=90; $s++) {
//echo chr($s);
$objPHPExcel->getActiveSheet()->getColumnDimension(chr($s))->setAutoSize(true);
}
For Linux, the following list of papers might be useful:
Personally, whilst Dummynet is good, I find NetEm to be the most versatile for my use-cases; I'm usually interested in the effect of delays, rather than bandwidth (i.e. WiFi connection issues), and it's super-easy to emulate random packet loss/corruption, etc. It's also very accessible, and free (unlike the hardware-based Linktropy).
On a side-note, for Windows, Clumsy is awesome. I would also like to add that (regarding websites) browser throttling is not an accurate method for emulating real-life network issues (I think "TKK" commented on a few of the reasons why above).
Hope this helps someone!
In ECS6, one may use Array.from()
:
const listItems = document.querySelector('ul').children;
const listArray = Array.from(listItems);
listArray.forEach((item) => {console.log(item)});
The only thing I would add to Mark Peters solution is that you don't need to iterate over the ArrayList - you should be able to use the addAll(Collection) method on the Set. You only need to iterate over the entire list to do the summations.
I find it very useful to append both stdout and stderr to a log file. I was glad to see a solution by alfonx with exec > >(tee -a)
, because I was wondering how to accomplish this using exec
. I came across a creative solution using here-doc syntax and .
: https://unix.stackexchange.com/questions/80707/how-to-output-text-to-both-screen-and-file-inside-a-shell-script
I discovered that in zsh, the here-doc solution can be modified using the "multios" construct to copy output to both stdout/stderr and the log file:
#!/bin/zsh
LOG=$0.log
# 8 is an arbitrary number;
# multiple redirects for the same file descriptor
# triggers "multios"
. 8<<\EOF /dev/fd/8 2>&2 >&1 2>>$LOG >>$LOG
# some commands
date >&2
set -x
echo hi
echo bye
EOF
echo not logged
It is not as readable as the exec
solution but it has the advantage of allowing you to log just part of the script. Of course, if you omit the EOF then the whole script is executed with logging. I'm not sure how zsh
implements multios, but it may have less overhead than tee
. Unfortunately it seems that one cannot use multios with exec
.
rake db:migrate:down VERSION=your_migrations's_version_number_here
The version is the numerical prefix on the migration's file name
How to find version:
Your migration files are stored in your rails_root/db/migrate
directory. Find appropriate file up to which you want to rollback and copy the prefix number.
for example
file name: 20140208031131_create_roles.rb
then the version is 20140208031131
There is a useful difference between call
and start /wait
when calling regsvr32.exe /s
for example, also referenced by Gary in
in his answer to how-do-i-get-the-application-exit-code-from-a-windows-command-line
call regsvr32.exe /s broken.dll
echo %errorlevel%
will always return 0 but
start /wait regsvr32.exe /s broken.dll
echo %errorlevel%
will return the error level from regsvr32.exe
Referring to @dylanvanw answer. You might still out of luck. I found that you might have a different path that you have installed Python. In my case, I have to move Chromedriver.exe from the cache path (C:\Users\Poom.wdm\drivers\chromedriver\win32\84.0.4147.30) to C:\Python38 then it work!
If you use Spring you may try http://docs.spring.io/spring/docs/4.0.5.RELEASE/javadoc-api/org/springframework/util/SocketUtils.html#findAvailableTcpPort--
You can use apply
for this, and it's a bit neater:
import numpy as np
import pandas as pd
np.random.seed(1)
df = pd.DataFrame(np.random.randn(4,4)* 4 + 3)
0 1 2 3
0 9.497381 0.552974 0.887313 -1.291874
1 6.461631 -6.206155 9.979247 -0.044828
2 4.276156 2.002518 8.848432 -5.240563
3 1.710331 1.463783 7.535078 -1.399565
df.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))
0 1 2 3
0 0.515087 0.133967 -0.651699 0.135175
1 0.125241 -0.689446 0.348301 0.375188
2 -0.155414 0.310554 0.223925 -0.624812
3 -0.484913 0.244924 0.079473 0.114448
Also, it works nicely with groupby
, if you select the relevant columns:
df['grp'] = ['A', 'A', 'B', 'B']
0 1 2 3 grp
0 9.497381 0.552974 0.887313 -1.291874 A
1 6.461631 -6.206155 9.979247 -0.044828 A
2 4.276156 2.002518 8.848432 -5.240563 B
3 1.710331 1.463783 7.535078 -1.399565 B
df.groupby(['grp'])[[0,1,2,3]].apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))
0 1 2 3
0 0.5 0.5 -0.5 -0.5
1 -0.5 -0.5 0.5 0.5
2 0.5 0.5 0.5 -0.5
3 -0.5 -0.5 -0.5 0.5
For .htaccess rewrite: http://learn.iis.net/page.aspx/557/translate-htaccess-content-to-iis-webconfig/
Or try aping .htaccess: http://www.helicontech.com/ape/
Here is a solution using Guava
private User findUserByName(List<User> userList, final String name) {
Optional<User> userOptional =
FluentIterable.from(userList).firstMatch(new Predicate<User>() {
@Override
public boolean apply(@Nullable User input) {
return input.getName().equals(name);
}
});
return userOptional.isPresent() ? userOptional.get() : null; // return user if found otherwise return null if user name don't exist in user list
}
$('#list option').each(function(index){
//do stuff
console.log(index);
});
logs the index :)
a more detailed example is below.
function run_each() {_x000D_
_x000D_
var $results = $(".results");_x000D_
_x000D_
$results.empty();_x000D_
_x000D_
$results.append("==================== START 1st each ====================");_x000D_
console.log("==================== START 1st each ====================");_x000D_
_x000D_
$('#my_select option').each(function(index, value) {_x000D_
$results.append("<br>");_x000D_
// log the index_x000D_
$results.append("index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log("index: " + index);_x000D_
// logs the element_x000D_
// $results.append(value); this would actually remove the element_x000D_
$results.append("<br>");_x000D_
console.log(value);_x000D_
// logs element property_x000D_
$results.append(value.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(value.innerHTML);_x000D_
// logs element property_x000D_
$results.append(this.text);_x000D_
$results.append("<br>");_x000D_
console.log(this.text);_x000D_
// jquery_x000D_
$results.append($(this).text());_x000D_
$results.append("<br>");_x000D_
console.log($(this).text());_x000D_
_x000D_
// BEGIN just to see what would happen if nesting an .each within an .each_x000D_
$('p').each(function(index) {_x000D_
$results.append("==================== nested each");_x000D_
$results.append("<br>");_x000D_
$results.append("nested each index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log(index);_x000D_
});_x000D_
// END just to see what would happen if nesting an .each within an .each_x000D_
_x000D_
});_x000D_
_x000D_
$results.append("<br>");_x000D_
$results.append("==================== START 2nd each ====================");_x000D_
console.log("");_x000D_
console.log("==================== START 2nd each ====================");_x000D_
_x000D_
_x000D_
$('ul li').each(function(index, value) {_x000D_
$results.append("<br>");_x000D_
// log the index_x000D_
$results.append("index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log(index);_x000D_
// logs the element_x000D_
// $results.append(value); this would actually remove the element_x000D_
$results.append("<br>");_x000D_
console.log(value);_x000D_
// logs element property_x000D_
$results.append(value.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(value.innerHTML);_x000D_
// logs element property_x000D_
$results.append(this.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(this.innerHTML);_x000D_
// jquery_x000D_
$results.append($(this).text());_x000D_
$results.append("<br>");_x000D_
console.log($(this).text());_x000D_
});_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(document).on("click", ".clicker", function() {_x000D_
_x000D_
run_each();_x000D_
_x000D_
});
_x000D_
.results {_x000D_
background: #000;_x000D_
height: 150px;_x000D_
overflow: auto;_x000D_
color: lime;_x000D_
font-family: arial;_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.one,_x000D_
.two,_x000D_
.three {_x000D_
width: 33.3%;_x000D_
}_x000D_
_x000D_
.one {_x000D_
background: yellow;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.two {_x000D_
background: pink;_x000D_
}_x000D_
_x000D_
.three {_x000D_
background: darkgray;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<div class="one">_x000D_
<select id="my_select">_x000D_
<option>apple</option>_x000D_
<option>orange</option>_x000D_
<option>pear</option>_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
<div class="two">_x000D_
<ul id="my_list">_x000D_
<li>canada</li>_x000D_
<li>america</li>_x000D_
<li>france</li>_x000D_
</ul>_x000D_
</div>_x000D_
_x000D_
<div class="three">_x000D_
<p>do</p>_x000D_
<p>re</p>_x000D_
<p>me</p>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<button class="clicker">run_each()</button>_x000D_
_x000D_
_x000D_
<div class="results">_x000D_
_x000D_
_x000D_
</div>
_x000D_
The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.
I think that there isn't a official naming convention to JSON, but you can follow some industry leaders to see how it is working.
Google, which is one of the biggest IT company of the world, has a JSON style guide: https://google.github.io/styleguide/jsoncstyleguide.xml
Taking advantage, you can find other styles guide, which Google defines, here: https://github.com/google/styleguide
In a single SQL query, without using the FOR XML clause.
A Common Table Expression is used to recursively concatenate the results.
-- rank locations by incrementing lexicographical order
WITH RankedLocations AS (
SELECT
VehicleID,
City,
ROW_NUMBER() OVER (
PARTITION BY VehicleID
ORDER BY City
) Rank
FROM
Locations
),
-- concatenate locations using a recursive query
-- (Common Table Expression)
Concatenations AS (
-- for each vehicle, select the first location
SELECT
VehicleID,
CONVERT(nvarchar(MAX), City) Cities,
Rank
FROM
RankedLocations
WHERE
Rank = 1
-- then incrementally concatenate with the next location
-- this will return intermediate concatenations that will be
-- filtered out later on
UNION ALL
SELECT
c.VehicleID,
(c.Cities + ', ' + l.City) Cities,
l.Rank
FROM
Concatenations c -- this is a recursion!
INNER JOIN RankedLocations l ON
l.VehicleID = c.VehicleID
AND l.Rank = c.Rank + 1
),
-- rank concatenation results by decrementing length
-- (rank 1 will always be for the longest concatenation)
RankedConcatenations AS (
SELECT
VehicleID,
Cities,
ROW_NUMBER() OVER (
PARTITION BY VehicleID
ORDER BY Rank DESC
) Rank
FROM
Concatenations
)
-- main query
SELECT
v.VehicleID,
v.Name,
c.Cities
FROM
Vehicles v
INNER JOIN RankedConcatenations c ON
c.VehicleID = v.VehicleID
AND c.Rank = 1
Keep it nice, short, simple, and maintainable! :]
// 3rd party plugins / script (don't forget the full path is necessary)
var FULL_PATH = '', s =
[
FULL_PATH + 'plugins/script.js' // Script example
FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library
FULL_PATH + 'plugins/crypto-js/hmac-sha1.js', // CryptoJS
FULL_PATH + 'plugins/crypto-js/enc-base64-min.js' // CryptoJS
];
function load(url)
{
var ajax = new XMLHttpRequest();
ajax.open('GET', url, false);
ajax.onreadystatechange = function ()
{
var script = ajax.response || ajax.responseText;
if (ajax.readyState === 4)
{
switch(ajax.status)
{
case 200:
eval.apply( window, [script] );
console.log("library loaded: ", url);
break;
default:
console.log("ERROR: library not loaded: ", url);
}
}
};
ajax.send(null);
}
// initialize a single load
load('plugins/script.js');
// initialize a full load of scripts
if (s.length > 0)
{
for (i = 0; i < s.length; i++)
{
load(s[i]);
}
}
This code is simply a short functional example that could require additional feature functionality for full support on any (or given) platform.
Just delete the whole directory. This will delete all the projects but also the Eclipse cache and settings for the workspace. These are kept in the .metadata
folder of an Eclipse workspace. Note that you can configure Eclipse to use project folders that are outside the workspace folder as well, so you may want to verify the location of each of the projects.
You can remove the workspace from the suggested workspaces by going into the General/Startup and Shutdown/Workspaces section of the preferences (via Preferences > General > Startup & Shudown > Workspaces > [Remove] ). Note that this does not remove the files itself. For old versions of Eclipse you will need to edit the org.eclipse.ui.ide.prefs
file in the configuration/.settings
directory under your installation directory (or in ~/.eclipse
on Unix, IIRC).
I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.
import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)
np.split(df, [100,200,300], axis=0]
wants explicit index numbers which may or may not be desirable.
I believe this does it:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
It's got built-in patterns for stuff like URLs and e-mail addresses, and I think you can have it use your own as well.
I wasn't having codec issues or dimension issues as the answers above. Instead, my issue was because my output frames were in greyscale.
I had to create a VideoWriter with the parameter isColor=False
out = cv2.VideoWriter(output_path,
cv2.VideoWriter_fourcc(*'mp4v'),
30,
(INPUT_VIDEO_WIDTH,INPUT_VIDEO_HEIGHT),
isColor=False
)
In the API Docs, it wrongly says that the flag is currently supported on Windows only. I have tested on Ubuntu 20.04, with opencv-python==4.2.0.34, and it finally writes out to file correctly.
One more solution for using input validation using a customized ValidationError
and a (optional) range validation for integer inputs:
class ValidationError(ValueError):
"""Special validation error - its message is supposed to be printed"""
pass
def RangeValidator(text,num,r):
"""Generic validator - raises 'text' as ValidationError if 'num' not in range 'r'."""
if num in r:
return num
raise ValidationError(text)
def ValidCol(c):
"""Specialized column validator providing text and range."""
return RangeValidator("Columns must be in the range of 0 to 3 (inclusive)",
c, range(4))
def ValidRow(r):
"""Specialized row validator providing text and range."""
return RangeValidator("Rows must be in the range of 5 to 15(exclusive)",
r, range(5,15))
Usage:
def GetInt(text, validator=None):
"""Aks user for integer input until a valid integer is given. If provided,
a 'validator' function takes the integer and either raises a
ValidationError to be printed or returns the valid number.
Non integers display a simple error message."""
print()
while True:
n = input(text)
try:
n = int(n)
return n if validator is None else validator(n)
except ValueError as ve:
# prints ValidationErrors directly - else generic message:
if isinstance(ve, ValidationError):
print(ve)
else:
print("Invalid input: ", n)
column = GetInt("Pleased enter column: ", ValidCol)
row = GetInt("Pleased enter row: ", ValidRow)
print( row, column)
Output:
Pleased enter column: 22
Columns must be in the range of 0 to 3 (inclusive)
Pleased enter column: -2
Columns must be in the range of 0 to 3 (inclusive)
Pleased enter column: 2
Pleased enter row: a
Invalid input: a
Pleased enter row: 72
Rows must be in the range of 5 to 15(exclusive)
Pleased enter row: 9
9, 2
I fixed my problem by using encodeURIComponent()
instead of escape()
.
This might be the fix for you if the problem happens when sending your string in a URL.
Try this with the phrase ("hi & % ‘")
escape()
returns
"hi%20%26%20%25%20%u2018"
Notice the %u2018
isn't very url friendly and can break the rest of the query string.
encodeURI()
returns
"hi%20&%20%25%20%E2%80%98"
Notice the ampersand is still there.
encodeURIComponent()
returns
"hi%20%26%20%25%20%E2%80%98"
Finally, all of our characters are properly encoded.
echo '1.2+3*[4]|5' | sed -r 's#([().+$*\[\]|])#\\&#g;s#\|#\\|#g'
This has now been fixed in Firefox Nightly and will be in the next firefox build.
Please see this bug for more information https://bugzilla.mozilla.org/show_bug.cgi?id=610733
Seems your resource POST
method won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).
Since in you already add Access-Control-Allow-Origin
headers to your Response, you can add new OPTIONS
method to your resource class.
@OPTIONS
@Path("{path : .*}")
public Response options() {
return Response.ok("")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "2000")
.build();
}
I actually just overwrite anything I want to change in the site.css, you should load the site.css after bootstrap so it will overwrite the classes. What I have done now is just made my own classes with my own little bootstrap theme. Little things like this
.navbar-nav li a{
color: #fff;
font-size: 15px;
margin-top: 9px;
}
.navbar-nav li a:hover{
background-color: #18678E;
height: 61px;
}
I also changed the likes of the validations errors the same way.
Crt + c works for Windows! user1852392
You have two options.
<colspan>
in your header to stretch a cell for two or more columns.<table>
with 2 columns inside the td
you want extra columns in.use Json & jQuery. It's way easier than oldschool javascript
function savedata1() {
var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
td_1: $row.find(':nth-child(1)').text(),
td_2: $row.find(':nth-child(2)').text(),
td_3: $row.find(':nth-child(3)').text()
};
}).get();
I think this will work. Use Calendar to manipulate time fields (reset them to zero), then get the Date from the Calendar.
Calendar c = GregorianCalendar.getInstance();
c.clear( Calendar.HOUR_OF_DAY );
c.clear( Calendar.MINUTE );
c.clear( Calendar.SECOND );
c.clear( Calendar.MILLISECOND );
Date today = c.getTime();
Or do the opposite. Put the date you want to compare to in a calendar and compare calendar dates
Date compareToDate; // assume this is set before going in.
Calendar today = GregorianCalendar.getInstance();
Calendar compareTo = GregorianCalendar.getInstance();
compareTo.setTime( compareToDate );
if( today.get( Calendar.YEAR ) == compareTo.get( Calendar.YEAR ) &&
today.get( Calendar.DAY_OF_YEAR ) == compareTo.get( Calendar.DAY_OF_YEAR ) ) {
// They are the same day!
}
This is the case from the question because the OP wants to commit to a new branch and also applies if your changes are compatible with the target branch without triggering an overwrite.
As in the accepted answer by John Brodie, you can simply checkout the new branch and commit the work:
git checkout -b branch_name
git add <files>
git commit -m "message"
If you get the error:
error: Your local changes to the following files would be overwritten by checkout:
...
Please commit your changes or stash them before you switch branches
Then you can stash your work, create a new branch, then pop your stash changes, and resolve the conflicts:
git stash
git checkout -b branch_name
git stash pop
It will be as if you had made those changes after creating the new branch. Then you can commit as usual:
git add <files>
git commit -m "message"
See the answer by Carl Norum with cherry-picking, which is the right tool in this case:
git checkout <target name>
git cherry-pick <original branch>
See the answer by joeytwiddle on this potential duplicate. Follow any of the above steps as appropriate, then roll back the original branch:
git branch -f <original branch> <earlier commit id>
If you have pushed your changes to a shared remote like GitHub, you should not attempt this roll-back unless you know what you are doing.
First of all, there can be two reasons for this:
To solve this :
i) Go to AWS VPC console and select the VPC you have created.
ii) Then click on Actions and then enable DNS Resolution.
OR
Here you cannot change the setting; so create an ami image and then recreate the instance from that.
Please remove all jar files of Http from libs folder and add below dependencies in gradle file :
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4.3'
Thanks.
For Node/Express developers you can use middleware and set this via server.
app.use(function(req, res, next) {
res.setHeader('X-UA-Compatible', 'IE=edge');
next();
});
I faced the same issue where I started a node app in port 3000 and it didn't close correctly and the process kept running even after restart.
None of the taskkill or powershell commands running in Administrator mode worked for me.
I used MS Process Expoler > Properties > Image > Current directory (which was supposed to be the my project directory).
Finally, I had to reboot in SafeMode and rename the project folder and restart. The Node processes which were consuming port 3000 killed itself.
With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.
We have three models:
1) Article (belongs to user and category)
2) Category (has many articles)
3) User (has many articles)
1) Article.php
<?php
namespace App\Models;
use Eloquent;
class Article extends Eloquent{
protected $table = 'articles';
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
}
2) Category.php
<?php
namespace App\Models;
use Eloquent;
class Category extends Eloquent
{
protected $table = "categories";
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
3) User.php
<?php
namespace App\Models;
use Eloquent;
class User extends Eloquent
{
protected $table = 'users';
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.
For example, if you want to retrieve an article by using the user and category, you would need to write:
$article = \App\Models\Article::with(['user','category'])->first();
and you can use this like so:
//retrieve user name
$article->user->user_name
//retrieve category name
$article->category->category_name
In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
You can learn more at http://laravel.com/docs/5.0/eloquent
$('.cw2').change(function () {
if ($('input.cw2').filter(':checked').length >= 1) {
$('input.cw2').not(this).prop('checked', false);
}
});
$('td, input').prop(function (){
$(this).css({ 'background-color': '#DFD8D1' });
$(this).addClass('changed');
});
As per comment from @Paul, If display: block is specified, span stops to be an inline element and an element after it appears on next line.
I came here to find solution to my span height problem and I got a solution of my own
Adding overflow:hidden;
and keeing it inline will solve the problem just tested in IE8 Quirks mode
Seems like no one looked at the original documentation. May be there was no it at that time))
Initialize a draggable with the disabled option specified.
$( ".selector" ).draggable({ disabled: true });
Get or set the disabled option, after init.
//getter
var disabled = $( ".selector" ).draggable( "option", "disabled" );
//setter
$( ".selector" ).draggable( "option", "disabled", true );
Something important has been said by Tom:
if you use the has-a concept, you avoid the issue.
Indeed, if instead of using extends and implements you define two attributes, one of type rectangle, one of type JLabel
in your Tile
class, then you can define a Rectangle
to be either an interface or a class.
Furthermore, I would normally encourage the use of interfaces in connection with has-a, but I guess it would be an overkill in your situation. However, you are the only one that can decide on this point (tradeoff flexibility/over-engineering).
Use this conda install spyder=4.0.0
This will not mess up your anaconda dependencies.
https://github.com/spyder-ide/spyder/releases
You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to int
it will be accepted as input (although it will be questionable if that's the right way to do it).
It would be better to convert your training scores by using scikit's labelEncoder
function.
The same is true for your DecisionTree and KNeighbors qualifier.
from sklearn import preprocessing
from sklearn import utils
lab_enc = preprocessing.LabelEncoder()
encoded = lab_enc.fit_transform(trainingScores)
>>> array([1, 3, 2, 0], dtype=int64)
print(utils.multiclass.type_of_target(trainingScores))
>>> continuous
print(utils.multiclass.type_of_target(trainingScores.astype('int')))
>>> multiclass
print(utils.multiclass.type_of_target(encoded))
>>> multiclass
You Can do it using jQuery
$("select").addClass("form-control")
here, Select is- html tag, Form-control is- class name
@Html.DropDownList("SupplierId", "Select Supplier")
and here, SupplierId is ViewBagList, Select Supplier is - Display Name
Best way to read large file, line by line is to use python enumerate function
with open(file_name, "rU") as read_file:
for i, row in enumerate(read_file, 1):
#do something
#i in line of that line
#row containts all data of that line
This one work for me , first you bind datepicker to text-box and in next line set (today as default date) the date to it
$("#date").datepicker();
$("#date").datepicker("setDate", new Date());
Just for the sake of completeness, we can use the operators [
and [[
:
set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])
Several options
df[df[1] < 0.5 | df[2] == "g", ]
df[df[[1]] < 0.5 | df[[2]] == "g", ]
df[df["v1"] < 0.5 | df["v2"] == "g", ]
df$name is equivalent to df[["name", exact = FALSE]]
Using dplyr
:
library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")
Using sqldf
:
library(sqldf)
sqldf('SELECT *
FROM df
WHERE v1 < 0.5 OR v2 = "g"')
Output for the above options:
v1 v2
1 0.26550866 a
2 0.37212390 b
3 0.20168193 e
4 0.94467527 g
5 0.06178627 j
[f,x]=hist(data)
The area for each individual bar is height*width. Since MATLAB will choose equidistant points for the bars, so the width is:
delta_x = x(2) - x(1)
Now if we sum up all the individual bars the total area will come out as
A=sum(f)*delta_x
So the correctly scaled plot is obtained by
bar(x, f/sum(f)/(x(2)-x(1)))
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
You could ask your colleague to create a patch, which will collapse all the changes that have been made into a single file that you can apply to your own check out. This will update all of your files appropriately and then you can revert the changes on his side and check yours in.
When content is in file.py
from branch2 that is no longer applies to branch1, it requires picking some changes and leaving others. For full control do an interactive merge using the --patch
switch:
$ git checkout --patch branch2 file.py
The interactive mode section in the man page for git-add(1)
explains the keys that are to be used:
y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk nor any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk nor any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help
The split command is particularly useful.
from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s
Where db
is your DbContext
. Generated query will look like (sample for EF6):
SELECT [Extent1].[Id] AS [Id]
-- other fields from Services table
FROM [dbo].[Services] AS [Extent1]
INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]
ON [Extent1].[Id] = [Extent2].[ServiceId]
WHERE [Extent2].[LocationId] = 1
Year(Date)
Year()
: Returns the year portion of the date argument.
Date
: Current date only.
Explanation of both of these functions from here.
From: jQuery text truncation (read more style)
Try this:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.split(" ").slice(0, -1).join(" ") + "...";
And you can also use a plugin:
As a extension of String
String.prototype.trimToLength = function(m) {
return (this.length > m)
? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
: this;
};
Use as
"This is your title".trimToLength(10);
if (myReader.HasRows) //The key Word is **.HasRows**
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null Or Empty";
}
I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.
What I though
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
What I've finally done
namespace mycompany\CutreApi;
use \vendor\AwesomeApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new \mycompany\CutreApi\ClassOfVendor();
}
}
So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.
One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.
Currently done
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function getWhatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.
Hope this can help someone.
Currently, they are the same. but previously
VARCHAR
is reserved by Oracle to support distinction between NULL
and empty string in future, as ANSI standard prescribes.
VARCHAR2
does not distinguish between a NULL
and empty string, and never will.
Emp_name varchar(10)
- if you enter value less than 10 digits then remaining space cannot be deleted. it used total of 10 spaces.
Emp_name varchar2(10)
- if you enter value less than 10 digits then remaining space is automatically deleted
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server
For specific versions, such as mysql-server-5.6
, you'll need to specify the version in like this:
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6
For mysql-community-server, the keys are slightly different:
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server
Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)
If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:
echo ... | sudo debconf-set-selections
The jsonlite package is easy to use and tries to convert json into data frames.
Example:
library(jsonlite)
# url with some information about project in Andalussia
url <- 'http://www.juntadeandalucia.es/export/drupaljda/ayudas.json'
# read url and convert to data.frame
document <- fromJSON(txt=url)
Check this - http://eppz.eu/blog/custom-uitableview-cell/ - really convenient way using a tiny class that ends up one line in controller implementation:
-(UITableViewCell*)tableView:(UITableView*) tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath
{
return [TCItemCell cellForTableView:tableView
atIndexPath:indexPath
withModelSource:self];
}
Try this
#include <stdio.h>
struct context;
struct funcptrs{
void (*func0)(struct context *ctx);
void (*func1)(void);
};
struct context{
struct funcptrs fps;
};
void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }
void getContext(struct context *con){
con->fps.func0 = func0;
con->fps.func1 = func1;
}
int main(int argc, char *argv[]){
struct context c;
c.fps.func0 = func0;
c.fps.func1 = func1;
getContext(&c);
c.fps.func0(&c);
getchar();
return 0;
}
Had a similar problem (using NHibernate, so the ESCAPE keyword would have been very difficult) and solved it using the bracket characters. So your sample would become
WHERE ... LIKE '%aa[%]bb%'
If you need proof:
create table test (field nvarchar(100))
go
insert test values ('abcdef%hijklm')
insert test values ('abcdefghijklm')
go
select * from test where field like 'abcdef[%]hijklm'
go
Couldn't your query just be written as:
SELECT u1.name as UserName from Message m1, User u1
WHERE u1.uid = m1.UserFromID GROUP BY u1.name HAVING count(m1.UserFromId)>3
That should also help with the known speed issues with subqueries in MySQL
Modern BASH has support for regular expressions:
while read -r line; do
if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
echo "${BASH_REMATCH[1]}"
fi
done
Since glibc version 2.17, the library linking -lrt
is no longer required.
The clock_*
are now part of the main C library. You can see the change history of glibc 2.17 where this change was done explains the reason for this change:
+* The `clock_*' suite of functions (declared in <time.h>) is now available
+ directly in the main C library. Previously it was necessary to link with
+ -lrt to use these functions. This change has the effect that a
+ single-threaded program that uses a function such as `clock_gettime' (and
+ is not linked with -lrt) will no longer implicitly load the pthreads
+ library at runtime and so will not suffer the overheads associated with
+ multi-thread support in other code such as the C++ runtime library.
If you decide to upgrade glibc, then you can check the compatibility tracker of glibc if you are concerned whether there would be any issues using the newer glibc.
To check the glibc version installed on the system, run the command:
ldd --version
(Of course, if you are using old glibc (<2.17) then you will still need -lrt
.)
You can directly go to Web IDE and upload your folder there.
Steps:
In some cases you may not be able to directly upload entire folder containing folders, In such cases, you will have to create directory structure yourself.
You should wrap them in a div with no float.
<div style="float:none;background:#FDD017;" class="clearfix">
<div id="response" style="float:left; width:65%;">Response with two lines</div>
<div id="note" style="float:left; width:35%;">single line note</div>
</div>
I also use the clearfix patch on here http://www.webtoolkit.info/css-clearfix.html
You can persist values using HTML5 storage, Flash Storage, or Gears. The dojo storage library provides a nice wrapper for this.
Both IanSR and bchhun suggested overriding TEMPLATE_CONTEXT_PROCESSORS in the settings. Be aware that this setting has a default that can cause some screwy things if you override it without re-setting the defaults. The defaults have also changed in recent versions of Django.
https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors
The default TEMPLATE_CONTEXT_PROCESSORS :
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")
Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.
Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).
function append_output(suffix, value) {
$("#output_"+suffix).append(value)
}
function kickOff() {
let start = new Promise((resolve, reject) => {
append_output("now", "start")
resolve("start")
})
let middle = new Promise((resolve, reject) => {
setTimeout(() => {
append_output("now", " middle")
resolve(" middle")
}, 1000)
})
let end = new Promise((resolve, reject) => {
append_output("now", " end")
resolve(" end")
})
Promise.all([start, middle, end]).then(results => {
results.forEach(
result => append_output("later", result))
})
}
kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
To list all local groups which have users assigned to them, use this command:
cut -d: -f1 /etc/group | sort
For more info- > Unix groups, Cut command, sort command
Don't reinvent the wheel. C has sprintf for a reason. Since your variable is called score, I'm guessing this is for a game where you're planning to use the individual digits of the score to display the numeral glyphs as images. In this case, sprintf has convenient format modifiers that will let you zero-pad, space-pad, etc. the score to a fixed width, which you may want to use.
I know the question is old, but if someone is looking for a great new android color picker that use material design I have forked an great project from github and made a simple-to-use android color picker dialog.
This is the project: Android Color Picker
The aar artifact is available at the jcenter repository. Declare the repository and the
dependency in your build.gradle
.
(root)
repositories {
jcenter()
}
(module)
dependencies {
compile 'com.pes.materialcolorpicker:library:1.0.2'
}
Create a color picker dialog object
final ColorPicker cp = new ColorPicker(MainActivity.this, defaultColorR, defaultColorG, defaultColorB);
defaultColorR, defaultColorG, defaultColorB are 3 integer ( value 0-255) for the initialization of the color picker with your custom color value. If you don't want to start with a color set them to 0 or use only the first argument
Then show the dialog (when & where you want) and save the selected color
/* Show color picker dialog */
cp.show();
/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button)cp.findViewById(R.id.okColorButton);
okColor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* You can get single channel (value 0-255) */
selectedColorR = cp.getRed();
selectedColorG = cp.getGreen();
selectedColorB = cp.getBlue();
/* Or the android RGB Color (see the android Color class reference) */
selectedColorRGB = cp.getColor();
cp.dismiss();
}
});
That's all :)
There are different ways but simplest would be to use the space-between see the example at the end
#container {
border: solid 1px #000;
display: flex;
flex-direction: row;
justify-content: space-between;
padding: 10px;
height: 50px;
}
.item {
width: 20%;
border: solid 1px #000;
text-align: center;
}
int o1 = date1.IndexOf("-");
int o2 = date1.IndexOf("-",o1 + 1);
string str11 = date1.Substring(0,o1);
string str12 = date1.Substring(o1 + 1, o2 - o1 - 1);
string str13 = date1.Substring(o2 + 1);
int o21 = date2.IndexOf("-");
int o22 = date2.IndexOf("-", o1 + 1);
string str21 = date2.Substring(0, o1);
string str22 = date2.Substring(o1 + 1, o2 - o1 - 1);
string str23 = date2.Substring(o2 + 1);
if (Convert.ToInt32(str11) > Convert.ToInt32(str21))
{
}
else if (Convert.ToInt32(str12) > Convert.ToInt32(str22))
{
}
else if (Convert.ToInt32(str12) == Convert.ToInt32(str22) && Convert.ToInt32(str13) > Convert.ToInt32(str23))
{
}
You have to set the path. See here.
I have faced the same problem and I have fixed. Please make sure some things as written bellow :
Mail::send('emails.auth.activate', array('link'=> URL::route('account-activate', $code),'username'=>$user->username),function($message) use ($user) {
$message->to($user->email , $user->username)->subject('Active your account !');
});
This should be your emails.activation
Hello {{ $username }} , <br> <br> <br>
We have created your account ! Awesome ! Please activate by clicking the following link <br> <br> <br>
----- <br>
{{ $link }} <br> <br> <br>
----
The answer to your why you can't call $email variable into your mail sending function. You need to call $user variable then you can write your desired variable as $user->variable
Thank You :)
Like Yuck's answer with a check to allow the script to be ran more than once without error. (less code/custom strings than using information_schema.columns)
IF object_id('DF_SomeName', 'D') IS NULL BEGIN
Print 'Creating Constraint DF_SomeName'
ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
END
I would recommend separating out all of the foreign-key constraints from your CREATE TABLE
statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.
You can add an FK constraint to a table using SQL like the following:
ALTER TABLE orders ADD CONSTRAINT orders_FK
FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);
In particular, your formats
and library
tables both have foreign-key constraints on one another. The two CREATE TABLE
statements to create these two tables can never run successfully, as each will only work when the other table has already been created.
Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE
statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.
You can use Schedule
inline fun Timer.schedule(
delay: Long,
crossinline action: TimerTask.() -> Unit
): TimerTask (source)
example (thanks @Nguyen Minh Binh - found it here: http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)
import java.util.Timer
import kotlin.concurrent.schedule
Timer("SettingUp", false).schedule(500) {
doSomething()
}
Other answers are correct, but in my case I need to handle other properties also (alpha
, animate
, completion
). Because of this, I modified a bit to expose these parameters as below:
extension UIView {
/// Helper function to update view's alpha with animation
/// - Parameter alpha: View's alpha
/// - Parameter animate: Indicate alpha changing with animation or not
/// - Parameter duration: Indicate time for animation
/// - Parameter completion: Completion block after alpha changing is finished
func set(alpha: CGFloat, animate: Bool, duration: TimeInterval = 0.3, completion: ((Bool) -> Void)? = nil) {
let animation = { (view: UIView) in
view.alpha = alpha
}
if animate {
UIView.animate(withDuration: duration, animations: {
animation(self)
}, completion: { finished in
completion?(finished)
})
} else {
layer.removeAllAnimations()
animation(self)
completion?(true)
}
}
}
To make it work you only need two things. Check if you are missing:
You need to add dependency for jersey-json if you are missing.For your reference I added this dependency into my pom.xml.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17.1</version>
</dependency>
Here's a pure Javascript function which allows you to wait for anything. Set the interval longer to take less CPU resource.
/**
* @brief Wait for something to be ready before triggering a timeout
* @param {callback} isready Function which returns true when the thing we're waiting for has happened
* @param {callback} success Function to call when the thing is ready
* @param {callback} error Function to call if we time out before the event becomes ready
* @param {int} count Number of times to retry the timeout (default 300 or 6s)
* @param {int} interval Number of milliseconds to wait between attempts (default 20ms)
*/
function waitUntil(isready, success, error, count, interval){
if (count === undefined) {
count = 300;
}
if (interval === undefined) {
interval = 20;
}
if (isready()) {
success();
return;
}
// The call back isn't ready. We need to wait for it
setTimeout(function(){
if (!count) {
// We have run out of retries
if (error !== undefined) {
error();
}
} else {
// Try again
waitUntil(isready, success, error, count -1, interval);
}
}, interval);
}
To call this, for example in jQuery, use something like:
waitUntil(function(){
return $('#myelement').length > 0;
}, function(){
alert("myelement now exists");
}, function(){
alert("I'm bored. I give up.");
});
I think using NOW()
function is incorrect for getting time difference. Because by NOW()
function every time your are calculating the past 24 hours.
You must use CURDATE()
instead.
function your_function($time, $your_date) {
if ($time == 'today') {
$timeSQL = ' Date($your_date)= CURDATE()';
}
if ($time == 'week') {
$timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
}
if ($time == 'month') {
$timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
}
$Sql = "SELECT * FROM jokes WHERE ".$timeSQL
return $Result = $this->db->query($Sql)->result_array();
}
Not from activities only:
public static String getStringByIdName(Context context, String idName) {
Resources res = context.getResources();
return res.getString(res.getIdentifier(idName, "string", context.getPackageName()));
}
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
Let avg be the list, then:
In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')
You can use %e
or %s
depending on your requirement.
The following works for me at a command prompt
cd ~/Library/MobileDevice/Provisioning\ Profiles/
for f in *.mobileprovision; do echo $f; openssl asn1parse -inform DER -in $f | grep -A1 application-identifier; done
Finding out which signing keys are used by a particular profile is harder to do with a shell one-liner. Basically you need to do:
openssl asn1parse -inform DER -in your-mobileprovision-filename
then cut-and-paste each block of base64 data after the DeveloperCertificates entry into its own file. You can then use:
openssl asn1parse -inform PEM -in file-with-base64
to dump each certificate. The line after the second commonName in the output will be the key name e.g. "iPhone Developer: Joe Bloggs (ABCD1234X)".
No solution here worked for me. Instead I added a class to the label and was able to select it that way.
<asp:Label ID="Label1" CssClass="myLabel1Class" runat="server" Text="Label"></asp:Label>
$(".myLabel1Class").val()
And, as mentioned by others, make sure you have your jquery loaded.
There are some funnies restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?
Use Master
Go
RESTORE DATABASE YourDB
FROM DISK = 'C:\YourBackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',--check and adjust path
MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf'
There's also a PHP extension: Pip - Python in PHP, which I've never tried but had it bookmarked for just such an occasion
List<T>
has a Reverse()
method, however it only reverses the order of two (or more) consecutive items.
your_list.Reverse(index, 2);
Where the second parameter 2
indicates we are reversing the order of 2 items, starting with the item at the given index
.
Source: https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx
Try this:
ls -l | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'
NR is an AWK builtin variable to count the no. of records
Although it is not Jquery , I use jquery myself but for browser detection I have used the script on this page a few times. It detects all major browsers, and then some. The work is pretty much all done for you.
Try this:
Custom formula is
=countif(A:A,A1)>1
(or change A
to your chosen column)A1:A100
).Anything written in the A1:A100 cells will be checked, and if there is a duplicate (occurs more than once) then it'll be coloured.
For locales using comma (,
) as a decimal separator, the argument separator is most likely a semi-colon (;
). That is, try: =countif(A:A;A1)>1
, instead.
For multiple columns, use countifs
.
In Windows, you also normally need to run command line as administrator.
As standard-user:
docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon 106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
Get https://mcr.microsoft.com/v2/: dial tcp: lookup mcr.microsoft.com on [::1]:53: read udp [::1]:45540->[::1]:53: read:
>>>connection refused
But as an administrator.
docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon 106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
3.0: Pulling from dotnet/core/runtime
68ced04f60ab: Pull complete e936bd534ffb: Pull complete caf64655bcbb: Pull complete d1927dbcbcab: Pull complete Digest: sha256:e0c67764f530a9cad29a09816614c0129af8fe3bd550eeb4e44cdaddf8f5aa40
Status: Downloaded newer image for mcr.microsoft.com/dotnet/core/runtime:3.0
---> f059cd71a22a
Successfully built f059cd71a22a
Successfully tagged myimage:latest
The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.
Use Calendar.add(int field,int amount)
method.
This is such a common problem, especially in GUI applications, that I'm surprised there isn't a BCL class to do this out of the box. Here's how I do it.
public static class ReflectiveEnumerator
{
static ReflectiveEnumerator() { }
public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
{
List<T> objects = new List<T>();
foreach (Type type in
Assembly.GetAssembly(typeof(T)).GetTypes()
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
{
objects.Add((T)Activator.CreateInstance(type, constructorArgs));
}
objects.Sort();
return objects;
}
}
A few notes:
Assembly.GetAssembly(typeof(T))
because your base class might be in a different assembly. type.IsClass
and !type.IsAbstract
because it'll throw an exception if you try to instantiate an interface or abstract class.IComparable
so that they can be sorted.Obviously, the solutions relying, for example, on
[[NSLocale preferredLanguages] objectAtIndex:0]
usually work fine and return the current device language.
But it could be misleading in some cases :
If the app in which you want to get this value has already changed the language, for example with this kind of code :
NSString *lg = @"en"; // or anything like @"en", @"fr", etc.
[[NSUserDefaults standardUserDefaults]
setObject:[NSArray arrayWithObjects:lg, nil]
forKey:@"AppleLanguages"]
In this case, [NSLocale preferredLanguages] actually returns the preferred language set (and used) in this particular app, not the current device language !
And... in this case the only way to properly get the actual current device language (and not that previously set in the app), is to firstly clear the key @"appleLanguages" in NSUserDefaults, like this :
[[NSUserDefaults standardUserDefaults]removeObjectForKey:@"AppleLanguages"];
Then, [NSLocale preferredLanguages] now returns the correct value.
Hope this help.
I changed all space areas to  , just like that and it worked without problem.
val.replace(" ", " ");
I hope it helps someone.
This is the approach to do this: -
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'DBName' AND
TABLE_SCHEMA = 'SchemaName' AND
TABLE_NAME = 'TableName' AND
COLUMN_NAME = 'ColumnName')
BEGIN
ALTER TABLE DBName.SchemaName.TableName ALTER COLUMN ColumnName [data type] NULL
END
If you don't have any schema then delete the schema line because you don't need to give the default schema.
For large lists, we can do it the iter-way:
product_iter_object = itertools.imap(operator.mul, [1,2,3,4], [2,3,4,5])
product_iter_object.next()
gives each of the element in the output list.
The output would be the length of the shorter of the two input lists.
I think what you want to do is
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
for…in
iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn’t use it to iterate over arrays. For them, there’s ES5’s forEach
method that passes both the value and the index to the function you give it:
var myArray = [123, 15, 187, 32];
myArray.forEach(function (value, i) {
console.log('%d: %s', i, value);
});
// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32
Or ES6’s Array.prototype.entries
, which now has support across current browser versions:
for (const [i, value] of myArray.entries()) {
console.log('%d: %s', i, value);
}
For iterables in general (where you would use a for…of
loop rather than a for…in
), there’s nothing built-in, however:
function* enumerate(iterable) {
let i = 0;
for (const x of iterable) {
yield [i, x];
i++;
}
}
for (const [i, obj] of enumerate(myArray)) {
console.log(i, obj);
}
If you actually did mean for…in
– enumerating properties – you would need an additional counter. Object.keys(obj).forEach
could work, but it only includes own properties; for…in
includes enumerable properties anywhere on the prototype chain.
CASE - 1
Using array.filter()
We can get an array of objects which will match with our condition.
see the working example.
var questions = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
function filter(){
console.clear();
var filter_id = document.getElementById("filter").value;
var filter_array = questions.filter(x => x.id == filter_id);
console.log(filter_array);
}
_x000D_
button {
background: #0095ff;
color: white;
border: none;
border-radius: 3px;
padding: 8px;
cursor: pointer;
}
input {
padding: 8px;
}
_x000D_
<div>
<label for="filter"></label>
<input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
<button onclick="filter()">Filter</button>
</div>
_x000D_
CASE - 2
Using array.find()
we can get first matched item and break the iteration.
var questions = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
function find(){
console.clear();
var find_id = document.getElementById("find").value;
var find_object = questions.find(x => x.id == find_id);
console.log(find_object);
}
_x000D_
button {
background: #0095ff;
color: white;
border: none;
border-radius: 3px;
padding: 8px;
cursor: pointer;
}
input {
padding: 8px;
width: 200px;
}
_x000D_
<div>
<label for="find"></label>
<input id="find" type="number" name="find" placeholder="Enter id which you want to find">
<button onclick="find()">Find</button>
</div>
_x000D_
There isn't a system feature to change the height of the table based upon the contents of the tableview. Having said that, it is possible to programmatically change the height of the tableview based upon the contents, specifically based upon the contentSize
of the tableview (which is easier than manually calculating the height yourself). A few of the particulars vary depending upon whether you're using the new autolayout that's part of iOS 6, or not.
But assuming you're configuring your table view's underlying model in viewDidLoad
, if you want to then adjust the height of the tableview, you can do this in viewDidAppear
:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self adjustHeightOfTableview];
}
Likewise, if you ever perform a reloadData
(or otherwise add or remove rows) for a tableview, you'd want to make sure that you also manually call adjustHeightOfTableView
there, too, e.g.:
- (IBAction)onPressButton:(id)sender
{
[self buildModel];
[self.tableView reloadData];
[self adjustHeightOfTableview];
}
So the question is what should our adjustHeightOfTableview
do. Unfortunately, this is a function of whether you use the iOS 6 autolayout or not. You can determine if you have autolayout turned on by opening your storyboard or NIB and go to the "File Inspector" (e.g. press option+command+1 or click on that first tab on the panel on the right):
Let's assume for a second that autolayout was off. In that case, it's quite simple and adjustHeightOfTableview
would just adjust the frame
of the tableview:
- (void)adjustHeightOfTableview
{
CGFloat height = self.tableView.contentSize.height;
CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;
// if the height of the content is greater than the maxHeight of
// total space on the screen, limit the height to the size of the
// superview.
if (height > maxHeight)
height = maxHeight;
// now set the frame accordingly
[UIView animateWithDuration:0.25 animations:^{
CGRect frame = self.tableView.frame;
frame.size.height = height;
self.tableView.frame = frame;
// if you have other controls that should be resized/moved to accommodate
// the resized tableview, do that here, too
}];
}
If your autolayout was on, though, adjustHeightOfTableview
would adjust a height constraint for your tableview:
- (void)adjustHeightOfTableview
{
CGFloat height = self.tableView.contentSize.height;
CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;
// if the height of the content is greater than the maxHeight of
// total space on the screen, limit the height to the size of the
// superview.
if (height > maxHeight)
height = maxHeight;
// now set the height constraint accordingly
[UIView animateWithDuration:0.25 animations:^{
self.tableViewHeightConstraint.constant = height;
[self.view setNeedsUpdateConstraints];
}];
}
For this latter constraint-based solution to work with autolayout, we must take care of a few things first:
Make sure your tableview has a height constraint by clicking on the center button in the group of buttons here and then choose to add the height constraint:
Then add an IBOutlet
for that constraint:
Make sure you adjust other constraints so they don't conflict if you adjust the size tableview programmatically. In my example, the tableview had a trailing space constraint that locked it to the bottom of the screen, so I had to adjust that constraint so that rather than being locked at a particular size, it could be greater or equal to a value, and with a lower priority, so that the height and top of the tableview would rule the day:
What you do here with other constraints will depend entirely upon what other controls you have on your screen below the tableview. As always, dealing with constraints is a little awkward, but it definitely works, though the specifics in your situation depend entirely upon what else you have on the scene. But hopefully you get the idea. Bottom line, with autolayout, make sure to adjust your other constraints (if any) to be flexible to account for the changing tableview height.
As you can see, it's much easier to programmatically adjust the height of a tableview if you're not using autolayout, but in case you are, I present both alternatives.
Try this
html {
background: url(image.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Simplified version
html {
background: url(image.jpg) center center / cover no-repeat fixed;
}
<style name="AppThemeDatePicker" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorAccent">@color/select2</item>
<item name="android:colorAccent">@color/select2</item>
<item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
</style>
<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">@color/select2</item>
</style>
You can try the following:
$group = array();
foreach ( $array as $value ) {
$group[$value['id']][] = $value;
}
var_dump($group);
Output:
array
96 =>
array
0 =>
array
'id' => int 96
'shipping_no' => string '212755-1' (length=8)
'part_no' => string 'reterty' (length=7)
'description' => string 'tyrfyt' (length=6)
'packaging_type' => string 'PC' (length=2)
1 =>
array
'id' => int 96
'shipping_no' => string '212755-1' (length=8)
'part_no' => string 'dftgtryh' (length=8)
'description' => string 'dfhgfyh' (length=7)
'packaging_type' => string 'PC' (length=2)
97 =>
array
0 =>
array
'id' => int 97
'shipping_no' => string '212755-2' (length=8)
'part_no' => string 'ZeoDark' (length=7)
'description' => string 's%c%s%c%s' (length=9)
'packaging_type' => string 'PC' (length=2)
By default, it begins by processing the first target that does not begin with a .
aka the default goal; to do that, it may have to process other targets - specifically, ones the first target depends on.
The GNU Make Manual covers all this stuff, and is a surprisingly easy and informative read.
There are many options out there. cElementTree looks excellent if speed and memory usage are an issue. It has very little overhead compared to simply reading in the file using readlines
.
The relevant metrics can be found in the table below, copied from the cElementTree website:
library time space
xml.dom.minidom (Python 2.1) 6.3 s 80000K
gnosis.objectify 2.0 s 22000k
xml.dom.minidom (Python 2.4) 1.4 s 53000k
ElementTree 1.2 1.6 s 14500k
ElementTree 1.2.4/1.3 1.1 s 14500k
cDomlette (C extension) 0.540 s 20500k
PyRXPU (C extension) 0.175 s 10850k
libxml2 (C extension) 0.098 s 16000k
readlines (read as utf-8) 0.093 s 8850k
cElementTree (C extension) --> 0.047 s 4900K <--
readlines (read as ascii) 0.032 s 5050k
As pointed out by @jfs, cElementTree
comes bundled with Python:
from xml.etree import cElementTree as ElementTree
.from xml.etree import ElementTree
(the accelerated C version is used automatically).For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments: [ "@doctrine.orm.entity_manager" ]
And then they would be available in the order they were listed via the arguments (if there are more than 1).
public function __construct(EntityManager $entityManager) {
$this->em = $entityManager;
}
You can add 1 to each example New = 5; old = 0;
(1+new) - (old+1) / (old +1) 5/ 1 * 100 ==> 500%
A table-cell can legitimately contain block-level elements so it's not, inherently, a faux-pas. Browser implentation, of course, leaves this a speculative-theoretical position. It may cause layout problems and bugs.
Though as tables were used for layout -and sometimes still are- I imagine that most browsers will render the content properly. Even IE.
In addition to the answers above:
If you created/edited your .sh script file in Windows, make sure it was saved with line ending in Unix format. By default many editors in Windows will convert Unix line endings to Windows format and Linux will not recognize shebang (#!/bin/sh) at the beginning of the file. So Linux will produce the error message like if there is no shebang.
Tips:
[parentView bringSubviewToFront:view] ;
SELECT ( Schema_name(A.schema_id) + '.' + A.NAME ) AS TableName,
Sum(B.rows)AS RecordCount
FROM sys.objects A INNER JOIN sys.partitions B
ON A.object_id = B.object_id WHERE A.type = 'U'
GROUP BY A.schema_id,A.NAME ;
You can also use border-style: double
with background-clip: padding-box
, without the use of any extra (pseudo-)elements. It's probably the most compact solution, but not as flexible as the others.
<div class="circle">Some text goes here...</div>
.circle{
width: 100px;
height: 100px;
padding: 50px;
border-radius: 200px;
border: double 15px rgba(255,255,255,0.7);
background: rgba(255,255,255,0.7);
background-clip: padding-box;
}
If you look closely you can see that the edge between the border and the background is not perfect. This seems to be an issue in current browsers. But it's not that noticeable when the border is small.
According to the VueJs 2.0, you should not mutate a prop inside the component. They are only mutated by their parents. Therefore, you should define variables in data with different names and keep them updated by watching actual props. In case the list prop is changed by a parent, you can parse it and assign it to mutableList. Here is a complete solution.
Vue.component('task', {
template: ´<ul>
<li v-for="item in mutableList">
{{item.name}}
</li>
</ul>´,
props: ['list'],
data: function () {
return {
mutableList = JSON.parse(this.list);
}
},
watch:{
list: function(){
this.mutableList = JSON.parse(this.list);
}
}
});
It uses mutableList to render your template, thus you keep your list prop safe in the component.
Twood, Visibility expression is the expressions you write on how you want the "visibility" to behave. So, if you would want to hide or show the textbox, you want to write this:
=IIf((CountRows("ScannerStatisticsData")=0),True,False)
This means, if the dataset is 0, you want to hide the textbox.
I agree with chrylis: you believe you changed your project's compliance settings but probably you didnt.
Right click on your project and:
By the way you can "tell" eclipse that jre8 is 1.6 compliance clicking on Window/Preferences/Java/Installed JREs/Execution Environment and selecting in the left panel, Execution Environments, JavaSE-1.6 and in the Compatible JRE's panel, jre8
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
For people using Kotlin, inazaruk's answer will not work, the IDE will require the variable to be initialized, so instead of using the postDelayed
inside the Runnable
, we'll use it in an separate method.
Initialize your Runnable
like this :
private var myRunnable = Runnable {
//Do some work
//Magic happens here ?
runDelayedHandler(1000) }
Initialize your runDelayedHandler
method like this :
private fun runDelayedHandler(timeToWait : Long) {
if (!keepRunning) {
//Stop your handler
handler.removeCallbacksAndMessages(null)
//Do something here, this acts like onHandlerStop
}
else {
//Keep it running
handler.postDelayed(myRunnable, timeToWait)
}
}
As you can see, this approach will make you able to control the lifetime of the task, keeping track of keepRunning
and changing it during the lifetime of the application will do the job for you.
This rings a bell. I came across a similar problem in the past,
You can generate an assemblyInfo.cs by right clicking the project and chosing properties. In the application tab fill in the details and press save, this will generate the assemblyInfo.cs file for you. If you build your project after that, it should work.
Cheers, Tarun
Update 2016-07-08:
For Visual Studio 2010 through the most recent version (2015 at time of writing), LandedGently's comment still applies:
After you select project Properties and the Application tab as @Tarun mentioned, there is a button "Assembly Information..." which opens another dialog. You need to at least fill in the Title here. VS will add the GUID and versions, but if the title is empty, it will not create the AssemblyInfo.cs file.
My version of reality. Loading a HTML file and streaming to the browser.
@Controller
@RequestMapping("/")
public class UIController {
@RequestMapping(value="index", method=RequestMethod.GET, produces = "text/html")
public @ResponseBody String GetBootupFile() throws IOException {
Resource resource = new ClassPathResource("MainPage.html");
String fileContents = FileUtils.readFileToString(resource.getFile());
return fileContents;
}
}
this works for me (Keltex said the same)
.foo {
height: 50px;
...
}
.foo span{
vertical-align: middle;
}
<span class="foo"> <span>middle!</span></span>
/tmp/myfile
first line text
wanted text
other text
the command
$ grep -n "wanted text" /tmp/myfile | awk -F ":" '{print $1}'
2
%>%
is similar to pipe in Unix. For example, in
a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()
the output of combined_data_set
will go into group_by
and its output will go into tally
, then the final output is assigned to a
.
This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.
<style>
.para{
color: black;
}
.para:hover{
cursor: pointer;
color: blue;
}
</style>
<div class="para">
In the above HTML code [:hover] is used to indicate that the following style must be applied only on hovering or keeping the mouse cursor on it.
There are several types of cursors available in CSS:
View the below code for types of cursor:
<style>
.alias {cursor: alias;}
.all-scroll {cursor: all-scroll;}
.auto {cursor: auto;}
.cell {cursor: cell;}
.context-menu {cursor: context-menu;}
.col-resize {cursor: col-resize;}
.copy {cursor: copy;}
.crosshair {cursor: crosshair;}
.default {cursor: default;}
.e-resize {cursor: e-resize;}
.ew-resize {cursor: ew-resize;}
.grab {cursor: -webkit-grab; cursor: grab;}
.grabbing {cursor: -webkit-grabbing; cursor: grabbing;}
.help {cursor: help;}
.move {cursor: move;}
.n-resize {cursor: n-resize;}
.ne-resize {cursor: ne-resize;}
.nesw-resize {cursor: nesw-resize;}
.ns-resize {cursor: ns-resize;}
.nw-resize {cursor: nw-resize;}
.nwse-resize {cursor: nwse-resize;}
.no-drop {cursor: no-drop;}
.none {cursor: none;}
.not-allowed {cursor: not-allowed;}
.pointer {cursor: pointer;}
.progress {cursor: progress;}
.row-resize {cursor: row-resize;}
.s-resize {cursor: s-resize;}
.se-resize {cursor: se-resize;}
.sw-resize {cursor: sw-resize;}
.text {cursor: text;}
.url {cursor: url(myBall.cur),auto;}
.w-resize {cursor: w-resize;}
.wait {cursor: wait;}
.zoom-in {cursor: zoom-in;}
.zoom-out {cursor: zoom-out;}
</style>
Click the below link for viewing how the cursor property acts:
https://www.w3schools.com/cssref/tryit.asp?filename=trycss_cursor
I used the page-checkout.php template to change the header for my cart page. I renamed it to page-cart.php in my /wp-content/themes/childtheme/woocommerce/. This gives you more control over the wrapping html, header and footer.
If to summ up what people say here, json_decode/encode seems faster than serialize/unserialize BUT If you do var_dump the type of the serialized object is changed. If for some reason you want to keep the type, go with serialize!
(try for example stdClass vs array)
serialize/unserialize:
Array cache:
array (size=2)
'a' => string '1' (length=1)
'b' => int 2
Object cache:
object(stdClass)[8]
public 'field1' => int 123
This cache:
object(Controller\Test)[8]
protected 'view' =>
json encode/decode
Array cache:
object(stdClass)[7]
public 'a' => string '1' (length=1)
public 'b' => int 2
Object cache:
object(stdClass)[8]
public 'field1' => int 123
This cache:
object(stdClass)[8]
As you can see the json_encode/decode converts all to stdClass, which is not that good, object info lost... So decide based on needs, especially if it is not only arrays...
There is no "standard place" for a sqlite database. The file's location is specified to the library, and may be in your home directory, in the invoking program's folder, or any other place.
If it helps, sqlite databases are, by convention, named with a .db
file extension.
you can get the json string as a param of your ActionResult
and afterwards serialize it using JSON.Net
HERE an example is being shown
in order to receive it in the serialized form as a param of the controller action you must either write a custom model binder or a Action filter (OnActionExecuting) so that the json string is serialized into the model of your liking and is available inside the controller body for use.
HERE is an implementation using the dynamic object
Try this. I added text-align: center
to body and display:inline-block
to wrap, and then removed your display: table
body {
background: #bbb;
text-align: center;
}
.wrap {
background: #aaa;
margin: 0 auto;
display: inline-block;
overflow: hidden;
}
You can't find a consistent reference because it seems to go by at least six different names!
You can use the reflect package to iterate over an interface whose concrete type is a slice:
func HasElem(s interface{}, elem interface{}) bool {
arrV := reflect.ValueOf(s)
if arrV.Kind() == reflect.Slice {
for i := 0; i < arrV.Len(); i++ {
// XXX - panics if slice element points to an unexported struct field
// see https://golang.org/pkg/reflect/#Value.Interface
if arrV.Index(i).Interface() == elem {
return true
}
}
}
return false
}
I'm adding this answer because it solved a related problem that I was having with the same error message.
Problem: I had installed cygwin under Windows and was getting this error: Pseudo-terminal will not be allocated because stdin is not a terminal
Resolution: It turns out that I had not installed the openssh client program and utilities. Because of that cygwin was using the Windows implementation of ssh, not the cygwin version. The solution was to install the openssh cygwin package.
Use the following to check if text box is empty or have more than 1 white spaces
var name = jQuery.trim($("#ContactUsName").val());
if ((name.length == 0))
{
Your code
}
else
{
Your code
}
Some advantages to the second option:
You can use this
inside onclick
to reference the anchor itself (doing the same in option 1 will give you window
instead).
You can set the href
to a non-JS compatible URL to support older browsers (or those that have JS disabled); browsers that support JavaScript will execute the function instead (to stay on the page you have to use onclick="return someFunction();"
and return false
from inside the function or onclick="return someFunction(); return false;"
to prevent default action).
I've seen weird stuff happen when using href="javascript:someFunction()"
and the function returns a value; the whole page would get replaced by just that value.
Pitfalls
Inline code:
Runs in document
scope as opposed to code defined inside <script>
tags which runs in window
scope; therefore, symbols may be resolved based on an element's name
or id
attribute, causing the unintended effect of attempting to treat an element as a function.
Is harder to reuse; delicate copy-paste is required to move it from one project to another.
Adds weight to your pages, whereas external code files can be cached by the browser.