Take a look at this.
Change your query to:
SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC;
SELECT @rank;
The last select is your count.
This is not the most robust solution - but if you're just looking to create a partitioned rank on a field with only a few different values, it may not be unwieldily to use some case when logic with as many variables as you require.
Something like this has worked for me in the past:
SELECT t.*,
CASE WHEN <partition_field> = @rownum1 := @rownum1 + 1
WHEN <partition_field> = @rownum2 := @rownum2 + 1
...
END AS rank
FROM YOUR_TABLE t,
(SELECT @rownum1 := 0) r1, (SELECT @rownum2 := 0) r2
ORDER BY <rank_order_by_field>
;
Hope that makes sense / helps!
In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.
I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.
I would do something like this:
;WITH x
AS (SELECT *,
Row_number()
OVER(
partition BY employeeid
ORDER BY datestart) rn
FROM employeehistory)
SELECT *
FROM x x1
LEFT OUTER JOIN x x2
ON x1.rn = x2.rn + 1
Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.
Try ROW_NUMBER()
http://msdn.microsoft.com/en-us/library/ms186734.aspx
Example:
SELECT
col1,
col2,
ROW_NUMBER() OVER (ORDER BY col1) AS rownum
FROM tbl
select
Ml.Hid,
ml.blockid,
row_number() over (partition by ml.blockid order by Ml.Hid desc) as rownumber,
H.HNAME
from MIT_LeadBechmarkHamletwise ML
join [MT.HAMLE] h on ML.Hid=h.HID
One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:
SELECT a.ID,
a.AText,
(SELECT Count(ID)
FROM table1 b WHERE b.ID <= a.ID
AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;
Please try
select NEWID()
Source: https://docs.microsoft.com/en-us/sql/t-sql/data-types/uniqueidentifier-transact-sql
SET @customerID=0;
SELECT @customerID:=@customerID+1 AS customerID
FROM CUSTOMER ;
you can obtain the dataset from SQL like this and populate it into a java data structure (like a List) and then make the necessary sorting over there. (maybe with the help of a comparable interface)
I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json)
. my_json_object
in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.
The way I ended up solving it: the write_to_file.json
will have everything up to the bytes object that is causing the issue.
In my particular case this was a line obtained through
for line in text:
json_object['line'] = line.strip()
I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:
for line in text:
json_object['line'] = line.strip().decode()
Here is the extra fast solution, that I finally implemented. Here I am using WinAPI and functions FindFirstFile, FindNextFile. It allows to avoid enumeration of all items in Folder and stops right after detecting the first object in the Folder. This approach is ~6(!!) times faster, than described above. 250 calls in 36ms!
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct WIN32_FIND_DATA
{
public uint dwFileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll")]
private static extern bool FindClose(IntPtr hFindFile);
public static bool CheckDirectoryEmpty_Fast(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException(path);
}
if (Directory.Exists(path))
{
if (path.EndsWith(Path.DirectorySeparatorChar.ToString()))
path += "*";
else
path += Path.DirectorySeparatorChar + "*";
WIN32_FIND_DATA findData;
var findHandle = FindFirstFile(path, out findData);
if (findHandle != INVALID_HANDLE_VALUE)
{
try
{
bool empty = true;
do
{
if (findData.cFileName != "." && findData.cFileName != "..")
empty = false;
} while (empty && FindNextFile(findHandle, out findData));
return empty;
}
finally
{
FindClose(findHandle);
}
}
throw new Exception("Failed to get directory first file",
Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
}
throw new DirectoryNotFoundException();
}
I hope it will be useful for somebody in the future.
The problem is that value
is ignored when ng-model
is present.
Firefox, which doesn't currently support type="date"
, will convert all the values to string. Since you (rightly) want date
to be a real Date
object and not a string, I think the best choice is to create another variable, for instance dateString
, and then link the two variables:
<input type="date" ng-model="dateString" />
function MainCtrl($scope, dateFilter) {
$scope.date = new Date();
$scope.$watch('date', function (date)
{
$scope.dateString = dateFilter(date, 'yyyy-MM-dd');
});
$scope.$watch('dateString', function (dateString)
{
$scope.date = new Date(dateString);
});
}
The actual structure is for demonstration purposes only. You'd be better off creating your own directive, especially in order to:
yyyy-MM-dd
,NgModelController#$formatters
and NgModelController#$parsers
rather than the artifical dateString
variable (see the documentation on this subject).Please notice that I've used yyyy-MM-dd
, because it's a format directly supported by the JavaScript Date
object. In case you want to use another one, you must make the conversion yourself.
EDIT
Here is a way to make a clean directive:
myModule.directive(
'dateInput',
function(dateFilter) {
return {
require: 'ngModel',
template: '<input type="date"></input>',
replace: true,
link: function(scope, elm, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.unshift(function (modelValue) {
return dateFilter(modelValue, 'yyyy-MM-dd');
});
ngModelCtrl.$parsers.unshift(function(viewValue) {
return new Date(viewValue);
});
},
};
});
That's a basic directive, there's still a lot of room for improvement, for example:
yyyy-MM-dd
,It's part of Xcode. You'll need to reinstall the developer tools.
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
Here is the code that will return all video ids under your channel
<?php
$baseUrl = 'https://www.googleapis.com/youtube/v3/';
// https://developers.google.com/youtube/v3/getting-started
$apiKey = 'API_KEY';
// If you don't know the channel ID see below
$channelId = 'CHANNEL_ID';
$params = [
'id'=> $channelId,
'part'=> 'contentDetails',
'key'=> $apiKey
];
$url = $baseUrl . 'channels?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
$params = [
'part'=> 'snippet',
'playlistId' => $playlist,
'maxResults'=> '50',
'key'=> $apiKey
];
$url = $baseUrl . 'playlistItems?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos = [];
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
while(isset($json['nextPageToken'])){
$nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
$json = json_decode(file_get_contents($nextUrl), true);
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
}
print_r($videos);
Note: You can get channel id at https://www.youtube.com/account_advanced after logged in.
Give this a try:
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
// do stuff here
}
Also please note that Type.GetProperties()
has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least don't forget to add the "system.Reflection" assembly reference.
For instance to resolve all public properties:
foreach (var propertyInfo in obj.GetType()
.GetProperties(
BindingFlags.Public
| BindingFlags.Instance))
{
// do stuff here
}
Please let me know whether this works as expected.
Library - Any set of classes or components that can be used as the client deems fit to accomplish a certain task.
Framework - mandates certain guidelines for you to "plug-in" into something bigger than you. You merely provide the pieces specific to your application/requirements in a published-required manner, so that 'the framwework can make your life easy'
if you have this error :
configure: error: Either a previously installed pkg-config or "glib-2.0 >= 2.16" could not be found. Please set GLIB_CFLAGS and GLIB_LIBS to the correct values or pass --with-internal-glib to configure to use the bundled copy.
Instead of do this command :
$ ./configure && make install
Do that :
./configure --with-internal-glib && make install
If you're storing the object as type object
, you need to use reflection. This is true of any object type, anonymous or otherwise. On an object o, you can get its type:
Type t = o.GetType();
Then from that you look up a property:
PropertyInfo p = t.GetProperty("Foo");
Then from that you can get a value:
object v = p.GetValue(o, null);
This answer is long overdue for an update for C# 4:
dynamic d = o;
object v = d.Foo;
And now another alternative in C# 6:
object v = o?.GetType().GetProperty("Foo")?.GetValue(o, null);
Note that by using ?.
we cause the resulting v
to be null
in three different situations!
o
is null
, so there is no object at allo
is non-null
but doesn't have a property Foo
o
has a property Foo
but its real value happens to be null
.So this is not equivalent to the earlier examples, but may make sense if you want to treat all three cases the same.
In my case I had a component in a Shared module.
The component was loading and worked well but typescript was highlighting the html tag with red line and showed this error message.
Inside this component, I noticed I didn't import a rxjs operator.
import {map} from 'rxjs/operators';
When I added this import the error message disappeared.
Check all imports inside the component.
Hope it helps someone.
On Mac OS X:
In terminal, run ifconfig | grep 192.
to get the internal IP of your machine on it's current network. It may be something like 192.168.1.140
Start a server. For example, node server.js
may start a server on some port.
On your phone, visit 192.168.1.140:3000
or whatever port your server is running on.
I've found this to work the best across all browsers and devices (PC, tables & mobile).
<script type="text/javascript">
function iframeLoaded() {
var iFrameID = document.getElementById('idIframe');
if(iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
}
</script>
<iframe id="idIframe" onload="iframeLoaded()" frameborder="0" src="yourpage.php" height="100%" width="100%" scrolling="no"></iframe>
If you want to get the form data directly from Http request, without any model bindings or FormCollection
you can use this:
[HttpPost]
public ActionResult SubmitAction() {
// This will return an string array of all keys in the form.
// NOTE: you specify the keys in form by the name attributes e.g:
// <input name="this is the key" value="some value" type="test" />
var keys = Request.Form.AllKeys;
// This will return the value for the keys.
var value1 = Request.Form.Get(keys[0]);
var value2 = Request.Form.Get(keys[1]);
}
This add all unversioned files even if it contains spaces
svn status | awk '{$1=""; print $0}' | xargs -i svn add "{}"
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
Meld is a free, open-source, and cross-platform (UNIX/Linux, OSX, Windows) diff/merge tool.
Here's how to install it on:
Not perfect but close:
newcol<-sapply(rownames(t), function(rn){z[match(rn, rownames(z)), 5]})
cbind(data.frame(t), newcol)
Too many overly-complicated answers. Just make a TableData tag that spans how many rows you want it to using rowspan. Then use the right-border for the actual bar.
Example:
<td rowspan="5" style="border-right-color: #000000; border-right-width: thin; border-right-style: solid"> </td>
<td rowspan="5"> </td>
Ensure that the " " in the second line runs the same amount of lines as the first. so that there's proper spacing between both.
This technique has served me rather well with my time in HTML5.
Installing a lxml binary would do the trick. Check this
if you want infos from the actual running batchfile, try this :
@echo off
set myNameFull=%0
echo myNameFull %myNameFull%
set myNameShort=%~n0
echo myNameShort %myNameShort%
set myNameLong=%~nx0
echo myNameLong %myNameLong%
set myPath=%~dp0
echo myPath %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%
more samples? C:> HELP CALL
%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters
First set keyboard return key in xib, otherwise you can write code in viewdidload
:
passWord.returnKeyType = UIReturnKeyNext;
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if(textField == eMail) {
[textField resignFirstResponder];
[userName becomeFirstResponder];
}
if (textField==userName) {
[textField resignFirstResponder];
[passWord becomeFirstResponder];
}
if (textField==passWord) {
[textField resignFirstResponder];
[country becomeFirstResponder];
}
if (textField==country) {
[textField resignFirstResponder];
}
return YES;
}
Using the map()
and reduce()
built-in functions
def file_to_list(file):
#stuff to parse file to a list
return list
files = [...list of files...]
L = map(file_to_list, files)
flat_L = reduce(lambda x,y:x+y, L)
Minimal "for looping" and elegant coding pattern :)
I do not agree that it's a better user experience to stay within one browser tab. If you want people to stay on your site, or come back to finish reading that article, send them off in a new tab.
Building on @davidmorrow's answer, throw this javascript into your site and turn just external links into links with target=_blank:
<script type="text/javascript" charset="utf-8">
// Creating custom :external selector
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/)
&& (obj.hostname != location.hostname);
};
$(function(){
// Add 'external' CSS class to all external links
$('a:external').addClass('external');
// turn target into target=_blank for elements w external class
$(".external").attr('target','_blank');
})
</script>
From JLS http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html#10.2
Here are examples of declarations of array variables that do not create arrays:
int[ ] ai; // array of int
short[ ][ ] as; // array of array of short
Object[ ] ao, // array of Object
otherAo; // array of Object
Collection<?>[ ] ca; // array of Collection of unknown type
short s, // scalar short
aas[ ][ ]; // array of array of short
Here are some examples of declarations of array variables that create array objects:
Exception ae[ ] = new Exception[3];
Object aao[ ][ ] = new Exception[2][3];
int[ ] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[ ] = { 'n', 'o', 't', ' ', 'a', ' ',
'S', 't', 'r', 'i', 'n', 'g' };
String[ ] aas = { "array", "of", "String", };
The [ ] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:
byte[ ] rowvector, colvector, matrix[ ];
This declaration is equivalent to:
byte rowvector[ ], colvector[ ], matrix[ ][ ];
As previous people have answered npm --save ../location-of-your-packages-root-directory
.
The ../location-of-your-packages-root-directory
however must have two things in order for it to work.
1) package.json
in that directory pointed towards
2) main
property in the package.json
must be set and working i.g. "main": "src/index.js",
if the entry file for ../location-of-your-packages-root-directory
is ../location-of-your-packages-root-directory/src/index.js
The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:
Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:
var foomodule = require('foo');
// do something with fooModule
What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...
var module = require(path); // Call RequireJS require
...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;
var moduleName = 'foo';
require([moduleName], function(fooModule){
// do something with fooModule
})
Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:
define(['dyn_modules'], function (dynModules) {
require(dynModules, function(){
// use arguments since you don't know how many modules you're getting in the callback
for (var i = 0; i < arguments.length; i++){
var mymodule = arguments[i];
// do something with mymodule...
}
});
});
EDIT: From your own answer, I see you're using underscore/lodash, so using _.values
and _.object
can simplify the looping through arguments array as above.
For PyCharm 4
File >> Settings >> Editor >> Code Style: Right margin (columns)
suggestion: Take a look at other options in that tab, they're very helpful
That's a simple one
UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);
Use a line algorithm to connect point A with point C, and in an outer loop, let point A wander towards point B with the same line algorithm and with the wandering coordinates, repeat drawing that line. You can probably also include a z delta with which is also incremented iteratively. For the line algorithm, just calculate two or three slopes for the delta change of each coordinate and set one slope to 1 after changing the two others proportionally so they are below 1. This is very important for drawing closed geometrical areas between connected mesh particles. Take a look at the Qt Elastic Nodes example and now imagine drawing triangles between the nodes after stretching this over a skeleton. As long as it will remain online
You could run: mvn exec:exec -Dexec.args="arg1"
.
This will pass the argument arg1 to your program.
You should specify the main class fully qualified, for example, a Main.java that is in a package test would need
mvn exec:java -Dexec.mainClass=test.Main
By using the -f
parameter, as decribed here, you can also run it from other directories.
mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm
For multiple arguments, simply separate them with a space as you would at the command line.
mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"
For arguments separated with a space, you can group using 'argument separated with space'
inside the quotation marks.
mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"
Only want to clone the structure of table:
CREATE TABLE foo SELECT * FROM bar WHERE 1 = 2;
Also wants to copy the data:
CREATE TABLE foo as SELECT * FROM bar;
If you want to use requirements.txt
file, you will need git
and something like the entry below to anonymously fetch the master branch in your requirements.txt
.
git+git://github.com/celery/django-celery.git
-e git://github.com/celery/django-celery.git#egg=django-celery
Editable mode downloads the project's source code into ./src
in the current directory. It allows pip freeze
to output the correct github location of the package.
Your code is correct you just used .div
instead of div
HTML
<div class="ui grid container">
<div class="ui center aligned three column grid">
<div class="column">
</div>
<div class="column">
</div>
</div>
CSS
div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}
Check out this Fiddle
Use
//find first element with "someAttr" attribute
document.querySelector('[someAttr]')
or
//find all elements with "someAttr" attribute
document.querySelectorAll('[someAttr]')
to find elements by attribute. It's now supported in all relevant browsers (even IE8): http://caniuse.com/#search=queryselector
egrep -v "^\s\s+"
egrep already do regex, and the \s is white space.
The + duplicates current pattern.
The ^ is for the start
Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
The AdamOptimizer class creates additional variables, called "slots", to hold values for the "m" and "v" accumulators.
See the source here if you're curious, it's actually quite readable: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/adam.py#L39 . Other optimizers, such as Momentum and Adagrad use slots too.
These variables must be initialized before you can train a model.
The normal way to initialize variables is to call tf.initialize_all_variables()
which adds ops to initialize the variables present in the graph when it is called.
(Aside: unlike its name suggests, initialize_all_variables() does not initialize anything, it only add ops that will initialize the variables when run.)
What you must do is call initialize_all_variables() after you have added the optimizer:
...build your model...
# Add the optimizer
train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Add the ops to initialize variables. These will include
# the optimizer slots added by AdamOptimizer().
init_op = tf.initialize_all_variables()
# launch the graph in a session
sess = tf.Session()
# Actually intialize the variables
sess.run(init_op)
# now train your model
for ...:
sess.run(train_op)
First of all, I suggest to modify a bit your sql query:
select * from shift
where shift.shiftid not in (select employeeshift.shiftid from employeeshift
where employeeshift.empid = 57);
This query provides same functionality. If you want to get the same result with LINQ, you can try this code:
//Variable dc has DataContext type here
//Here we get list of ShiftIDs from employeeshift table
List<int> empShiftIds = dc.employeeshift.Where(p => p.EmpID = 57).Select(s => s.ShiftID).ToList();
//Here we get the list of our shifts
List<shift> shifts = dc.shift.Where(p => !empShiftIds.Contains(p.ShiftId)).ToList();
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
If you are getting a JS based date String
then first use the new Date(String)
constructor and then pass the Date
object to the moment
method. Like:
var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
In case dateString
is 15-07-2016
, then you should use the moment(date:String, format:String)
method
var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
$('document').ready(function () {
$("#imgload").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgshow').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="imgload" >
<img src="#" id="imgshow" align="left">
_x000D_
That works for me in jQuery.
The below code will give you list of all the rows:-
df[df['C'] != 'XYZ']
To store the values from the above code into a dataframe :-
newdf = df[df['C'] != 'XYZ']
Just adding another way of doing this (using Angular) if you don't wanna dirt the HTML with even more code:
You only have to subscribe to the field valueChanges and set the Value as an absolute value (taking care of not emitting a new event because that will cause another valueChange hence a recursive call and trigger a Maximum call size exceeded error)
HTML CODE
<form [formGroup]="myForm">
<input type="number" formControlName="myInput"/>
</form>
TypeScript CODE (Inside your Component)
formGroup: FormGroup;
ngOnInit() {
this.myInput.valueChanges
.subscribe(() => {
this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
});
}
get myInput(): AbstractControl {
return this.myForm.controls['myInput'];
}
import os
os.path.getsize(fullpathhere) > 0
Once you have the source trees, e.g.
diff -ENwbur repos1/ repos2/
Even better
diff -ENwbur repos1/ repos2/ | kompare -o -
and have a crack at it in a good gui tool :)
Consider the below situation
public class Person{
public String Name{get; set;}
public String Email {get; set;}
public virtual Employer employer {get; set;}
}
public List<EF.Person> GetPerson(){
using(EF.DbEntities db = new EF.DbEntities()){
return db.Person.ToList();
}
}
Now after this method is called, you cannot lazy load the Employer
entity anymore. Why? because the db
object is disposed. So you have to do Person.Include(x=> x.employer)
to force that to be loaded.
I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.
int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
for(int i=0; i<=names.size()-1; ++i) {
if(names[i]==req_name){
cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
return 0;
}
else if(names[i]!=req_name && i==names.size()-1) {
cout<<"That name is not an element in this vector"<<'\n';
} else {
continue;
}
}
There's more than one way to do this obviously.
# This will find files recursively (you can limit it by using some 'find' parameters.
# see the man pages
# Final backslash required for exec example to work
find . -name '*.gz' -exec gunzip '{}' \;
# This will do it only in the current directory
for a in *.gz; do gunzip $a; done
I'm sure there's other ways as well, but this is probably the simplest.
And to remove it, just do a rm -rf *.gz
in the applicable directory
On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:
Content-Disposition: attachment; filename=quot.pdf;
See content-disposition on the wikipedia MIME page.
Or add "sort name" to list alphabetically
Get-ADPrincipalGroupMembership username | select name | sort name
Depending on your tool - you can also inject HTML into markdown.
<img src="./img/Isolated.png">
This assumes your folder structure is:
+-- img
+-- Isolated.jpg
+-- README.md
ping (ICMP protocol) and ssh are two different protocols.
It could be that ssh service is not running or not installed
firewall restriction (local to server like iptables or even sshd config lock down ) or (external firewall that protects incomming traffic to network hosting 111.111.111.111)
First check is to see if ssh port is up
nc -v -w 1 111.111.111.111 -z 22
if it succeeds then ssh should communicate if not then it will never work until restriction is lifted or ssh is started
extension Date {
func isBetween(_ date1: Date, and date2: Date) -> Bool {
return (min(date1, date2) ... max(date1, date2)).contains(self)
}
}
let resultArray = dateArray.filter { $0.dateObj!.isBetween(startDate, and: endDate) }
Quicksort is usually the fastest on average, but It has some pretty nasty worst-case behaviors. So if you have to guarantee no bad data gives you O(N^2)
, you should avoid it.
Merge-sort uses extra memory, but is particularly suitable for external sorting (i.e. huge files that don't fit into memory).
Heap-sort can sort in-place and doesn't have the worst case quadratic behavior, but on average is slower than quicksort in most cases.
Where only integers in a restricted range are involved, you can use some kind of radix sort to make it very fast.
In 99% of the cases, you'll be fine with the library sorts, which are usually based on quicksort.
It needs to go directly under the root <configuration>
node and you need to set a path like this:
<?xml version="1.0"?>
<configuration>
<location path="." inheritInChildApplications="false">
<!-- Stuff that shouldn't be inherited goes in here -->
</location>
</configuration>
A better way to handle configuration inheritance is to use a <clear/>
in the child config wherever you don't want to inherit. So if you didn't want to inherit the parent config's connection strings you would do something like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<clear/>
<!-- Child config's connection strings -->
</connectionStrings>
</configuration>
Check to see if there are any triggers on the table you are trying to execute queries against. They can sometimes throw this error as they are trying to run the update/select/insert trigger that is on the table.
You can modify your query to disable then enable the trigger if the trigger DOES NOT need to be executed for whatever query you are trying to run.
ALTER TABLE your_table DISABLE TRIGGER [the_trigger_name]
UPDATE your_table
SET Gender = 'Female'
WHERE (Gender = 'Male')
ALTER TABLE your_table ENABLE TRIGGER [the_trigger_name]
I have added toArray()
after pluck
$items = Item::get()->pluck('name', 'id')->toArray();
{{ Form::select('item_id', [null=>'Please Select'] + $items) }}
For some git-commands you can specify --verbose
,
git 'command' --verbose
or
git 'command' -v
.
Make sure the switch is after the actual git command. Otherwise - it won't work!
Also useful:
git 'command' --dry-run
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Scale can be used for both full data frame and specific columns. For specific columns, following code can be used:
trainingSet[, 3:7] = scale(trainingSet[, 3:7]) # For column 3 to 7
trainingSet[, 8] = scale(trainingSet[, 8]) # For column 8
Full data frame
trainingSet <- scale(trainingSet)
There are several ways to do that. But do not just update to the earlier revision as suggested here.
The easiest way to revert the changes from a single revision, or from a range of revisions, is to use the revision log dialog. This is also the method to use of you want to discard recent changes and make an earlier revision the new HEAD.
Show All
or Next 100
to show the revision(s) you are interested in.Context Menu
? Revert
changes from this revision.Context Menu
? Revert to this revision
. This will discard all changes after the selected revision. You have reverted the changes within your working copy. Check the results, then commit the changes.
All solutions are explained in the "How Do I..." part of the TortoiseSVN docs.
I assume you understand the difference in semantics now (though honestly I wonder why people ask 'what does operator X mean' questions on stack overflow rather than reading, you know, a book or web tutorial or something.
But anyway, as far as which one to use, ignore questions of performance, which are unlikely important even in C++. This is the principle you should use when deciding which to use:
Say what you mean in code.
If you don't need the value-before-increment in your statement, don't use that form of the operator. It's a minor issue, but unless you are working with a style guide that bans one version in favor of the other altogether (aka a bone-headed style guide), you should use the form that most exactly expresses what you are trying to do.
QED, use the pre-increment version:
for (int i = 0; i != X; ++i) ...
Use kafka-consumer-groups.sh
For example
bin/kafka-consumer-groups.sh --list --bootstrap-server localhost:9092
bin/kafka-consumer-groups.sh --describe --group mygroup --bootstrap-server localhost:9092
/* Microsoft Edge Browser 12-18 (All versions before Chromium) */
This one should work:
@supports (-ms-ime-align:auto) {
.selector {
property: value;
}
}
For more see: Browser Strangeness
sudo apt-get update
OpenGL: sudo apt-get install libglu1-mesa-dev freeglut3-dev mesa-common-dev
Locate your Visual Studio folder for where it puts libraries and also header files, download and copy lib files to lib folder and header files to header. Then copy dll files to system32. Then your code will 100% run.
Also Windows: For all of those includes you just need to download glut32.lib
, glut.h
, glut32.dll
.
If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time
with the ability to do arithmetic. If you go past midnight, it just wraps around:
>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'
It's available from PyPi as nptime
("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime
The documentation is at http://tgs.github.io/nptime/
This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.
tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000
This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.
I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:
#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000
It requires a minor CSS addition to make it work with Bootstrap 3:
.input-group-btn:last-child > .form-control {_x000D_
margin-left: -1px;_x000D_
width: auto;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="form-group">_x000D_
<div class="input-group">_x000D_
<input class="form-control" name="q" type="text" placeholder="Search">_x000D_
_x000D_
<div class="input-group-btn">_x000D_
<select class="form-control" name="category">_x000D_
<option>select</option>_x000D_
<option>1</option>_x000D_
<option>2</option>_x000D_
<option>3</option>_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>
_x000D_
If this is part of a batch script (.bat
file) and you have a large list of files, you can use a multi-line ^
, and optional /Y
flag to suppresses prompting to confirm you want to overwrite an existing destination file.
REM Concatenate several files to one
COPY /Y ^
this_is_file_1.csv + ^
this_is_file_2.csv + ^
this_is_file_3.csv + ^
this_is_file_4.csv + ^
this_is_file_5.csv + ^
this_is_file_6.csv + ^
this_is_file_7.csv + ^
this_is_file_8.csv + ^
this_is_file_9.csv ^
output_file.csv
This is tidier than performing the command on one line.
I'm using EasyPHP in making my Thesis about Content Management System. So far, this tool is very good and easy to use.
use this for custom dismissal
var dismissKeyboard = require('dismissKeyboard');
var TestView = React.createClass({
render: function(){
return (
<TouchableWithoutFeedback
onPress={dismissKeyboard}>
<View />
</TouchableWithoutFeedback>
)
}
})
Here's a weird one, make sure you have consistent spacing in the config file.
For example:
processManagement:
timeZoneInfo: /usr/share/zoneinfo
security:
authorization: 'enabled'
If the authorization key has 4 spaces before it, like above and the rest are 2 spaces then it won't work.
This should get you started:
log4j.rootLogger=QuietAppender, LoudAppender, TRACE
# setup A1
log4j.appender.QuietAppender=org.apache.log4j.RollingFileAppender
log4j.appender.QuietAppender.Threshold=INFO
log4j.appender.QuietAppender.File=quiet.log
...
# setup A2
log4j.appender.LoudAppender=org.apache.log4j.RollingFileAppender
log4j.appender.LoudAppender.Threshold=DEBUG
log4j.appender.LoudAppender.File=loud.log
...
log4j.logger.com.yourpackage.yourclazz=TRACE
Methods description:
*toLowerCase()* Returns a new string with all characters converted to lowercase.
*toUpperCase()* Returns a new string with all characters converted to uppercase.
For example:
"Welcome".toLowerCase()
returns a new string, welcome
"Welcome".toUpperCase()
returns a new string, WELCOME
I tried with a rest client.
Headers :
it works fine. I retrieve 200 OK with a good body.
Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.
You need to run the ng server from the c:\project\angular-src location. Not just the root of your project.
Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.
Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House.
The above two are forms of containment (hence the parent-child relationships).
Dependency is a weaker form of relationship and in code terms indicates that a class uses another by parameter or return type.
Dependency is a form of association.
To get a compact list without dependencies simply use
npm list -g --depth 0
The accepted answer above is great if you are loading the image based on a button click, however if you are doing it in a new activity it freezes up the UI for a second or two. Looking around I found that a simple asynctask eliminated this problem.
To use an asynctask to add this class at the end of your activity:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
And call from your onCreate() method using:
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(MY_URL_STRING);
Dont forget to add below permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>
Works great for me. :)
<ul>
<li><strong>This text will be bold.</strong>This text will NOT be bold.
</li>
</ul>
Simple seven step to solve issue in case of WampServer:
Execute Statement
SET PASSWORD FOR root@localhost=PASSWORD('root');
open D:\wamp\apps\phpmyadmin4.1.14\config.inc.php file set value
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = '';
Restart All services
This is sufficient...
xpath xhtmlfile.xhtml '/html/head/title/text()' > titleOfXHTMLPage.txt
-We can create ParentComponent and with handleInputChange method to update the ParentComponent state. Import the ChildComponent and we pass two props from parent to child component ie.handleInputChange function and count.
import React, { Component } from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.state = {
count: '',
};
}
handleInputChange(e) {
const { value, name } = e.target;
this.setState({ [name]: value });
}
render() {
const { count } = this.state;
return (
<ChildComponent count={count} handleInputChange={this.handleInputChange} />
);
}
}
Now we create the ChildComponent file and save as ChildComponent.jsx. This component is stateless because the child component doesn't have a state. We use the prop-types library for props type checking.
import React from 'react';
import { func, number } from 'prop-types';
const ChildComponent = ({ handleInputChange, count }) => (
<input onChange={handleInputChange} value={count} name="count" />
);
ChildComponent.propTypes = {
count: number,
handleInputChange: func.isRequired,
};
ChildComponent.defaultProps = {
count: 0,
};
export default ChildComponent;
You wouldn’t: it’s messy and hard to read.
You’re looking for the switch
statement in the first case. The second is fine as it is but still could be converted for consistency
Ternary statements are much more suited to boolean values and alternating logic.
Make sure upload
plugin implements this.each
in it so that it will execute the logic for all the matching elements. It should ideally work
$("#upload_link,#upload_link2,#upload_link3").upload(function(){ });
from documentation http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute means a request was cancelled before going anywhere
I think here "inflating a view" means fetching the layout.xml file drawing a view specified in that xml file and POPULATING ( = inflating ) the parent viewGroup with the created View.
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.Please check the directory or the folder in which you're installing your new package. This happened to me as well, My whole project was in a subdirectory and I was trying to install in the main directory. After checking the whole thing I found out that I had to install in the subdirectory where my project files and package.json files are located and it's done. Hope this helps...
I got trouble to get it so I post pictures showing different options:
Very very similar UI since at least Chrome 38.0.2125.111 [11 December 2014]
In tab Sources
:
When button is activated, you can Pause On Caught Exceptions
with the checkbox below:
Chrome 27.0.1453.93 Stable
One of the aspects of .NET I like the most are generics. Even if you write procedural code in F#, you will still benefit from type inference. It makes writing generic code easy.
In C#, you write concrete code by default, and you have to put in some extra work to write generic code.
In F#, you write generic code by default. After spending over a year of programming in both F# and C#, I find that library code I write in F# is both more concise and more generic than the code I write in C#, and is therefore also more reusable. I miss many opportunities to write generic code in C#, probably because I'm blinded by the mandatory type annotations.
There are however situations where using C# is preferable, depending on one's taste and programming style.
We can use drush command also to check logs
drush watchdog-show
it will show recent 10 messages.
or if we want to continue showing logs with more information we can user
drush watchdog-show --tail --full.
You probably get the error because your video path may be wrong in a way. Be sure your path is completely correct.
Bootstrap 3 now has Responsive tables out of the box. Hooray! :)
You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive
Add a <div class="table-responsive">
surrounding your table and you should be good to go:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
To make it work on all layouts you can do this:
.table-responsive
{
overflow-x: auto;
}
I was looking for the onClick option to set the title and body of the modal based on the item in a list. T145's answer helped a lot, so I wanted to share how I used it.
Make sure the tag containing the JavaScript function is of type text/javascript to avoid conflicts:
<script type="text/javascript"> function showMyModalSetTitle(myTitle, myBodyHtml) {
/*
* '#myModayTitle' and '#myModalBody' refer to the 'id' of the HTML tags in
* the modal HTML code that hold the title and body respectively. These id's
* can be named anything, just make sure they are added as necessary.
*
*/
$('#myModalTitle').html(myTitle);
$('#myModalBody').html(myBodyHtml);
$('#myModal').modal('show');
}</script>
This function can now be called in the onClick method from inside an element such as a button:
<button type="button" onClick="javascript:showMyModalSetTitle('Some Title', 'Some body txt')"> Click Me! </button>
As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.
To guess what's the source encoding you can use the file
*nix command.
Example:
$ file --mime jumper.xml
jumper.xml: application/xml; charset=utf-8
We have used the following approach in one of our websites from http://seclab.stanford.edu/websec/framebusting/framebust.pdf
<style>
body {
display : none
}
</style>
<script>
if(self == top) {
document.getElementsByTagName("body")[0].style.display = 'block';
}
else{
top.location = self.location;
}
</script>
Just set all the selected time unit's displayFormat
to MMM DD
options: {
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MMM DD',
'second': 'MMM DD',
'minute': 'MMM DD',
'hour': 'MMM DD',
'day': 'MMM DD',
'week': 'MMM DD',
'month': 'MMM DD',
'quarter': 'MMM DD',
'year': 'MMM DD',
}
...
Notice that I've set all the unit's display format to MMM DD
. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'MMM DD'
}
...
Fiddle - http://jsfiddle.net/prfd1m8q/
I don't think it guarantees the order of calling logger.log(res);
Actually, it does. That statement is executed before the resolve
call.
Any suggestions?
Lots. The most important is your use of the create-promise-manually antipattern - just do only
promiseWhile(…, function() {
return db.getUser(email)
.then(function(res) {
logger.log(res);
count++;
});
})…
Second, that while
function could be simplified a lot:
var promiseWhile = Promise.method(function(condition, action) {
if (!condition()) return;
return action().then(promiseWhile.bind(null, condition, action));
});
Third, I would not use a while
loop (with a closure variable) but a for
loop:
var promiseFor = Promise.method(function(condition, action, value) {
if (!condition(value)) return value;
return action(value).then(promiseFor.bind(null, condition, action));
});
promiseFor(function(count) {
return count < 10;
}, function(count) {
return db.getUser(email)
.then(function(res) {
logger.log(res);
return ++count;
});
}, 0).then(console.log.bind(console, 'all done'));
This worked for me, including recursively into submodules (perhaps that's why your -f didn't work, cause you changed a submodule inside the submodule):
git submodule update -f --recursive
This is how I do it in Laravel 5
return Response::json(['hello' => $value],201);
Or using a helper function:
return response()->json(['hello' => $value], 201);
SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:
-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);
-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here
-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted
Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:
-(void)someMethod:(NSTimer*)timer;
So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:
@implementation MyObject
-(void)myTimerCallback:(NSTimer*)timer
{
// do some computations
if( timerShouldEnd ) {
[timer invalidate];
}
}
@end
// ...
int main(int argc, const char **argv)
{
// do setup stuff
MyObject* obj = [[MyObject alloc] init];
SEL mySelector = @selector(myTimerCallback:);
[NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
// do some tear-down
return 0;
}
In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
From the Perldoc page on sleep:
For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep().
Actually, it provides usleep()
(which sleeps in microseconds) and nanosleep()
(which sleeps in nanoseconds). You may want usleep()
, which should let you deal with easier numbers. 1 millisecond sleep (using each):
use strict;
use warnings;
use Time::HiRes qw(usleep nanosleep);
# 1 millisecond == 1000 microseconds
usleep(1000);
# 1 microsecond == 1000 nanoseconds
nanosleep(1000000);
If you don't want to (or can't) load a module to do this, you may also be able to use the built-in select()
function:
# Sleep for 250 milliseconds
select(undef, undef, undef, 0.25);
This works on MacOS Mountain Lion (10.8), Solaris 10 (SunOS 5.10) and RHE Linux (Red Hat Enterprise Linux Server release 5.3, Tikanga)...
$ sed 's/{pattern}/\^J/g' foo.txt > foo2.txt
... where the ^J
is done by doing ctrl+v+j. Do mind the \
before the ^J
.
PS, I know the sed in RHEL is GNU, the MacOS sed is FreeBSD based, and although I'm not sure about the Solaris sed, I believe this will work pretty much with any sed. YMMV tho'...
It took me more than 4 hours to fix this problem. I followed the guide from http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android
I'm using Android Studio (Eclipse with ADT could not work properly because of the build problem).
Solution that worked for me:
I put the /assets/www/index.html under app/src/main/assets directory. (take care AndroidStudio has different perspectives like Project or Android)
use super.loadUrl("file:///android_asset/www/index.html"); instead of super.loadUrl("file:///android_assets/www/index.html"); (no s)
Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary
// fordictionary
var x = (from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() })
.ToDictionary( t => t.type, t => t.count);
//for stringbuilder not sure for this
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
StringBuilder MyStringBuilder = new StringBuilder();
foreach (var res in x)
{
//: is separator between to object
MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
}
Console.WriteLine(MyStringBuilder.ToString());
I know this doesn't answer OPs exact question but I came here with the same symptom but a different cause:
I had the .scss files of Slick Slider included like this:
@import "../../../node_modules/slick-carousel/slick/slick.scss";
On closer inspection it turned out that the it was trying to load the font from an invalid location (<host>/assets/css/fonts/slick.woff
), the way it was referenced from the stylesheet.
I ended up simply copying the /font/
to my assets/css/
and the issue was resolved for me.
To activate "test" profile write in your build.gradle:
test.doFirst {
systemProperty 'spring.profiles.active', 'test'
activeProfiles = 'test'
}
Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:
<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>
This error occurs mostly because of field size. CHECK all the field sizes in a database table.
Cast/Convert the values to a Date
type for your group by.
GROUP BY CAST(myDateTime AS DATE)
DECLARE @id INT
DECLARE @filename NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT top 3 id,
filename
FROM table
OPEN @getid
WHILE 1=1
BEGIN
FETCH NEXT
FROM @getid INTO @id, @filename
IF @@FETCH_STATUS < 0 BREAK
print @id
END
CLOSE @getid
DEALLOCATE @getid
Here is how to tackle three different browsers: IE, FF and Chrome
<style type='text/css'>
/*This will work for chrome */
#categoryBackNextButtons
{
width:490px;
}
/*This will work for firefox*/
@-moz-document url-prefix() {
#categoryBackNextButtons{
width:486px;
}
}
</style>
<!--[if IE]>
<style type='text/css'>
/*This will work for IE*/
#categoryBackNextButtons
{
width:486px;
}
</style>
<![endif]-->
Recaptcha will not work on localhost/
Use `127.0.0.1/` instead of `localhost/`
Since there's no mention of how to compile a .c file together with a bunch of .o files, and this comment asks for it:
where's the main.c in this answer? :/ if file1.c is the main, how do you link it with other already compiled .o files? – Tom Brito Oct 12 '14 at 19:45
$ gcc main.c lib_obj1.o lib_obj2.o lib_objN.o -o x0rbin
Here, main.c is the C file with the main() function and the object files (*.o) are precompiled. GCC knows how to handle these together, and invokes the linker accordingly and results in a final executable, which in our case is x0rbin.
You will be able to use functions not defined in the main.c but using an extern reference to functions defined in the object files (*.o).
You can also link with .obj or other extensions if the object files have the correct format (such as COFF).
Is that an actual compiler error or a Code Analysis error? Some times the code analysis can be a bit sketchy and report non-valid errors.
To turn off code analysis for the project, right click on your project in the Project Explorer, click on Properties, then go to the C/C++ General tab, then Code Analysis. Then click on "Use Project Settings" and disable the ones that you do not wish for.
Also, are you sure you are compiling with the C++11 compiler?
# I'd use tkinter for python 3
import tkinter
tk = tkinter.Tk()
tk.geometry("400x300+500+300")
l = Label(tk,text="")
l.pack()
e = Entry(tk)
e.pack()
def click():
e['text'] = 'You clicked the button'
b = Button(tk,text="Click me",command=click)
b.pack()
tk.mainloop()
# After this I would you py2exe
# search for the use of this module on stakoverflow
# otherwise I could edit this to let you know how to do it
Then you should use py2exe, for example, to bring in one folder all the files needed to run the app, even if the user has not python on his pc (I am talking of windows... for the apple os there is no need of an executable file, I think, as it come with python in it without any need of installing it.
with this code:
from distutils.core import setup
import py2exe
setup(console=['l4h.py'])
2) Put your program in the same folder of setup.py put in this folder the program you want to make it distribuitable: es: l4h.py
3) Run cmd from that folder (on the folder, right click + shift and choose start cmd here)
4) write in cmd:>python setup.py py2exe
5) in the dist folder there are all the files you need
6) you can zip it and distribute it
**
pip install pyinstaller
**
**
pyinstaller file.py
**
FOR IMAGE VIEW (set these parameters)
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:scaleType = "fitCenter"
android:adjustViewBounds = "true"
Now whatever the size of the image is there, it's width will match the parent and height will be according to match the ratio. I have tested this and I am 100% sure.
// Results will be:
Image width -> stretched as match parent
Image height -> according to image width (maximum to aspect ratio)
// like the first one
<?php
$to1 = '[email protected]';
$subject = 'Tester subject';
// To send HTML mail, the Content-type header must be set
$headers .= "Reply-To: The Sender <[email protected]>\r\n";
$headers .= "Return-Path: The Sender <[email protected]>\r\n";
$headers .= "From: [email protected]" ."\r\n" .
$headers .= "Organization: Sender Organization\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
?>
Try this one add this code to your manifest file
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
provide your path type path.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
and add this code to your functionality
File file = new File(tempPathNameFileString);
Intent viewPdf = new Intent(Intent.ACTION_VIEW);
viewPdf.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
Uri URI = FileProvider.getUriForFile(ReportsActivity.this, ReportsActivity.this.getApplicationContext().getPackageName() + ".provider", file);
viewPdf.setDataAndType(URI, "application/pdf");
viewPdf.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ReportsActivity.this.startActivity(viewPdf);
The cool thing about the new Google Recaptcha is that the validation is now completely encapsulated in the widget. That means, that the widget will take care of asking questions, validating responses all the way till it determines that a user is actually a human, only then you get a g-recaptcha-response value.
But that does not keep your site safe from HTTP client request forgery.
Anyone with HTTP POST knowledge could put random data inside of the g-recaptcha-response form field, and foll your site to make it think that this field was provided by the google widget. So you have to validate this token.
In human speech it would be like,
Validating the response is really easy. Just make a GET Request to
And replace the response_string with the value that you earlier got by the g-recaptcha-response field.
You will get a JSON Response with a success field.
More information here: https://developers.google.com/recaptcha/docs/verify
Edit: It's actually a POST, as per documentation here.
In addition to Gilson PJ answer:
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
with
"scripts": {
"build": "NODE_ENV=production webpack -p --config ./webpack.production.config.js"
},
cause that the it tries to uglify your code twice. See https://webpack.github.io/docs/cli.html#production-shortcut-p for more information.
You can fix this by removing the UglifyJsPlugin from plugins-array or add the OccurrenceOrderPlugin and remove the "-p"-flag. so one possible solution would be
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
and
"scripts": {
"build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},
Today, we should just use Flexbox.
OLD ANSWER:
OK, although I've upvoted both the font-size: 0;
and the not implemented CSS3 feature
answers,
after trying I found out that none of them is a real solution.
Actually, there is not even one workaround without strong side effects.
Then I decided to remove the spaces (this answers is about this argument) between the inline-block
divs from my HTML
source (JSP
),
turning this:
<div class="inlineBlock">
I'm an inline-block div
</div>
<div class="inlineBlock">
I'm an inline-block div
</div>
to this
<div class="inlineBlock">
I'm an inline-block div
</div><div class="inlineBlock">
I'm an inline-block div
</div>
that is ugly, but working.
But, wait a minute... what if I'm generating my divs inside Taglibs loops
(Struts2
, JSTL
, etc...) ?
For example:
<s:iterator begin="0" end="6" status="ctrDay">
<br/>
<s:iterator begin="0" end="23" status="ctrHour">
<s:push value="%{days[#ctrDay.index].hours[#ctrHour.index]}">
<div class="inlineBlock>
I'm an inline-block div in a matrix
(Do something here with the pushed object...)
</div>
</s:push>
</s:iterator>
</s:iterator>
It is absolutely not thinkable to inline all that stuff, it would mean
<s:iterator begin="0" end="6" status="ctrDay">
<br/>
<s:iterator begin="0" end="23" status="ctrHour"><s:push value="%{days[#ctrDay.index].hours[#ctrHour.index]}"><div class="inlineBlock>
I'm an inline-block div in a matrix
(Do something here with the pushed object...)
</div></s:push></s:iterator>
</s:iterator>
That is not readable, hard to maintain and understand, etc.
The solution I found:
use HTML comments to connect the end of one div to the begin of the next one!
<s:iterator begin="0" end="6" status="ctrDay">
<br/>
<s:iterator begin="0" end="23" status="ctrHour"><!--
--><s:push value="%{days[#ctrDay.index].hours[#ctrHour.index]}"><!--
--><div class="inlineBlock>
I'm an inline-block div in a matrix
(Do something here with the pushed object...)
</div><!--
--></s:push><!--
--></s:iterator>
</s:iterator>
This way you will have a readable and correctly indented code.
And, as a positive side effect, the HTML source
, although infested by empty comments,
will result correctly indented;
let's take the first example. In my humble opinion, this:
<div class="inlineBlock">
I'm an inline-block div
</div><!--
--><div class="inlineBlock">
I'm an inline-block div
</div>
is better than this:
<div class="inlineBlock">
I'm an inline-block div
</div><div class="inlineBlock">
I'm an inline-block div
</div>
If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.
<input id="addButton" type="button" value="Add" />
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#addButton').click(function()
{
showDialog('#addPerson');
});
});
</script>
If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:
<asp:Button ID="buttonAdd" runat="server" Text="Add" />
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#<%= buttonAdd.ClientID %>').click(function(e)
{
showDialog('#addPerson');
if(/*Some Condition Is Not Met*/)
return false;
});
});
</script>
double d = Double.parseDouble(aString);
This should convert the string aString into the double d.
You can write the function this way also Which helps to build your code one time just to add class name or ID at the end
function equalHeight(group) {
tallest = 0;
group.each(function() {
thisHeight = jQuery(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}
equalHeight(jQuery("Add your class"));
Though the carret will be preferable way to do this here's one more approach using macro that constructs a command by the passed arguments:
@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "{{=setlocal enableDelayedExpansion&for %%a in (" & set "}}="::end::" ) do if "%%~a" neq "::end::" (set command=!command! %%a) else (call !command! & endlocal)"
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
%{{%
echo
"command"
written
on a
few lines
%}}%
command is easier to read without the carets but using special symbols e.g. brackets,redirection and so on will break it. So you can this for more simpler cases. Though you can still enclose parameters in double quotes
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info:
Prepend the url prefix git+
(See VCS Support):
pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6
And specify the branch name without the leading /
.
Timing with random strings of ASCII printables:
from inspect import getsource
from random import sample
import re
from string import printable
from timeit import timeit
pattern_single = re.compile(r'[\W]')
pattern_repeat = re.compile(r'[\W]+')
translation_tb = str.maketrans('', '', ''.join(c for c in map(chr, range(256)) if not c.isalnum()))
def generate_test_string(length):
return ''.join(sample(printable, length))
def main():
for i in range(0, 60, 10):
for test in [
lambda: ''.join(c for c in generate_test_string(i) if c.isalnum()),
lambda: ''.join(filter(str.isalnum, generate_test_string(i))),
lambda: re.sub(r'[\W]', '', generate_test_string(i)),
lambda: re.sub(r'[\W]+', '', generate_test_string(i)),
lambda: pattern_single.sub('', generate_test_string(i)),
lambda: pattern_repeat.sub('', generate_test_string(i)),
lambda: generate_test_string(i).translate(translation_tb),
]:
print(timeit(test), i, getsource(test).lstrip(' lambda: ').rstrip(',\n'), sep='\t')
if __name__ == '__main__':
main()
Result (Python 3.7):
Time Length Code
6.3716264850008880 00 ''.join(c for c in generate_test_string(i) if c.isalnum())
5.7285426190064750 00 ''.join(filter(str.isalnum, generate_test_string(i)))
8.1875841680011940 00 re.sub(r'[\W]', '', generate_test_string(i))
8.0002205439959650 00 re.sub(r'[\W]+', '', generate_test_string(i))
5.5290945199958510 00 pattern_single.sub('', generate_test_string(i))
5.4417179649972240 00 pattern_repeat.sub('', generate_test_string(i))
4.6772285089973590 00 generate_test_string(i).translate(translation_tb)
23.574712151996210 10 ''.join(c for c in generate_test_string(i) if c.isalnum())
22.829975890002970 10 ''.join(filter(str.isalnum, generate_test_string(i)))
27.210196289997840 10 re.sub(r'[\W]', '', generate_test_string(i))
27.203713296003116 10 re.sub(r'[\W]+', '', generate_test_string(i))
24.008979928999906 10 pattern_single.sub('', generate_test_string(i))
23.945240008994006 10 pattern_repeat.sub('', generate_test_string(i))
21.830899796994345 10 generate_test_string(i).translate(translation_tb)
38.731336012999236 20 ''.join(c for c in generate_test_string(i) if c.isalnum())
37.942474347000825 20 ''.join(filter(str.isalnum, generate_test_string(i)))
42.169366310001350 20 re.sub(r'[\W]', '', generate_test_string(i))
41.933375883003464 20 re.sub(r'[\W]+', '', generate_test_string(i))
38.899814646996674 20 pattern_single.sub('', generate_test_string(i))
38.636144253003295 20 pattern_repeat.sub('', generate_test_string(i))
36.201238164998360 20 generate_test_string(i).translate(translation_tb)
49.377356811004574 30 ''.join(c for c in generate_test_string(i) if c.isalnum())
48.408927293996385 30 ''.join(filter(str.isalnum, generate_test_string(i)))
53.901889764994850 30 re.sub(r'[\W]', '', generate_test_string(i))
52.130339455994545 30 re.sub(r'[\W]+', '', generate_test_string(i))
50.061149017004940 30 pattern_single.sub('', generate_test_string(i))
49.366573111998150 30 pattern_repeat.sub('', generate_test_string(i))
46.649754120997386 30 generate_test_string(i).translate(translation_tb)
63.107938601999194 40 ''.join(c for c in generate_test_string(i) if c.isalnum())
65.116287978999030 40 ''.join(filter(str.isalnum, generate_test_string(i)))
71.477421126997800 40 re.sub(r'[\W]', '', generate_test_string(i))
66.027950693998720 40 re.sub(r'[\W]+', '', generate_test_string(i))
63.315361931003280 40 pattern_single.sub('', generate_test_string(i))
62.342320287003530 40 pattern_repeat.sub('', generate_test_string(i))
58.249303059004890 40 generate_test_string(i).translate(translation_tb)
73.810345625002810 50 ''.join(c for c in generate_test_string(i) if c.isalnum())
72.593953348005020 50 ''.join(filter(str.isalnum, generate_test_string(i)))
76.048324580995540 50 re.sub(r'[\W]', '', generate_test_string(i))
75.106637657001560 50 re.sub(r'[\W]+', '', generate_test_string(i))
74.681338128997600 50 pattern_single.sub('', generate_test_string(i))
72.430461594005460 50 pattern_repeat.sub('', generate_test_string(i))
69.394243567003290 50 generate_test_string(i).translate(translation_tb)
str.maketrans
& str.translate
is fastest, but includes all non-ASCII characters.
re.compile
& pattern.sub
is slower, but is somehow faster than ''.join
& filter
.
I tried the solutions mentioned above and none of them worked for me. I used JSON.parse and it worked:
$http.get('/api/getAdPolling')
.success(function (data) {
console.log('success: ' + data.length);
if (JSON.stringify(data) != "not found") {
$scope.adPoll = JSON.parse(data);
}
})
.error(function (data) {
console.log('Error: ' + data);
});
In order:
i got the same issue, i updated the hosts file with the server address and it worked
Suggested From Android Studio lint check : Remove Unnecessary boxing : So, unboxing is :
public static long integerToLong (int minute ){
int delay = minute*1000;
long diff = (long) delay;
return diff ;
}
You are not permitted to remove elements from the list while iterating over it using a for
loop.
The best way to rewrite the code depends on what it is you're trying to do.
For example, your code is equivalent to:
for item in a:
print item
a[:] = []
Alternatively, you could use a while
loop:
while a:
print a.pop(0)
I'm trying to remove items if they match a condition. Then I go to next item.
You could copy every element that doesn't match the condition into a second list:
result = []
for item in a:
if condition is False:
result.append(item)
a = result
Alternatively, you could use filter
or a list comprehension and assign the result back to a
:
a = filter(lambda item:... , a)
or
a = [item for item in a if ...]
where ...
stands for the condition that you need to check.
From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection
:
library(devtools)
install_github("twitter/AnomalyDetection")
does the trick.
Use this:
Format(Now, "MMMM dd, yyyy")
More: Format Function
xargs and seq will help
function __run_times { seq 1 $1| { shift; xargs -i -- "$@"; } }
the view :
abon@abon:~$ __run_times 3 echo hello world
hello world
hello world
hello world
Your main objective in crafting your questions should be to make it as easy as possible for readers to understand and reproduce your problem on their systems. To do so:
This does take some work, but it seems like a fair trade-off since you ask others to do work for you.
The best option by far is to rely on built-in datasets. This makes it very easy for others to work on your problem. Type data()
at the R prompt to see what data is available to you. Some classic examples:
iris
mtcars
ggplot2::diamonds
(external package, but almost everyone has it)Inspect the built-in datasets to find one suitable for your problem.
If you can rephrase your problem to use the built-in datasets, you are much more likely to get good answers (and upvotes).
If your problem is specific to a type of data that is not represented in the existing data sets, then provide the R code that generates the smallest possible dataset that your problem manifests itself on. For example
set.seed(1) # important to make random data reproducible
myData <- data.frame(a=sample(letters[1:5], 20, rep=T), b=runif(20))
Someone trying to answer my question can copy/paste those two lines and start working on the problem immediately.
As a last resort, you can use dput
to transform a data object to R code (e.g. dput(myData)
). I say as a "last resort" because the output of dput
is often fairly unwieldy, annoying to copy-paste, and obscures the rest of your question.
Someone once said:
A picture of expected output is worth 1000 words
-- a sage person
If you can add something like "I expected to get this result":
cyl mean.hp
1: 6 122.28571
2: 4 82.63636
3: 8 209.21429
to your question, people are much more likely to understand what you are trying to do quickly. If your expected result is large and unwieldy, then you probably haven't thought enough about how to simplify your problem (see next).
The main thing to do is simplify your problem as much as possible before you ask your question. Re-framing the problem to work with the built-in datasets will help a lot in this regard. You will also often find that just by going through the process of simplification, you will answer your own problem.
Here are some examples of good questions:
In both cases, the user's problems are almost certainly not with the simple examples they provide. Rather they abstracted the nature of their problem and applied it to a simple data set to ask their question.
This answer focuses on what I think is the best practice: use built-in data sets and provide what you expect as a result in a minimal form. The most prominent answers focus on other aspects. I don't expect this answer to rising to any prominence; this is here solely so that I can link to it in comments to newbie questions.
From Bootstrap's docs about the remote
option;
This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.
If a remote URL is provided, content will be loaded one time via jQuery's
load
method and injected into the.modal-content
div. If you're using the data-api, you may alternatively use thehref
attribute to specify the remote source. An example of this is shown below:<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>
That's the .modal-content
div, not .modal-body
. If you want to put content inside .modal-body
then you need to do that with custom javascript.
So I would call jQuery.load
programmatically, meaning you can keep the functionality of the dismiss and/or other buttons as required.
To do this you could use a data tag with the URL from the button that opens the modal, and use the show.bs.modal
event to load content into the .modal-body
div.
HTML Link/Button
<a href="#" data-toggle="modal" data-load-url="remote.html" data-target="#myModal">Click me</a>
jQuery
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = $(e.relatedTarget).data('load-url');
$(this).find('.modal-body').load(loadurl);
});
You can use the application called Supervisor. In supervisor config you can define multiple services and ways to execute the same.
For Java and Spring boot applications the command would be
java -jar springbootapp.jar
.
Options can be provided to keep the application running always.So if the EC2 restart then Supervisor will restart you application
I found Supervisor easy to use compared to putting startup scripts in /etc/init.d/.The startup scripts would hang or go into waiting state in case of errors .
You're missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
...
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...
This may be of some help (do not literally write out the backslashes '\' in the commands, they are meant to indicate that "everything has to be on one line"):
It seems that all the commands (in grey) take any type of key file (in green) as "in" argument. Which is nice.
Here are the commands again for easier copy-pasting:
openssl rsa -in $FF -out $TF
openssl rsa -aes256 -in $FF -out $TF
openssl pkcs8 -topk8 -nocrypt -in $FF -out $TF
openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -in $FF -out $TF
and
openssl rsa -check -in $FF
openssl rsa -text -in $FF
If you are using numpy
and your array is an np.array
of np.array
elements like:
A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
and you want to access the inner elements (like 10,11,12 13,14.......
) then use:
A[0][0]
instead of A[0,0]
For example:
>>> import numpy as np
>>>A = np.array([np.array([10,11,12,13]), np.array([15,16,17,18]), np.array([19,110,111,112])])
>>> A[0][0]
>>> 10
>>> A[0,0]
>>> Throws ERROR
(P.S.: Might be useful when using numpy.array_split()
)
Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:
@AllArgsConstructor public class Parent { private String a; } public class Child extends Parent { private String b; @Builder public Child(String a, String b){ super(a); this.b = b; } }
As a result you can then use the generated builder like this:
Child.builder().a("testA").b("testB").build();
The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.
I also found this works nicely with Spring Data JPA.
Try this :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<style type="text/css">
#btn_s{
width:100px;
}
#btn_i {
width:125px;
}
#formbox {
width:400px;
margin:auto 0;
text-align: center;
}
</style>
</head>
<body>
<form method="post" action="">
<div id="formbox">
<input value="Search" title="Search" type="submit" id="btn_s">
<input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit" id="btn_i">
</div>
</form>
</body>
This has 2 examples, you can use the one that fits best in your situation.
text-align:center
on the parent container, or create a container for this.auto
left and right margins to center it in the parent container.note that auto
is used with single blocks to center them in the parent space by distrubuting the empty space to the left and right.
With @Lob
I always end up with a LONGTEXT
in MySQL.
To get TEXT
I declare it that way (JPA 2.0):
@Column(columnDefinition = "TEXT")
private String text
Find this better, because I can directly choose which Text-Type the column will have in database.
For columnDefinition
it is also good to read this.
EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT"
.
I think there is no need to specify
'http://localhost:8080`"
in the URI part.. because. if you specify it, You'll have to change it manually for every environment.
Only
"/restws/json/product/get" also works
Split-Path -Path (Get-Location).Path -Parent
You should consult the documentation of whatever library is throwing the exception, to see how to get an error message out of its exceptions.
Alternatively, a good way to debug this kind of thing is to say:
except Exception, e:
print dir(e)
to see what properties e
has - you'll probably find it has a message
property or similar.
Open Terminal:
vi ~/.bash_profile
Apply changing to system (no need restart computer):
source ~/.bash_profile
(Also work with macOS Sierra 10.12.1)
@mshobnr / @olegkhuss solution made into a simple macro:
{% macro trunc(txt, len) -%}
{{ txt|length > len ? txt|slice(0, len) ~ '…' : txt }}
{%- endmacro %}
Usage example:
{{ tools.trunc('This is the text to truncate. ', 50) }}
N.b. I import a Twig template containing macros and import it as 'tools' like this (Symfony):
{% import "@AppBundle/tools.html.twig" as tools -%}
Also, I replaced the html character code with the actual character, this should be no problem when using UTF-8 as the file encoding. This way you don't have to use |raw
(as it could cause a security issue).
You can!
Extending @marcg 's UtilException
and adding throw E
where necessary: this way, the compiler will ask you to add throw clauses and everything's as if you could throw checked exceptions natively on java 8's streams.
Instructions: just copy/paste LambdaExceptionUtil
in your IDE and then use it as shown in the below LambdaExceptionUtilTest
.
public final class LambdaExceptionUtil {
@FunctionalInterface
public interface Consumer_WithExceptions<T, E extends Exception> {
void accept(T t) throws E;
}
@FunctionalInterface
public interface Function_WithExceptions<T, R, E extends Exception> {
R apply(T t) throws E;
}
/**
* .forEach(rethrowConsumer(name -> System.out.println(Class.forName(name))));
*/
public static <T, E extends Exception> Consumer<T> rethrowConsumer(Consumer_WithExceptions<T, E> consumer) throws E {
return t -> {
try {
consumer.accept(t);
} catch (Exception exception) {
throwActualException(exception);
}
};
}
/**
* .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
*/
public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E {
return t -> {
try {
return function.apply(t);
} catch (Exception exception) {
throwActualException(exception);
return null;
}
};
}
@SuppressWarnings("unchecked")
private static <E extends Exception> void throwActualException(Exception exception) throws E {
throw (E) exception;
}
}
Some test to show usage and behaviour:
public class LambdaExceptionUtilTest {
@Test(expected = MyTestException.class)
public void testConsumer() throws MyTestException {
Stream.of((String)null).forEach(rethrowConsumer(s -> checkValue(s)));
}
private void checkValue(String value) throws MyTestException {
if(value==null) {
throw new MyTestException();
}
}
private class MyTestException extends Exception { }
@Test
public void testConsumerRaisingExceptionInTheMiddle() {
MyLongAccumulator accumulator = new MyLongAccumulator();
try {
Stream.of(2L, 3L, 4L, null, 5L).forEach(rethrowConsumer(s -> accumulator.add(s)));
fail();
} catch (MyTestException e) {
assertEquals(9L, accumulator.acc);
}
}
private class MyLongAccumulator {
private long acc = 0;
public void add(Long value) throws MyTestException {
if(value==null) {
throw new MyTestException();
}
acc += value;
}
}
@Test
public void testFunction() throws MyTestException {
List<Integer> sizes = Stream.of("ciao", "hello").<Integer>map(rethrowFunction(s -> transform(s))).collect(toList());
assertEquals(2, sizes.size());
assertEquals(4, sizes.get(0).intValue());
assertEquals(5, sizes.get(1).intValue());
}
private Integer transform(String value) throws MyTestException {
if(value==null) {
throw new MyTestException();
}
return value.length();
}
@Test(expected = MyTestException.class)
public void testFunctionRaisingException() throws MyTestException {
Stream.of("ciao", null, "hello").<Integer>map(rethrowFunction(s -> transform(s))).collect(toList());
}
}
In my case the error happened when I placed my macro (public sub) into a ThisWorkbook
section of the file expecting it will make it visible for Application.Run
function. This was not the case and I got that error you mentioned.
I moved my macro into a separate Module and it resolved the problem.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
function timerCtrl ($scope,$interval) {
$scope.seconds = 0;
var timer = $interval(function(){
$scope.seconds++;
$scope.$apply();
console.log($scope.countDown);
}, 1000);
}
Boilerplate in software development can mean different things to different people but generally means the block of code that is used over and over again.
In MEAN stack development, this term refers to code generation through use of template. It's easier than hand coding the entire application from scratch and it gives the code block consistency and fewer bugs as it is clean, tested and proven code and it's open source so it is constantly getting updated or fixed therefore it saves a lot of time as using framework or code generator. For more information about MEAN stack, click here.
Use the value
property of the <select>
element. For example:
var value = document.getElementById('your_select_id').value;
alert(value);
You can use this method to draw polyline on googleMap
// Draw polyline on map
public void drawPolyLineOnMap(List<LatLng> list) {
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(Color.RED);
polyOptions.width(5);
polyOptions.addAll(list);
googleMap.clear();
googleMap.addPolyline(polyOptions);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : list) {
builder.include(latLng);
}
final LatLngBounds bounds = builder.build();
//BOUND_PADDING is an int to specify padding of bound.. try 100.
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, BOUND_PADDING);
googleMap.animateCamera(cu);
}
You need to add this line in your gradle in case you haven't.
compile 'com.google.android.gms:play-services-maps:8.4.0'
I had the same problem
I fixed that by using two options
contentType: false
processData: false
Actually I Added these two command to my $.ajax({}) function
Like stated in this question: Git: Create a branch from unstagged/uncommited changes on master: stash is not necessary.
Just use:
git checkout -b topic/newbranch
Any uncommitted work will be taken along to the new branch.
If you try to push you will get the following message
fatal: The current branch feature/NEWBRANCH has no upstream branch. To push the current branch and set the remote as upstream, use
git push --set-upstream origin feature/feature/NEWBRANCH
Just do as suggested to create the branch remotely:
git push --set-upstream origin feature/feature/NEWBRANCH
HtmlHelper adds an hidden input to notify the controller about Unchecked status. So to have the correct checked status:
bool bChecked = form[key].Contains("true");
I found the gtag()
function worked, instead of the ga()
function.
In the index.html file, within the <head>
section:
<script async src="https://www.googletagmanager.com/gtag/js?id=TrackingId"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'TrackingId');
</script>
In the AngularJS code:
app.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeSuccess', function() {
gtag('config', 'TrackingId', {'page_path': $location.path()});
});
});
Replace TrackingId
with your own Tracking Id.
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
Try this snippet of code:
String timeSettings = android.provider.Settings.System.getString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME);
if (timeSettings.contentEquals("0")) {
android.provider.Settings.System.putString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME, "1");
}
Date now = new Date(System.currentTimeMillis());
Log.d("Date", now.toString());
Make sure to add permission in Manifest
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
following should be your right solution
ren somefile.txt somefile_%time:~0,2%%time:~3,2%-%DATE:/=%.txt
The above answer is useful but in graphs, it is difficult to distinguish between darker gradients of black. One alternative I found is to use gradients of gray colors as follows
palette(gray.colors(10, 0.9, 0.4))
plot(rep(1,10),col=1:10,pch=19,cex=3))
More info on gray scale here.
Added
When I used the code above for different colours like blue and black, the gradients were not that clear.
heat.colors()
seems more useful.
This document has more detailed information and options. pdf
<?php_x000D_
if(isset($_POST["loginForm"]))_x000D_
{_x000D_
print_r ($_POST); // FOR Showing POST DATA_x000D_
}_x000D_
elseif(isset($_POST["registrationForm"]))_x000D_
{_x000D_
print_r ($_POST);_x000D_
}_x000D_
elseif(isset($_POST["saveForm"]))_x000D_
{_x000D_
print_r ($_POST);_x000D_
}_x000D_
else{_x000D_
_x000D_
}_x000D_
?>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<fieldset>_x000D_
<legend>FORM-1 with 2 buttons</legend>_x000D_
<form method="post" >_x000D_
<input type="text" name="loginname" value ="ABC" >_x000D_
_x000D_
<!--Always use type="password" for password --> _x000D_
<input type="text" name="loginpassword" value ="abc123" >_x000D_
_x000D_
<input type="submit" name="loginForm" value="Login"><!--SUBMIT Button 1 -->_x000D_
<input type="submit" name="saveForm" value="Save"> <!--SUBMIT Button 2 -->_x000D_
</form>_x000D_
</fieldset>_x000D_
_x000D_
_x000D_
_x000D_
<fieldset>_x000D_
<legend>FORM-2 with 1 button</legend>_x000D_
<form method="post" >_x000D_
<input type="text" name="registrationname" value ="XYZ" >_x000D_
_x000D_
<!--Always use type="password" for password -->_x000D_
<input type="text" name="registrationpassword" value ="xyz123" >_x000D_
_x000D_
<input type="submit" name="registrationForm" value="Register"> <!--SUBMIT Button 3 -->_x000D_
</form>_x000D_
</fieldset>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
When click on Login -> loginForm
After enough googling I found the answer from controller you need only a backslash like return \Response::json(['success' => 'hi, atiq']);
. Or you can just return the array return array('success' => 'hi, atiq');
which will be rendered as json in Laravel version 5.2 .
And it works, thanks @trichetriche. The problem was in my RequestOptions
, apparently, you can not pass params
or body
to the RequestOptions
while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.
public post(cmd: string, data: string): Observable<any> {
const options = new RequestOptions({
headers: this.getAuthorizedHeaders(),
responseType: ResponseContentType.Json,
withCredentials: false
});
console.log('Options: ' + JSON.stringify(options));
return this.http.post(this.BASE_URL, JSON.stringify({
cmd: cmd,
data: data}), options)
.map(this.handleData)
.catch(this.handleError);
}
Here is a thing I made for myself to clear out how things work. I guess others too can find this concrete example useful:
doit().then(function() { log('Now finally done!') });_x000D_
log('---- But notice where this ends up!');_x000D_
_x000D_
// For pedagogical reasons I originally wrote the following doit()-function so that _x000D_
// it was clear that it is a promise. That way wasn't really a normal way to do _x000D_
// it though, and therefore Slikts edited my answer. I therefore now want to remind _x000D_
// you here that the return value of the following function is a promise, because _x000D_
// it is an async function (every async function returns a promise). _x000D_
async function doit() {_x000D_
log('Calling someTimeConsumingThing');_x000D_
await someTimeConsumingThing();_x000D_
log('Ready with someTimeConsumingThing');_x000D_
}_x000D_
_x000D_
function someTimeConsumingThing() {_x000D_
return new Promise(function(resolve,reject) {_x000D_
setTimeout(resolve, 2000);_x000D_
})_x000D_
}_x000D_
_x000D_
function log(txt) {_x000D_
document.getElementById('msg').innerHTML += txt + '<br>'_x000D_
}
_x000D_
<div id='msg'></div>
_x000D_
This is an example that works out of the box. If you want less "hacky", you should use inheritance library or such.
Well in a file animal.js you would write:
var method = Animal.prototype;
function Animal(age) {
this._age = age;
}
method.getAge = function() {
return this._age;
};
module.exports = Animal;
To use it in other file:
var Animal = require("./animal.js");
var john = new Animal(3);
If you want a "sub class" then inside mouse.js:
var _super = require("./animal.js").prototype,
method = Mouse.prototype = Object.create( _super );
method.constructor = Mouse;
function Mouse() {
_super.constructor.apply( this, arguments );
}
//Pointless override to show super calls
//note that for performance (e.g. inlining the below is impossible)
//you should do
//method.$getAge = _super.getAge;
//and then use this.$getAge() instead of super()
method.getAge = function() {
return _super.getAge.call(this);
};
module.exports = Mouse;
Also you can consider "Method borrowing" instead of vertical inheritance. You don't need to inherit from a "class" to use its method on your class. For instance:
var method = List.prototype;
function List() {
}
method.add = Array.prototype.push;
...
var a = new List();
a.add(3);
console.log(a[0]) //3;
You can change layout visibility just in the same way as for regular view. Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.
Here documents with the <<-HERE
terminator work well for indented multi-line text strings. It will remove any leading tabs from the here document. (Line terminators will still remain, though.)
cat <<-____HERE
continuation
lines
____HERE
See also http://ss64.com/bash/syntax-here.html
If you need to preserve some, but not all, leading whitespace, you might use something like
sed 's/^ //' <<____HERE
This has four leading spaces.
Two of them will be removed by sed.
____HERE
or maybe use tr
to get rid of newlines:
tr -d '\012' <<-____
continuation
lines
____
(The second line has a tab and a space up front; the tab will be removed by the dash operator before the heredoc terminator, whereas the space will be preserved.)
For wrapping long complex strings over many lines, I like printf
:
printf '%s' \
"This will all be printed on a " \
"single line (because the format string " \
"doesn't specify any newline)"
It also works well in contexts where you want to embed nontrivial pieces of shell script in another language where the host language's syntax won't let you use a here document, such as in a Makefile
or Dockerfile
.
printf '%s\n' >./myscript \
'#!/bin/sh` \
"echo \"G'day, World\"" \
'date +%F\ %T' && \
chmod a+x ./myscript && \
./myscript
The best way using background with gradient as it does not increase app size of your app images are poison for android app so try to use it less instead of using one color as a background you can use multiple colors in one background.
There are several good articles on the subject on dev2qa.com site, about Contacts Provider
API:
How To Add Contact In Android Programmatically
How To Update Delete Android Contacts Programmatically
How To Get Contact List In Android Programmatically
Contacts are stored in SQLite .db files in bunch of tables, the structure is discussed here: Android Contacts Database Structure
Official Google documentation on Contacts Provider here
I would always use sp_executesql these days, all it really is is a wrapper for EXEC which handles parameters & variables.
However do not forget about OPTION RECOMPILE when tuning queries on very large databases, especially where you have data spanned over more than one database and are using a CONSTRAINT to limit index scans.
Unless you use OPTION RECOMPILE, SQL server will attempt to create a "one size fits all" execution plan for your query, and will run a full index scan each time it is run.
This is much less efficient than a seek, and means it is potentially scanning entire indexes which are constrained to ranges which you are not even querying :@
handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
ftp.retrbinary('RETR %s' % filename, handle.write)
Using http.createServer
is very low-level and really not useful for creating web applications as-is.
A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express
.
When you have, you can create a basic application to handle your form:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
You can make your form point to it using:
<form action="http://127.0.0.1:8080/myaction" method="post">
The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html
). You could use Express to also serve static content, like index.html
, using the express.static
middleware.
You could use inline styles and define the width in the <th>
tag. Make it so that the sum of the widths = 100%.
<tr>
<th style="width:10%">Size</th>
<th style="width:30%">Bust</th>
<th style="width:50%">Waist</th>
<th style="width:10%">Hips</th>
</tr>
Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.
Try this. It forces navbar to grow as content added, and keeps main area centered.
<html>
<head>
<style>
section.sidebar {
width: 250px;
min-height:100vh;
position: sticky;
top: 0;
bottom: 0;
background-color: green;
}
section.main { position:sticky; top:0;bottom:0;background-color: red; margin-left: 250px;min-height:100vh; }
</style>
<script lang="javascript">
var i = 0;
function AddOne()
{
for(i = 0;i<20;i++)
{
var node = document.createElement("LI");
var textnode = document.createTextNode(' Water ' + i.toString());
node.appendChild(textnode);
document.getElementById("list").appendChild(node);
}
}
</script>
</head>
<body>
<section class="sidebar">
<button id="add" onclick="AddOne()">Add</button>
<ul id="list">
<li>bullshit 1</li>
</ul>
</section>
<section class="main">I'm the main section.</section>
</body>
</html>
Sometimes the simple method is the best. Just pad your strings with spaces. If it is only a few textboxes etc this is by far the simplest method.
You can also simply insert blank columns/rows with a fixed size. Extremely simple and you can easily change it.
HTML:
First, we will need to add a class to your text container so that we can access and style it accordingly.
<div class="col-xs-5 textContainer">
<h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>
CSS:
Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.
.textContainer {
height: 345px;
line-height: 340px;
}
.textContainer h3 {
vertical-align: middle;
display: inline-block;
}
All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.
The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *
. Also, the map
method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply
is used for.
So, if you must use the above approach, I would write it like this
df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
There's actually no reason to use zip here. You can simply do this:
df["A1"], df["A2"] = calculate(df['a'])
This second method is also much faster on larger DataFrames
df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})
DataFrame created with 300,000 rows
%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
60x faster than zip
Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above
%%timeit
A1, A2 = [], []
for val in df['a']:
A1.append(val**2)
A2.append(val**3)
df['A1'] = A1
df['A2'] = A2
298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:
%load_ext cython
%%cython
cpdef power(vals):
A1, A2 = [], []
cdef double val
for val in vals:
A1.append(val**2)
A2.append(val**3)
return A1, A2
%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
You can get even greater speed improvements if you use the direct vectorized operations.
%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.
apply
The above example should clearly show how slow apply
can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply
s = pd.Series(np.random.rand(10000000))
%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Without apply is 50x faster
%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
Wrap the contents of the cell with a div and you can do anything you want, but you have to wrap every cell in a column to get a uniform effect. For example, to just get wider left & right margins:
So the CSS will be,
div.cellwidener {_x000D_
margin: 0px 15px 0px 15px;_x000D_
}_x000D_
td.tight {_x000D_
padding: 0px;_x000D_
}
_x000D_
<table border="0">_x000D_
<tr>_x000D_
<td class="tight">_x000D_
<div class="cellwidener">My content</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Yes, it's a hassle. Yes, it works with Internet Explorer. In fact, I've only tested this with Internet Explorer, because that's all we're allowed to use at work.
As Pekka stated above
foreach ($array as $key => $value)
Also you might want to try a recursive function
displayRecursiveResults($site);
function displayRecursiveResults($arrayObject) {
foreach($arrayObject as $key=>$data) {
if(is_array($data)) {
displayRecursiveResults($data);
} elseif(is_object($data)) {
displayRecursiveResults($data);
} else {
echo "Key: ".$key." Data: ".$data."<br />";
}
}
}
Specifically, the MySQLi extension provides the following extremely useful benefits over the old MySQL extension..
OOP Interface (in addition to procedural) Prepared Statement Support Transaction + Stored Procedure Support Nicer Syntax Speed Improvements Enhanced Debugging
PDO Extension
PHP Data Objects extension is a Database Abstraction Layer. Specifically, this is not a MySQL interface, as it provides drivers for many database engines (of course including MYSQL).
PDO aims to provide a consistent API that means when a database engine is changed, the code changes to reflect this should be minimal. When using PDO, your code will normally "just work" across many database engines, simply by changing the driver you're using.
In addition to being cross-database compatible, PDO also supports prepared statements, stored procedures and more, whilst using the MySQL Driver.
See the github help on cloning URL. With HTTPS, if you are not authorized to push, you would basically have a read-only access. So yes, you need to ask the author to give you permission.
If the author doesn't give you permission, you can always fork (clone) his repository and work on your own. Once you made a nice and tested feature, you can then send a pull request to the original author.
I would approach this by using re.match
in the following way:
import re
match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
if match:
items = match.groups()
print(items)
>> ("foofo", "21")
public String millsToDateFormat(long mills) {
Date date = new Date(mills);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String dateFormatted = formatter.format(date);
return dateFormatted; //note that it will give you the time in GMT+0
}
If you have to remove the first few characters that are preceded by a special character like #
, this is a good one:
UPDATE tblInvalidID
SET [ColumnName] =stuff(ColumnName, 1, charindex('#', ColumnName), ' ')
Update MVC 5.1 now supports the below approach directly, so it works for built in editor too. http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features (It's either a case of Great mind thinking alike or they read my answer :)
End Update
If your using your own editor template or with MVC 5.1 which now supports the below approach directly for built in editors.
@Html.EditorFor(modelItem => item.YourProperty,
new { htmlAttributes = new { @class="verificationStatusSelect", style = "Width:50px" } })
then in your template (not required for simple types in MVC 5.1)
@Html.TextBoxFor(m => m, ViewData["htmlAttributes"])
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
The self answer given by MagngooSasa did the trick, but for anyone else trying to understand the answer, here are a few bit more details:
When developing Cordova apps with Visual Studio, I tried to import a remote JavaScript file [located here http://Guess.What.com/MyScript.js], but I have the error mentioned in the title.
Here is the meta tag before, in the index.html file of the project:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
Here is the corrected meta tag, to allow importing a remote script:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;**script-src 'self' http://onlineerp.solution.quebec 'unsafe-inline' 'unsafe-eval';** ">
And no more error!
check what is using your GPU memory with
sudo fuser -v /dev/nvidia*
Your output will look something like this:
USER PID ACCESS COMMAND
/dev/nvidia0: root 1256 F...m Xorg
username 2057 F...m compiz
username 2759 F...m chrome
username 2777 F...m chrome
username 20450 F...m python
username 20699 F...m python
Then kill the PID that you no longer need on htop
or with
sudo kill -9 PID.
In the example above, Pycharm was eating a lot of memory so I killed 20450 and 20699.