For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
After this it will send ajax request like you submit regular form with enctype="multipart/form-data"
Update: This request cannot work without type:"POST"
in options since all files must be sent via POST request.
Note: contentType: false
only available from jQuery 1.6 onwards
if(isset($_POST["newsletter"]) && $_POST["newsletter"] == "newsletter"){
//checked
}
You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation
They use JQuery validation.
jquery.validate.js
jquery.validate.min.js
jquery-1.7.1.min.js
And you'll get the source code there.
<form id="registration-form" class="form-horizontal">
<h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
<div class="form-control-group">
<label class="control-label" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">User Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="username" id="username"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="password" id="password">
</div>
</div>
<div class="form-control-group">
<label class="control-label" for="name"> Retype Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message">Your Address</label>
<div class="controls">
<textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
<input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success btn-large">Register</button>
<button type="reset" class="btn">Cancel</button></div>
</form>
And The JQuery :
<script src="assets/js/jquery-1.7.1.min.js"></script>
<script src="assets/js/jquery.validate.js"></script>
<script src="script.js"></script>
<script>
addEventListener('load', prettyPrint, false);
$(document).ready(function(){
$('pre').addClass('prettyprint linenums');
});
Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/
Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/
happy coding.
You can use HTMLFormElement.prototype.reset
according to MDN
document.getElementById("myForm").reset();
Try ajaxsubmit library. It does ajax submition as well as validation via ajax.
Also configuration is very flexible to support any kind of UI.
Live demo available with js, css and html examples.
An alternative solution would be to not use form tag and handle click event on submit button through jquery. This way there wont be any page refresh but at the same time there is a downside that "enter" button for submission wont work and also on mobiles you wont get a go button( a style in some mobiles). So stick to use of form tag and use the accepted answer.
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
location ~* \.php$ {
...
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
Change default
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
to
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
solved my problem.
I was working on this type of function, maybe this will interests some of you ...
public boolean deleteFile(File file) throws IOException {
if (file != null) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f: files) {
deleteFile(f);
}
}
return Files.deleteIfExists(file.toPath());
}
return false;
}
There's a python module especially made for reading and writing to and from binary encoded data called 'struct'. Since versions of Python under 2.6 doesn't support str.format, a custom method needs to be used to create binary formatted strings.
import struct
# binary string
def bstr(n): # n in range 0-255
return ''.join([str(n >> x & 1) for x in (7,6,5,4,3,2,1,0)])
# read file into an array of binary formatted strings.
def read_binary(path):
f = open(path,'rb')
binlist = []
while True:
bin = struct.unpack('B',f.read(1))[0] # B stands for unsigned char (8 bits)
if not bin:
break
strBin = bstr(bin)
binlist.append(strBin)
return binlist
Honestly, given our "modern times" I'd go with a functional programming approach whenever possible, like so:
const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);
Our accumulator acc
, starting with a value of 0, is accumulating all looped values of our object. This has the added benefit of not depending on any internal or external variables; it's a constant function so it won't be accidentally overwritten... win for ES2015!
A lot of good opinions here. I'll add what's not here. My experience:
Setup Resources
Live Deployment for Development/Testing
Learning
The image below is from the article written by Erwin van der Valk:
The article explains the differences and gives some code examples in C#
The problem is, you are creating a transport
object and using it's connect method to authenticate yourself.
But then you use a static
method to send the message which ignores authentication done by the object.
So, you should either use the sendMessage(message, message.getAllRecipients())
method on the object or use an authenticator as suggested by others to get authorize
through the session.
Here's the Java Mail FAQ, you need to read.
This is how to get the last record from all MongoDB documents from the "foo" collection.(change foo,x,y.. etc.)
db.foo.aggregate([{$sort:{ x : 1, date : 1 } },{$group: { _id: "$x" ,y: {$last:"$y"},yz: {$last:"$yz"},date: { $last : "$date" }}} ],{ allowDiskUse:true })
you can add or remove from the group
help articles: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group
https://docs.mongodb.com/manual/reference/operator/aggregation/last/
function function_one()_x000D_
{_x000D_
alert("The function called 'function_one' has been called.")_x000D_
//Here u would like to call function_two._x000D_
function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
With Java 8 you can create a stream and check if any entries in the stream matches "s"
:
String[] values = {"AB","BC","CD","AE"};
boolean sInArray = Arrays.stream(values).anyMatch("s"::equals);
Or as a generic method:
public static <T> boolean arrayContains(T[] array, T value) {
return Arrays.stream(array).anyMatch(value::equals);
}
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
In [44]: df['gdp'] = df['gdp'].shift(-1)
In [45]: df
Out[45]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
4 6 NaN 7
In [46]: df[:-1]
Out[46]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
You are using two WHERE
clauses but only one is allowed. Use it like this:
SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
table1.f_com_id = '430'
AND table1.f_status = 'Submitted'
AND table2.f_type = 'InProcess'
Bill Horst's - Converting SQL to LINQ is a very good resource for this task (as well as LINQPad).
LINQ Tools has a decent list of tools as well but I do not believe there is anything else out there that can do what Linqer did.
Generally speaking, LINQ is a higher-level querying language than SQL which can cause translation loss when trying to convert SQL to LINQ. For one, LINQ emits shaped results and SQL flat result sets. The issue here is that an automatic translation from SQL to LINQ will often have to perform more transliteration than translation - generating examples of how NOT to write LINQ queries. For this reason, there are few (if any) tools that will be able to reliably convert SQL to LINQ. Analogous to learning C# 4 by first converting VB6 to C# 4 and then studying the resulting conversion.
I know I am a bit late to the party, but here is another way. That is, this method should wait until the first one is done, the second, and so on.
start "" /wait cmd.exe /c msbuild.bat
start "" /wait cmd.exe /c unit-tests.bat
start "" /wait cmd.exe /c deploy.bat
The only issue that may come out of using this method, is that with new instances of cmd.exe being spawned, is that Errorlevel checking is kept within in each instance of cmd.exe.
Or..
start "" /wait call msbuild.bat
start "" /wait call unit-tests.bat
start "" /wait call deploy.bat
Hope this helps.
Instead of calling every time AppendAllText()
you could think about opening the file once and then write the whole content once:
var file = @"C:\myOutput.csv";
using (var stream = File.CreateText(file))
{
for (int i = 0; i < reader.Count(); i++)
{
string first = reader[i].ToString();
string second = image.ToString();
string csvRow = string.Format("{0},{1}", first, second);
stream.WriteLine(csvRow);
}
}
It isn't always possible to do repetitive things in a simple and elegant way.
Just do what you always do when you have common code that gets replicated across many projects:
Search CPAN, someone may have already the code for you. For this issue I found Scalar::MoreUtils.
If you don't find something you like on CPAN, make a module and put the code in a subroutine:
package My::String::Util;
use strict;
use warnings;
our @ISA = qw( Exporter );
our @EXPORT = ();
our @EXPORT_OK = qw( is_nonempty);
use Carp qw(croak);
sub is_nonempty ($) {
croak "is_nonempty() requires an argument"
unless @_ == 1;
no warnings 'uninitialized';
return( defined $_[0] and length $_[0] != 0 );
}
1;
=head1 BOILERPLATE POD
blah blah blah
=head3 is_nonempty
Returns true if the argument is defined and has non-zero length.
More boilerplate POD.
=cut
Then in your code call it:
use My::String::Util qw( is_nonempty );
if ( is_nonempty $name ) {
# do something with $name
}
Or if you object to prototypes and don't object to the extra parens, skip the prototype in the module, and call it like: is_nonempty($name)
.
It can be done all on the client-side using the OnClientClick
[MSDN] event handler and window.open
[MDN]:
<asp:Button
runat="server"
OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
Open a new window!
</asp:Button>
#include <stdio.h>
#include <string.h>
int main()
{
char *data = "hello world";
int length=strlen(data);
char bytes[length];
int n=0;
while(n<=length)
{
bytes[n] = data[length-n-1];
n++;
}
printf("%s\n", bytes);
return 0;
}
(For the record and before the thread disappears on the msdn forums) You can't disable the warning (at least under VS2010) because it is on the list of the warnings that can't be disabled (so /wd4099 will not work), but what you can do instead is patch link.exe (usually C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\link.exe) to remove it from said list . Sounds like a jackhammer, i know. It works though.
For instance, if you want to remove the warning for 4099, open link.exe with an hex editor, goto line 15A0 which reads 03 10 (little endian for 4099) and replace it with FF 00 (which does not exist.)
a='\nu + \lambda + \theta'
d=a.encode('string_escape').replace('\\\\','\\')
print(d)
# \nu + \lambda + \theta
This shows that there is a single backslash before the n
, l
and t
:
print(list(d))
# ['\\', 'n', 'u', ' ', '+', ' ', '\\', 'l', 'a', 'm', 'b', 'd', 'a', ' ', '+', ' ', '\\', 't', 'h', 'e', 't', 'a']
There is something funky going on with your GUI. Here is a simple example of grabbing some user input through a Tkinter.Entry
. Notice that the text retrieved only has a single backslash before the n
, l
, and t
. Thus no extra processing should be necessary:
import Tkinter as tk
def callback():
print(list(text.get()))
root = tk.Tk()
root.config()
b = tk.Button(root, text="get", width=10, command=callback)
text=tk.StringVar()
entry = tk.Entry(root,textvariable=text)
b.pack(padx=5, pady=5)
entry.pack(padx=5, pady=5)
root.mainloop()
If you type \nu + \lambda + \theta
into the Entry box, the console will (correctly) print:
['\\', 'n', 'u', ' ', '+', ' ', '\\', 'l', 'a', 'm', 'b', 'd', 'a', ' ', '+', ' ', '\\', 't', 'h', 'e', 't', 'a']
If your GUI is not returning similar results (as your post seems to suggest), then I'd recommend looking into fixing the GUI problem, rather than mucking around with string_escape
and string replace
.
If you insist on using ForEach-Object, then I would suggest adding a "break condition" like this:
$Break = $False;
1,2,3,4 | Where-Object { $Break -Eq $False } | ForEach-Object {
$Break = $_ -Eq 3;
Write-Host "Current number is $_";
}
The above code must output 1,2,3 and then skip (break before) 4. Expected output:
Current number is 1
Current number is 2
Current number is 3
Try the solution below, it's O(n)
and it will store and return the second greatest number in the second
variable. UPDATE: I've adjusted the code to work with Python 3, because now arithmetic comparisons against None
are invalid.
Notice that if all elements in numbers
are equal, or if numbers
is empty or if it contains a single element, the variable second
will end up with a value of None
- this is correct, as in those cases there isn't a "second greatest" element.
Beware: this finds the "second maximum" value, if there's more than one value that is "first maximum", they will all be treated as the same maximum - in my definition, in a list such as this: [10, 7, 10]
the correct answer is 7
.
def second_largest(numbers):
minimum = float('-inf')
first, second = minimum, minimum
for n in numbers:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return second if second != minimum else None
Here are some tests:
second_largest([20, 67, 3, 2.6, 7, 74, 2.8, 90.8, 52.8, 4, 3, 2, 5, 7])
=> 74
second_largest([1, 1, 1, 1, 1, 2])
=> 1
second_largest([2, 2, 2, 2, 2, 1])
=> 1
second_largest([10, 7, 10])
=> 7
second_largest( [1, 3, 10, 16])
=> 10
second_largest([1, 1, 1, 1, 1, 1])
=> None
second_largest([1])
=> None
second_largest([])
=> None
If you want nice validation popups and images when an error occurs you can use the setError
method of the EditText
class as I describe here
As far as I can read in API's. The event is only fired when the user clicks on an option.
For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
You could also try:
if ((!isset($action)) || !($action == "add" || $action == "delete")) {
// Do your stuff
}
Incase if you have access to iframe page and want a different CSS to apply on it only when you load it via iframe on your page, here I found a solution for these kind of things
this works even if iframe is loading a different domain
check about postMessage()
plan is, send the css to iframe as a message like
iframenode.postMessage('h2{color:red;}','*');
*
is to send this message irrespective of what domain it is in iframe
and receive the message in iframe and add the received message(CSS) to that document head.
code to add in iframe page
window.addEventListener('message',function(e){
if(e.data == 'send_user_details')
document.head.appendChild('<style>'+e.data+'</style>');
});
Try this if you want to display one of duplicate rows based on RequestID and CreatedDate and show the latest HistoryStatus.
with t as (select row_number()over(partition by RequestID,CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)
or if you want to select one of duplicate rows considering CreatedDate only and show the latest HistoryStatus then try the query below.
with t as (select row_number()over(partition by CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t where rnum = (SELECT Max(rnum) FROM t)
Or if you want to select one of duplicate rows considering Request ID only and show the latest HistoryStatus then use the query below
with t as (select row_number()over(partition by RequestID order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)
All the above queries I have written in sql server 2005.
let INT_VALUE=80
let FLOAT_VALUE:Double= 80.9999
let doubleValue=65.0
let DOUBLE_VALUE:Double= 65.56
let STRING_VALUE="Hello"
let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE);
println(str);
Create a serialization surrogate.
Example, you have a class with public property of type Dictionary.
To support Xml serialization of this type, create a generic key-value class:
public class SerializeableKeyValue<T1,T2>
{
public T1 Key { get; set; }
public T2 Value { get; set; }
}
Add an XmlIgnore attribute to your original property:
[XmlIgnore]
public Dictionary<int, string> SearchCategories { get; set; }
Expose a public property of array type, that holds an array of SerializableKeyValue instances, which are used to serialize and deserialize into the SearchCategories property:
public SerializeableKeyValue<int, string>[] SearchCategoriesSerializable
{
get
{
var list = new List<SerializeableKeyValue<int, string>>();
if (SearchCategories != null)
{
list.AddRange(SearchCategories.Keys.Select(key => new SerializeableKeyValue<int, string>() {Key = key, Value = SearchCategories[key]}));
}
return list.ToArray();
}
set
{
SearchCategories = new Dictionary<int, string>();
foreach (var item in value)
{
SearchCategories.Add( item.Key, item.Value );
}
}
}
I use the following .gitignore file generated in gitignore.io:
### Xcode ###
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.xcuserstate
### Objective-C ###
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
Pods/
This code works for me. When keyboard appears, you can scroll screen
In AndroidManifest.xml
<activity android:name=".signup.screen_2.SignUpNameAndPasswordActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
</activity>
activity_sign_up.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
tools:context=".signup.screen_2.SignUpNameAndPasswordActivity">
<LinearLayout
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_marginTop="@dimen/dp_24"
android:layout_marginStart="@dimen/dp_24"
android:layout_marginEnd="@dimen/dp_24"
android:id="@+id/lin_name_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:fontFamily="sans-serif-medium"
android:text="@string/name_and_password"
android:textColor="@color/colorBlack"
android:layout_marginTop="@dimen/dp_5"
android:textSize="@dimen/ts_16"/>
<EditText
android:id="@+id/edit_full_name"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
app:layout_constraintTop_toTopOf="parent"
android:hint="@string/email_address_hint"
android:inputType="textPersonName"
android:imeOptions="flagNoFullscreen"
android:textSize="@dimen/ts_15"
android:background="@drawable/rounded_border_edittext"
android:layout_marginTop="@dimen/dp_15"
android:paddingStart="@dimen/dp_8"
android:paddingEnd="@dimen/dp_8"
android:maxLength="100"
android:maxLines="1"/>
<EditText
android:id="@+id/edit_password"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
app:layout_constraintTop_toTopOf="parent"
android:hint="@string/password"
android:inputType="textPassword"
android:imeOptions="flagNoFullscreen"
android:textSize="@dimen/ts_15"
android:background="@drawable/rounded_border_edittext"
android:layout_marginTop="@dimen/dp_15"
android:paddingStart="@dimen/dp_8"
android:paddingEnd="@dimen/dp_8"
android:maxLength="100"
android:maxLines="1"/>
<TextView
android:id="@+id/btn_continue_and_sync_contacts"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="@dimen/dp_15"
android:background="@drawable/btn_blue_selector"
android:enabled="false"
android:text="@string/continue_and_sync_contacts"
android:textColor="@color/colorWhite"
android:textSize="@dimen/ts_15"
android:textStyle="bold"/>
<TextView
android:id="@+id/btn_continue_without_syncing_contacts"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="@dimen/dp_10"
android:enabled="false"
android:text="@string/continue_without_syncing_contacts"
android:textColor="@color/colorBlue"
android:textSize="@dimen/ts_15"
android:textStyle="bold"/>
</LinearLayout>
<!--RelativeLayout is scaled when keyboard appears-->
<RelativeLayout
android:layout_marginStart="@dimen/dp_24"
android:layout_marginEnd="@dimen/dp_24"
android:layout_marginBottom="@dimen/dp_20"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_learn_more_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:layout_gravity="center_horizontal"
android:text="@string/learn_more_syncing_contacts"
android:textColor="@color/black_alpha_70"
android:gravity="center"
android:layout_marginBottom="1dp"
android:textSize="@dimen/ts_13"/>
<TextView
android:id="@+id/tv_learn_more_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:layout_gravity="center_horizontal"
android:text="@string/learn_more"
android:fontFamily="sans-serif-medium"
android:textColor="@color/black_alpha_70"
android:textSize="@dimen/ts_13"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</ScrollView>
rounded_border_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true">
<shape android:shape="rectangle">
<solid android:color="#F6F6F6"/>
<corners android:radius="3dp"/>
<stroke
android:width="1dp"
android:color="@color/red"/>
</shape>
</item>
<item android:state_activated="false">
<shape android:shape="rectangle">
<solid android:color="#F6F6F6"/>
<corners android:radius="3dp"/>
<stroke
android:width="1dp"
android:color="@color/colorGray"/>
</shape>
</item>
</selector>
btn_blue_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_pressed="true">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="@color/colorBlueLight"/>
<stroke android:width="1dp" android:color="@color/colorBlueLight"/>
</shape>
</item>
<item android:state_enabled="true">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="@color/colorBlue"/>
<stroke android:width="1dp" android:color="@color/colorBlue"/>
</shape>
</item>
<item android:state_enabled="false">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="@color/colorBlueAlpha"/>
<stroke android:width="0dp" android:color="@color/colorBlueAlpha"/>
</shape>
</item>
</selector>
Super duper easy with PCRE;
As a script, or replace $@
with your files.
#!/usr/bin/env bash
perl -pi -e 's/\r\n/\n/g' -- $@
This will overwrite your files in place!
I recommend only doing this with a backup (version control or otherwise)
You use the error_page property in the nginx config.
For example, if you intend to set the 404 error page to /404.html
, use
error_page 404 /404.html;
Setting the 500 error page to /500.html
is just as easy as:
error_page 500 /500.html;
Whenever you try to load any data in this window this gif will load.
HTML
Make a Div
<div class="loader"></div>
CSS .
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('https://lkp.dispendik.surabaya.go.id/assets/loading.gif') 50% 50% no-repeat rgb(249,249,249);
jQuery
$(window).load(function() {
$(".loader").fadeOut("slow");
});
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
Actually, you should set a config on your Terminal, when your Terminal is up press ?+, then you will see below screen:
Then press shell tab and you will see below screen:
Now select Close if the shell exited cleanly
for When the shell exits.
By the above config each time with exit
command the Terminal will close but won't quit.
One addition to @Omid Ariyan's answer is permissions on directories. Add this after the for
loop's done
in his pre-commit
script.
for DIR in $(find ./ -mindepth 1 -type d -not -path "./.git" -not -path "./.git/*" | sed 's@^\./@@')
do
# Save the permissions of all the files in the index
echo $DIR";"`stat -c "%a;%U;%G" $DIR` >> $DATABASE
done
This will save directory permissions as well.
The logcat shows the error, you should call super.onCreate(savedInstanceState)
:
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//... your code
}
You can get a circular gradient using android:type="radial"
:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:type="radial" android:gradientRadius="250dp"
android:startColor="#E9E9E9" android:endColor="#D4D4D4" />
</shape>
The merge method returns the merged collection, it doesn't mutate the original collection, thus you need to do the following
$original = new Collection(['foo']);
$latest = new Collection(['bar']);
$merged = $original->merge($latest); // Contains foo and bar.
Applying the example to your code
$related = new Collection();
foreach ($question->tags as $tag)
{
$related = $related->merge($tag->questions);
}
If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
It means the object you are trying to access None
. None
is a Null
variable in python.
This type of error is occure de to your code is something like this.
x1 = None
print(x1.something)
#or
x1 = None
x1.someother = "Hellow world"
#or
x1 = None
x1.some_func()
# you can avoid some of these error by adding this kind of check
if(x1 is not None):
... Do something here
else:
print("X1 variable is Null or None")
getch()
can also be used which is defined in conio.h.
The sample program would look like this :
#include <stdio.h>
#include <conio.h>
int main()
{
//your code
getch();
return 0;
}
getch()
waits for any character input from the keyboard (not necessarily enter key).
Use this, FrontData
is JSON string:
var objResponse1 = JsonConvert.DeserializeObject<List<DataTransfer>>(FrontData);
and extract list:
var a = objResponse1[0];
var b = a.CustomerData;
Today I was checking some resources about the same question and I got an example very interesting.
It is possible to call the same method by GET and POST protocol, but you need to overload the parameters like that:
@using (Ajax.BeginForm("Index", "MyController", ajaxOptions, new { @id = "form-consulta" }))
{
//code
}
The action:
[ActionName("Index")]
public async Task<ActionResult> IndexAsync(MyModel model)
{
//code
}
By default a method without explicit protocol is GET, but in that case there is a declared parameter which allows the method works like a POST.
When GET is executed the parameter does not matter, but when POST is executed the parameter is required on your request.
I found that in some cases you should try to delete this key before you install it. So do the following:
sn -d VS_XXXX
sn -i mykey.pfx VS_XXX
Here is how to create the desired outcome:
library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() +
geom_tile(aes(X1, X2, fill = value)) +
scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom",
legend.spacing.x = unit(0, 'cm'))+
guides(fill = guide_legend(label.position = "bottom"))
Created on 2019-12-07 by the reprex package (v0.3.0)
Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.
Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).
library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom", legend.direction="vertical")
p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")
Created on 2019-02-28 by the reprex package (v0.2.1)
The following is a decent solution across Unix/Linux installations, that does not rely on any unusual program features. This supports a multi-line message body, multiple attachments, and all the other typical features of mailx
.
Unfortunately, it does not fit on a single line.
#!/bin/ksh
# Get the date stamp for temporary files
DT_STAMP=`date +'%C%y%m%d%H%M%S'`
# Create a multi-line body
echo "here you put the message body
which can be split across multiple lines!
woohoo!
" > body-${DT_STAMP}.mail
# Add several attachments
uuencode File1.pdf File1.pdf > attachments-${DT_STAMP}.mail
uuencode File2.pdf File2.pdf >> attachments-${DT_STAMP}.mail
# Put everything together and send it off!
cat body-${DT_STAMP}.mail attachments-${DT_STAMP}.mail > out-${DT_STAMP}.mail
mailx -s "here you put the message subject" [email protected] < out-${DT_STAMP}.mail
# Clean up temporary files
rm body-${DT_STAMP}.mail
rm attachments-${DT_STAMP}.mail
rm out-${DT_STAMP}.mail
I too had this problem, its easy to solve:
Go to Control panel - System and maintenance - System - Advanced system settings - Environment variables - System variables - path - click edit - add
"c:\xampp\mysql\bin"
- it should look like this :
\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\QuickTime Alternative\QTSystem;c:\xampp\mysql\bin
And don't forget to start MySQL from control panel of Xampp.
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.
You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.
Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.
In my case, display: block was breaking the design as intended.
The max-width
property just saved me.
and for styling, you can use text-overflow: ellipsis
as well.
my code was
max-width: 255px
overflow:hidden
it is very easy:
add \documentclass[oneside]{book}
and youre fine ;)
For those wanting the box-shadow on the col-*
container itself and not on the .container
, you can add another div
just inside the col-*
element, and add the shadow to that. This element will not have the padding, and therefor not interfere.
The first image has the box-shadow
on the col-*
element. Because of the 15px padding on the col
element, the shadow is pushed to the outside of the div
element rather than on the visual edges of it.
<div class="col-md-4" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
<div class="thumbnail">
{!! HTML::image('images/sampleImage.png') !!}
</div>
</div>
The second image has a wrapper div
with the box-shadow
on it. This will place the box-shadow
on the visual edges of the element.
<div class="col-md-4">
<div id="wrapper-div" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
<div class="thumbnail">
{!! HTML::image('images/sampleImage.png') !!}
</div>
</div>
</div>
Because comparison doesn't work that way. 'Y' || 'y'
is a logical-or operator; it returns 1
(true) if either of its arguments is true. Since 'Y'
and 'y'
are both true, you're comparing *answer
with 1.
What you want is if(*answer == 'Y' || *answer == 'y')
or perhaps:
switch (*answer) {
case 'Y':
case 'y':
/* Code for Y */
break;
default:
/* Code for anything else */
}
I think you need MonoTouch (not free!) for that plugin.
And no, there is no way to run Xcode on Linux.
Sorry for all the bad news. :)
You missed in specifying the intent filter elements in your manifest file.Manifest file is:
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="Your Activity Name"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Add and check this correctly. Hope this will help..
You can do it like this:
var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");
EDIT: New standard has fromHexString rather than fromString
If condition is wrong. Also return type for lower is needed.
#include <stdio.h>
int lower(int a)
{
if ((a >= 65) && (a <= 90))
a = a + 32;
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
putchar(lower('A'));
return 0;
}
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
If you install PHP with homebrew, you can switch between versions very easily. Say you want php56
to point to Version 5.6.17, you just do:
brew switch php56 5.6.17
This is the simple answer I can give.
Section 3.13 of the Unicode standard defines algorithms for caseless matching.
X.casefold() == Y.casefold()
in Python 3 implements the "default caseless matching" (D144).
Casefolding does not preserve the normalization of strings in all instances and therefore the normalization needs to be done ('å'
vs. 'a°'
). D145 introduces "canonical caseless matching":
import unicodedata
def NFD(text):
return unicodedata.normalize('NFD', text)
def canonical_caseless(text):
return NFD(NFD(text).casefold())
NFD()
is called twice for very infrequent edge cases involving U+0345 character.
Example:
>>> 'å'.casefold() == 'a°'.casefold()
False
>>> canonical_caseless('å') == canonical_caseless('a°')
True
There are also compatibility caseless matching (D146) for cases such as '?'
(U+3392) and "identifier caseless matching" to simplify and optimize caseless matching of identifiers.
I had the same problem with SQLite and Android. Here is my Solution:
List<String> tables = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String tableName = cursor.getString(1);
if (!tableName.equals("android_metadata") &&
!tableName.equals("sqlite_sequence"))
tables.add(tableName);
cursor.moveToNext();
}
cursor.close();
for(String tableName:tables) {
db.execSQL("DROP TABLE IF EXISTS " + tableName);
}
First just to answer a comment in the accepts answer.
"What does bind do? What if I have an interface and an implementation?"
It simply reads bind( implementation ).to( contract )
. You can alternative chain .in( scope )
. Default scope of PerLookup
. So if you want a singleton, you can
bind( implementation ).to( contract ).in( Singleton.class );
There's also a RequestScoped
available
Also, instead of bind(Class).to(Class)
, you can also bind(Instance).to(Class)
, which will be automatically be a singleton.
Adding to the accepted answer
For those trying to figure out how to register your AbstractBinder
implementation in your web.xml (i.e. you're not using a ResourceConfig
), it seems the binder won't be discovered through package scanning, i.e.
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
your.packages.to.scan
</param-value>
</init-param>
Or this either
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.YourBinderImpl
</param-value>
</init-param>
To get it to work, I had to implement a Feature
:
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
@Provider
public class Hk2Feature implements Feature {
@Override
public boolean configure(FeatureContext context) {
context.register(new AppBinder());
return true;
}
}
The @Provider
annotation should allow the Feature
to be picked up by the package scanning. Or without package scanning, you can explicitly register the Feature
in the web.xml
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.Hk2Feature
</param-value>
</init-param>
...
<load-on-startup>1</load-on-startup>
</servlet>
See Also:
and for general information from the Jersey documentation
Aside from the basic binding in the accepted answer, you also have factories, where you can have more complex creation logic, and also have access to request context information. For example
public class MyServiceFactory implements Factory<MyService> {
@Context
private HttpHeaders headers;
@Override
public MyService provide() {
return new MyService(headers.getHeaderString("X-Header"));
}
@Override
public void dispose(MyService service) { /* noop */ }
}
register(new AbstractBinder() {
@Override
public void configure() {
bindFactory(MyServiceFactory.class).to(MyService.class)
.in(RequestScoped.class);
}
});
Then you can inject MyService
into your resource class.
This site has two pretty simple solutions - just check the code, I provided the descriptions in case you wanted them - saves you some clicks.
http://www.richardlord.net/blog/dates-in-php-and-mysql
1.One common solution is to store the dates in DATETIME fields and use PHPs date() and strtotime() functions to convert between PHP timestamps and MySQL DATETIMEs. The methods would be used as follows -
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
$phpdate = strtotime( $mysqldate );
2.Our second option is to let MySQL do the work. MySQL has functions we can use to convert the data at the point where we access the database. UNIX_TIMESTAMP will convert from DATETIME to PHP timestamp and FROM_UNIXTIME will convert from PHP timestamp to DATETIME. The methods are used within the SQL query. So we insert and update dates using queries like this -
$query = "UPDATE table SET
datetimefield = FROM_UNIXTIME($phpdate)
WHERE...";
$query = "SELECT UNIX_TIMESTAMP(datetimefield)
FROM table WHERE...";
The accepted answer above is correct. If, however, you only want to reload the cache periodically, and you are using Firefox, the Web Developer tools (under the Tools menu item as of November 2015) provides a Network option. This includes a Reload button. Select the Reload for a once off cache reset.
Replacing FROM tablename
with FROM (SELECT DISTINCT * FROM tablename)
should give you the result you want (ignoring duplicated rows) for example:
SELECT name, COUNT(*)
FROM (SELECT DISTINCT * FROM Table1) AS T1
GROUP BY name
Result for your test data:
dave 2
mark 2
I had the same problem. I'm using DB2. What I have done is a bit not too professional solution, but it works in every DBMS:
ALTER TABLE USERS ADD COLUMN LOGIN_OLD VARCHAR(50) NOT NULL DEFAULT '';
UPDATE USERS SET LOGIN_OLD=LOGIN;
ALTER TABLE USERS DROP COLUMN LOGIN;
ALTER TABLE USERS RENAME COLUMN LOGIN_OLD TO LOGIN;
CALL SYSPROC.ADMIN_CMD('REORG TABLE USERS');
The syntax of the ALTER commands may be different in other DBMS
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
Consider below 2 tables:
EMP
empid name dept_id salary
1 Rob 1 100
2 Mark 1 300
3 John 2 100
4 Mary 2 300
5 Bill 3 700
6 Jose 6 400
Department
deptid name
1 IT
2 Accounts
3 Security
4 HR
5 R&D
Mostly written as just JOIN in sql queries. It returns only the matching records between the tables.
Select a.empid, a.name, b.name as dept_name
FROM emp a
JOIN department b
ON a.dept_id = b.deptid
;
empid name dept_name
1 Rob IT
2 Mark IT
3 John Accounts
4 Mary Accounts
5 Bill Security
As you see above, Jose
is not printed from EMP in the output as it's dept_id 6
does not find a match in the Department table. Similarly, HR
and R&D
rows are not printed from Department table as they didn't find a match in the Emp table.
So, INNER JOIN or just JOIN, returns only matching rows.
This returns all records from the LEFT table and only matching records from the RIGHT table.
Select a.empid, a.name, b.name as dept_name
FROM emp a
LEFT JOIN department b
ON a.dept_id = b.deptid
;
empid name dept_name
1 Rob IT
2 Mark IT
3 John Accounts
4 Mary Accounts
5 Bill Security
6 Jose
So, if you observe the above output, all records from the LEFT table(Emp) are printed with just matching records from RIGHT table.
HR
and R&D
rows are not printed from Department table as they didn't find a match in the Emp table on dept_id.
So, LEFT JOIN returns ALL rows from Left table and only matching rows from RIGHT table.
Can also check DEMO here.
I think this is caused by force-quitting your app on the iPhone prior to pressing the stop button in Xcode. Sometimes when you press the stop button in Xcode, then it takes extra time to quit the app if it hung. But just be patient, it will eventually quit most of the time.
You want a multiple attribute selector
$("input[type='checkbox'][name='ProductCode']").each(function(){ ...
or
$("input:checkbox[name='ProductCode']").each(function(){ ...
It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName
method which will be used to select elements and be much faster than selecting by the name
attribute
Here is simple way to do it: var num = Number(str); in this example str is the variable that contains the string. You can tested and see how it works open: Google chrome developer tools, then go to the console and paste the following code. read the comments to understand better how the conversion is done.
// Here Im creating my variable as a string
var str = "258";
// here im printing the string variable: str
console.log ( str );
// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);
// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);
I tired all the answers and in the end i was able to fix it by adding pod library into the Xcode Build scheme , after i was able to run it, tried to remove this from the build scheme and still it worked fine for me. couldn't figure out the exact reason.
macOS:
Shorter way:
var queue = function (args){
typeof variableToCheck !== "undefined"? doSomething(args) : setTimeout(function () {queue(args)}, 2000);
};
You can also pass arguments
try this
ArrayList<Datapoint > searchList = new ArrayList<Datapoint >();
String search = "a";
int searchListLength = searchList.size();
for (int i = 0; i < searchListLength; i++) {
if (searchList.get(i).getName().contains(search)) {
//Do whatever you want here
}
}
project link:
https://github.com/your_username/you_repo_name/settings
you will get a page like this, go to Collaborator and add collaborator
s.erase(std::remove(s.begin(), s.end(), '\n'), s.end());
Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");
. See this.
You can also do:
NSString * query = @"SELECT * FROM foo "
@"WHERE "
@"bar = 42 "
@"AND baz = datetime() "
@"ORDER BY fizbit ASC";
If your application only works in portrait orientation, this is enough:
[[[UIApplication sharedApplication] keyWindow] addSubview:yourView]
And your view will not be shown over keyboard and status bar.
If you want to get a topmost view that over keyboard or status bar, or you want the topmost view can rotate correctly with devices, please try this framework:
https://github.com/HarrisonXi/TopmostView
It supports iOS7/8/9.
Am I the only one who finds unwinding lists boring? ;-)
Let's try with objects. Real world example by the way.
Given: Object representing repetitive task. About important task fields: reminders are starting to ring at start
and repeat every repeatPeriod
repeatUnit
(e.g. 5 HOURS) and there will be repeatCount
reminders in total(including starting one).
Goal: achieve a list of task copies, one for each task reminder invocation.
List<Task> tasks =
Arrays.asList(
new Task(
false,//completed sign
"My important task",//task name (text)
LocalDateTime.now().plus(2, ChronoUnit.DAYS),//first reminder(start)
true,//is task repetitive?
1,//reminder interval
ChronoUnit.DAYS,//interval unit
5//total number of reminders
)
);
tasks.stream().flatMap(
x -> LongStream.iterate(
x.getStart().toEpochSecond(ZoneOffset.UTC),
p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds())
).limit(x.getRepeatCount()).boxed()
.map( y -> new Task(x,LocalDateTime.ofEpochSecond(y,0,ZoneOffset.UTC)))
).forEach(System.out::println);
Output:
Task{completed=false, text='My important task', start=2014-10-01T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-02T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-03T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-04T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-05T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
P.S.: I would appreciate if someone suggested a simpler solution, I'm not a pro after all.
UPDATE:
@RBz asked for detailed explanation so here it is.
Basically flatMap puts all elements from streams inside another stream into output stream. A lot of streams here :). So, for each Task in initial stream lambda expression x -> LongStream.iterate...
creates a stream of long values that represent task start moments. This stream is limited to x.getRepeatCount()
instances. It's values start from x.getStart().toEpochSecond(ZoneOffset.UTC)
and each next value is calculated using lambda p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds()
. boxed()
returns the stream with each long value as a Long wrapper instance. Then each Long in that stream is mapped to new Task instance that is not repetitive anymore and contains exact execution time. This sample contains only one Task in input list. But imagine that you have a thousand. You will have then a stream of 1000 streams of Task objects. And what flatMap
does here is putting all Tasks from all streams onto the same output stream. That's all as I understand it. Thank you for your question!
For Oracle 11g:
SELECT COL1
FROM TABLE1
WHERE length(COL1) = (SELECT max(length(COL1)) FROM TABLE1);
I may be way way too late but it could help someone in the future.
This answer is a modification to mangu23
answer
I only added a for loop to avoid repetition and to easily add more fragments without boilerplate code.
We first need a list of the fragments that should be displayed
public class MainActivity extends AppCompatActivity{
//...
List<Fragment> fragmentList = new ArrayList<>();
}
Then we need to fill it with our fragments
@Override
protected void onCreate(Bundle savedInstanceState) {
//...
HomeFragment homeFragment = new HomeFragment();
MessagesFragment messagesFragment = new MessagesFragment();
UserFragment userFragment = new UserFragment();
FavoriteFragment favoriteFragment = new FavoriteFragment();
MapFragment mapFragment = new MapFragment();
fragmentList.add(homeFragment);
fragmentList.add(messagesFragment);
fragmentList.add(userFragment);
fragmentList.add(favoriteFragment);
fragmentList.add(mapFragment);
}
And we need a way to know which fragment were selected from the list, so we need getFragmentIndex
function
private int getFragmentIndex(Fragment fragment) {
int index = -1;
for (int i = 0; i < fragmentList.size(); i++) {
if (fragment.hashCode() == fragmentList.get(i).hashCode()){
return i;
}
}
return index;
}
And finally, the displayFragment
method will like this:
private void displayFragment(Fragment fragment) {
int index = getFragmentIndex(fragment);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (fragment.isAdded()) { // if the fragment is already in container
transaction.show(fragment);
} else { // fragment needs to be added to frame container
transaction.add(R.id.placeholder, fragment);
}
// hiding the other fragments
for (int i = 0; i < fragmentList.size(); i++) {
if (fragmentList.get(i).isAdded() && i != index) {
transaction.hide(fragmentList.get(i));
}
}
transaction.commit();
}
In this way, we can call displayFragment(homeFragment)
for example.
This will automatically show the HomeFragment
and hide any other fragment in the list.
This solution allows you to append more fragments to the fragmentList
without having to repeat the if
statements in the old displayFragment
version.
I hope someone will find this useful.
For UTF-8 textual information, you should use utf8_general_ci
because...
utf8_bin
: compare strings by the
binary value of each character in
the string
utf8_general_ci
: compare strings
using general language rules and
using case-insensitive comparisons
a.k.a. it will should making searching and indexing the data faster/more efficient/more useful.
I installed pysocks and monkey patched create_connection in urllib3, like this:
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "127.0.0.1", 1080)
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, socket_options=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
if host.startswith('['):
host = host.strip('[]')
err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socks.socksocket(af, socktype, proto)
# If provided, set socket level options before connecting.
# This is the only addition urllib3 makes to this function.
urllib3.util.connection._set_socket_options(sock, socket_options)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except socket.error as e:
err = e
if sock is not None:
sock.close()
sock = None
if err is not None:
raise err
raise socket.error("getaddrinfo returns an empty list")
# monkeypatch
urllib3.util.connection.create_connection = create_connection
This solution reads in an input file line by line, writing each line out to a StringBuilder variable. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. Then it deletes file content and put the StringBuilder variable content.
public void removeLineFromFile(String lineToRemove, File f) throws FileNotFoundException, IOException{
//Reading File Content and storing it to a StringBuilder variable ( skips lineToRemove)
StringBuilder sb = new StringBuilder();
try (Scanner sc = new Scanner(f)) {
String currentLine;
while(sc.hasNext()){
currentLine = sc.nextLine();
if(currentLine.equals(lineToRemove)){
continue; //skips lineToRemove
}
sb.append(currentLine).append("\n");
}
}
//Delete File Content
PrintWriter pw = new PrintWriter(f);
pw.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(f, true));
writer.append(sb.toString());
writer.close();
}
Using java 8 LocalDateTime
and java 7 try-with statement:
public class WriteFile {
public static void main(String[] args) {
String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
File logFile = new File(timeLog);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile)))
{
System.out.println("File was written to: " + logFile.getCanonicalPath());
bw.write("Hello world!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
If you give a Scanner object a String, it will read it in as data. That is, "a.txt" does not open up a file called "a.txt". It literally reads in the characters 'a', '.', 't' and so forth.
This is according to Core Java Volume I, section 3.7.3.
If I find a solution to reading the actual paths, I will return and update this answer. The solution this text offers is to use
Scanner in = new Scanner(Paths.get("myfile.txt"));
But I can't get this to work because Path isn't recognized as a variable by the compiler. Perhaps I'm missing an import statement.
Note that the %
syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:
instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)
This also fixes the error that you happened to have.
You can do this using Escape Sequence.
\"
So you will have to write something like this :
String name = "\"john\"";
You can learn about Escape Sequences from here.
Or Joiner from Google Guava.
Joiner joiner = Joiner.on("+");
String join = joiner.join(joinList);
For me, this issue was slightly different than other answers, as I was only receiving 404s on OPTIONS, yet I already had OPTIONS specifically stated in my Integrated Extensionless URL Handler options. Very confusing.
By adding the following security node to the web.config was necessary to knock that out - full system.webserver included for context:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<remove name="WebDAV" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<security>
<requestFiltering>
<verbs>
<remove verb="OPTIONS" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
Although it's not the perfect answer for this question, it is the first result for "IIS OPTIONS 404" on Google, so I hope this helps someone out; cost me an hour today.
Animations are not supported on table rows.
From "Learning jQuery" by Chaffer and Swedberg
Table rows present particular obstacles to animation, since browsers use different values (table-row and block) for their visible display property. The .hide() and .show() methods, without animation, are always safe to use with table rows. As of jQuery version 1.1.3, .fadeIn() and .fadeOut() can be used as well.
You can wrap your td contents in a div and use the slideDown on that. You need to decide if the animation is worth the extra markup.
It works using ajax. The jsp then display in iframe returned by controller in response to request.
function openPage() {
jQuery.ajax({
type : 'POST',
data : jQuery(this).serialize(),
url : '<%=request.getContextPath()%>/post_action',
success : function(data, textStatus) {
jQuery('#iframeId').contents().find('body').append(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
I didn't see this method shown, so if someone else is looking to do this I found that ggplot documentation suggested a technique for using the gam
method that produced similar results to loess
when working with small data sets.
library(ggplot2)
x <- 1:10
y <- c(2,4,6,8,7,8,14,16,18,20)
df <- data.frame(x,y)
r <- ggplot(df, aes(x = x, y = y)) + geom_smooth(method = "gam", formula = y ~ s(x, bs = "cs"))+geom_point()
r
First with the loess method and auto formula Second with the gam method with suggested formula
I have encountered this problem twice. First time I used VS 2013 and the second time I used VS 2015 with different solution. The first solution on VS 2013 and python 2.7 is:
SET VS90COMNTOOLS=%VS120COMNTOOLS%
Now, one year later, I have found an easier method to fix it. This time I use VS 2015 and python 3.4.
VS100COMNTOOLS
to the variable nameVS140COMNTOOLS
to the new variable.Now I'm sure you will ask some question what is the VSXXXCOMNTOOLS
and what should I do if I use VS2008 or other compiler.
There is a file python\Lib\distutils\msvc9compiler.py, beginning on line 216 we see
def find_vcvarsall(version):
"""Find the vcvarsall.bat file
At first it tries to find the productdir of VS 2010 in the registry. If
that fails it falls back to the VS100COMNTOOLS env var.
"""
It means that you must give the productdir of VS 2010 for it, so if you are using python 2.x and
Visual Studio 2010 (VS10):SET VS90COMNTOOLS=%VS100COMNTOOLS%
Visual Studio 2012 (VS11):SET VS90COMNTOOLS=%VS110COMNTOOLS%
Visual Studio 2013 (VS12):SET VS90COMNTOOLS=%VS120COMNTOOLS%
Visual Studio 2015 (VS15):SET VS90COMNTOOLS=%VS140COMNTOOLS%
or if you are using python 3.x and
Visual Studio 2010 (VS10):SET VS100COMNTOOLS=%VS100COMNTOOLS%
Visual Studio 2012 (VS11):SET VS100COMNTOOLS=%VS110COMNTOOLS%
Visual Studio 2013 (VS12):SET VS100COMNTOOLS=%VS120COMNTOOLS%
Visual Studio 2015 (VS15):SET VS100COMNTOOLS=%VS140COMNTOOLS%
And it's the same as adding a new system variable. See the second ways.
Update:Sometimes,it still doesn't work.Check your path,ensure that contains VSxxxCOMNTOOLS
CustomRequest is a way to solve the Volley's JSONObjectRequest can't post parameters like the StringRequest
here is the helper class which allow to add params:
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
thanks to Greenchiu
I don't think there's a jQuery-way to directly access the pseudoclass' rules, but you could always append a new style
element to the document's head like:
$('head').append('<style>.column:before{width:800px !important;}</style>');
See a live demo here
I also remember having seen a plugin that tackles this issue once but I couldn't find it on first googling unfortunately.
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
For Angular9+, according to this, you can use:
.mat-select-panel {
background: red;
....
}
mat-select-content
as class name for the select list content. For its styling I would suggest four options.
1. Use ::ng-deep:
Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
CSS:
::ng-deep .mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
2. Use ViewEncapsulation
... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.
None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:
Typscript:
import {ViewEncapsulation } from '@angular/core';
....
@Component({
....
encapsulation: ViewEncapsulation.None
})
CSS
.mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
3. Set class style in style.css
This time you have to 'force' styles with !important
too.
style.css
.mat-select-content{
width:2000px !important;
background-color: red !important;
font-size: 10px !important;
}
4. Use inline style
<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>
My solution:
#ifdef WIN32
#include <Windows.h>
#include <tchar.h>
#else
#include <unistd.h>
#endif
void GetMachineName(char machineName[150])
{
char Name[150];
int i=0;
#ifdef WIN32
TCHAR infoBuf[150];
DWORD bufCharCount = 150;
memset(Name, 0, 150);
if( GetComputerName( infoBuf, &bufCharCount ) )
{
for(i=0; i<150; i++)
{
Name[i] = infoBuf[i];
}
}
else
{
strcpy(Name, "Unknown_Host_Name");
}
#else
memset(Name, 0, 150);
gethostname(Name, 150);
#endif
strncpy(machineName,Name, 150);
}
Maybe this trick gives u an idea
Boolean var= new anonymousClass(){
private String myVar; //String for example
@Overriden public Boolean method(int i){
//use myVar and i
}
public String setVar(String var){myVar=var; return this;} //Returns self instane
}.setVar("Hello").method(3);
Another possibility only present in comments yet:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(c -> c.getName(), c -> c)));
Useful if you want to use a parameter of a sub-object as Key:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(c -> c.getUser().getName(), c -> c)));
As you are probably programming in Visual studio you'd better take advantage of the possibility of using breakpoints for such easy debugging steps (getting an idea what the problem is as in your case). Just place them just in front / at the place where you check ModelState.isValid and hover over the ModelState. Now you can easily browse through all the values inside and see what error causes the isvalid return false.
If you just happen to have a Map
with Integer
keys you cannot change, you could write a custom EL function to convert a Long
to Integer
. This would allow you to do something like:
<c:out value="${map[myLib:longToInteger(1)]}"/>
Collation defines how you sort and compare string values
For example, it defines how to deal with
äàa
etc)Aa
)cote < côte < coté < côté.
cote < coté < côte < côté
You need to open the Service.cs file in the designer, right click it and choose the menu-option "Add Installer".
It won't install right out of the box... you need to create the installer class first.
Some reference on service installer:
How to: Add Installers to Your Service Application
Quite old... but this is what I am talking about:
Windows Services in C#: Adding the Installer (part 3)
By doing this, a ProjectInstaller.cs
will be automaticaly created. Then you can double click this, enter the designer, and configure the components:
serviceInstaller1
has the properties of the service itself: Description
, DisplayName
, ServiceName
and StartType
are the most important.
serviceProcessInstaller1
has this important property: Account
that is the account in which the service will run.
For example:
this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;
For me (being on Windows 10) the npmrc file was located in:
%USERPROFILE%\.npmrc
Tested with:
The z-index
property only works on elements with a position
value other than static
(e.g. position: absolute;
, position: relative;
, or position: fixed
).
There is also position: sticky;
that is supported in Firefox, is prefixed in Safari, worked for a time in older versions of Chrome under a custom flag, and is under consideration by Microsoft to add to their Edge browser.
Important
For regular positioning, be sure to include position: relative
on the elements where you also set the z-index
. Otherwise, it won't take effect.
This should work:
p <- ggplot(df, aes(x=rating, fill=cond)) +
geom_density(alpha=.3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")
p <- p + guides(fill=guide_legend(title="New Legend Title"))
(or alternatively)
p + scale_fill_discrete(name = "New Legend Title")
$('li[rel=7]').siblings().andSelf();
// or:
$('li[rel=7]').parent().children();
Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:
var rels = [];
$('ul').each(function() {
var localRels = [];
$(this).find('li').each(function(){
localRels.push( $(this).attr('rel') );
});
rels.push(localRels);
});
One NuGet package can reference another NuGet package. So, please be very careful about inter-package dependencies. I just uninstalled a Google map package and it subsequently uninstalled underlying packages like Newtonsoft, Entity Framework, etc.
So, manually deleting particular package from packages folder would be safer.
#include <termios.h>
#include <stdio.h>
static struct termios old, current;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
current = old; /* make new settings same as old settings */
current.c_lflag &= ~ICANON; /* disable buffered i/o */
if (echo) {
current.c_lflag |= ECHO; /* set echo mode */
} else {
current.c_lflag &= ~ECHO; /* set no echo mode */
}
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}
/* Read 1 character with echo */
char getche(void)
{
return getch_(1);
}
/* Let's test it out */
int main(void) {
char c;
printf("(getche example) please type a letter: ");
c = getche();
printf("\nYou typed: %c\n", c);
printf("(getch example) please type a letter...");
c = getch();
printf("\nYou typed: %c\n", c);
return 0;
}
Output:
(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
Select * from Table name ..i.e(are you save table name in sql(TEST) k.
Select * from TEST then you will execute your project.
Try this...
<a href="/path/to/image" download>
<img src="/path/to/image" />
</a>
You can even add the size of the terms (indexed terms). Have a look at Elastic Search: how to see the indexed data
You can do it like this:
I have a folder named utilities and inside that I have a file named _variables.scss
in that file i declare variables like so:
$black: #000;
$white: #fff;
then I have the style.scss file in which i import all of my other scss files like this:
// Utilities
@import "utilities/variables";
// Base Rules
@import "base/normalize";
@import "base/global";
then, within any of the files I have imported, I should be able to access the variables I have declared.
Just make sure you import the variable file before any of the others you would like to use it in.
Others are suggesting a wrapping div
but you should be able to do this without adding complexity to your html...
check this out:
#message {
box-sizing: border-box;
padding: 8px;
}
The book has a note how to find help on tag sets, e.g.:
nltk.help.upenn_tagset()
Others are probably similar. (Note: Maybe you first have to download tagsets
from the download helper's Models section for this)
First, change your directory:
cd your_project name
Then run:
python manage.py runserver
You could use regex and dict comprehension:
import re
s = "aeiouuaaieeeeeeee"
The regex function findall() returns a list containing all matches
Here x is the key and the lenght of the list returned by the regex is the count of each vowel in this string, note that regex will find any character you introduce into the "aeiou" string.
foo = {x: len(re.findall(f"{x}", s)) for x in "aeiou"}
print(foo)
returns:
{'a': 3, 'e': 9, 'i': 2, 'o': 1, 'u': 2}
Map :
- It processes one row at a time , very similar to map() method of MapReduce.
- You return from the transformation after every row.
MapPartitions
- It processes the complete partition in one go.
- You can return from the function only once after processing the whole partition.
- All intermediate results needs to be held in memory till you process the whole partition.
- Provides you like setup() map() and cleanup() function of MapReduce
Map Vs mapPartitions
http://bytepadding.com/big-data/spark/spark-map-vs-mappartitions/
Spark Map
http://bytepadding.com/big-data/spark/spark-map/
Spark mapPartitions
http://bytepadding.com/big-data/spark/spark-mappartitions/
As you run your spark app on top of HDFS, according to Sandy Ryza
I’ve noticed that the HDFS client has trouble with tons of concurrent threads. A rough guess is that at most five tasks per executor can achieve full write throughput, so it’s good to keep the number of cores per executor below that number.
So I believe that your first configuration is slower than third one is because of bad HDFS I/O throughput
You are probably looking for 'chr()':
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'
Short answer: Start with SQL and add NoSQL only when/if needed. (unless you don't need anything beyond very simple queries)
My personal experience: I haven't used MongoDB for queries but as of April 2015 DynamoDB is still very crippled when it comes to anything beyond the most basic key/value queries. I love it for the basic stuff but if you want query language then look to a real SQL database solution.
In DynamoDB you can query on a hash or on a hash and range key, and you can have multiple secondary global indexes. I'm doing queries on a single table with 4 possible filter parameters and sorting the results, this is supported (barely) through the use of the global secondary indexes with filter expressions. The problem comes in when you try to get the total results matching the filter, you can't just search for the first 10 items matching the filter, but rather it checks 10 items and you may get 0 valid results forcing you to keep re-scanning from the continue key - pain in the neck and consumes too much of your table read quota for a simple scenario.
To be specific about the limit problem with filters in the query, this is from the docs (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#ScanQueryLimit):
In a response, DynamoDB returns all the matching results within the scope of the Limit value. For example, if you issue a Query or a Scan request with a Limit value of 6 and without a filter expression, the operation returns the first six items in the table that match the request parameters. If you also supply a FilterExpression, the operation returns the items within the first six items in the table that match the filter requirements.
My conclusion is that queries involving FilterExpressions are only usable on very rare occasions and are not scalable because each query can easily read most or all of your of your table which consumes far too many DynamoDB read units. Once you use too many read units you'll get throttled and see poor performance.
Expert opinion: In the AWS summit on Apr 9, 2015 Brett Hollman, Manager, Solutions Architecture, AWS in his talk on scalling to your first 10 million users advocates starting with a SQL database and then using NoSQL only when and if it makes sense. Because sooner or later you'll probably need a SQL server somewhere in your stack. His slides are here: http://www.slideshare.net/AmazonWebServices/deep-dive-scaling-up-to-your-first-10-million-users See slide 28.
Javascript is a fine development environment so it seems odd than it doesn't provide a solution to this small problem. The solutions offered elsewhere on this page are potentially slow. Here is my solution. It employs the inbuilt functionality that decodes base64 image and sound data urls.
var req = new XMLHttpRequest;
req.open('GET', "data:application/octet;base64," + base64Data);
req.responseType = 'arraybuffer';
req.onload = function fileLoaded(e)
{
var byteArray = new Uint8Array(e.target.response);
// var shortArray = new Int16Array(e.target.response);
// var unsignedShortArray = new Int16Array(e.target.response);
// etc.
}
req.send();
The send request fails if the base 64 string is badly formed.
The mime type (application/octet) is probably unnecessary.
Tested in chrome. Should work in other browsers.
This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.
EDIT - And yes it is C syntax, used mostly for art or live media presentations.
I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.
A similar solution might work for you.
We can also use it for the guideline of the constraint layout.
Create integer.xml file and add into
<item name="guideline_button_top" type="integer" format="float">0.60</item>
Use from a layout.xml file
app:layout_constraintGuide_percent="@integer/guideline_button_top"
You might need to do some checking. You cannot safely convert factors directly to numeric. as.character
must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor
then coerce to numeric as necessary.
df1[] <- lapply(df1, function(x) {
if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
# a b
# "numeric" "numeric"
A facade exposes simplified functions that are mostly called and the implementation conceals the complexity that clients would otherwise have to deal with. In general the implementation uses multiple packages, classes and function there in. Well written facades make direct access of other classes rare. For example when I visit an ATM and withdraw some amount. The ATM hides whether it is going straight to the owned bank or is it going over a negotiated network for an external bank. The ATM acts like a facade consuming multiple devices and sub-systems that as a client I do not have to directly deal with.
For Bootstrap 3 the default radio/button-group structure is :
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="radio" name="options" id="option1"> Option 1
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2"> Option 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3"> Option 3
</label>
</div>
And you can select the active one like this:
$('.btn-primary').on('click', function(){
alert($(this).find('input').attr('id'));
});
I use this.
var iframe = parent.document.getElementById("theiframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var currentFrame = innerDoc.location.href;
Partially. The text is inserted, but the warning is still generated.
I found a discussion that indicated the text needed to be preceded with 'E', as such:
insert into EscapeTest (text) values (E'This is the first part \n And this is the second');
This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.
As such:
insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.
I think I use the simplest method to get the full profile picture. You can get full profile picture or you can set the profile picture dimension yourself:
$facebook->api(me?fields=picture.width(800).height(800))
You can set width
and height
as per your need. Though Facebook doesn't return the exact size asked for, It returns the closest dimension picture available with them.
This will solve the problem,
var blogPosts = (from p in dc.BlogPosts
where p.BlogPostID == ID
select p);
if(blogPosts.Any())
{
var post = post.Single();
}
Here's a bit more complicated example with piping and variable assignment inside recipe:
getpodname:
# Getting pod name
@eval $$(minikube docker-env) ;\
$(eval PODNAME=$(shell sh -c "kubectl get pods | grep profile-posts-api | grep Running" | awk '{print $$1}'))
echo $(PODNAME)
Just use window.open()
:
window.open('Prosjektplan.pdf')
Anyway, what guys are saying on comments is true. You better use <a target="_blank">
instead of click events.
If you don't want to use API 21 you can use the older version of appcompact library, use older app compact library without updating it.
you can achieve this by simply following steps:
1) Extract the downloaded version of complete sdk and eclipse bundle.
2) Simply import appCompact library from sdk\extras\android\support\v7\appcompact
now you are done.
In my case, the problem was that the Archive was being built with a different TEAM-ID than the one who generated the Provisioning Profile (Me). Therefore I Got the error:
"No matching provisioning profile found: Your build settings specify a provisioning profile with the UUID, however, no such provisioning profile was found."
To Solve this:
in the GENERAL Tab of the Project properties, got to TEAM:
Change the current team to the Same team but the one under the ACCOUNT you generated the provisioning profile with.
Clean & Build
Viola!
Hope this helps someone.
we can find upper case letter by using regular expression as well
private static void findUppercaseFirstLetterInString(String content) {
Matcher m = Pattern
.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(
content);
System.out.println("Given input string : " + content);
while (m.find()) {
if (m.group(1).equals(m.group(1).toUpperCase())) {
System.out.println("First Letter Upper case match found :"
+ m.group());
}
}
}
for detailed example . please visit http://www.onlinecodegeek.com/2015/09/how-to-determines-if-string-starts-with.html
I am about 8 years late, well...anyways, I don't really know what then() does but maybe MDN might have an answer. Actually, I might actually understand it a little more.
This will show you all the information (hopefully), you need. Unless someone already posted this link. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
The format is promise.prototype.then() The promise and prototype are kind of like variables but not like variables in javascript, I mean like other things go there like navigator.getBattery().then() where this one actually exists but is barely used on the web, this one shows statuses about the battery of the device, more information and more on MDN if you are curious.
You can use this to delete ALL Files Inside a Folder and Subfolders:
DEL "C:\Folder\*.*" /S /Q
Or use this to Delete Certain File Types Only:
DEL "C:\Folder\*.mp4" /S /Q
DEL "C:\Folder\*.dat" /S /Q
Attaching / Detaching
Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let's imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach method:
$user = App\User::find(1);
$user->roles()->attach($roleId);
When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:
$user->roles()->attach($roleId, ['expires' => $expires]);
You can also use Sync if you want to remove old roles and only keep the new ones you are attaching now
$user->roles()->sync([1 => ['expires' => $expires], 2 => ['expires' => $expires]);
The default behaviour can be changed by passing a 'false' as a second argument. This will attach the roles with ids 1,2,3 without affecting the existing roles.
In this mode sync behaves similar to the attach method.
$user->roles()->sync([1 => ['expires' => $expires], 2 => ['expires' => $expires], false);
Reference: https://laravel.com/docs/5.4/eloquent-relationships
I think there is no way to find out whether a dynamic
variable has a certain member without trying to access it, unless you re-implemented the way dynamic binding is handled in the C# compiler. Which would probably include a lot of guessing, because it is implementation-defined, according to the C# specification.
So you should actually try to access the member and catch an exception, if it fails:
dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();
try
{
var x = myVariable.MyProperty;
// do stuff with x
}
catch (RuntimeBinderException)
{
// MyProperty doesn't exist
}
How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...
Since Trung Le Nguyen Nhat's fiddle isn't correct at all
(it just uses the original image in the last step)
I wrote my own general fiddle with performance comparison:
Basically it's:
img.onload = function() {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d"),
oc = document.createElement('canvas'),
octx = oc.getContext('2d');
canvas.width = width; // destination canvas size
canvas.height = canvas.width * img.height / img.width;
var cur = {
width: Math.floor(img.width * 0.5),
height: Math.floor(img.height * 0.5)
}
oc.width = cur.width;
oc.height = cur.height;
octx.drawImage(img, 0, 0, cur.width, cur.height);
while (cur.width * 0.5 > width) {
cur = {
width: Math.floor(cur.width * 0.5),
height: Math.floor(cur.height * 0.5)
};
octx.drawImage(oc, 0, 0, cur.width * 2, cur.height * 2, 0, 0, cur.width, cur.height);
}
ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height);
}
To use video extensions that are MKV. You should use video, not source
For example :
<!-- mkv -->
<video width="320" height="240" controls src="assets/animation.mkv"></video>
<!-- mp4 -->
<video width="320" height="240" controls>
<source src="assets/animation.mp4" type="video/mp4" />
</video>
_x000D_
You could add a diffrent class onto the BODY tag on each page e.g. on the homepage you could have this:
<body class="nav-1-on">
Then this css:
.nav-1-on .nav-1 a, .nav-2-on .nav-2 a, .nav-3-on .nav-3 a, .nav-4-on .nav-4 a {
// set your styles here
}
The NAV element:
<ul>
<li class="nav-1"><a href="#">Home</a></li>
<li class="nav-2"><a href="#">Services</a></li>
<li class="nav-3"><a href="#">About</a></li>
<li class="nav-4"><a href="#">Contact</a></li>
</ul>
#
Alternatively you could place a class on the BODY on each page and then grab that via jQuery and add the .active class to the correct nav item based on that tag.
Following works perfectly for me: -*click on COMMAND and click on APPLY SOURCE FORMATTING - *And click on Clean Up HTML
Thank you PEKA
Or you can do this without using Delay.
set /a "counter=0"
-> your for loop here
do (
statement1
statement2
call :increaseby1
)
:increaseby1
set /a "counter+=1"
sdkmanager
(for advanced users / CI):You can find the download links for all individual packages, including various revisions, in the repository XML file: https://dl.google.com/android/repository/repository-12.xml
(where 12 is the version of the repository index and will increase in the future).
All <sdk:url>
values are relative to https://dl.google.com/android/repository
, so
<sdk:url>platform-27_r03.zip</sdk:url>
can be downloaded at https://dl.google.com/android/repository/platform-27_r03.zip
Similar summary XML files exist for system images as well:
right click on your project and choose properties. click on Deployement Assembly. click add click on "Java Build Path Entries" select Maven Dependencies" click Finish.
<div *ngFor="let thing of show ? stuff : []">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
After some investigation I wrote this:
import Foundation
struct Math {
private static var seeded = false
static func randomFractional() -> CGFloat {
if !Math.seeded {
let time = Int(NSDate().timeIntervalSinceReferenceDate)
srand48(time)
Math.seeded = true
}
return CGFloat(drand48())
}
}
Now you can just do Math.randomFraction()
to get random numbers [0..1[ without having to remember seeding first. Hope this helps someone :o)
If your values are non-null strings or numbers, you can use an object as a dictionary:
var map = {}, result = [], i;
for (i = 0; i < array1.length; ++i) {
map[array1[i]] = 1;
}
for (i = 0; i < array2.length; ++i) {
if (map[array2[i]] === 1) {
result.push(array2[i]);
// avoid returning a value twice if it appears twice in array 2
map[array2[i]] = 0;
}
}
return result;
#register a:link
{
color:#fffff;
}
There is a much easier solution here than adding empty event listeners.
Just set pointer-events: none
to your image. If you still need it to be clickable, add a container around it which triggers the event.
An approximated solution (based on an equirectangular projection), much faster (it requires only 1 trig and 1 square root).
This approximation is relevant if your points are not too far apart. It will always over-estimate compared to the real haversine distance. For example it will add no more than 0.05382 % to the real distance if the delta latitude or longitude between your two points does not exceed 4 decimal degrees.
The standard formula (Haversine) is the exact one (that is, it works for any couple of longitude/latitude on earth) but is much slower as it needs 7 trigonometric and 2 square roots. If your couple of points are not too far apart, and absolute precision is not paramount, you can use this approximate version (Equirectangular), which is much faster as it uses only one trigonometric and one square root.
// Approximate Equirectangular -- works if (lat1,lon1) ~ (lat2,lon2)
int R = 6371; // km
double x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
double y = (lat2 - lat1);
double distance = Math.sqrt(x * x + y * y) * R;
You can optimize this further by either:
For more info see: http://www.movable-type.co.uk/scripts/latlong.html
There is a nice reference implementation of the Haversine formula in several languages at: http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe
You will need to cast or convert the values to decimal before division. Take a look at this http://msdn.microsoft.com/en-us/library/aa226054.aspx
For example
DECLARE @num1 int = 3 DECLARE @num2 int = 2
SELECT @num1/@num2
SELECT @num1/CONVERT(decimal(4,2), @num2)
The first SELECT will result in what you're seeing while the second SELECT will have the correct answer 1.500000
You can do this with a string datatype. Use the PadLeft
method:
var myString = "1";
myString = myString.PadLeft(myString.Length + 5, '0');
000001
If you don't like split()
and you don't mind NAs padding out your short tail:
chunk <- function(x, n) { if((length(x)%%n)==0) {return(matrix(x, nrow=n))} else {return(matrix(append(x, rep(NA, n-(length(x)%%n))), nrow=n))} }
The columns of the returned matrix ([,1:ncol]) are the droids you are looking for.
The following VBA code should get you started. It will copy all of the data in the original workbook to a new workbook, but it will have added 1 to each value, and all blank cells will have been ignored.
Option Explicit
Public Sub exportDataToNewBook()
Dim rowIndex As Integer
Dim colIndex As Integer
Dim dataRange As Range
Dim thisBook As Workbook
Dim newBook As Workbook
Dim newRow As Integer
Dim temp
'// set your data range here
Set dataRange = Sheet1.Range("A1:B100")
'// create a new workbook
Set newBook = Excel.Workbooks.Add
'// loop through the data in book1, one column at a time
For colIndex = 1 To dataRange.Columns.Count
newRow = 0
For rowIndex = 1 To dataRange.Rows.Count
With dataRange.Cells(rowIndex, colIndex)
'// ignore empty cells
If .value <> "" Then
newRow = newRow + 1
temp = doSomethingWith(.value)
newBook.ActiveSheet.Cells(newRow, colIndex).value = temp
End If
End With
Next rowIndex
Next colIndex
End Sub
Private Function doSomethingWith(aValue)
'// This is where you would compute a different value
'// for use in the new workbook
'// In this example, I simply add one to it.
aValue = aValue + 1
doSomethingWith = aValue
End Function
I see that this problem was discussed some time ago, but if anyone 'll meet with this again, here is my solution:
In your *.cshtml View file:
<script>
var data = JsFunction("@Html.Raw(Model.Path)");
$(function () {
$("#btn").click(function () {
var model = { Id: '@Html.Raw(Model.Id)', Data: data }
$.ajax({
type: "POST",
url: "/Controller/Action",
data: model,
datatype: "html",
success: function() {
console.log('Success');
}
});
});
});
</script>
JavaScript variable model is something that I need to pass to Razor ViewModel. It can be done with ajax request. You just need to have proper argument/s in your action, that matches Json object created in JavaScript.
Hope it'll help someone!
Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...
Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);
You can also use TextAttribute.
Map<TextAttribute, Object> attributes = new HashMap<>();
attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);
g.setFont(myFont);
The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.
One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.
Simple answer - 5 is Italian "yy" and 105 is Italian "yyyy". Therefore:
SELECT convert(datetime,'21-02-12 6:10:00 PM',5)
will work correctly, but
SELECT convert(datetime,'21-02-12 6:10:00 PM',105)
will give error.
Likewise,
SELECT convert(datetime,'21-02-2012 6:10:00 PM',5)
will give error, where as
SELECT convert(datetime,'21-02-2012 6:10:00 PM',105)
will work.
^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$
Matches the following cases:
123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890
Change appBase
in server.xml
If you want to keep both previous webapps and a new one, you can use another Host instance with another port defined in tomcat.
Try this jsfiddle. This is using jQuery and made from Hashem Qolami's answer. At first, make a regular table then make it scrollable.
const makeScrollableTable = function (tableSelector, tbodyHeight) {
let $table = $(tableSelector);
let $bodyCells = $table.find('tbody tr:first').children();
let $headCells = $table.find('thead tr:first').children();
let headColWidth = 0;
let bodyColWidth = 0;
headColWidth = $headCells.map(function () {
return $(this).outerWidth();
}).get();
bodyColWidth = $bodyCells.map(function () {
return $(this).outerWidth();
}).get();
$table.find('thead tr').children().each(function (i, v) {
$(v).css("width", headColWidth[i]+"px");
$(v).css("min-width", headColWidth[i]+"px");
$(v).css("max-width", headColWidth[i]+"px");
});
$table.find('tbody tr').children().each(function (i, v) {
$(v).css("width", bodyColWidth[i]+"px");
$(v).css("min-width", bodyColWidth[i]+"px");
$(v).css("max-width", bodyColWidth[i]+"px");
});
$table.find('thead').css("display", "block");
$table.find('tbody').css("display", "block");
$table.find('tbody').css("height", tbodyHeight+"px");
$table.find('tbody').css("overflow-y", "auto");
$table.find('tbody').css("overflow-x", "hidden");
};
Then you can use this function as follows:
makeScrollableTable('#test-table', 250);
In Java 8:
Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));
Reverse order:
Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));
label.text = [NSString stringWithFormat:@"%d", XYZ];
//result: label.text = XYZ
//use %d for int values
Adding to Andrew's answer, you can even introduce a maxResults
property and use it this way:
$("#auto").autocomplete({
maxResults: 10,
source: function(request, response) {
var results = $.ui.autocomplete.filter(src, request.term);
response(results.slice(0, this.options.maxResults));
}
});
jsFiddle: http://jsfiddle.net/vqwBP/877/
This should help code readability and maintainability!
To copy remote-to-remote files you can use the synchronize module with 'delegate_to: source-server
' keyword:
- hosts: serverB
tasks:
- name: Copy Remote-To-Remote (from serverA to serverB)
synchronize: src=/copy/from_serverA dest=/copy/to_serverB
delegate_to: serverA
This playbook can run from your machineC.
You should define a key name while storing data to local storage which should be a string and value should be a string
localStorage.setItem('dataSource', this.dataSource.length);
and to print, you should use getItem
console.log(localStorage.getItem('dataSource'));
This commonly happened use case for any developer.
It is better to have it as function in your local system. (So better to keep this script in one of the shell profile like ksh/zsh or bash profile based on the user preference)
function killport {
kill -9 `lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'`
}
Usage:
killport port_number
Example:
killport 8080
I know its long after this question was asked and answered - and I am sure that the accepted solution is right, but the purist in me would rather not add an extra element to the SVG when I can achieve the same or similar with straight CSS.
Whilst it is true that you cannot style the g
container element in most ways - you can definitely add an outline to it and style that - even changing it on hover of the g
- as shown in the snippet.
It not as good in one regard as the other way - you can put the outline box around the grouped elements - but not a background behind it. Sot its not perfect and won't solve the issue for everyone - but I would rather have the outline done with css than have to add extra elements to the code just to provide styling hooks.
And this method definitely allows you to show grouping of related objects in your SVG's.
Just a thought.
g {_x000D_
outline: solid 3px blue;_x000D_
outline-offset: 5px;_x000D_
}_x000D_
_x000D_
g:hover {_x000D_
outline-color: red_x000D_
}
_x000D_
<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">_x000D_
<g>_x000D_
<rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/>_x000D_
<ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/> _x000D_
</g>_x000D_
</svg>
_x000D_
<script type="text/javascript">
$(document).ready(function(){
$('.appBanner').fadeOut('slow');
});
</script>
or
<script type="text/javascript">
$(document).ready(function(){
$('.appBanner').hide();
});
</script>
public List<DealInfo> getDealInfos(List<String> dealIds) {
String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
query.setParameter("inclList", dealIds);
return query.getResultList();
}
Works for me with JPA 2, Jboss 7.0.2
replace()
returns an new string, and the original string is not modified. You need to do
str = str.replace(/-/g, ' ');
Here what i found. C:\Users\User\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\TempState
There is snapshot of your sticky note in .png format. Open it and create your new note.
I have successfully used ampq-purge
from amqp-utils to do this:
git clone https://github.com/dougbarth/amqp-utils.git
cd amqp-utils
# extracted from Rakefile
echo "source 'https://rubygems.org'
gem 'amqp', '~> 0.7.1'
gem 'trollop', '~> 1.16.2'
gem 'facets', '~> 2.9'
gem 'clio', '~> 0.3.0'
gem 'json', '~> 1.5'
gem 'heredoc_unindent', '~> 1.1.2'
gem 'msgpack', '~> 0.4.5'" > Gemfile
bundle install --path=$PWD/gems
export RUBYLIB=.
export GEM_HOME=$PWD/gems/ruby/1.9.1
ruby bin/amqp-purge -v -V /vhost -u user -p queue
# paste password at prompt
From the point of view of porting a C program, a good way to understand this is to take an example:
#include <sys/stat.h>
#include <stdlib.h>
int main(void)
{
struct stat stbuf;
stat("c:foo.txt", &stbuf);
system("command");
printf("Hello, World\n");
return 0;
}
If we change stat
to _stat
, we can compile this program with Microsoft Visual C. We can also compile this program with MinGW, and with Cygwin.
Under Microsoft Visual C, the program will be linked to a MSVC redistributable run-time library: mxvcrtnn.dll
, where nn
is some version suffix. To ship this program we will have to include that DLL. That DLL provides _stat
, system
and printf
. (We also have the option of statically linking the run-time.)
Under MinGW, the program will be linked to msvcrt.dll
, which is an internal, undocumented, unversioned library that is part of Windows, and off-limits to application use. That library is essentially a fork of the redistributable run-time library from MS Visual C for use by Windows itself.
Under both of these, the program will have similar behaviors:
stat
function will return very limited information—no useful permissions or inode number, for instance.c:file.txt
is resolved according to the current working directory associated with drive c:
. system
uses cmd.exe /c
for running the external command.We can also compile the program under Cygwin. Similarly to the redistributable run-time used by MS Visual C, the Cygwin program will be linked to Cygwin's run-time libraries: cygwin1.dll
(Cygwin proper) and cyggcc_s-1.dll
(GCC run-time support). Since Cygwin is now under the LGPL, we can package with our program, even if it isn't GPL-compatible free software, and ship the program.
Under Cygwin, the library functions will behave differently:
stat
function has rich functionality, returning meaningful values in most of the fields.c:file.txt
is not understood at all as containing a drive letter reference, since c:
isn't followed by a slash. The colon is considered part of the name and somehow mangled into it. There is no concept of a relative path against a volume or drive in Cygwin, no "currently logged drive" concept, and no per-drive current working directory.system
function tries to use the /bin/sh -c
interpreter. Cygwin will resolve the /
path according to the location of your executable, and expect a sh.exe
program to be co-located with your executable.Both Cygwin and MinGW allow you to use Win32 functions. If you want to call MessageBox
or CreateProcess
, you can do that. You can also easily build a program which doesn't require a console window, using gcc -mwindows
, under MinGW and Cygwin.
Cygwin is not strictly POSIX. In addition to providing access to the Windows API, it also provides its own implementations of some Microsoft C functions (stuff found in msvcrt.dll
or the re-distributable msvcrtnn.dll
run-times). An example of this are the spawn*
family of functions like spawnvp
. These are a good idea to use instead of fork
and exec
on Cygwin since they map better to the Windows process creation model which has no concept of fork
.
Thus:
Cygwin programs are no less "native" than MS Visual C programs on grounds of requiring the accompaniment of libraries. Programming language implementations on Windows are expected to provide their own run-time, even C language implementations. There is no "libc" on Windows for public use.
The fact that MinGW requires no third-party DLL is actually a disadvantage; it is depending on an undocumented, Windows-internal fork of the Visual C run-time. MinGW does this because the GPL system library exception applies to msvcrt.dll
, which means that GPL-ed programs can be compiled and redistributed with MinGW.
Due to its much broader and deeper support for POSIX compared to msvcrt.dll
, Cygwin is by far the superior environment for porting POSIX programs. Since it is now under the LGPL, it allows applications with all sorts of licenses, open or closed source, to be redistributed. Cygwin even contains VT100 emulation and termios
, which work with the Microsoft console! A POSIX application that sets up raw mode with tcsetattr
and uses VT100 codes to control the cursor will work right in the cmd.exe
window. As far as the end-user is concerned, it's a native console app making Win32 calls to control the console.
However:
/bin/sh
and other issues. These differences are what render Cygwin programs "non-native". If a program takes a path as an argument, or input from a dialog box, Windows users expect that path to work the same way as it does in other Windows programs. If it doesn't work that way, that's a problem.Plug: Shortly after the LGPL announcement, I started the Cygnal (Cygwin Native Application Library) project to provide a fork of the Cygwin DLL which aims to fix these issues. Programs can be developed under Cygwin, and then deployed with the Cygnal version of cygwin1.dll
without recompiling. As this library improves, it will gradually eliminate the need for MinGW.
When Cygnal solves the path handling problem, it will be possible to develop a single executable which works with Windows paths when shipped as a Windows application with Cygnal, and seamlessly works with Cygwin paths when installed in your /usr/bin
under Cygwin. Under Cygwin, the executable will transparently work with a path like /cygdrive/c/Users/bob
. In the native deployment where it is linking against the Cygnal version of cygwin1.dll
, that path will make no sense, whereas it will understand c:foo.txt
.
skill doB
skill
is a version of the kill command that lets you select one or multiple processes based on a given criteria.
Call make this way
make CFLAGS=-Dvar=42
because you do want to override your Makefile's CFLAGS, and not just the environment (which has a lower priority with regard to Makefile variables).
Or if you dont know the url, you can use
hadoop fs -rm -r -f /user/the/path/to/your/dir
function Zip-File
{
param (
[string]$ZipName,
[string]$SourceDirectory
)
Add-Type -Assembly System.IO.Compression.FileSystem
$Compress = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($SourceDirectory,
$ZipName, $Compress, $false)
}
Note:
ZipName: Full Path of the Zip File which you want to create.
SourceDirectory: Full path to the directory containing the files which you would like to zip.
- each side with the same color
:root{
--color: #f0f;
}
div {
display: flex;
flex-flow: row nowrap;
align-items: center;
justify-content: center;
box-sizing: border-box;
margin: 50px auto;
width: 200px;
height: 100px;
background: #ccc;
}
.four-sides-with-same-color {
box-shadow: 0px 0px 10px 5px var(--color);
}
_x000D_
<div class="four-sides-with-same-color"></div>
_x000D_
- each side with a different color
:root{
--color1: #00ff4e;
--color2: #ff004e;
--color3: #b716e6;
--color4: #FF5722;
}
div {
display: flex;
flex-flow: row nowrap;
align-items: center;
justify-content: center;
box-sizing: border-box;
margin: 50px auto;
width: 200px;
height: 100px;
background-color: rgba(255,255,0,0.7);
}
.four-sides-with-different-color {
box-shadow:
10px 0px 5px 0px var(--color1),
0px 10px 5px 0px var(--color2),
-10px 0px 5px 0px var(--color3),
0px -10px 5px 0px var(--color4);
}
_x000D_
<div class="four-sides-with-different-color"></div>
_x000D_
The :empty
pseudo-selector is used to see if an element contains no childs, you should check the value :
$('#apply-form input').blur(function() {
if(!this.value) { // zero-length string
$(this).parents('p').addClass('warning');
}
});