Add JSTL library as dependency to your project (javax.servlet.jsp.jstl.core.Config
is a part of this package).
For example, if you were using Gradle, you could write in a build.gradle:
dependencies {
compile 'javax.servlet:jstl:1.2'
}
Thanks All for your responses. Good solution was to use 'brain`s' method:
List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
Object[] row = (Object[]) list.get(i);
System.out.println("Element "+i+Arrays.toString(row));
}
Problem solved. Thanks again.
Here's my modified version of Bill's code:
CREATE TRIGGER mytrigger ON sometable
INSTEAD OF INSERT
AS BEGIN
INSERT INTO sometable SELECT * FROM inserted WHERE ISNUMERIC(somefield) = 1 FROM inserted;
INSERT INTO sometableRejects SELECT * FROM inserted WHERE ISNUMERIC(somefield) = 0 FROM inserted;
END
This lets the insert always succeed, and any bogus records get thrown into your sometableRejects where you can handle them later. It's important to make your rejects table use nvarchar fields for everything - not ints, tinyints, etc - because if they're getting rejected, it's because the data isn't what you expected it to be.
This also solves the multiple-record insert problem, which will cause Bill's trigger to fail. If you insert ten records simultaneously (like if you do a select-insert-into) and just one of them is bogus, Bill's trigger would have flagged all of them as bad. This handles any number of good and bad records.
I used this trick on a data warehousing project where the inserting application had no idea whether the business logic was any good, and we did the business logic in triggers instead. Truly nasty for performance, but if you can't let the insert fail, it does work.
Okey,Other people's view are very clear, but I would like to do some added, as follow:
Cursor tempCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
//do Time-consuming Operations
Cursor.Current = tempCursor;
Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.
var stack = [];
stack.push(firstObject);
// while not empty
while (stack.length) {
// Pop off end of stack.
obj = stack.pop();
// Do stuff.
// Push other objects on the stack as needed.
...
}
Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:
foo(first);
foo(second);
has to be replaced by
stack.push(second);
stack.push(first);
Edit: The article Stacks and Recursion Elimination (or Article Backup link) goes into more details on this subject.
Try this: Adding users to MySQL
You need grant privileges to the user if you want external acess to database(ie. web pages).
Also, if you create a new account on Github you will have the option to add .gitignore and it will be setup automatically on the right/standard location of your working place. You don't have to add anything in there at the begin, just alter the contents any time you want.
function doesNotContainAbcOrDef(x) {
return (x.match('abc') || x.match('def')) === null;
}
Try with:
@Scheduled(cron = "0 1 1 * * ?")
Below you can find the example patterns from the spring forum:
* "0 0 * * * *" = the top of every hour of every day.
* "*/10 * * * * *" = every ten seconds.
* "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
* "0 0 8,10 * * *" = 8 and 10 o'clock of every day.
* "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 0 0 25 12 ?" = every Christmas Day at midnight
Cron expression is represented by six fields:
second, minute, hour, day of month, month, day(s) of week
(*)
means match any
*/X
means "every X"
?
("no specific value") - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but I don't care what day of the week that happens to be, I would put "10" in the day-of-month field and "?" in the day-of-week field.
PS: In order to make it work, remember to enable it in your application context: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support
If for a some reason can't use rsyslog, this will do:
ExecStart=/bin/bash -ce "exec /usr/local/bin/binary1 agent -config-dir /etc/sample.d/server >> /var/log/agent.log 2>&1"
In this sample in catch block i change the value of counter and it will break while block:
class TestBreak {
public static void main(String[] a) {
int counter = 0;
while(counter<5) {
try {
counter++;
int x = counter/0;
}
catch(Exception e) {
counter = 1000;
}
}
}
}k
The short answer is install Media Feature Pack for N and KN versions of Windows 8.1
Big thanks to Matej Drolc that had it solved in hit blog post here.
Repairing Visual Studio 2015 seems to have resolved this issue for me. See this issue for NuGet in GitHub.
I used this solution to allow manual snapshot in app while disallowing screen capture when the app goes in background, hope it helps.
@Override
protected void onResume() {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
super.onResume();
}
@Override
protected void onPause() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
super.onPause();
}
As of Spark 2.0, CSV can be read directly into a DataFrame
.
If the data file does not have a header row, then it would be:
val df = spark.read.csv("file://path/to/data.csv")
That will load the data, but give each column generic names like _c0
, _c1
, etc.
If there are headers then adding .option("header", "true")
will use the first row to define the columns in the DataFrame
:
val df = spark.read
.option("header", "true")
.csv("file://path/to/data.csv")
For a concrete example, let's say you have a file with the contents:
user,topic,hits
om,scala,120
daniel,spark,80
3754978,spark,1
Then the following will get the total hits grouped by topic:
import org.apache.spark.sql.functions._
import spark.implicits._
val rawData = spark.read
.option("header", "true")
.csv("file://path/to/data.csv")
// specifies the query, but does not execute it
val grouped = rawData.groupBy($"topic").agg(sum($"hits))
// runs the query, pulling the data to the master node
// can fail if the amount of data is too much to fit
// into the master node's memory!
val collected = grouped.collect
// runs the query, writing the result back out
// in this case, changing format to Parquet since that can
// be nicer to work with in Spark
grouped.write.parquet("hdfs://some/output/directory/")
// runs the query, writing the result back out
// in this case, in CSV format with a header and
// coalesced to a single file. This is easier for human
// consumption but usually much slower.
grouped.coalesce(1)
.write
.option("header", "true")
.csv("hdfs://some/output/directory/")
Does it have to be String.Format
?
This looks like a job for String.Padleft
myString=myString.PadLeft(3, '0');
Or, if you are converting direct from an int:
myInt.toString("D3");
Try:
$('#myModal').on('show.bs.modal', function () {
$('.modal-content').css('height',$( window ).height()*0.8);
});
Didn't find the answer I wanted, so I solved it myself:
modify a container div!
<div class="rotation"> <!-- Set the container div's css -->
<div class="content" id='content-1'>This div gets scaled on hover</div>
</div>
<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>
css you want to persist after executing $target.css()
.content:hover {
transform: scale(1.5);
}
modify content's containing div with css()
$(".rotation").css("transform", "rotate(" + degrees + "deg)");
In my case the sub domain name causes the problem. Here are details
I used app_development.something.com
, here underscore(_
) sub domain is creating CORS error. After changing app_development
to app-development
it works fine.
Edit your C:\Windows\System32\drivers\etc\hosts
file
Make sure there is an entry that looks like this:
127.0.0.1 localhost
If there is an entry like
:: localhost
Comment it out to look like this
\#:: localhost
This should fix your problem, I've had this problem in the past.
Slight change to make it work on my region, Europe (. as thousands separator, comma as decimal separator):
[<1000000]#.##0,00" KB";[<1000000000]#.##0,00.." MB";#.##0,00..." GB"
Still same issue on data conversion (1000 != 1024) but it does the job for me.
public static bool isnull(object T)
{
return T == null ? true : false;
}
use:
isnull(object.check.it)
Conditional use:
isnull(object.check.it) ? DoWhenItsTrue : DoWhenItsFalse;
Update (another way) updated 08/31/2017 and 01/25/2021. Thanks for the comment.
public static bool IsNull(object T)
{
return (bool)T ? true : false;
}
And for the records, you have my code on Github, go check it out: https://github.com/j0rt3g4/ValidateNull PS: This one is especially for you Chayim Friedman, don't use beta software assuming that is all true. Wait for final versions or use your own environment to test, before assuming true beta software without any sort of documentation or demonstration from your end.
Nothing will be perfect. If you just want something to stop non-programmers then here's a little script I wrote you can use:
<?php
$infile=$_SERVER['argv'][1];
$outfile=$_SERVER['argv'][2];
if (!$infile || !$outfile) {
die("Usage: php {$_SERVER['argv'][0]} <input file> <output file>\n");
}
echo "Processing $infile to $outfile\n";
$data="ob_end_clean();?>";
$data.=php_strip_whitespace($infile);
// compress data
$data=gzcompress($data,9);
// encode in base64
$data=base64_encode($data);
// generate output text
$out='<?ob_start();$a=\''.$data.'\';eval(gzuncompress(base64_decode($a)));$v=ob_get_contents();ob_end_clean();?>';
// write output text
file_put_contents($outfile,$out);
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
You could extend FutureTask
class, and override the done()
method, then add the FutureTask
object to the ExecutorService
, so the done()
method will invoke when the FutureTask
completed immediately.
You can use sprintf-like formatting to inject values into the string. For that the string must include placeholders. Put your arguments into an array and use on of these ways: (For more info look at the documentation for Kernel::sprintf.)
fmt = 'The %s %s the %s'
res = fmt % [animal, action, other_animal] # using %-operator
res = sprintf(fmt, animal, action, other_animal) # call Kernel.sprintf
You can even explicitly specify the argument number and shuffle them around:
'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']
Or specify the argument using hash keys:
'The %{animal} %{action} the %{second_animal}' %
{ :animal => 'cat', :action=> 'eats', :second_animal => 'mouse'}
Note that you must provide a value for all arguments to the %
operator. For instance, you cannot avoid defining animal
.
I also experienced np.array_split not working with Pandas DataFrame my solution was to only split the index of the DataFrame and then introduce a new column with the "group" label:
indexes = np.array_split(df.index,N, axis=0)
for i,index in enumerate(indexes):
df.loc[index,'group'] = i
This makes grouby operations very convenient for instance calculation of mean value of each group:
df.groupby(by='group').mean()
Previous answer is not correct in my experience, you can't pass it a simple string, needs to be a datetime object. So:
import datetime
df.loc[datetime.date(year=2014,month=1,day=1):datetime.date(year=2014,month=2,day=1)]
This seemed far harder to find than it needs to be for OSX. Too many conflicting posts
For MAC OSX Mavericks Java JDK 7, follow these steps to locate keytool
:
Firstly make sure to install Java JDK
:
http://docs.oracle.com/javase/7/docs/webnotes/install/mac/mac-jdk.html
Then type this into command prompt:
/usr/libexec/java_home -v 1.7
it will spit out something like:
/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home
keytool
is located in the same directory as javac
. ie:
/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/bin
From bin
directory you can use the keytool
.
I had this problem in a list of post in a blog, the post are in a view inside a foreach, then is difficult select it in javascript, and the problem of post method and token also exists.
This the code for javascript at the end of the view, I generate the token in javascript functión inside the view and not in a external js file, then is easy use php lavarel to generate it with csrf_token() function, and send the "delete" method directly in params. You can see that I don´t use in var route: {{ route('post.destroy', $post->id}} because I don´t know the id I want delete until someone click in destroy button, if you don´t have this problem you can use {{ route('post.destroy', $post->id}} or other like this.
$(function(){
$(".destroy").on("click", function(){
var vid = $(this).attr("id");
var v_token = "{{csrf_token()}}";
var params = {_method: 'DELETE', _token: v_token};
var route = "http://imagica.app/posts/" + vid + "";
$.ajax({
type: "POST",
url: route,
data: params
});
});
});
and this the code of content in view (inside foreach there are more forms and the data of each post but is not inportant by this example), you can see I add a class "delete" to button and I call class in javascript.
@foreach($posts as $post)
<form method="POST">
<button id="{{$post->id}}" class="btn btn-danger btn-sm pull-right destroy" type="button" >eliminar</button>
</form>
@endforeach
We can use assert
here.
def _input(inp_str:str):
try:
assert len(inp_str)<=15,print('More than 15 characters present')
assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
return inp_str
except Exception as e:
pass
_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present
This one never failed me:
one.sh:
LFILE=/tmp/one-`echo "$@" | md5sum | cut -d\ -f1`.pid
if [ -e ${LFILE} ] && kill -0 `cat ${LFILE}`; then
exit
fi
trap "rm -f ${LFILE}; exit" INT TERM EXIT
echo $$ > ${LFILE}
$@
rm -f ${LFILE}
cron job:
* * * * * /path/to/one.sh <command>
As @DSM points out, you can do this more directly using the vectorised string methods:
df['Date'].str[-4:].astype(int)
Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):
df['Date'].str.extract('(?P<year>\d{4})').astype(int)
An alternative slightly more flexible way, might be to use apply
(or equivalently map
) to do this:
df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
# converts the last 4 characters of the string to an integer
The lambda function, is taking the input from the Date
and converting it to a year.
You could (and perhaps should) write this more verbosely as:
def convert_to_year(date_in_some_format):
date_as_string = str(date_in_some_format) # cast to string
year_as_string = date_in_some_format[-4:] # last four characters
return int(year_as_string)
df['Date'] = df['Date'].apply(convert_to_year)
Perhaps 'Year' is a better name for this column...
//get file input
var $el = $('input[type=file]');
//set the next siblings (the span) text to the input value
$el.next().text( $el.val() );
I was getting this error and tried most of the suggestions here. Finally I did a "Clean" on the report project and tried again. It finally worked!!
If your switch Install by USB on and you are getting "the device is temporarily restricted" error, then apply any of the default mobile themes. If any other developer theme is applied then it will not Allow you to switch Install by USB on. This works for me.
C/program files/
and user/sukhendra/AppData
then only Anaconda is remaining in my PC so opened Anaconda and then it's all working fine for me
Yup, use printf("hello%%");
and it's done.
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
CSS height: 100% only works if the element's parent has an explicitly defined height. For example, this would work as expected:
td {
height: 200px;
}
td div {
/* div will now take up full 200px of parent's height */
height: 100%;
}
Since it seems like your <td>
is going to be variable height, what if you added the bottom right icon with an absolutely positioned image like so:
.thatSetsABackgroundWithAnIcon {
/* Makes the <div> a coordinate map for the icon */
position: relative;
/* Takes the full height of its parent <td>. For this to work, the <td>
must have an explicit height set. */
height: 100%;
}
.thatSetsABackgroundWithAnIcon .theIcon {
position: absolute;
bottom: 0;
right: 0;
}
With the table cell markup like so:
<td class="thatSetsABackground">
<div class="thatSetsABackgroundWithAnIcon">
<dl>
<dt>yada
</dt>
<dd>yada
</dd>
</dl>
<img class="theIcon" src="foo-icon.png" alt="foo!"/>
</div>
</td>
Edit: using jQuery to set div's height
If you keep the <div>
as a child of the <td>
, this snippet of jQuery will properly set its height:
// Loop through all the div.thatSetsABackgroundWithAnIcon on your page
$('div.thatSetsABackgroundWithAnIcon').each(function(){
var $div = $(this);
// Set the div's height to its parent td's height
$div.height($div.closest('td').height());
});
For Xcode 6 it is a little different.
After adding the device UDID in the developer site (https://developer.apple.com/account/ios/device/deviceList.action), go back to Xcode.
Xcode -> Preferences -> Accounts Select the Apple ID you added the device under and in the bottom right, click "View Details..."
Hit the refresh icon on the bottom left and then try to run the app again.
Adding onto Bojan Kogoj's answer:
In your app.module.ts, add a new provider for storage.
@NgModule({
providers: [
{ provide: Storage, useValue: localStorage }
],
imports:[],
declarations:[]
})
And then you can use DI to get it wherever you need it.
@Injectable({
providedIn:'root'
})
export class StateService {
constructor(private storage: Storage) { }
}
In Python 3.x, you can convert an integer value (including large ones, which the other answers don't allow for) into a series of bytes like this:
import math
x = 0x1234
number_of_bytes = int(math.ceil(x.bit_length() / 8))
x_bytes = x.to_bytes(number_of_bytes, byteorder='big')
x_int = int.from_bytes(x_bytes, byteorder='big')
x == x_int
So far, most "hacks" here suggest to abuse JSON. But instead, why not abuse the underlying scripting language?
Edit The initial response was putting the description on the right using # add comments here
to wrap it; however, this does not work on Windows, because flags (e.g., npm run myframework -- --myframework-flags
) would be ignored. I changed my response to make it work on all platforms, and added some indents for readability purposes.
{
"scripts": {
"help": " echo 'Display help information (this screen)'; npm run",
"myframework": "echo 'Run myframework binary'; myframework",
"develop": " echo 'Run in development mode (with terminal output)'; npm run myframework"
"start": " echo 'Start myFramework as a daemon'; myframework start",
"stop": " echo 'Stop the myFramework daemon'; myframework stop"
"test": "echo \"Error: no test specified\" && exit 1"
}
}
This will:
npm run myframework -- --help
npm run
(which is the actual command to run to get information about available scripts)package.json
(using less
or your favorite IDE)In MSDN, Assembly.GetExecutingAssembly Method, is remark about method "getexecutingassembly", that for performance reasons, you should call this method only when you do not know at design time what assembly is currently executing.
The recommended way to retrieve an Assembly object that represents the current assembly is to use the Type.Assembly
property of a type found in the assembly.
The following example illustrates:
using System;
using System.Reflection;
public class Example
{
public static void Main()
{
Console.WriteLine("The version of the currently executing assembly is: {0}",
typeof(Example).Assembly.GetName().Version);
}
}
/* This example produces output similar to the following:
The version of the currently executing assembly is: 1.1.0.0
Of course this is very similar to the answer with helper class "public static class CoreAssembly", but, if you know at least one type of executing assembly, it isn't mandatory to create a helper class, and it saves your time.
Try change your url for requst to
https://www.googleapis.com/oauth2/v4/token
Make sure that your code is returning a value of given return-type irrespective of conditional statements
This code snippet was showing the same error
int search(char arr[], int start, int end, char value)
{
int i;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
return i;
}
}
This is the working code after little changes
int search(char arr[], int start, int end, char value)
{
int i;
int index=-1;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
index=i;
}
return index;
}
#This valid till 4 digit number
numbers={1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine',
10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen',
17:'seventeen', 18:'eighteen', 19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty',
60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety', 100:'hundred', 1000:'thousand'}
def my_fun(num):
list = []
num_len = len(str(num)) - 1
while num_len > 0 and num > 0:
while num_len > 0 and num > 0:
if num in numbers and num < 1000:
list.append(numbers[num])
num_len = 0
elif num < 100:
list.extend([numbers[num - num%10], numbers[num%10]])
num_len = 0
else:
quotent = num//10**num_len # 4567//1000= 4
num = num % 10**num_len #4567%1000 =567
if quotent != 0 :
list.append(numbers[quotent])
list.append(numbers[10**num_len])
else:
list.append(numbers[num])
num_len -= 1
return ' '.join(list)
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
what is the best way to do this in C++?
Because you asked it this way:
std::string msg(65546, 0); // all characters will be set to 0
Or:
std::vector<char> msg(65546); // all characters will be initialized to 0
If you are working with C functions which accept char* or const char*, then you can do:
some_c_function(&msg[0]);
You can also use the c_str() method on std::string if it accepts const char* or data().
The benefit of this approach is that you can do everything you want to do with a dynamically allocating char buffer but more safely, flexibly, and sometimes even more efficiently (avoiding the need to recompute string length linearly, e.g.). Best of all, you don't have to free the memory allocated manually, as the destructor will do this for you.
Simply put you can't do the following:
class C(object):
def x(self, y, **kwargs):
# Which y to use, kwargs or declaration?
pass
c = C()
y = "Arbitrary value"
kwargs["y"] = "Arbitrary value"
c.x(y, **kwargs) # FAILS
Because you pass the variable 'y' into the function twice: once as kwargs and once as function declaration.
To check if the value exists:
[#if userName??]
Hi ${userName}, How are you?
[/#if]
Or with the standard freemarker syntax:
<#if userName??>
Hi ${userName}, How are you?
</#if>
To check if the value exists and is not empty:
<#if userName?has_content>
Hi ${userName}, How are you?
</#if>
git update-ref newref oldref
git update-ref -d oldref newref
If I've understood your problem correctly, there are two possible problems here:
resultset
is null
- I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.resultset.getString(i++)
will get columns 1,2,3 and so on from each subsequent row.I think that the second point is probably your problem here.
Lets say you only had 1 row returned, as follows:
Col 1, Col 2, Col 3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
Edit:
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
Before User Shift + = or Shift - , you have to first set the key map as mentioned below
If you have the options -H
and -n
available (man grep
is your friend):
$ cat file
foo
bar
foobar
$ grep -H foo file
file:foo
file:foobar
$ grep -Hn foo file
file:1:foo
file:3:foobar
Options:
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search.
-n, --line-number
Prefix each line of output with the 1-based line number within its input file. (-n is specified by POSIX.)
-H
is a GNU extension, but -n
is specified by POSIX
<asp:DropDownList ID="DdlMonths" runat="server">
<asp:ListItem Enabled="true" Text="Select Month" Value="-1"></asp:ListItem>
<asp:ListItem Text="January" Value="1"></asp:ListItem>
<asp:ListItem Text="February" Value="2"></asp:ListItem>
....
<asp:ListItem Text="December" Value="12"></asp:ListItem>
</asp:DropDownList>
You can even use a RequiredFieldValidator
which ignore this item, it considers it as unselected.
<asp:RequiredFieldValidator ID="ReqMonth" runat="server" ControlToValidate="DdlMonths"
InitialValue="-1">
</asp:RequiredFieldValidator>
I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.
Use "javascript.validate.enable": false
in your VS Code settings, It doesn't disable ESLINT. I use both ESLINT & Flow. Simply follow the instructions Flow For Vs Code Setup
Adding this line in settings.json. Helps
"javascript.validate.enable": false
Check the URL it should be using https rather than http protocol.
In my case changing http to https in the URL solved it.
A function to cope with the cross-browser stuff:
addCssRule = function(/* string */ selector, /* string */ rule) {
if (document.styleSheets) {
if (!document.styleSheets.length) {
var head = document.getElementsByTagName('head')[0];
head.appendChild(bc.createEl('style'));
}
var i = document.styleSheets.length-1;
var ss = document.styleSheets[i];
var l=0;
if (ss.cssRules) {
l = ss.cssRules.length;
} else if (ss.rules) {
// IE
l = ss.rules.length;
}
if (ss.insertRule) {
ss.insertRule(selector + ' {' + rule + '}', l);
} else if (ss.addRule) {
// IE
ss.addRule(selector, rule, l);
}
}
};
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
$('#myModal').modal('hide')
should do it
run
ps -ef | grep name-related-to-process
above command will give all the details like pid, start time about the process.
like if you want all java realted process give java or if you have name of process place the name
/// <summary>
/// Validates the email if it follows the valid email format
/// </summary>
/// <param name="emailAddress"></param>
/// <returns></returns>
public static bool EmailIsValid(string emailAddress)
{
//if string is not null and empty then check for email follow the format
return string.IsNullOrEmpty(emailAddress)?false : new Regex(@"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$", RegexOptions.IgnoreCase).IsMatch(emailAddress);
}
If you want to take into consideration the platform (x64, x86 etc) and the configuration (Debug or Release) it would be something like this:
xcopy "$(SolutionDir)\$(Platform)\$(Configuration)\$(TargetName).dll" "$(SolutionDir)TestDirectory\bin\$(Platform)\$(Configuration)\" /F /Y
I would try setting it to max-width:50px;
Here is a slightly more involved version, based on christophe31's answer. It does not rely on the "readonly" attribute. This makes its problems, like select boxes still being changeable and datapickers still popping up, go away.
Instead, it wraps the form fields widget in a readonly widget, thus making the form still validate. The content of the original widget is displayed inside <span class="hidden"></span>
tags. If the widget has a render_readonly()
method it uses that as the visible text, otherwise it parses the HTML of the original widget and tries to guess the best representation.
import django.forms.widgets as f
import xml.etree.ElementTree as etree
from django.utils.safestring import mark_safe
def make_readonly(form):
"""
Makes all fields on the form readonly and prevents it from POST hacks.
"""
def _get_cleaner(_form, field):
def clean_field():
return getattr(_form.instance, field, None)
return clean_field
for field_name in form.fields.keys():
form.fields[field_name].widget = ReadOnlyWidget(
initial_widget=form.fields[field_name].widget)
setattr(form, "clean_" + field_name,
_get_cleaner(form, field_name))
form.is_readonly = True
class ReadOnlyWidget(f.Select):
"""
Renders the content of the initial widget in a hidden <span>. If the
initial widget has a ``render_readonly()`` method it uses that as display
text, otherwise it tries to guess by parsing the html of the initial widget.
"""
def __init__(self, initial_widget, *args, **kwargs):
self.initial_widget = initial_widget
super(ReadOnlyWidget, self).__init__(*args, **kwargs)
def render(self, *args, **kwargs):
def guess_readonly_text(original_content):
root = etree.fromstring("<span>%s</span>" % original_content)
for element in root:
if element.tag == 'input':
return element.get('value')
if element.tag == 'select':
for option in element:
if option.get('selected'):
return option.text
if element.tag == 'textarea':
return element.text
return "N/A"
original_content = self.initial_widget.render(*args, **kwargs)
try:
readonly_text = self.initial_widget.render_readonly(*args, **kwargs)
except AttributeError:
readonly_text = guess_readonly_text(original_content)
return mark_safe("""<span class="hidden">%s</span>%s""" % (
original_content, readonly_text))
# Usage example 1.
self.fields['my_field'].widget = ReadOnlyWidget(self.fields['my_field'].widget)
# Usage example 2.
form = MyForm()
make_readonly(form)
About the speed!
import time
s_time = time.time()
print 'start'
a = range(100000000)
del a[:]
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 3.25
s_time = time.time()
print 'start'
a = range(100000000)
a = []
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 2.11
I don't there there is any DataSource
for the gridview
Though you have DataBind
in your code as
gvdetails.DataBind();
Why not use a media query range.
I'm currently working on a responsive layout for my employer and the ranges I'm using are as follows:
You have your main desktop styles in the body of the CSS file (1024px and above) and then for specific screen sizes I'm using:
@media all and (min-width:960px) and (max-width: 1024px) {
/* put your css styles in here */
}
@media all and (min-width:801px) and (max-width: 959px) {
/* put your css styles in here */
}
@media all and (min-width:769px) and (max-width: 800px) {
/* put your css styles in here */
}
@media all and (min-width:569px) and (max-width: 768px) {
/* put your css styles in here */
}
@media all and (min-width:481px) and (max-width: 568px) {
/* put your css styles in here */
}
@media all and (min-width:321px) and (max-width: 480px) {
/* put your css styles in here */
}
@media all and (min-width:0px) and (max-width: 320px) {
/* put your css styles in here */
}
This will cover pretty much all devices being used - I would concentrate on getting the styling correct for the sizes at the end of the range (i.e. 320, 480, 568, 768, 800, 1024) as for all the others they will just be responsive to the size available.
Also, don't use px anywhere - use em's or %.
Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.
Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B");
}
if(j%100==0){ //Adding a line break in second loop
System.out.println();
}
}
System.out.println("");
}
Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.
I don't think you can "legally" load only part of an XML file, since then it would be malformed (there would be a missing closing element somewhere).
Using LINQ-to-XML, you can do var doc = XDocument.Load("yourfilepath")
. From there its just a matter of querying the data you want, say like this:
var authors = doc.Root.Elements().Select( x => x.Element("Author") );
HTH.
EDIT:
Okay, just to make this a better sample, try this (with @JWL_'s suggested improvement):
using System;
using System.Xml.Linq;
namespace ConsoleApplication1 {
class Program {
static void Main( string[] args ) {
XDocument doc = XDocument.Load( "XMLFile1.xml" );
var authors = doc.Descendants( "Author" );
foreach ( var author in authors ) {
Console.WriteLine( author.Value );
}
Console.ReadLine();
}
}
}
You will need to adjust the path in XDocument.Load()
to point to your XML file, but the rest should work. Ask questions about which parts you don't understand.
The newly released PyCharm 5 supports type hinting. In their blog post about it (see Python 3.5 type hinting in PyCharm 5) they offer a great explanation of what type hints are and aren't along with several examples and illustrations for how to use them in your code.
Additionally, it is supported in Python 2.7, as explained in this comment:
PyCharm supports the typing module from PyPI for Python 2.7, Python 3.2-3.4. For 2.7 you have to put type hints in *.pyi stub files since function annotations were added in Python 3.0.
For InnoDB tables, Percona has a recovery tool which may help. It is far from fail-safe or perfect, and how fast you stopped your MySQL server after the accidental deletes has a major impact. If you're quick enough, changes are you can recover quite a bit of data, but recovering all data is nigh impossible.
Of cours, proper daily backups, binlogs, and possibly a replication slave (which won't help for accidental deletes but does help in case of hardware failure) are the way to go, but this tool could enable you to save as much data as possible when you did not have those yet.
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
Since the other answers don't talk about the rules in C++11 here's one. From C++11 standard (draft n3337) §5/9 (emphasized the difference):
This pattern is called the usual arithmetic conversions, which are defined as follows:
— If either operand is of scoped enumeration type, no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
— If either operand is of type long double, the other shall be converted to long double.
— Otherwise, if either operand is double, the other shall be converted to double.
— Otherwise, if either operand is float, the other shall be converted to float.
— Otherwise, the integral promotions shall be performed on both operands. Then the following rules shall be applied to the promoted operands:
— If both operands have the same type, no further conversion is needed.
— Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.
— Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.
— Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.
— Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
See here for a list that's frequently updated.
You can find it in your "Home" directory:
On Windows 7:
C:\Users\<YOUR_ACCOUNT>\.keystore
On Linux (Ubuntu):
/home/<YOUR_ACCOUNT>/.keystore
IDE: The MS Office of Programming. It's where you type your code, plus some added features to make you a happier programmer. (e.g. Eclipse, Netbeans). Car body: It's what you really touch, see and work on.
Library: A library is a collection of functions, often grouped into multiple program files, but packaged into a single archive file. This contains programs created by other folks, so that you don't have to reinvent the wheel. (e.g. junit.jar, log4j.jar). A library generally has a key role, but does all of its work behind the scenes, it doesn't have a GUI. Car's engine.
API: The library publisher's documentation. This is how you should use my library. (e.g. log4j API, junit API). Car's user manual - yes, cars do come with one too!
What is a kit? It's a collection of many related items that work together to provide a specific service. When someone says medicine kit, you get everything you need for an emergency: plasters, aspirin, gauze and antiseptic, etc.
SDK: McDonald's Happy Meal. You have everything you need (and don't need) boxed neatly: main course, drink, dessert and a bonus toy. An SDK is a bunch of different software components assembled into a package, such that they're "ready-for-action" right out of the box. It often includes multiple libraries and can, but may not necessarily include plugins, API documentation, even an IDE itself. (e.g. iOS Development Kit).
Toolkit: GUI. GUI. GUI. When you hear 'toolkit' in a programming context, it will often refer to a set of libraries intended for GUI development. Since toolkits are UI-centric, they often come with plugins (or standalone IDE's) that provide screen-painting utilities. (e.g. GWT)
Framework: While not the prevalent notion, a framework can be viewed as a kit. It also has a library (or a collection of libraries that work together) that provides a specific coding structure & pattern (thus the word, framework). (e.g. Spring Framework)
Use the getResourceAsStream()
method on the ServletContext object, e.g.
servletContext.getResourceAsStream("/WEB-INF/myfile");
How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?
EDITED: If you're inside a Servlet object, then call getServletContext()
. If you're in JSP, use the predefined variable application
.
The simple naive way that is slow because it opens and positions the file pointer to End-Of-File multiple times.
@echo off
command1 >output.txt
command2 >>output.txt
...
commandN >>output.txt
A better way - easier to write, and faster because the file is opened and positioned only once.
@echo off
>output.txt (
command1
command2
...
commandN
)
Another good and fast way that only opens and positions the file once
@echo off
call :sub >output.txt
exit /b
:sub
command1
command2
...
commandN
Edit 2020-04-17
Every now and then you may want to repeatedly write to two or more files. You might also want different messages on the screen. It is still possible to to do this efficiently by redirecting to undefined handles outside a parenthesized block or subroutine, and then use the &
notation to reference the already opened files.
call :sub 9>File1.txt 8>File2.txt
exit /b
:sub
echo Screen message 1
>&9 File 1 message 1
>&8 File 2 message 1
echo Screen message 2
>&9 File 1 message 2
>&8 File 2 message 2
exit /b
I chose to use handles 9 and 8 in reverse order because that way is more likely to avoid potential permanent redirection due to a Microsoft redirection implementation design flaw when performing multiple redirections on the same command. It is highly unlikely, but even that approach could expose the bug if you try hard enough. If you stage the redirection than you are guaranteed to avoid the problem.
3>File1.txt ( 4>File2.txt call :sub)
exit /b
:sub
etc.
public String getLocalIpAddress() {
try {
for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
In your GET action, create an object of your view model, load the EmployeeList
collection property and send that to the view.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.EmployeesList = new List<Employee>
{
new Employee { Id = 1, FullName = "Shyju" },
new Employee { Id = 2, FullName = "Bryan" }
};
return View(vm);
}
And in your create view, create a new SelectList
object from the EmployeeList
property and pass that as value for the asp-items
property.
@model MyViewModel
<form asp-controller="Home" asp-action="Create">
<select asp-for="EmployeeId"
asp-items="@(new SelectList(Model.EmployeesList,"Id","FullName"))">
<option>Please select one</option>
</select>
<input type="submit"/>
</form>
And your HttpPost action method to accept the submitted form data.
[HttpPost]
public IActionResult Create(MyViewModel model)
{
// check model.EmployeeId
// to do : Save and redirect
}
Or
If your view model has a List<SelectListItem>
as the property for your dropdown items.
public class MyViewModel
{
public int EmployeeId { get; set; }
public string Comments { get; set; }
public List<SelectListItem> Employees { set; get; }
}
And in your get action,
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Sean", Value = "2"}
};
return View(vm);
}
And in the view, you can directly use the Employees
property for the asp-items
.
@model MyViewModel
<form asp-controller="Home" asp-action="Create">
<label>Comments</label>
<input type="text" asp-for="Comments"/>
<label>Lucky Employee</label>
<select asp-for="EmployeeId" asp-items="@Model.Employees" >
<option>Please select one</option>
</select>
<input type="submit"/>
</form>
The class SelectListItem
belongs to Microsoft.AspNet.Mvc.Rendering
namespace.
Make sure you are using an explicit closing tag for the select element. If you use the self closing tag approach, the tag helper will render an empty SELECT element!
The below approach will not work
<select asp-for="EmployeeId" asp-items="@Model.Employees" />
But this will work.
<select asp-for="EmployeeId" asp-items="@Model.Employees"></select>
The above examples are using hard coded items for the options. So i thought i will add some sample code to get data using Entity framework as a lot of people use that.
Let's assume your DbContext object has a property called Employees
, which is of type DbSet<Employee>
where the Employee
entity class has an Id
and Name
property like this
public class Employee
{
public int Id { set; get; }
public string Name { set; get; }
}
You can use a LINQ query to get the employees and use the Select method in your LINQ expression to create a list of SelectListItem
objects for each employee.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = context.Employees
.Select(a => new SelectListItem() {
Value = a.Id.ToString(),
Text = a.Name
})
.ToList();
return View(vm);
}
Assuming context
is your db context object. The view code is same as above.
Some people prefer to use SelectList
class to hold the items needed to render the options.
public class MyViewModel
{
public int EmployeeId { get; set; }
public SelectList Employees { set; get; }
}
Now in your GET action, you can use the SelectList
constructor to populate the Employees
property of the view model. Make sure you are specifying the dataValueField
and dataTextField
parameters.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new SelectList(GetEmployees(),"Id","FirstName");
return View(vm);
}
public IEnumerable<Employee> GetEmployees()
{
// hard coded list for demo.
// You may replace with real data from database to create Employee objects
return new List<Employee>
{
new Employee { Id = 1, FirstName = "Shyju" },
new Employee { Id = 2, FirstName = "Bryan" }
};
}
Here I am calling the GetEmployees
method to get a list of Employee objects, each with an Id
and FirstName
property and I use those properties as DataValueField
and DataTextField
of the SelectList
object we created. You can change the hardcoded list to a code which reads data from a database table.
The view code will be same.
<select asp-for="EmployeeId" asp-items="@Model.Employees" >
<option>Please select one</option>
</select>
Sometimes you might want to render a select element from a list of strings. In that case, you can use the SelectList
constructor which only takes IEnumerable<T>
var vm = new MyViewModel();
var items = new List<string> {"Monday", "Tuesday", "Wednesday"};
vm.Employees = new SelectList(items);
return View(vm);
The view code will be same.
Some times,you might want to set one option as the default option in the SELECT element (For example, in an edit screen, you want to load the previously saved option value). To do that, you may simply set the EmployeeId
property value to the value of the option you want to be selected.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "11"},
new SelectListItem {Text = "Tom", Value = "12"},
new SelectListItem {Text = "Jerry", Value = "13"}
};
vm.EmployeeId = 12; // Here you set the value
return View(vm);
}
This will select the option Tom in the select element when the page is rendered.
If you want to render a multi select dropdown, you can simply change your view model property which you use for asp-for
attribute in your view to an array type.
public class MyViewModel
{
public int[] EmployeeIds { get; set; }
public List<SelectListItem> Employees { set; get; }
}
This will render the HTML markup for the select element with the multiple
attribute which will allow the user to select multiple options.
@model MyViewModel
<select id="EmployeeIds" multiple="multiple" name="EmployeeIds">
<option>Please select one</option>
<option value="1">Shyju</option>
<option value="2">Sean</option>
</select>
Similar to single select, set the EmployeeIds
property value to the an array of values you want.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "11"},
new SelectListItem {Text = "Tom", Value = "12"},
new SelectListItem {Text = "Jerry", Value = "13"}
};
vm.EmployeeIds= new int[] { 12,13} ;
return View(vm);
}
This will select the option Tom and Jerry in the multi select element when the page is rendered.
If you do not prefer to keep a collection type property to pass the list of options to the view, you can use the dynamic ViewBag to do so.(This is not my personally recommended approach as viewbag is dynamic and your code is prone to uncatched typo errors)
public IActionResult Create()
{
ViewBag.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Sean", Value = "2"}
};
return View(new MyViewModel());
}
and in the view
<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
<option>Please select one</option>
</select>
It is same as above. All you have to do is, set the property (for which you are binding the dropdown for) value to the value of the option you want to be selected.
public IActionResult Create()
{
ViewBag.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Bryan", Value = "2"},
new SelectListItem {Text = "Sean", Value = "3"}
};
vm.EmployeeId = 2; // This will set Bryan as selected
return View(new MyViewModel());
}
and in the view
<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
<option>Please select one</option>
</select>
The select tag helper method supports grouping options in a dropdown. All you have to do is, specify the Group
property value of each SelectListItem
in your action method.
public IActionResult Create()
{
var vm = new MyViewModel();
var group1 = new SelectListGroup { Name = "Dev Team" };
var group2 = new SelectListGroup { Name = "QA Team" };
var employeeList = new List<SelectListItem>()
{
new SelectListItem() { Value = "1", Text = "Shyju", Group = group1 },
new SelectListItem() { Value = "2", Text = "Bryan", Group = group1 },
new SelectListItem() { Value = "3", Text = "Kevin", Group = group2 },
new SelectListItem() { Value = "4", Text = "Alex", Group = group2 }
};
vm.Employees = employeeList;
return View(vm);
}
There is no change in the view code. the select tag helper will now render the options inside 2 optgroup items.
If you want to initialize the array to -1
then you can use the following,
memset(array, -1, sizeof(array[0][0]) * row * count)
But this will work 0
and -1
only
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
Yesterday Date can be calculated as:-
let now = new Date();
var defaultDate = now - 1000 * 60 * 60 * 24 * 1;
defaultDate = new Date(defaultDate);
I have been looking for simple and clean way to clear HTML file input, the above answers are great, but none of them really answers what i'm looking for, until i came across on the web with simple an elegant way to do it :
var $input = $("#control");
$input.replaceWith($input.val('').clone(true));
all the credit go's to Chris Coyier.
// Referneces_x000D_
var control = $("#control"),_x000D_
clearBn = $("#clear");_x000D_
_x000D_
// Setup the clear functionality_x000D_
clearBn.on("click", function(){_x000D_
control.replaceWith( control.val('').clone( true ) );_x000D_
});_x000D_
_x000D_
// Some bound handlers to preserve when cloning_x000D_
control.on({_x000D_
change: function(){ console.log( "Changed" ) },_x000D_
focus: function(){ console.log( "Focus" ) }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" id="control">_x000D_
<br><br>_x000D_
<a href="#" id="clear">Clear</a>
_x000D_
This maybe because Chrome is still running in background after you close the browser. Try to disable this feature by doing following:
However, I think Chrome should check and delete previous session cookies at it starting instead of closing.
Based on @MaBi 's answer, I made this:
trait ClassShortNameTrait
{
public static function getClassShortName()
{
if ($pos = strrchr(static::class, '\\')) {
return substr($pos, 1);
} else {
return static::class;
}
}
}
Which you may use like that:
namespace Foo\Bar\Baz;
class A
{
use ClassShortNameTrait;
}
A::class
returns Foo\Bar\Baz\A
, but A::getClassShortName()
returns A
.
Works for PHP >= 5.5.
In Selenium to get the URL of the active tab try,
from selenium import webdriver
driver = webdriver.Firefox()
print driver.current_url # This will print the URL of the Active link
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
print driver.current_url
I am here just providing a pseudo code for you.
You can put this in a loop and create your own flow.
I new to Stackoverflow so still learning how to write proper answers.
### example01 -------------------
mystring = 'coup_ate_grouping'
backwards = mystring[::-1]
print backwards
### ... or even ...
mystring = 'coup_ate_grouping'[::-1]
print mystring
### result01 -------------------
'''
gnipuorg_eta_puoc
'''
This answer is provided to address the following concern from @odigity:
Wow. I was horrified at first by the solution Paolo proposed, but that took a back seat to the horror I felt upon reading the first comment: "That's very pythonic. Good job!" I'm so disturbed that such a bright community thinks using such cryptic methods for something so basic is a good idea. Why isn't it just s.reverse()?
string.reverse()
string.reverse()
to avoid slice notation.print 'coup_ate_grouping'[-4:] ## => 'ping'
print 'coup_ate_grouping'[-4:-1] ## => 'pin'
print 'coup_ate_grouping'[-1] ## => 'g'
[-1]
may throw some developers offPython has a special circumstance to be aware of: a string is an iterable type.
One rationale for excluding a string.reverse()
method is to give python developers incentive to leverage the power of this special circumstance.
In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential arrangement of elements, just like arrays in other programming languages.
To understand how this works, reviewing example02 can provide a good overview.
### example02 -------------------
## start (with positive integers)
print 'coup_ate_grouping'[0] ## => 'c'
print 'coup_ate_grouping'[1] ## => 'o'
print 'coup_ate_grouping'[2] ## => 'u'
## start (with negative integers)
print 'coup_ate_grouping'[-1] ## => 'g'
print 'coup_ate_grouping'[-2] ## => 'n'
print 'coup_ate_grouping'[-3] ## => 'i'
## start:end
print 'coup_ate_grouping'[0:4] ## => 'coup'
print 'coup_ate_grouping'[4:8] ## => '_ate'
print 'coup_ate_grouping'[8:12] ## => '_gro'
## start:end
print 'coup_ate_grouping'[-4:] ## => 'ping' (counter-intuitive)
print 'coup_ate_grouping'[-4:-1] ## => 'pin'
print 'coup_ate_grouping'[-4:-2] ## => 'pi'
print 'coup_ate_grouping'[-4:-3] ## => 'p'
print 'coup_ate_grouping'[-4:-4] ## => ''
print 'coup_ate_grouping'[0:-1] ## => 'coup_ate_groupin'
print 'coup_ate_grouping'[0:] ## => 'coup_ate_grouping' (counter-intuitive)
## start:end:step (or start:end:stride)
print 'coup_ate_grouping'[-1::1] ## => 'g'
print 'coup_ate_grouping'[-1::-1] ## => 'gnipuorg_eta_puoc'
## combinations
print 'coup_ate_grouping'[-1::-1][-4:] ## => 'puoc'
The cognitive load associated with understanding how slice notation works in python may indeed be too much for some adopters and developers who do not wish to invest much time in learning the language.
Nevertheless, once the basic principles are understood, the power of this approach over fixed string manipulation methods can be quite favorable.
For those who think otherwise, there are alternate approaches, such as lambda functions, iterators, or simple one-off function declarations.
If desired, a developer can implement her own string.reverse() method, however it is good to understand the rationale behind this aspect of python.
webapps
folderhttp://host:port/manager
. You will have to setup some users beforehand.webapps/webappname
Sometimes administrators configure tomcat so that war files are deployed outside the tomcat folder. Even in that case:
After you have it deployed (check the /logs
dir for any problems), it should be accessible via: http://host:port/yourwebappname/
. So in your case, one of those:
http://bilgin.ath.cx/TestWebApp/
http://bilgin.ath.cx:8080/TestWebApp/
If you don't manage by doing the above and googling - turn to your support. There might be an alternative port, or there might be something wrong with the application (and therefore in the logs)
I used the follow code.
var mobileNumber=parseInt(no)
if(!mobileNumber || mobileNumber.toString().length!=10){
Alert("Please provide 10 Digit numeric value")
}
If the mobile number is not a number, it will give NaN
value.
This is the method that works for me. It's based in samnau anwser but allows to submit the form with ENTER
, increase and decrease the number with UP
and DOWN
arrows, edition with DEL
,BACKSPACE
,LEFT
and RIGHT
, and navigate trough fields with TAB
. Note that it works for positive integers such as an amount.
HTML:
<input ng-keypress="onlyNumbers($event)" min="0" type="number" step="1" ng-pattern="/^[0-9]{1,8}$/" ng-model="... >
ANGULARJS:
$scope.onlyNumbers = function(event){
var keys={
'up': 38,'right':39,'down':40,'left':37,
'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
'0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
};
for(var index in keys) {
if (!keys.hasOwnProperty(index)) continue;
if (event.charCode==keys[index]||event.keyCode==keys[index]) {
return; //default event
}
}
event.preventDefault();
};
File > Settings > Editor > General >Auto Import (Mac: Android Studio > Preferences > Editor > General >Auto Import).
Select all check boxes and set Insert imports on paste to All. Unambiguous imports are now added automatically to your files.
In Access SQL, I would use this. I'd imagine that SQLserver has the same syntax.
select * from jobdetails where job_no like "0711*" or job_no like "0712*"
Once you have parsed the timestamp string and have a time object (see other answers for details), you can use Time.to_formatted_s from Rails. It has several formats built in that you can specify with symbols.
Quote:
time = Time.now # => Thu Jan 18 06:10:17 CST 2007
time.to_formatted_s(:time) # => "06:10"
time.to_s(:time) # => "06:10"
time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
time.to_formatted_s(:number) # => "20070118061017"
time.to_formatted_s(:short) # => "18 Jan 06:10"
time.to_formatted_s(:long) # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
(Time.to_s is an alias)
You can also define your own formats - usually in an initializer (Thanks to Dave Newton for pointing this out). This is how it's done:
# config/initializers/time_formats.rb
Time::DATE_FORMATS[:month_and_year] = "%B %Y"
Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
Lets assume your broadcastReceiver
is defined like this:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your code
}
};
If you are using LocalBroadcast
in an Activity, then this is how you'll unregister:
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
If you are using LocalBroadcast
in a Fragment, then this is how you'll unregister:
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
If you are using normal broadcast in an Activity, then this is how you'll unregister:
unregisterReceiver(broadcastReceiver);
If you are using normal broadcast in a Fragment, then this is how you'll unregister:
getActivity().unregisterReceiver(broadcastReceiver);
You can try this
String text = "ddd123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
try {
double numVal = Double.valueOf(numOnly);
System.out.println(text +" contains numbers");
} catch (NumberFormatException e){
System.out.println(text+" not contains numbers");
}
Paul Irish has a way to do this that covers most of the common problems. See his bullet-proof @font-face article:
The final variant, which stops unnecessary data from being downloaded by IE, and works in IE8, Firefox, Opera, Safari, and Chrome looks like this:
@font-face {
font-family: 'Graublau Web';
src: url('GraublauWeb.eot');
src: local('Graublau Web Regular'), local('Graublau Web'),
url("GraublauWeb.woff") format("woff"),
url("GraublauWeb.otf") format("opentype"),
url("GraublauWeb.svg#grablau") format("svg");
}
He also links to a generator that will translate the fonts into all the formats you need.
As others have already specified, this will only work in the latest generation of browsers. Your best bet is to use this in conjunction with something like Cufon, and only load Cufon if the browser doesn't support @font-face
.
emulator -writable-system
For people using an Emulator: Another possibility is that you need to start the emulator with -writable-system. That was the only thing that worked for me when using the standard emulator packaged with android studio with a 4.1 image. Check here: https://stackoverflow.com/a/41332316/4962858
SELECT eb.n_EmpId,
em.s_EmpName,
deg.s_DesignationName,
dm.s_DeptName
FROM tbl_EmployeeMaster em
INNER JOIN tbl_DesignationMaster deg ON em.n_DesignationId=deg.n_DesignationId
INNER JOIN tbl_DepartmentMaster dm ON dm.n_DeptId = em.n_DepartmentId
INNER JOIN tbl_EmployeeBranch eb ON eb.n_BranchId = em.n_BranchId;
As of HTML5 browsers one can use inputElement.form
- the value of the attribute must be an id of a <form>
element in the same document.
More info on MDN.
The Uri
class implements Parcelable
, so you can add and extract it directly from the Intent
// Add a Uri instance to an Intent
intent.putExtra("imageUri", uri);
// Get a Uri from an Intent
Uri uri = intent.getParcelableExtra("imageUri");
You can use the same method for any objects that implement Parcelable
, and you can implement Parcelable
on your own objects if required.
I tried with various approaches, but nothing worked. I kept getting "Cannot click element" or ElementNotVisibleException.
I was able to find the input, but I couldn't check it. Now, I'm clicking on the div that contains the checkbox and it works with following HTML (CSS based on Bootstrap).
@foreach (var item in Model)
{
<tr>
<td>
<div id="@item.Id" class="checkbox">
<label><input type="checkbox" class="selectone" value="@item.Id"></label>
</div>
</td>
<td val="@item.Id">
@item.Detail
</td>
<td>
<div>@item.Desc
</div>
</td>
<td>
@Html.ActionLink("Edit", "Create", new { EditId = item.Id })
</td>
</tr>
}
This is the code for WebDriver:
var table = driver.FindElement(By.TagName("table"));
var tds = table.FindElements(By.TagName("td"));
var itemTds = tds.Where(t => t.Text == itemtocheck);
foreach (var td in itemTds)
{
var CheckBoxTd = tds[tds.IndexOf(td) - 1];
var val = td.GetAttribute("val");
CheckBoxTd.FindElement(By.Id(val)).Click();
}
In this approach, I give the item id as id for the div and also add an attribute for td with that id. Once I find the td of the item that needs to be checked, I can find the div before that td and click it. We can also use the XPath query that supports before (here is the example http://learn-automation.com/how-to-write-dynamic-xpath-in-selenium/).
Label
is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div
element is a block element so its width is by default 100%.
You will have to place the text-align: right;
on the div
element in your case, or applying display: block;
to your label
Another option is to set a width for each label and then use text-align
. The display: block
method will not be necessary using this.
I had similar issue and I found a solution that is working for Mac, Windows and Linux. It takes few key ingredients that are in the answer above:
To be able to see conda env in Jupyter notebook, you need:
the following package in you base env:
conda install nb_conda
the following package in each env you create:
conda install ipykernel
check the configurationn of jupyter_notebook_config.py
first check if you have a jupyter_notebook_config.py
in one of the location given by jupyter --paths
if it doesn't exist, create it by running jupyter notebook --generate-config
add or be sure you have the following: c.NotebookApp.kernel_spec_manager_class='nb_conda_kernels.manager.CondaKernelSpecManager'
The env you can see in your terminal:
On Jupyter Lab you can see the same env as above both the Notebook and Console:
And you can choose your env when have a notebook open:
The safe way is to create a specific env from which you will run your example of envjupyter lab
command. Activate your env. Then add jupyter lab extension example jupyter lab extension. Then you can run jupyter lab
One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications:
public class TokenTree : Dictionary<string, string>
{
public IDictionary<string, string> SubPairs;
}
This gives you the advantage of not having to enforce the rules of IDictionary for your Key (e.g., key uniqueness, etc).
And yup you got the concept of the constructor right :)
I encountered this using it in Mac, resolved it by using --ignore-platform-reqs
option.
composer install --ignore-platform-reqs
In your case you need to
android:scaleType
to fitXY
Below is an example:
<ImageView
android:id="@+id/photo"
android:layout_width="200dp"
android:layout_height="100dp"
android:src="@drawable/iclauncher"
android:scaleType="fitXY"/>
For more information regarding ImageView scaleType please refer to the developer website.
Really, there isn't. there are about a half-zillion different regex syntaxes; they seem to come down to Perl, EMACS/GNU, and AT&T in general, but I'm always getting surprised too.
Update: After several attempts, it looks like this may have been fixed in latest Chrome builds (per Paul Irish's comment below). That would suggest we will see this fixed in stable Chrome June-July 2016. Let's see ...
This is a known bug with the official Chromecast JavaScript library. Instead of failing silently, it dumps these error messages in all non-Chrome browsers as well as Chrome browsers where the Chromecast extension isn't present.
The Chromecast team have indicated they won't fix this bug.
If you are a developer shipping with this library, you can't do anything about it according to Chromecast team. You can only inform users to ignore the errors. (I believe Chromecast team is not entirely correct as the library could, at the least, avoid requesting the extension scipt if the browser is not Chrome. And I suspect it could be possible to suppress the error even if it is Chrome, but haven't tried anything.)
If you are a user annoyed by these console messages, you can switch to Chrome if not using it already. Within Chrome, either:
Update [Nov 13, 2014]: The problem has now been acknowledged by Google. A member of the Chromecast team seems to suggest the issue will be bypassed by a change the team is currently working on.
Update 2 [Feb 17, 2015]: The team claim there's nothing they can do to remove the error logs as it's a standard Chrome network error and they are still working on a long-term fix. Public comments on the bug tracker were closed with that update.
Update 3 [Dec 4, 2015]: This has finally been fixed! In the end, Chrome team simply added some code to block out this specific error. Hopefully some combination of devtools and extensions API will be improved in the future to make it possible to fix this kind of problem without patching the browser. Chrome Canary already has the patch, so it should roll out to all users around mid-January. Additionally, the team has confirmed the issue no longer affects other browsers as the SDK was updated to only activate if it's in Chrome.
Update 4 (April 30): Nope, not yet anyway. Thankfully Google's developer relations team are more aware than certain other stakeholders how badly this has affected developer experience. More whitelist updates have recently been made to clobber these log messages. Current status at top of the post.
If you know what the sections are, you can do:
select top 10 * from table where section=1
union
select top 10 * from table where section=2
union
select top 10 * from table where section=3
Please check this https://stackoverflow.com/a/9519493/1074944 and try this way also $('input[type="date"]').datepicker().prop('type','text');
check the demo
have you tried?
<td title="This is Title">
its working fine here on Firefox v 18 (Aurora), Internet Explorer 8 & Google Chrome v 23x
I don't think it is very important to find the location of Svcutil.exe. You can use Visual Studio Command prompt to execute directly without its absolute path,
Syntax:
svcutil.exe /language:[vb|cs] /out:[YourClassName].[cs|vb] /config:[YourAppConfigFile.config] [YourServiceAddress]
example:
svcutil.exe /language:cs /out:MyClientClass.cs /config:app.config http://localhost:8370/MyService/
You can read up elsewhere on substitution variables; they're quite handy in SQL Developer. But I have fits trying to use bind variables in SQL Developer. This is what I do:
SET SERVEROUTPUT ON
declare
v_testnum number;
v_teststring varchar2(1000);
begin
v_testnum := 2;
DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);
SELECT 36,'hello world'
INTO v_testnum, v_teststring
from dual;
DBMS_OUTPUT.put_line('v_testnum is now ' || v_testnum);
DBMS_OUTPUT.put_line('v_teststring is ' || v_teststring);
end;
SET SERVEROUTPUT ON
makes it so text can be printed to the script output console.
I believe what we're doing here is officially called PL/SQL. We have left the pure SQL land and are using a different engine in Oracle. You see the SELECT
above? In PL/SQL you always have to SELECT ... INTO
either variable or a refcursor. You can't just SELECT
and return a result set in PL/SQL.
Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here
http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/
for a list of invalid characters that you may want to check for.
Update
Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).
Dim WS As Worksheet
Dim i As Long
With ThisWorkbook
Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With
For i = 1 To 1000
DoEvents
Next i
WS.Name = txtSheetName.Value
Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.
(originally posted by leepowers in his question)
The error message is confusing for one big reason:
Primitive type names are not reserved in PHP
The following are all valid class declarations:
class string { }
class int { }
class float { }
class double { }
My mistake was in thinking that the error message was referring solely to the string primitive type - the word 'instance' should have given me pause. An example to illustrate further:
class string { }
$n = 1234;
$s1 = (string)$n;
$s2 = new string();
$a = array('no', 'yes');
printf("\$s1 - primitive string? %s - string instance? %s\n",
$a[is_string($s1)], $a[is_a($s1, 'string')]);
printf("\$s2 - primitive string? %s - string instance? %s\n",
$a[is_string($s2)], $a[is_a($s2, 'string')]);
Output:
$s1 - primitive string? yes - string instance? no
$s2 - primitive string? no - string instance? yes
In PHP it's possible for a string
to be a string
except when it's actually a string
. As with any language that uses implicit type conversion, context is everything.
The proper way to install an MSI silently is via the msiexec.exe command line
as follows:
msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"
Quick explanation:
/L*V "C:\Temp\msilog.log"= verbose logging
/QN = run completely silently
/i = run install sequence
There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.
Based on the other answers, this is a simple example of how to accomplish the most common requirement:
const app = express()
app.use(express.static('public')) // relative path of client-side code
app.get('*', function(req, res) {
res.sendFile('index.html', { root: __dirname })
})
app.listen(process.env.PORT)
This also doubles as a simple way to respond with index.html on every request, because I'm using a star *
to catch all files that weren't found in your static (public) directory; which is the most common use case for web-apps. Change to /
to return the index only in the root path.
Use the title
attribute, for example:
<div title="them's hoverin' words">hover me</div>
_x000D_
or:
<span title="them's hoverin' words">hover me</span>
_x000D_
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Styling links</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
hr{
margin: 2px 0 0 0;
}
a{
cursor:pointer;
}
#yearBetween{
margin-left: 67px;
}
</style>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="YearPicker.js"></script>
</head>
<body>
<div class="form-group col-sm-8" style="display:inline-flex;">
<div style="display:inline-flex;">
<label class="col-sm-4">Select Year</label>
<input type="text" id="txtYear1" class="form-control cols-sm-2"/>
<img id="yearImage" src="https://cdn4.iconfinder.com/data/icons/VISTA/accounting/png/400/calendar_year.png" style="cursor: pointer;width:50px; height:35px;"></img>
</div>
<div id="divYear1" style="display:none;border: 0.5px solid lightgrey; height:auto;">
<div style="background:lightgrey;height: 12%;">
<a id="btnPrev1" class="btnPrev glyphicon glyphicon glyphicon-menu-left" style="float:left;margin: 4px;"></a>
<input style="text-align: center; width: 43%; border: none; margin-left: 20%;" type="text" id="yearBetween" class="btn-default"/>
<a id="btnNext1" class="btnNext glyphicon glyphicon glyphicon-menu-right" style="float:right;margin: 4px;"></a>
</div>
<hr/>
<div id="yearContainer" style="width:260px; height:auto;">
</div>
</div>
</div>
</body>
</html>
$(document).ready(function(){
// initial value of the start year for the dynamic binding of the picker.
var startRange = 2000;
// given the previous sixteen years from the current start year.
$(".btnPrev").click(function(){
endRange = startRange;
startRange = startRange - 16;
$("#yearBetween").text('');
// finding the current div
var container = event.currentTarget.nextElementSibling.parentElement.nextElementSibling.nextElementSibling;
// find the values between the years from the textbox in year picker.
createButtons(container);
//bind the click function for the dynamically created buttons.
bindButtons();
var rangeValues = startRange+ " - "+(endRange-1) ;
$("#yearBetween").val(rangeValues);
});
// given the next sixteen years from the current end year.
$(".btnNext").click(function(){
startRange = endRange;
endRange = endRange + 16;
//clearing the cuurent values of the picker
$("#yearBetween").text('');
// finding the current div
var container = event.currentTarget.parentElement.nextElementSibling.nextElementSibling;
createButtons(container);
//bind the click function for the dynamically created buttons.
bindButtons();
// find the values between the years from the textbox in year picker.
var rangeValues = startRange+ " - "+(endRange-1) ;
// writes the value in textbox shows above the button div.
$("#yearBetween").val(rangeValues);
});
$("#txtYear1,#yearImage").click(function(){
debugger;
$("#divYear1").toggle();
endRange = startRange + 16;
//clearing the cuurent values of the picker
$("#yearBetween").text('');
var container = "#yearContainer";
// Creating the button for the years in yearpicker.
createButtons(container);
//bind the click function for the dynamically created buttons.
bindButtons();
// find the values between the years from the textbox in year picker.
var rangeValues = startRange+ " - "+(endRange-1) ;
// writes the value in textbox shows above the button div.
$("#yearBetween").val(rangeValues);
});
// binding the button for the each dynamically created buttons.
function bindButtons(){
$(".button").bind('click', function(evt)
{
debugger;
$(this).css("background","#ccc");
$("#txtYear1").val($(this).val());
$('#divYear1').hide();
});
}
// created the button for the each dynamically created buttons.
function createButtons(container){
var count=0;
$(container).empty();
for(var i= startRange; i< endRange; i++)
{
var btn = "<input type='button' style='margin:3px;' class='button btn btn-default' value=" + i + "></input>";
count = count + 1;
$(container).append(btn);
if(count==4)
{
$(container).append("<br/>");
count = 0;
}
}
}
$("#yearBetween").focusout(function(){
var yearValue = $("#yearBetween").val().split("-");
startRange = parseInt(yearValue[0].trim());
if(startRange>999 && startRange < 9985){
endRange = startRange + 16;
$("#yearBetween").text('');
var container = "#yearContainer";
createButtons(container);
bindButtons();
var rangeValues = startRange+ " - "+(endRange-1) ;
$("#yearBetween").val(rangeValues);
}
else
{
$("#yearBetween").focus();
}
});
$("#yearBetween, #txtYear1").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
Add this connection string tag in web.config file:
<connectionStrings>
<add name="itmall"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>
And use it like you mentioned. :)
You can also easily compare branches for changed files using for example TortoiseGit. Just click on Browse References and pick the branches you want to compare.
For example if you compare your branch with master you will get as a result list of files that will be changed in master if you decide to merge your-branch into master.
Remmber that you will have different result if you compare master with your-branch and your-branch with master.
Working for me:
var st = new StackTrace(e, true);
// Get the bottom stack frame
var frame = st.GetFrame(st.FrameCount - 1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
var method = frame.GetMethod().ReflectedType.FullName;
var path = frame.GetFileName();
See jsFiddle demo
I needed a list exactly as described for a project that showed employees at a company, with their photo on the left, and information on the right. I managed to accomplish the clearing by using psuedo-elements after every DD
:
.myList dd:after {
content: '';
display: table;
clear: both;
}
In addition, I wanted the text to only display to the right of the image, without wrapping under the floated image (pseudo-column effect). This can be accomplished by adding a DIV
element with the CSS overflow: hidden;
around the content of the DD
tag. You can omit this extra DIV
, but the content of the DD
tag will wrap under the floated DT
.
After playing with it a while, I was able to support multiple DT
elements per DD
, but not multiple DD
elements per DT
. I tried adding another optional class to clear only after the last DD
, but subsequent DD
elements wrapped under the DT
elements (not my desired effect… I wanted the DT
and DD
elements to form columns, and the extra DD
elements were too wide).
By all rights, this should only work in IE8+, but due to a quirk in IE7 it works there as well.
For compatibility with Tensorflow 2.0, you can use tf.get_logger
import logging
tf.get_logger().setLevel(logging.ERROR)
For a simple java String
Array you should try
String arr_str [] = { "value1`", "value2", "value3" };
JSONArray arr_strJson = new JSONArray(Arrays.asList(arr_str));
System.out.println(arr_strJson.toString());
If you have an Generic ArrayList of type String like ArrayList<String>
. then you should try
ArrayList<String> obj_list = new ArrayList<>();
obj_list.add("value1");
obj_list.add("value2");
obj_list.add("value3");
JSONArray arr_strJson = new JSONArray(obj_list));
System.out.println(arr_strJson.toString());
I was also using the official image (FROM postgres
)
and I was able to change the config by executing the following commands.
The first thing is to locate the PostgreSQL config file. This can be done by executing this command in your running database.
SHOW config_file;
I my case it returns /data/postgres/postgresql.conf
.
The next step is to find out what is the hash of your running PostgreSQL docker container.
docker ps -a
This should return a list of all the running containers. In my case it looks like this.
...
0ba35e5427d9 postgres "docker-entrypoint.s…" ....
...
Now you have to switch to the bash inside your container by executing:
docker exec -it 0ba35e5427d9 /bin/bash
Inside the container check if the config is at the correct path and display it.
cat /data/postgres/postgresql.conf
I wanted to change the max connections from 100 to 1000 and the shared buffer from 128MB to 3GB. With the sed command I can do a search and replace with the corresponding variables ins the config.
sed -i -e"s/^max_connections = 100.*$/max_connections = 1000/" /data/postgres/postgresql.conf
sed -i -e"s/^shared_buffers = 128MB.*$/shared_buffers = 3GB/" /data/postgres/postgresql.conf
The last thing we have to do is to restart the database within the container. Find out which version you of PostGres you are using.
cd /usr/lib/postgresql/
ls
In my case its 12
So you can now restart the database by executing the following command with the correct version in place.
su - postgres -c "PGDATA=$PGDATA /usr/lib/postgresql/12/bin/pg_ctl -w restart"
try this code [updated]:
Scanner scan = null;
int range, smallest = 0, input;
for(;;){
boolean error=false;
scan = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
continue;
}
range = scan.nextInt();
if(range < 1) {
System.out.println("Invalid input!");
error=true;
}
if(error)
{
//do nothing
}
else
{
break;
}
}
for(int ii = 1; ii <= range; ii++) {
scan = new Scanner(System.in);
System.out.print("Enter value " + ii + ": ");
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
ii--;
continue;
}
}
Just my 2 cents. This code combines two matrices or data.frames into one. If one data structure have lower number of rows then missing rows will be added with NA values.
combine.df <- function(x, y) {
rows.x <- nrow(x)
rows.y <- nrow(y)
if (rows.x > rows.y) {
diff <- rows.x - rows.y
df.na <- matrix(NA, diff, ncol(y))
colnames(df.na) <- colnames(y)
cbind(x, rbind(y, df.na))
} else {
diff <- rows.y - rows.x
df.na <- matrix(NA, diff, ncol(x))
colnames(df.na) <- colnames(x)
cbind(rbind(x, df.na), y)
}
}
df1 <- data.frame(1:10, row.names = 1:10)
df2 <- data.frame(1:5, row.names = 10:14)
combine.df(df1, df2)
May be join two ..
folder, to get parent of the parent folder?
path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))
The JSON.stringify
method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/
This method is also included with json2.js, for supporting older browsers.
If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.
Python is a language: a set of rules that can be used to write programs. There are several implementaions of this language.
No matter what implementation you take, they do pretty much the same thing: take the text of your program and interpret it, executing its instructions. None of them compile your code into C or any other language.
CPython is the original implementation, written in C. (The "C" part in "CPython" refers to the language that was used to write Python interpreter itself.)
Jython is the same language (Python), but implemented using Java.
IronPython interpreter was written in C#.
There's also PyPy - a Python interpreter written in Python. Make your pick :)
After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops
GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:
alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.
It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.
Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.
Though The above answers are right, I found something more user-friendly approach while using ternary operator.
{{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
If someone need to work through foreach then,
{% for attachment in attachments %}
{{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
{% endfor %}
You could select and style this with JavaScript or jQuery, but CSS alone can't do this.
For example, if you have jQuery implemented on the site, you could just do:
var last_visible_element = $('div:visible:last');
Although hopefully you'll have a class/ID wrapped around the divs you're selecting, in which case your code would look like:
var last_visible_element = $('#some-wrapper div:visible:last');
There are two approaches that I know of. The first is to tell the browser not to cache the page. Setting the Response to no cache takes care of that, however as you suspect the browser will often ignore this directive. The other approach is to set the date time of your response to a point in the future. I believe all browsers will correct this to the current time when they add the page to the cache, but it will show the page as newer when the comparison is made. I believe there may be some cases where a comparison is not made. I am not sure of the details and they change with each new browser release. Final note I have had better luck with pages that "refresh" themselves (another response directive). The refresh seems less likely to come from the cache.
Hope that helps.
Use code as follows:
mylist <- lapply(pressure, function(i)read.xlsx(i,colNames = FALSE))#
mydata <- do.call('rbind',mylist)#
This recently happen to me when enabling JMX on two running tomcat service within Eclipse. I mistakenly put the same port for each server.
Simply give each jmx remote a different port
Server 1
-Dcom.sun.management.jmxremote.port=9000
Server 2
-Dcom.sun.management.jmxremote.port=9001
One Line Answer:
Monitor: controls only ONE thread at a time can execute in the monitor. (need to acquire lock to execute the single thread)
Semaphore: a lock that protects a shared resource. (need to acquire the lock to access resource)
The route-map express example matches url paths with objects which in turn matches http verbs with functions. This lays the routing out in a tree, which is concise and easy to read. The apps's entities are also written as objects with the functions as enclosed methods.
var express = require('../../lib/express')
, verbose = process.env.NODE_ENV != 'test'
, app = module.exports = express();
app.map = function(a, route){
route = route || '';
for (var key in a) {
switch (typeof a[key]) {
// { '/path': { ... }}
case 'object':
app.map(a[key], route + key);
break;
// get: function(){ ... }
case 'function':
if (verbose) console.log('%s %s', key, route);
app[key](route, a[key]);
break;
}
}
};
var users = {
list: function(req, res){
res.send('user list');
},
get: function(req, res){
res.send('user ' + req.params.uid);
},
del: function(req, res){
res.send('delete users');
}
};
var pets = {
list: function(req, res){
res.send('user ' + req.params.uid + '\'s pets');
},
del: function(req, res){
res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid);
}
};
app.map({
'/users': {
get: users.list,
del: users.del,
'/:uid': {
get: users.get,
'/pets': {
get: pets.list,
'/:pid': {
del: pets.del
}
}
}
}
});
app.listen(3000);
You can try this
<select name="select1" onmousedown="if(this.options.length>8){this.size=8;}" onchange='this.size=0;' onblur="this.size=0;">_x000D_
<option value="1">This is select number 1</option>_x000D_
<option value="2">This is select number 2</option>_x000D_
<option value="3">This is select number 3</option>_x000D_
<option value="4">This is select number 4</option>_x000D_
<option value="5">This is select number 5</option>_x000D_
<option value="6">This is select number 6</option>_x000D_
<option value="7">This is select number 7</option>_x000D_
<option value="8">This is select number 8</option>_x000D_
<option value="9">This is select number 9</option>_x000D_
<option value="10">This is select number 10</option>_x000D_
<option value="11">This is select number 11</option>_x000D_
<option value="12">This is select number 12</option>_x000D_
</select>
_x000D_
It worked for me
The desired result can be obtained using IGrouping, which represents a collection of objects that have a common key in this case a GroupID
var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
.Select(group => new { GroupID = group.Key, Customers = group.ToList() })
.ToList();
SELECT * INTO #TempTable
FROM SampleTable
WHERE...
SELECT * FROM #TempTable
DROP TABLE #TempTable
To convert a pandas dataframe (df) to a numpy ndarray, use this code:
df.values
array([[nan, 0.2, nan],
[nan, nan, 0.5],
[nan, 0.2, 0.5],
[0.1, 0.2, nan],
[0.1, 0.2, 0.5],
[0.1, nan, 0.5],
[0.1, nan, nan]])
A Java virtual machine (JVM) is a virtual machine that can execute Java ByteCode. It is the code execution component of the Java software platform.
The Java Development Kit (JDK) is an Oracle Corporation product aimed at Java developers. Since the introduction of Java, it has been by far the most widely used Java Software Development Kit (SDK).
Java Runtime Environment, is also referred to as the Java Runtime, Runtime Environment
OpenJDK (Open Java Development Kit) is a free and open source implementation of the Java programming language. It is the result of an effort Sun Microsystems began in 2006. The implementation is licensed under the GNU General Public License (GPL) with a linking exception.
I had a different approach. I've sub-classed a Thread class and in the constructor I've created an Event object. Then I've written custom join() method, which first sets this event and then calls a parent's version of itself.
Here is my class, I'm using for serial port communication in wxPython app:
import wx, threading, serial, Events, Queue
class PumpThread(threading.Thread):
def __init__ (self, port, queue, parent):
super(PumpThread, self).__init__()
self.port = port
self.queue = queue
self.parent = parent
self.serial = serial.Serial()
self.serial.port = self.port
self.serial.timeout = 0.5
self.serial.baudrate = 9600
self.serial.parity = 'N'
self.stopRequest = threading.Event()
def run (self):
try:
self.serial.open()
except Exception, ex:
print ("[ERROR]\tUnable to open port {}".format(self.port))
print ("[ERROR]\t{}\n\n{}".format(ex.message, ex.traceback))
self.stopRequest.set()
else:
print ("[INFO]\tListening port {}".format(self.port))
self.serial.write("FLOW?\r")
while not self.stopRequest.isSet():
msg = ''
if not self.queue.empty():
try:
command = self.queue.get()
self.serial.write(command)
except Queue.Empty:
continue
while self.serial.inWaiting():
char = self.serial.read(1)
if '\r' in char and len(msg) > 1:
char = ''
#~ print('[DATA]\t{}'.format(msg))
event = Events.PumpDataEvent(Events.SERIALRX, wx.ID_ANY, msg)
wx.PostEvent(self.parent, event)
msg = ''
break
msg += char
self.serial.close()
def join (self, timeout=None):
self.stopRequest.set()
super(PumpThread, self).join(timeout)
def SetPort (self, serial):
self.serial = serial
def Write (self, msg):
if self.serial.is_open:
self.queue.put(msg)
else:
print("[ERROR]\tPort {} is not open!".format(self.port))
def Stop(self):
if self.isAlive():
self.join()
The Queue is used for sending messages to the port and main loop takes responses back. I've used no serial.readline() method, because of different end-line char, and I have found the usage of io classes to be too much fuss.
As far as I know, a browser session doesn't have an id.
If you mean the server session, that is usually stored in a cookie. The cookie that ASP.NET stores, for example, is named "ASP.NET_SessionId".
Use btn-primary-spacing
class for all buttons remove margin-left
class
Example :
<button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 btn-primary-spacing">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> ADD PACKET
</button>
CSS will be like :
.btn-primary-spacing
{
margin-right: 5px;
margin-bottom: 5px !important;
}
import java.util.Scanner;
public class sort {
public static void main(String args[])
{
int i,n,t;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of array");
n=sc.nextInt();
int a[] = new int[n];
System.out.println("Enter elements in array");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
t=a[1];
for(i=0;i<n;i++)
{
if(a[i]>t)
t=a[i];
}
System.out.println("Greates integer is" +t);
}
}
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
This answer is correct for old versions of iOS, but is now obsolete. You should use Micky Duncan's answer, which covers custom containers.
Don't do this! The intent of the UIViewController
is to drive the entire screen. It just isn't appropriate for this, and it doesn't really add anything you need.
All you need is an object that owns your custom view. Just use a subclass of UIView
itself, so it can be added to your window hierarchy and the memory management is fully automatic.
Point the subview NIB's owner a custom subclass of UIView
. Add a contentView
outlet to this custom subclass, and point it at the view within the nib. In the custom subclass do something like this:
- (id)initWithFrame: (CGRect)inFrame;
{
if ( (self = [super initWithFrame: inFrame]) ) {
[[NSBundle mainBundle] loadNibNamed: @"NibNameHere"
owner: self
options: nil];
contentView.size = inFrame.size;
// do extra loading here
[self addSubview: contentView];
}
return self;
}
- (void)dealloc;
{
self.contentView = nil;
// additional release here
[super dealloc];
}
(I'm assuming here you're using initWithFrame:
to construct the subview.)
None of the solutions here and elsewhere worked for me. Turns out an incompatible 32bit version of mysqlclient is being installed on my 64bit Windows 10 OS because I'm using a 32bit version of Python
I had to uninstall my current Python 3.7 32bit, and reinstalled Python 3.7 64bit and everything is working fine now
To complete some of the answers here, I had to get the ParametrizedType of MyGenericClass, no matter how high is the hierarchy, with the help of recursion:
private Class<T> getGenericTypeClass() {
return (Class<T>) (getParametrizedType(getClass())).getActualTypeArguments()[0];
}
private static ParameterizedType getParametrizedType(Class clazz){
if(clazz.getSuperclass().equals(MyGenericClass.class)){ // check that we are at the top of the hierarchy
return (ParameterizedType) clazz.getGenericSuperclass();
} else {
return getParametrizedType(clazz.getSuperclass());
}
}
The simple and straightforward answer -->
using System;
namespace DemoApp.App
{
public class TestClassDate
{
public static DateTime GetDate(string string_date)
{
DateTime dateValue;
if (DateTime.TryParse(string_date, out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", string_date, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", string_date);
return dateValue;
}
public static void Main()
{
string inString = "05/01/2009 06:32:00";
GetDate(inString);
}
}
}
/**
* Output:
* Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
* */
I second jdk's answer: any public static member of any class of your application can be considered as a "global variable".
However, do note that this is an ASP.NET application, and as such, it's a multi-threaded context for your global variables. Therefore, you should use some locking mechanism when you update and/or read the data to/from these variables. Otherwise, you might get your data in a corrupted state.
If you've not pushed either commit to your remote repository, you could use interactive rebasing to 'reorder' your commits and stash the (new) most recent commit's changes only.
Assuming you have the tip of your current branch (commit 111 in your example) checked out, execute the following:
git rebase -i HEAD~2
This will open your default editor, listing most recent 2 commits and provide you with some instructions. Be very cautious as to what you do here, as you are going to effectively 'rewrite' the history of your repository, and can potentially lose work if you aren't careful (make a backup of the whole repository first if necessary). I've estimated commit hashes/titles below for example
pick 222 commit to be stashed
pick 111 commit to be pushed to remote
# Rebase 111..222 onto 333
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
Reorder the two commits (they are listed oldest => newest) like this:
pick 111 commit to be pushed to remote
pick 222 commit to be stashed
Save and exit, at which point git will do some processing to rewrite the two commits you have changed. Assuming no issues, you should have reversed the order of your two changesets. This can be confirmed with git log --oneline -5
which will output newest-first.
At this point, you can simply do a soft-reset on the most recent commit, and stash your working changes:
git reset --soft HEAD~1
git stash
It's important to mention that this option is only really viable if you have not previously pushed any of these changes to your remote, otherwise it can cause issues for everyone using the repository.
You would use it if you are using RenderAction
in any of your views, usually to render a partial view.
The reason for marking it with [ChildActionOnly]
is that you need the controller method to be public so you can call it with RenderAction
but you don't want someone to be able to navigate to a URL (e.g. /Controller/SomeChildAction) and see the results of that action directly.
Example using std::string
find method:
#include <iostream>
#include <string>
int main (){
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
size_t found = str.find(str2);
if(found!=std::string::npos){
std::cout << "first 'needle' found at: " << found << '\n';
}
return 0;
}
Result:
first 'needle' found at: 14.
File -> Source Control -> Advanced -> Change Source Control and then unbind and/or disconnect all projects and the solution.
This should remove all bindings from the solution and project files. (After this you can switch the SCC provider in Tools -> Options -> Source Control -> Plug-in Selection).
The SCC specification prescribes that all SCC providers should implement this behavior. (I only tested it for VSS, TFS and AnkhSVN)
My 2 cents on this error, even if not related to an export/import scenario:
when adding the mobile provisioning certificate (i.e. the PROV
file), DO NOT drag the file from Finder to Keychain Access. Instead, just double click the PROV file within Finder, while keeping the Keychain Access application running somewhere.
I've actually seen my former provisioning item in Keychain (the one with yellow light) being substituted with a new, green one with same name and app ID. HTH
https://github.com/extensionsapp/progre.sh
Create 40 percent progress: progreSh 40
json_encode($response, JSON_UNESCAPED_SLASHES);
Like this:
<c:forEach var="entry" items="${myMap}">
Key: <c:out value="${entry.key}"/>
Value: <c:out value="${entry.value}"/>
</c:forEach>
You need to instruct the console to clear.
For serial terminals this was typically done through so called "escape sequences", where notably the vt100 set has become very commonly supported (and its close ANSI-cousin).
Windows has traditionally not supported such sequences "out-of-the-box" but relied on API-calls to do these things. For DOS-based versions of Windows, however, the ANSI.SYS driver could be installed to provide such support.
So if you are under Windows, you need to interact with the appropriate Windows API. I do not believe the standard Java runtime library contains code to do so.
UIColor's RGB components are scaled between 0 and 1, not up to 255.
Try
categoryTitle.textColor = [UIColor colorWithRed:(188/255.f) green:... blue:... alpha:1.0];
In Swift:
categoryTitle.textColor = UIColor(red: 188/255.0, green: ..., blue: ..., alpha: 1)
const CallStack = createStackNavigator({
Calls: Calls,
CallsScreen:CallsScreen,
}, {headerMode: 'none'});
CallStack.navigationOptions = {
tabBarLabel: 'Calls',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={Platform.OS === 'ios' ? 'ios-options' : 'md-options'}
/>
),
header: null,
headerVisible: false,
};
Built a tiny, confirm-like vanilla js yes / no dialog.
https://www.npmjs.com/package/yesno-dialog
In the Android Studio go to File
then Close Project
. Then take the folder (in the workspace folder) of the project and copy it to a flash memory or whatever. Then when you get comfortable at home, copy this folder in the workspace folder you've already created, open the Android Studio and go to File
then Open
and import this project into your workspace.
The problem you have with this is that you're searching for the wrong term here, because in Android, exporting a project means compiling it to .apk
file (not exporting the project). Import/Export is used for the .apk
management, what you need is Open/Close project, the other thing is just copy/paste.
In vb.net either on button click or on link button click, this will work.
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "openModal", "window.open('CertificatePrintViewAll.aspx' ,'_blank');", True)
If you already have a database, keep it in your asset folder and copy it in your application. For more detail, see Android database basics.
As a sidenote to this:
netsh http add urlacl url=http://vaidesg:8080/ user=everyone
This will only work on English versions of Windows. If you are using a localized version you have to replace "everyone" with something else, for example:
Otherwise you will get an error (Create SDDL failed, Error: 1332)
.table td.abbreviation {_x000D_
max-width: 30px;_x000D_
}_x000D_
.table td.abbreviation p {_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
_x000D_
}
_x000D_
<table class="table">_x000D_
<tr>_x000D_
<td class="abbreviation"><p>ABC DEF</p></td>_x000D_
</tr>_x000D_
</table>
_x000D_
Read up on Cancellation (which was introduced in .NET 4.0 and is largely unchanged since then) and the Task-Based Asynchronous Pattern, which provides guidelines on how to use CancellationToken
with async
methods.
To summarize, you pass a CancellationToken
into each method that supports cancellation, and that method must check it periodically.
private async Task TryTask()
{
CancellationTokenSource source = new CancellationTokenSource();
source.CancelAfter(TimeSpan.FromSeconds(1));
Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token);
// (A canceled task will raise an exception when awaited).
await task;
}
private int slowFunc(int a, int b, CancellationToken cancellationToken)
{
string someString = string.Empty;
for (int i = 0; i < 200000; i++)
{
someString += "a";
if (i % 1000 == 0)
cancellationToken.ThrowIfCancellationRequested();
}
return a + b;
}
Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)
Recommended reading. Lists in the Java Tutorial
2020: The official AOSP code search https://cs.android.com/
You can view the source code through http://developer.android.com, when you're reading the API there will be a link to the matching source code on GitHub, you just need to add the Android SDK Reference Search Plugin on Chrome.
I blogged about it here:
http://blog.blundellapps.com/add-source-code-links-to-android-apis/
If you are only concerned with 8 bit characters (which all other answers except Milan Babuškov assume as well) you can get the fastest speed by generating a look-up table at compile time using metaprogramming. On ideone.com this runs 7x faster than the library function and 3x faster than a hand written version (http://ideone.com/sb1Rup). It is also customizeable through traits with no slow down.
template<int ...Is>
struct IntVector{
using Type = IntVector<Is...>;
};
template<typename T_Vector, int I_New>
struct PushFront;
template<int ...Is, int I_New>
struct PushFront<IntVector<Is...>,I_New> : IntVector<I_New,Is...>{};
template<int I_Size, typename T_Vector = IntVector<>>
struct Iota : Iota< I_Size-1, typename PushFront<T_Vector,I_Size-1>::Type> {};
template<typename T_Vector>
struct Iota<0,T_Vector> : T_Vector{};
template<char C_In>
struct ToUpperTraits {
enum { value = (C_In >= 'a' && C_In <='z') ? C_In - ('a'-'A'):C_In };
};
template<typename T>
struct TableToUpper;
template<int ...Is>
struct TableToUpper<IntVector<Is...>>{
static char at(const char in){
static const char table[] = {ToUpperTraits<Is>::value...};
return table[in];
}
};
int tableToUpper(const char c){
using Table = TableToUpper<typename Iota<256>::Type>;
return Table::at(c);
}
with use case:
std::transform(in.begin(),in.end(),out.begin(),tableToUpper);
For an in depth (many page) decription of how it works allow me to shamelessly plug my blog: http://metaporky.blogspot.de/2014/07/part-4-generating-look-up-tables-at.html
Try putting a space before each \;
Works:
find . -name "*.log" -exec echo {} \;
Doesn't Work:
find . -name "*.log" -exec echo {}\;
As with anything: if used with care, it can be an elegant tool.
However, I think the drawbacks more than justify not to use it, and finally not to allow it anymore (C#). Among the problems are:
Good use of a switch/case fall-through:
switch (x)
{
case 1:
case 2:
case 3:
Do something
break;
}
Baaaaad use of a switch/case fall-through:
switch (x)
{
case 1:
Some code
case 2:
Some more code
case 3:
Even more code
break;
}
This can be rewritten using if/else constructs with no loss at all in my opinion.
My final word: stay away from fall-through case labels as in the bad example, unless you are maintaining legacy code where this style is used and well understood.
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
I did two things inspired by @OscarJovanny comment, with some hacks.
Step 1:
Step 2:
<style>
ul {
list-style-type: none;
margin-left: 10px;
}
ul li {
margin-bottom: 12px;
margin-left: -10px;
display: flex;
align-items: center;
}
ul li::before {
color: transparent;
font-size: 1px;
content: " ";
margin-left: -1.3em;
margin-right: 15px;
padding: 10px;
background-color: orange;
-webkit-mask-image: url("./assets/img/check-circle-solid.svg");
-webkit-mask-size: cover;
}
</style>
Results
Simple:
string[] someName = new string[] {"10", "15", "25", "50", "100", "1000"};
myViewData.PageOptionsDropDown = new SelectList(someName, "15");
<script type="text/javascript">
$(document).ready(function () {
$("#txtDate").datepicker({ dateFormat: 'yy/mm/dd' }).datepicker("setDate", "0");
$("#txtDate2").datepicker({ dateFormat: 'yy/mm/dd', }).datepicker("setDate", new Date().getDay+15); }); </script>
I would think so. Why not? Wouldn't be much of a CDN w/o offering the CSS to support the script files
This link suggests that they are:
We find it particularly exciting that the jQuery UI CSS themes are now hosted on Google's Ajax Libraries CDN.
I wrote this one today while trying to recreate _.sortBy
in TypeScript, and thought I would leave it for anyone in need.
// ** Credits for getKeyValue at the bottom **
export const getKeyValue = <T extends {}, U extends keyof T>(key: U) => (obj: T) => obj[key]
export const sortBy = <T extends {}>(index: string, list: T[]): T[] => {
return list.sort((a, b): number => {
const _a = getKeyValue<keyof T, T>(index)(a)
const _b = getKeyValue<keyof T, T>(index)(b)
if (_a < _b) return -1
if (_a > _b) return 1
return 0
})
}
It expects an array of generic type T, hence the cast for <T extends {}>
, as well as typing the parameter and function return type with T[]
const x = [{ label: 'anything' }, { label: 'goes'}]
const sorted = sortBy('label', x)
** getByKey
fn found here
At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.
$mail->ClearReplyTos();
$mail->addReplyTo([email protected], 'EXAMPLE');
$rootbeer = (float) $InvoicedUnits;
Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.
For Eclipse PDT in Mac OS, once you have deleted the actual workspace directory the option to select and switch to that workspace will still be available unless you delete the entry from Preferences >> General >> Startup and Shutdown >> Workspaces.
SELECT 'Free &' || ' Clear' FROM DUAL;
jquery.ajax({
url: `//your api url`
type: "GET",
dataType: "json",
success: function(data) {
jQuery.each(data, function(index, value) {
console.log(data);
`All you API data is here`
}
}
});
You can use these to factor out code common to all tests in the test suite.
If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.
You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.
If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.
For example:
class TurretTest(unittest.TestCase):
def setUp(self):
self.turret_factory = TurretFactory()
self.turret = self.turret_factory.CreateTurret()
def test_turret_is_on_by_default(self):
self.assertEquals(True, self.turret.is_on())
def test_turret_turns_can_be_turned_off(self):
self.turret.turn_off()
self.assertEquals(False, self.turret.is_on())
<?php $sql = "SELECT * FROM guest_book";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$query = mysql_query("SELECT * FROM guest_book ORDER BY id");
$i=1;
while($row = mysql_fetch_assoc($query)){
?>
<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>" />
<?php $i++; }} ?>
<input type="submit" value="Delete" name="Delete" />
if($_REQUEST['Delete'] != '')
{
if(!empty($_REQUEST['checkboxstatus'])) {
$checked_values = $_REQUEST['checkboxstatus'];
foreach($checked_values as $val) {
$sqldel = "DELETE from guest_book WHERE id = '$val'";
mysql_query($sqldel);
}
}
}
<table cellpadding="pixels"cellspacing="pixels"></table>
<td align="position"valign="position"></td>
cellpadding
="length in pixels" ~ The cellpadding attribute, used in the <table>
tag, specifies how much blank space to display in between the content of each table cell and its respective border. The value is defined as a length in pixels. Hence, a cellpadding="10"
attribute-value pair will display 10 pixels of blank space on all four sides of the content of each cell in that table.
cellspacing
="length in pixels" ~ The cellspacing attribute, also used in the <table>
tag, defines how much blank space to display in between adjacent table cells and in between table cells and the table border. The value is defined as a length in pixels. Hence, a cellspacing="10"
attribute-value pair will horizontally and vertically separate all adjacent cells in the respective table by a length of 10 pixels. It will also offset all cells from the table's frame on all four sides by a length of 10 pixels.
go to AndroidManifest.xml There you will find package as the attribute of manifest tag. Just select the part you want to change, right click-> refactor -> rename
Maybe earlier it was hard, but as of today it is not anymore.
You might also want to change the app id in
defaultConfig {
applicationId
}
Short & Sweet
If you are looking for UML sequence diagrams, you might be interested in pkf-umlsd, which is based on TiKZ. Nice demos can be found here.
It already is:
var mystring = 'foobar';_x000D_
console.log(mystring[0]); // Outputs 'f'_x000D_
console.log(mystring[3]); // Outputs 'b'
_x000D_
Or for a more older browser friendly version, use:
var mystring = 'foobar';_x000D_
console.log(mystring.charAt(3)); // Outputs 'b'
_x000D_
why not simply
public Date(){
data = new int[]{0,0,0};
}
the reason you got the error is because int[] data = ...
declares a new variable and hides the field data
however it should be noted that the contents of the array are already initialized to 0 (the default value of int
)