NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy
, you can compute this with the ppf
method of the scipy.stats.norm
object. The acronym ppf
stands for percent point function, which is another name for the quantile function.
In [20]: from scipy.stats import norm
In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722
Check that it is the inverse of the CDF:
In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996
By default, norm.ppf
uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc
and scale
arguments, respectively.
In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945
If you look at the source code for scipy.stats.norm
, you'll find that the ppf
method ultimately calls scipy.special.ndtri
. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:
In [43]: from scipy.special import ndtri
In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722
You are applying shapiro.test()
to a data.frame
instead of the column. Try the following:
shapiro.test(heisenberg$HWWIchg)
Use std::tr1::normal_distribution
.
The std::tr1 namespace is not a part of boost. It's the namespace that contains the library additions from the C++ Technical Report 1 and is available in up to date Microsoft compilers and gcc, independently of boost.
Normality tests don't do what most think they do. Shapiro's test, Anderson Darling, and others are null hypothesis tests AGAINST the the assumption of normality. These should not be used to determine whether to use normal theory statistical procedures. In fact they are of virtually no value to the data analyst. Under what conditions are we interested in rejecting the null hypothesis that the data are normally distributed? I have never come across a situation where a normal test is the right thing to do. When the sample size is small, even big departures from normality are not detected, and when your sample size is large, even the smallest deviation from normality will lead to a rejected null.
For example:
> set.seed(100)
> x <- rbinom(15,5,.6)
> shapiro.test(x)
Shapiro-Wilk normality test
data: x
W = 0.8816, p-value = 0.0502
> x <- rlnorm(20,0,.4)
> shapiro.test(x)
Shapiro-Wilk normality test
data: x
W = 0.9405, p-value = 0.2453
So, in both these cases (binomial and lognormal variates) the p-value is > 0.05 causing a failure to reject the null (that the data are normal). Does this mean we are to conclude that the data are normal? (hint: the answer is no). Failure to reject is not the same thing as accepting. This is hypothesis testing 101.
But what about larger sample sizes? Let's take the case where there the distribution is very nearly normal.
> library(nortest)
> x <- rt(500000,200)
> ad.test(x)
Anderson-Darling normality test
data: x
A = 1.1003, p-value = 0.006975
> qqnorm(x)
Here we are using a t-distribution with 200 degrees of freedom. The qq-plot shows the distribution is closer to normal than any distribution you are likely to see in the real world, but the test rejects normality with a very high degree of confidence.
Does the significant test against normality mean that we should not use normal theory statistics in this case? (another hint: the answer is no :) )
Take a loot at the Wikipedia article on random numbers as it talks about using sampling techniques. You can find the equation for your normal distribution by plugging into this one
(equation via Wikipedia)
As for the second issue, go into Options under the circle Office icon, go to formulas, and change calculations to "Manual". That will maintain your sheet and not recalculate the formulas each time.
The standard Python library module random has what you want:
normalvariate(mu, sigma)
Normal distribution. mu is the mean, and sigma is the standard deviation.
For the algorithm itself, take a look at the function in random.py in the Python library.
For The Bootstrap 4+
This Code Worked Well for me
<div class="row">
<div class="col">
<div class="ml-auto">
this content will be in the Right
</div>
</div>
<div class="col mr-auto">
<div class="mr-auto">
this content will be in the leftt
</div>
</div>
</div>
Try to set response dataType property directly:
dataType: 'text'
and put
die('');
in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.
Yes. 'Z' stands for Zulu time, which is also GMT and UTC.
From http://en.wikipedia.org/wiki/Coordinated_Universal_Time:
The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.
Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.
From wikipedia again, http://en.wikipedia.org/wiki/Nautical_time:
Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.
Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.
When you pass an instance as an argument to the method it passes the copy
of the instance. Now, if the instance you pass is a value type
(resides in the stack
) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack
) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.
You can use FileReader
to read the Blob
as an ArrayBuffer
.
Here's a short example:
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);
Here's a longer example:
// ArrayBuffer -> Blob
var uint8Array = new Uint8Array([1, 2, 3]);
var arrayBuffer = uint8Array.buffer;
var blob = new Blob([arrayBuffer]);
// Blob -> ArrayBuffer
var uint8ArrayNew = null;
var arrayBufferNew = null;
var fileReader = new FileReader();
fileReader.onload = function(event) {
arrayBufferNew = event.target.result;
uint8ArrayNew = new Uint8Array(arrayBufferNew);
// warn if read values are not the same as the original values
// arrayEqual from: http://stackoverflow.com/questions/3115982/how-to-check-javascript-array-equals
function arrayEqual(a, b) { return !(a<b || b<a); };
if (arrayBufferNew.byteLength !== arrayBuffer.byteLength) // should be 3
console.warn("ArrayBuffer byteLength does not match");
if (arrayEqual(uint8ArrayNew, uint8Array) !== true) // should be [1,2,3]
console.warn("Uint8Array does not match");
};
fileReader.readAsArrayBuffer(blob);
fileReader.result; // also accessible this way once the blob has been read
This was tested out in the console of Chrome 27—69, Firefox 20—60, and Safari 6—11.
Here's also a live demonstration which you can play with: https://jsfiddle.net/potatosalad/FbaM6/
Update 2018-06-23: Thanks to Klaus Klein for the tip about event.target.result
versus this.result
Reference:
The safest way to do this is to prompt for the password beforehand and then pipe it into the command. Prompting for the password will avoid having the password saved anywhere in your code and it also won't show up in your bash history. Here's an example:
from getpass import getpass
from subprocess import Popen, PIPE
password = getpass("Please enter your password: ")
# sudo requires the flag '-S' in order to take input from stdin
proc = Popen("sudo -S apach2ctl restart".split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
# Popen only accepts byte-arrays so you must encode the string
proc.communicate(password.encode())
You need some tools like pdf2text to first convert your pdf to a text file and then search inside the text. (You will probably miss some information or symbols).
If you are using a programming language there are probably pdf libraries written for this purpose. e.g. http://search.cpan.org/dist/CAM-PDF/ for Perl
Sorry there's no simple method call that can do it. All you'd need to do though is create a map and count frequency with it.
HashMap<String,int> frequencymap = new HashMap<String,int>();
foreach(String a in animals) {
if(frequencymap.containsKey(a)) {
frequencymap.put(a, frequencymap.get(a)+1);
}
else{ frequencymap.put(a, 1); }
}
This does not work in Python 3.
You can use functools cmp_to_key to have old-style comparison functions work though.
from functools import cmp_to_key
def cmp_items(a, b):
if a.foo > b.foo:
return 1
elif a.foo == b.foo:
return 0
else:
return -1
cmp_items_py3 = cmp_to_key(cmp_items)
alist.sort(cmp_items_py3)
you can round your double and cast ist:
(int)Math.Round(myDouble);
I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.
You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.
Here is my solution:
<div class="form-group row">
<div class="col-xs-8">
<label class="control-label">My Label</label>
<div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
<input class="form-control" type="text" readonly="" value="12-02-2012">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
</div>
CSS changes in datepicker.css on lines 176-177:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 34:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;
UPDATE
Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:
CSS changes in datepicker.css on lines 446-447:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 46:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;
Finally, the JavaScript to enable the datepicker (with some options):
$(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });
Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.
Now (2020) NetBeans 11 does it automatically with the "Build" command (right click on the project's name and choose "Build")
Setting the image using picture.ImageLocation()
works fine, but you are using a relative path. Check your path against the location of the .exe
after it is built.
For example, if your .exe
is located at:
<project folder>/bin/Debug/app.exe
The image would have to be at:
<project folder>/bin/Image/1.jpg
Of course, you could just set the image at design-time (the Image
property on the PictureBox
property sheet).
If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image
. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory
to Copy if newer
.
At this point the image file will be copied when you build the application and you can use
picture.ImageLocation = @"Image\1.jpg";
TypeGuards
interface MyInterfaced {
x: number
}
function isMyInterfaced(arg: any): arg is MyInterfaced {
return arg.x !== undefined;
}
if (isMyInterfaced(obj)) {
(obj as MyInterfaced ).x;
}
Steps:
1)Add the required permissions in the Manifest.xml
file.
<!--For using the phone calls -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!--For reading phone call state-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
2)Create a listener for the phone state changes.
public class EndCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if(TelephonyManager.CALL_STATE_RINGING == state) {
}
if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
//wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
}
if(TelephonyManager.CALL_STATE_IDLE == state) {
//when this state occurs, and your flag is set, restart your app
Intent i = context.getPackageManager().getLaunchIntentForPackage(
context.getPackageName());
//For resuming the application from the previous state
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//Uncomment the following if you want to restart the application instead of bring to front.
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(i);
}
}
}
3)Initialize the listener in your OnCreate
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
but if you want to resume your application last state or to bring it back from the back stack, then replace FLAG_ACTIVITY_CLEAR_TOP
with FLAG_ACTIVITY_SINGLE_TOP
Reference this Answer
On particular table
<table style="border-collapse: separate; border-spacing: 10px;" >_x000D_
<tr>_x000D_
<td>Hi</td>_x000D_
<td>Hello</td>_x000D_
<tr/>_x000D_
<tr>_x000D_
<td>Hola</td>_x000D_
<td>Oi!</td>_x000D_
<tr/>_x000D_
</table>
_x000D_
Bit late to the party but a good solution which is also Linq to SQL compatible is:
List<string> list1 = new List<string>() { "1", "2", "3" };
List<string> list2 = new List<string>() { "2", "4" };
List<string> inList1ButNotList2 = (from o in list1
join p in list2 on o equals p into t
from od in t.DefaultIfEmpty()
where od == null
select o).ToList<string>();
List<string> inList2ButNotList1 = (from o in list2
join p in list1 on o equals p into t
from od in t.DefaultIfEmpty()
where od == null
select o).ToList<string>();
List<string> inBoth = (from o in list1
join p in list2 on o equals p into t
from od in t.DefaultIfEmpty()
where od != null
select od).ToList<string>();
Kudos to http://www.dotnet-tricks.com/Tutorial/linq/UXPF181012-SQL-Joins-with-C
I had this problem because I was trying to set up a multiplatform library configurations.
I had deleted all the source sets with their dependencies from the "build.gradle" file but kept the "common" source set.
Native was working fine but the JVM was not able to build and showed your error.
In the end, the solution was to not delete the Source set of the JVM neither it's dependencies
Yes, something like this:
SELECT
id,
action_heading,
CASE
WHEN action_type = 'Income' THEN action_amount
ELSE NULL
END AS income_amt,
CASE
WHEN action_type = 'Expense' THEN action_amount
ELSE NULL
END AS expense_amt
FROM tbl_transaction;
As other answers have pointed out, MySQL also has the IF()
function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE
is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.
There's a far more simpler solution to tackle this.
The reason why you get ValueError: Index contains duplicate entries, cannot reshape
is because, once you unstack "Location
", then the remaining index columns "id
" and "date
" combinations are no longer unique.
You can avoid this by retaining the default index column (row #) and while setting the index using "id
", "date
" and "location
", add it in "append
" mode instead of the default overwrite mode.
So use,
e.set_index(['id', 'date', 'location'], append=True)
Once this is done, your index columns will still have the default index along with the set indexes. And unstack
will work.
Let me know how it works out.
A solution that works great for me, is still missing here. It requires having a visually hidden <submit>
or <input type="submit">
element whithin the <form>
, and an associated <label>
element outside of it. It would look like this:
<form method="get" action="something.php">
<input type="text" name="name" />
<input type="submit" id="submit-form" class="hidden" />
</form>
<label for="submit-form" tabindex="0">Submit</label>
Now this link enables you to 'click' the form <submit>
element by clicking the <label>
element.
Just use Control.Invoke Method or Control.BeginInvoke Method.
Great example: How to: Make Thread-Safe Calls to Windows Forms Controls.
Write this;
SELECT f from Student f LEFT JOIN f.classTbls s WHERE s.ClassName = 'abc'
Because your Student entity has One To Many relationship with ClassTbl entity.
You need to make sure that the files on the device mounted by fuse will not have the same paths and file names as files which already existing in the nonempty mountpoint. Otherwise this would lead to confusion. If you are sure, pass -o nonempty
to the mount command.
You can try what is happening using the following commands.. (Linux rocks!) .. without destroying anything..
// create 10 MB file
dd if=/dev/zero of=partition bs=1024 count=10240
// create loopdevice from that file
sudo losetup /dev/loop0 ./partition
// create filesystem on it
sudo e2mkfs.ext3 /dev/loop0
// mount the partition to temporary folder and create a file
mkdir test
sudo mount -o loop /dev/loop0 test
echo "bar" | sudo tee test/foo
# unmount the device
sudo umount /dev/loop0
# create the file again
echo "bar2" > test/foo
# now mount the device (having file with same name on it)
# and see what happens
sudo mount -o loop /dev/loop0 test
For external url you have to use "http://www.yahoo.com" as the redirect url.
This is explained in the redirect: prefix of Spring reference documentation.
redirect:/myapp/some/resource
will redirect relative to the current Servlet context, while a name such as
will redirect to an absolute URL
Since C++17 the inline specifier also applies to variables. You can now define static member variables in the class definition:
#include <string>
class foo {
public:
foo();
foo( int );
private:
inline static const std::string s { "foo" };
};
In my case, it had absolute nothing to do with network issues.
I had been using my local laravel testing environment using laradock. Because laradock runs the mysql server in a different container, you have to set your mysql host in the .env file to the name of the docker mysql container, which by default is mysql.
When I switched back to using homestead, it was trying to connect to a host named mysql, when in fact is should be looking on localhost.
What a DUH moment!
Yes, safari will detect the *.ipa and will try to install it, but the ipa needs to be correctly signed and only allowed devices would be able to install it.
http://www.diawi.com is a service that will help you with this process.
All of this is for Ad-hoc distribution, not for production apps.
More information on below link : Is there a way to install iPhone App via browser?
I solved the problem by adding target="_blank"
to the link.
With this, chrome opens a new tab and loads the PDF without warning even in responsive mode.
Create an xml file any name (say progressBar.xml) in drawable
and add <color name="silverGrey">#C0C0C0</color>
in color.xml.
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="720" >
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="6"
android:useLevel="false" >
<size
android:height="200dip"
android:width="300dip" />
<gradient
android:angle="0"
android:endColor="@color/silverGrey"
android:startColor="@android:color/transparent"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Now in your xml file where you have your listView add this code:
<ListView
android:id="@+id/list_form_statusMain"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<ProgressBar
android:id="@+id/progressBar"
style="@style/CustomAlertDialogStyle"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:indeterminateDrawable="@drawable/circularprogress"
android:visibility="gone"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
In AsyncTask in the method:
@Override
protected void onPreExecute()
{
progressbar_view.setVisibility(View.VISIBLE);
// your code
}
And in onPostExecute:
@Override
protected void onPostExecute(String s)
{
progressbar_view.setVisibility(View.GONE);
//your code
}
I wanted to add my pure CSS answer to this problem of modals with dynamic width and height. The following code also works with the following requirements:
HTML:
<div class="modal">
<div class="modal__content">
(Long) Content
</div>
</div>
CSS/LESS:
.modal {
position: fixed;
display: flex;
align-items: center;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: @qquad;
overflow-y: auto;
background: rgba(0, 0, 0, 0.7);
z-index: @zindex-modal;
&__content {
width: 900px;
margin: auto;
max-width: 90%;
padding: @quad;
background: white;
box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.75);
}
}
This way the modal is always within the viewport. The width and height of the modal are as flexible as you like. I removed my close icon from this for simplicity.
"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:
file.py
will be uploaded into your HOME
dir on remote server.
or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:
After connecting to the server pscp will ask for a password.
People using Android Studio 0.8.6 could do these:
Copy ONLY facebook dir under the Facebook-android-sdk-xxx dir into your project along with app/
Now you should see Android Studio showing facebook as module
provided files('./libs/bolts.jar')
compileSdkVersion 20
or other version you defined in the appbuildToolsVersion '20.0.0'
minSdkVersion 14
targetSdkVersion 20
apply plugin: 'android-library'
dependencies {
compile 'com.android.support:support-v4:19.1.+'
provided files('./libs/bolts.jar')
}
android {
compileSdkVersion 20
buildToolsVersion '20.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 20
}
lintOptions {
abortOnError false
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
res.srcDirs = ['res']
}
}
}
Resync your gradle file & it should just work fine!
if you use routing in your application
make sure Add new components into the routing path
for example :
const appRoutes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'home', component: HomeComponent },
{ path: 'fundList', component: FundListComponent },
];
Depending on the data (e.g. tsv extension) it may use tab as separators, so you may try sep = '\t'
with read.csv
.
window.history.pushState({urlPath:'/page1'},"",'/page1')
Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.
What you should do here is knowing to which URL you are getting redirected when you reload this page. And on that page you can get the conditions by getting the current URL and making all of your conditions.
Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).
The facade is another Request class, access it with the full path:
$input = \Request::all();
From laravel 5 you can also access it through the request()
function:
$input = request()->all();
This worked for me !
if it is not necessary to modify the variable than a general workaround for this kind of problem would be to extract the part of code which use lambda and use final keyword on method-parameter.
If you control the API being called, consider using Guava's Optional class
More info here. Change your method to return an Optional<Boolean>
instead of a Boolean
.
This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional
This query:
SELECT ROW_NUMBER() OVER(ORDER BY UserId) From Users WHERE UserName='Joe'
will return all rows where the UserName
is 'Joe'
UNLESS you have no UserName='Joe'
They will be listed in order of UserID
and the row_number
field will start with 1 and increment however many rows contain UserName='Joe'
If it does not work for you then your WHERE
command has an issue OR there is no UserID
in the table. Check spelling for both fields UserID
and UserName
.
From SQL Server 2008 SSMS (SQL Server Management Studio), simply:
Either:
Right-click, Tasks, Restore, Database
PS: Again, I emphasize: you can easily do this on a "scratch database" - you do not need to overwrite your current database. But you do need to RESTORE.
PPS: You can also accomplish the same thing with T-SQL commands, if you wished to script it.
Simple just log into your GitHub account and on the far right side in the navigation menu choose Settings, in the Settings Tab choose Default Branch and return back to main page of your repository that did the trick for me.
Firstly Use this:
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
Then set operation of button click in onOptionsItemSelected
method
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
the easiest way is using bootstrap and badge class
<span class="badge">1</span>
Add the Git\bin
directory to the Path
environment variable. The directory is %ProgramFiles%\Git\bin
by default. By this way you can access Git Bash with simply typing bash
in every terminal including the integrated terminal of Visual Studio Code.
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
The following worked for me:
hdiutil detach <path to sshfs mount>
Example:
hdiutil detach /Users/user1/sshfs
One can also locate the volume created by sshfs in Finder, right-click, and select Eject. Which is, to the best of my knowledge, the GUI version of the above command.
I had the same problem, and I haven't gotten that error since I close the project before I close myEclipse and don't tidy up the default location.
My project source and compiled files are outside the default workspace but there are stubb folders created by default by myEclipse in the default workspace. When I setup the project, there are two .project files - one in the default workspace that points to the working dir, and one .project in my chosen directory.
Oracle provides some simple examples:
http://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html#CHDJBGFC
Assuming you are in ~/ and the java source tree is in ./saxon_source/net and you want to recurse through the whole source tree net is both a directory and the top package name.
mkdir saxon_docs
javadoc -d saxon_docs -sourcepath saxon_source -subpackages net
Of course AJAX is the solution,
To perform an AJAX request (for easiness we can use jQuery library).
Step1.
Include jQuery library in your web page
a. you can download jQuery library from jquery.com and keep it locally.
b. or simply paste the following code,
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Step 2.
Call a javascript function on button click
<button type="button" onclick="foo()">Click Me</button>
Step 3.
and finally the function
function foo () {
$.ajax({
url:"test.php", //the page containing php script
type: "POST", //request type
success:function(result){
alert(result);
}
});
}
it will make an AJAX request to test.php when ever you clicks the button and alert the response.
For example your code in test.php is,
<?php echo 'hello'; ?>
then it will alert "hello" when ever you clicks the button.
If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:
myTimer.Elapsed += PlayMusicEvent;
where
public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
music.player.Stop();
System.Timers.Timer myTimer = (System.Timers.Timer)sender;
myTimer.Stop();
}
But you need to think about where to store your note.
this metod delate all data from database
public void deleteAll()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ TABLE_NAME);
db.close();
}
Without script:
<form action="where-you-want-to-go"><input type="submit"></form>
Better yet, since you are just going somewhere, present the user with the standard interface for "just going somewhere":
<a href="where-you-want-to-go">ta da</a>
Although, the context sounds like "Simulate a normal search where the user submits a form", in which case the first option is the way to go.
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
Here's one I wrote:
/**
* Format bytes as human-readable text.
*
* @param bytes Number of bytes.
* @param si True to use metric (SI) units, aka powers of 1000. False to use
* binary (IEC), aka powers of 1024.
* @param dp Number of decimal places to display.
*
* @return Formatted string.
*/
function humanFileSize(bytes, si=false, dp=1) {
const thresh = si ? 1000 : 1024;
if (Math.abs(bytes) < thresh) {
return bytes + ' B';
}
const units = si
? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
let u = -1;
const r = 10**dp;
do {
bytes /= thresh;
++u;
} while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);
return bytes.toFixed(dp) + ' ' + units[u];
}
console.log(humanFileSize(1551859712)) // 1.4 GiB
console.log(humanFileSize(5000, true)) // 5.0 kB
console.log(humanFileSize(5000, false)) // 4.9 KiB
console.log(humanFileSize(-10000000000000000000000000000)) // -8271.8 YiB
console.log(humanFileSize(999949, true)) // 999.9 kB
console.log(humanFileSize(999950, true)) // 1.0 MB
console.log(humanFileSize(999950, true, 2)) // 999.95 kB
console.log(humanFileSize(999500, true, 0)) // 1 MB
_x000D_
// Regex - Check Singapore valid mobile numbers
public static boolean isSingaporeMobileNo(String str) {
Pattern mobNO = Pattern.compile("^(((0|((\\+)?65([- ])?))|((\\((\\+)?65\\)([- ])?)))?[8-9]\\d{7})?$");
Matcher matcher = mobNO.matcher(str);
if (matcher.find()) {
return true;
} else {
return false;
}
}
because it is autoincrement, here's my take:
Select * from tbl
where certainconditionshere
and autoincfield >= (select max(autoincfield) from tbl) - $n
private bool CheckAll()
{
if ( ....)
{
return true;
}
return false;
}
When the if-condition is false the method doesn't know what value should be returned (you probably get an error like "not all paths return a value").
As CQQL pointed out if you mean to return true when your if-condition is true you could have simply written:
private bool CheckAll()
{
return (your_condition);
}
If you have side effects, and you want to handle them before you return, the first (long) version would be required.
Looking at http.Request you can find the following member variables:
// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header
// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string
You can use RemoteAddr
to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).
This is all you have for sure.
Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:
req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter
This is because internally http.Header.Get
will normalise the key for you. (If you want to access header map directly, and not through Get
, you would need to use http.CanonicalHeaderKey first.)
Finally, "X-Forwarded-For"
is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:
// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
fmt.Println(ip)
}
will produce:
10.0.0.1
10.0.0.2
10.0.0.3
Building on what is mentioned in the comments, the simplest solution would be:
@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {
//whatever
}
class SomeDto {
private List<WhateverBudgerPerDateDTO> budgetPerDate;
//getters setters
}
The solution assumes that the HTTP request you are creating actually has
Content-Type:application/json
instead of text/plain
You can not perform a cross-database query like SQL Server; PostgreSQL does not support this.
The DbLink extension of PostgreSQL is used to connect one database to another database. You have install and configure DbLink to execute a cross-database query.
I have already created a step-by-step script and example for executing cross database query in PostgreSQL. Please visit this post: PostgreSQL [Video]: Cross Database Queries using the DbLink Extension
To start with, I'd use double.Parse
rather than Convert.ToDouble
in the first place.
As to whether you should use Parse
or TryParse
: can you proceed if there's bad input data, or is that a really exceptional condition? If it's exceptional, use Parse
and let it blow up if the input is bad. If it's expected and can be cleanly handled, use TryParse
.
PUT = replace the ENTIRE RESOURCE with the new representation provided
PATCH = replace parts of the source resource with the values provided AND|OR other parts of the resource are updated that you havent provided (timestamps) AND|OR updating the resource effects other resources (relationships)
Employee Table
Name, DoB, Salary
Tomas , 2/10/1982, 300
Daniel , 3/11/1990, 400
Kwame , 2/10/1998, 520
The Comparable interface allows you to sort a list of objects eg Employees with reference to one primary field – for instance, you could sort by name or by salary with the CompareTo() method
emp1.getName().compareTo(emp2.getName())
A more flexible interface for such requirements is provided by the Comparator interface, whose only method is compare()
public interface Comparator<Employee> {
int compare(Employee obj1, Employee obj2);
}
Sample code
public class NameComparator implements Comparator<Employee> {
public int compare(Employee e1, Employee e2) {
// some conditions here
return e1.getName().compareTo(e2.getName()); // returns 1 since (T)omas > (D)an
return e1.getSalary().compareTo(e2.getSalary()); // returns -1 since 400 > 300
}
}
By HTML specifications, browsers are required to canonicalize line breaks in user input to CR LF (\r\n
), and I don’t think any browser gets this wrong. Reference: clause 17.13.4 Form content types in the HTML 4.01 spec.
In HTML5 drafts, the situation is more complicated, since they also deal with the processes inside a browser, not just the data that gets sent to a server-side form handler when the form is submitted. According to them (and browser practice), the textarea
element value exists in three variants:
If you are using Jackson as your JSON parser then this is how you enable it to allow comments:
ObjectMapper mapper = new ObjectMapper().configure(Feature.ALLOW_COMMENTS, true);
Then you can have comments like this:
{
key: "value" // Comment
}
And you can also have comments starting with #
by setting:
mapper.configure(Feature.ALLOW_YAML_COMMENTS, true);
But in general (as answered before) the specification does not allow comments.
This is what you need : ternary operator, please take a look at this
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx
Got it working! I should have been building a JSONArray
of JSONObject
s and then add the array to a final "Addresses" JSONObject
. Observe the following:
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new JSONObject();
address.put("CustomerName" , "Decepticons" + i);
address.put("AccountId" , "1999" + i);
address.put("SiteId" , "1888" + i);
address.put("Number" , "7" + i);
address.put("Building" , "StarScream Skyscraper" + i);
address.put("Street" , "Devestator Avenue" + i);
address.put("City" , "Megatron City" + i);
address.put("ZipCode" , "ZZ00 XX1" + i);
address.put("Country" , "CyberTron" + i);
addresses.add(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.setContentType("application/json");
response.getWriter().write(json.toString());
This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel
Try underscore-cli:
cat myfile.json | underscore print --color
It's a pretty nifty tool that can elegantly do a lot of manipulation of structured data, execute js snippets, fill templates, etc. It's ridiculously well documented, polished, and ready for serious use. And I wrote it. :)
To improve on @Dmitry Nogin's answer: this worked in my case.
However, it's not tested, since I am not sure how the file dialogue works on various OS/browser combinations. (Thus community wiki.)
<script>
$('#download').click(function () {
download(['http://www.arcelormittal.com/ostrava/doc/cv.doc',
'http://www.arcelormittal.com/ostrava/doc/cv.doc']);
});
var download = function (ar) {
var prevfun=function(){};
ar.forEach(function(address) {
var pp=prevfun;
var fun=function() {
var iframe = $('<iframe style="visibility: collapse;"></iframe>');
$('body').append(iframe);
var content = iframe[0].contentDocument;
var form = '<form action="' + address + '" method="POST"></form>';
content.write(form);
$(form).submit();
setTimeout(function() {
$(document).one('mousemove', function() { //<--slightly hacky!
iframe.remove();
pp();
});
},2000);
}
prevfun=fun;
});
prevfun();
}
</script>
You can get table/view details through below query.
For table :sp_help table_name For View :sp_help view_name
Like this:
from c in db.Company
group c by c.Name into grp
where grp.Count() > 1
select grp.Key
Or, using the method syntax:
Company
.GroupBy(c => c.Name)
.Where(grp => grp.Count() > 1)
.Select(grp => grp.Key);
git add . (add all files in this directory)
git add -all (add all files in all directories)
git add -N can be helpful for for listing which ones for later....
$("#"+styleTarget).css('font-size', newFontSize);
A much easier way to do this is with the standard copy algorithm:
#include <iostream>
#include <algorithm> // for copy
#include <iterator> // for ostream_iterator
#include <vector>
int main() {
/* Set up vector to hold chars a-z */
std::vector<char> path;
for (int ch = 'a'; ch <= 'z'; ++ch)
path.push_back(ch);
/* Print path vector to console */
std::copy(path.begin(), path.end(), std::ostream_iterator<char>(std::cout, " "));
return 0;
}
The ostream_iterator is what's called an iterator adaptor. It is templatized over the type to print out to the stream (in this case, char
). cout
(aka console output) is the stream we want to write to, and the space character (" "
) is what we want printed between each element stored in the vector.
This standard algorithm is powerful and so are many others. The power and flexibility the standard library gives you are what make it so great. Just imagine: you can print a vector to the console with just one line of code. You don't have to deal with special cases with the separator character. You don't need to worry about for-loops. The standard library does it all for you.
There is no specific convenience function.
You'd have to do something like:
first_ten = pd.DataFrame()
rest = pd.DataFrame()
if df.shape[0] > 10: # len(df) > 10 would also work
first_ten = df[:10]
rest = df[10:]
bool
exists in the current C - C99, but not in C89/90.
In C99 the native type is actually called _Bool
, while bool
is a standard library macro defined in stdbool.h
(which expectedly resolves to _Bool
). Objects of type _Bool
hold either 0 or 1, while true
and false
are also macros from stdbool.h
.
Note, BTW, that this implies that C preprocessor will interpret #if true
as #if 0
unless stdbool.h
is included. Meanwhile, C++ preprocessor is required to natively recognize true
as a language literal.
$('#tblCart tr').click(function () {
var tr_id = $(this).attr('id');
alert(tr_id );
});
<table class="table table-striped table-bordered table-hover" id="tblCart" cellspacing="0" align="center" >
<tr>
<th>
@Html.DisplayNameFor(model => model.Item.ItemName)
</th>
<th>
@Html.DisplayNameFor(model => model.Price.PriceAmount)
</th>
<th>
@Html.DisplayNameFor(model => model.Quantity)
</th>
<th>
@Html.DisplayNameFor(model => model.Subtotal)
</th>
<th></th>
</tr>
@if (cart != null)
{
foreach (var vm in cart)
{
<tr id="@vm.Id">
<td>
@Html.DisplayFor(modelItem => vm.Item.ItemName)
</td>
<td>
@Html.DisplayFor(modelItem => vm.Price.PriceAmount)
</td>
<td>
@Html.DisplayFor(modelItem => vm.Quantity)
</td>
<td>
@Html.DisplayFor(modelItem => vm.Subtotal)
</td>
<td >
<span style="width:80px; text-align:center;" class="glyphicon glyphicon-minus-sign" />
</td>
</tr>
}
}
</table>
It escapes a string that cannot be passed to XML as usual:
Example:
The string contains "&" in it.
You can not:
<FL val="Company Name">Dolce & Gabbana</FL>
Therefore, you must use CDATA:
<FL val="Company Name"> <![CDATA["Dolce & Gabbana"]]> </FL>
I found that Jason's answer wasn't quite working for me and I was still getting a jump. The Javascript ensured there was no gap at the top of the page but the background was still jumping whenever the address bar disappeared/reappeared. So as well as the Javascript fix, I applied transition: height 999999s
to the div. This creates a transition with a duration so long that it virtually freezes the element.
You can also use printf to pipe the input to your script.
var=val
printf "yes\nno\nmaybe\n$var\n" | ./your_script.sh
The most common ways to use the shutdown
command are:
shutdown -s
— Shuts down.shutdown -r
— Restarts.shutdown -l
— Logs off.shutdown -h
— Hibernates.
Note: There is a common pitfall wherein users think -h
means "help" (which it does for every other command-line program... except shutdown.exe
, where it means "hibernate"). They then run shutdown -h
and accidentally turn off their computers. Watch out for that.
shutdown -i
— "Interactive mode". Instead of performing an action, it displays a GUI dialog.
shutdown -a
— Aborts a previous shutdown command.The commands above can be combined with these additional options:
-f
— Forces programs to exit. Prevents the shutdown process from getting stuck.-t <seconds>
— Sets the time until shutdown. Use -t 0
to shutdown immediately.-c <message>
— Adds a shutdown message. The message will end up in the Event Log.-y
— Forces a "yes" answer to all shutdown queries.
Note: This option is not documented in any official documentation. It was discovered by these StackOverflow users.
I want to make sure some other really good answers are also mentioned along with this one. Here they are in no particular order.
-f
option from JosephStyonsrundll32
from VonCi install mysql for visual studio and the problem simply solved.although version of my visual studio is 2012!
Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.
So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:
Using scp, copy file to a directory in the remote user's account, for example the Documents directory:
scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents
Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:
ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www
from: http://www.codeproject.com/KB/WCF/WCF_Operation_Timeout_.aspx
To avoid this timeout error, we need to configure the OperationTimeout property for Proxy in the WCF client code. This configuration is something new unlike other configurations such as Send Timeout, Receive Timeout etc., which I discussed early in the article. To set this operation timeout property configuration, we have to cast our proxy to IContextChannel in WCF client application before calling the operation contract methods.
The Ubuntu/Debian Linux version of this answer is to install openjdk 8 and set the default via update-alternatives
# install (open)jdk 8
sudo apt-get install -y openjdk-8-jdk
# update java compiler and set to 1.8
update-alternatives --config javac
# update java runtime (optional)
update-alternatives --config java
# Also set $JAVA_HOME and $PATH to your .bashrc (optional)
echo 'export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64' >> ~/.bashrc
echo 'export PATH="$PATH:$JAVA_HOME/bin' >> ~/.bashrc
# load in current bash session
source ~/.bashrc
Request and response.
To understand the req
, try out console.log(req);
.
For the point that 'returns the value as soon as you find the first row/record that meets the requirements and NOT iterating other rows', the following code would work:
def pd_iter_func(df):
for row in df.itertuples():
# Define your criteria here
if row.A > 4 and row.B > 3:
return row
It is more efficient than Boolean Indexing
when it comes to a large dataframe.
To make the function above more applicable, one can implements lambda functions:
def pd_iter_func(df: DataFrame, criteria: Callable[[NamedTuple], bool]) -> Optional[NamedTuple]:
for row in df.itertuples():
if criteria(row):
return row
pd_iter_func(df, lambda row: row.A > 4 and row.B > 3)
As mentioned in the answer to the 'mirror' question, pandas.Series.idxmax
would also be a nice choice.
def pd_idxmax_func(df, mask):
return df.loc[mask.idxmax()]
pd_idxmax_func(df, (df.A > 4) & (df.B > 3))
From the documentation of InetAddress.getByName(String host)
:
The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.
So you can use it.
l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']
l.sort()
print(l1)
Result
['abc', 'ba', 'cd', 'dc', 'xy']
This answer is not working since the urllib2
module has been split across several modules in Python 3.
You need to do
from urllib import request
opener = request.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")
Use your mydate object and call getMonth() and getFullYear()
See this for more info: http://www.w3schools.com/jsref/jsref_obj_date.asp
item's border color in swift 4.2:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell_lastOrderId") as! Cell_lastOrder
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.white.cgColor
cell.layer.cornerRadius = 10
I've never used it but there is a JWT implementation on NuGet.
Package: https://nuget.org/packages/JWT
Source: https://github.com/johnsheehan/jwt
.NET 4.0 compatible: https://www.nuget.org/packages/jose-jwt/
You can also go here: https://jwt.io/ and click "libraries".
You could take any of the answers above that use the string.length method and replace it with string.size.
They both work the same way.
if string.size <= 25
puts "No problem here!"
else
puts "Sorry too long!"
end
@Test
public void emptyJsonParseTest() {
JsonNode emptyJsonNode = new ObjectMapper().createObjectNode();
Assert.assertTrue(emptyJsonNode.asText().isEmpty());
}
it is always good to restrict the DOM search. so better to use a parent also, so that the entire DOM won't be traversed.
IT IS VERY FAST
<div id="radioBtnDiv">
<input name="myButton" type="radio" class="radioClass" value="manual" checked="checked"/>
<input name="myButton" type="radio" class="radioClass" value="auto" checked="checked"/>
</div>
$("input[name='myButton']",$('#radioBtnDiv')).change(
function(e)
{
// your stuffs go here
});
Sometimes such behavior may be achieved if you try to install python3 lib in python2 folder using pip instead of pip3.
process.env.ENV_VARIABLE
Where ENV_VARIABLE
is the name of the variable you wish to access.
You may run:
git log <SHA1>..HEAD --ancestry-path --merges
From comment of last commit in the output you may find original branch name
Example:
c---e---g--- feature
/ \
-a---b---d---f---h---j--- master
git log e..master --ancestry-path --merges
commit h
Merge: g f
Author: Eugen Konkov <>
Date: Sat Oct 1 00:54:18 2016 +0300
Merge branch 'feature' into master
Manifest.MF contains information about the files contained in the JAR file.
Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.
Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,
Main-Class: {fully qualified classname}
The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.
Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,
Class-Path: {jar1-name jar2-name directory-name/jar3-name}
This header can be used to specify the external JAR files on the same local network and not inside the current JAR.
Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:
Headers in a manifest
Header | Definition
-------------------------------------------------------------------
Name | The name of the specification.
Specification-Title | The title of the specification.
Specification-Version | The version of the specification.
Specification-Vendor | The vendor of the specification.
Implementation-Title | The title of the implementation.
Implementation-Version | The build number of the implementation.
Implementation-Vendor | The vendor of the implementation.
Package sealing related headers:
We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,
Name: {package/some-package/} Sealed:true
Here, the package name must end with ‘/’.
Enhancing security with manifest files:
We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.
META-INF folder:
This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.
Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
Even I faced the same situation before...and didn't have any help. try these things maybe these will work for you
in login page <head>
tag:
<script type="text/javascript">
window.history.forward();
</script>
in Logout Button I did this:
protected void Btn_Logout_Click(object sender, EventArgs e)
{
connObj.Close();
Session.Abandon();
Session.RemoveAll();
Session.Clear();
HttpContext.Current.Session.Abandon();
}
and on login page I have put the focus on Username textbox like this:
protected void Page_Load(object sender, EventArgs e)
{
_txtUsername.Focus();
}
hope this helps... :) someone plz teach me how to edit this page...
In VS2019, the project property page, TypeScript Build tab has a setting (dropdown) for "Module System". When I changed that from "ES2015" to CommonJS, then VS2019 IDE stopped complaining that it could find neither axios nor redux-thunk (TS2307).
tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"baseUrl": "src",
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"lib": [
"es6",
"dom",
"es2015.promise"
],
"module": "esnext",
"moduleResolution": "node",
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"outDir": "build/dist",
"rootDir": "src",
"sourceMap": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es5",
"skipLibCheck": true,
"strict": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"exclude": [
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts",
"node_modules",
"obj",
"**/*.spec.ts"
],
"include": [
"src",
"src/**/*.ts",
"@types/**/*.d.ts",
"node_modules/axios",
"node_modules/redux-thunk"
]
}
NsUserDefaults saves only small variable sizes. If you want to save many objects you can use CoreData as a native solution, or I created a library that helps you save objects as easy as .save() function. It’s based on SQLite.
Check it out and tell me your comments
Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".
class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
public:
SubClass(int foo, int bar)
: SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};
More info on the constructor's initialization list here and here.
By default, inheritance is private. You have to explicitly use public
:
class Bar : public Foo
Something to try --- tell python to not use https with the index directive and a http:// address (not https://)
pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org Scrapy
You may be behind a corporate firewall and Ive have experiences where even the above failed, though Im not going to pretend like I know enough about firewalls or SSL to understand why. In that case the only way I was able to get around that was to get a certificate file and pass it to python. See kenorb’s answer here for details.
Oddly, it works with some types of input. At least in Chrome,
<input type="checkbox" />
works fine, same as
<input type="radio" />
It's just type=text
and some others that don't work.
Improvisation to the function "humanTiming" by arnorhs. It would calculate a "fully stretched" translation of time string to human readable text version. For example to say it like "1 week 2 days 1 hour 28 minutes 14 seconds"
function humantime ($oldtime, $newtime = null, $returnarray = false) {
if(!$newtime) $newtime = time();
$time = $newtime - $oldtime; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
$htarray = array();
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
$htarray[$text] = $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
$time = $time - ( $unit * $numberOfUnits );
}
if($returnarray) return $htarray;
return implode(' ', $htarray);
}
The Key Disappears, whether it is numeric or not. Try out the test script below.
<?php
$t = array( 'a', 'b', 'c', 'd' );
foreach($t as $k => $v)
echo($k . ": " . $v . "<br/>");
// Output: 0: a, 1: b, 2: c, 3: d
unset($t[1]);
foreach($t as $k => $v)
echo($k . ": " . $v . "<br/>");
// Output: 0: a, 2: c, 3: d
?>
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
Using the client manager affects all connections or sets a client machine specific alias.
Use the comma as above: this can be used in an app.config too
It's probably needed if you have firewalls between you and the server too...
module Rails
def self.root
File.expand_path("..", __dir__)
end
end
add these dependecies to your .pom file:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.healthmarketscience.jackcess</groupId>
<artifactId>jackcess-encrypt</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
and add to your code to call a driver:
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://{file_location}/{accessdb_file_name.mdb};memory=false");
Ok. As the other answerers explained, a stack is a last-in, first-out data structure. You add an element to the top of the stack with a Push operation. You take an element off the top with a Pop operation. The elements are removed in reverse order to the order they were put inserted (hence Last In, First Out). For example, if you push the elments 1,2,3 in that order, the number 3 will be at the top of the stack. A Pop operation will remove it (it was the last in) and leave 2 at the top of the stack.
Regarding the rest of the lecture, the lecturer tried to describe a stack-based machine that evaluates arithmetic expressions. The machine operates by continuously popping 3 elements from the top of the stack. The first two elements are operands and the third is an operator (+, -, *, /). It then applies this operator on the operands, and pushes the result onto the stack. The process continues until there is only one element on the stack, which is the value of the expression.
So, suppose we begin by pushing the values "+/*23-21*5-41" in left-to-right order onto the stack. We then pop 3 elements from the top. The last in is first out, which means the first 3 element are "1", "4", and "-" in that order. We push the number 3 (the result of 4-1) onto the stack, then pop the three topmost elements: 3, 5, *. Push the result, 15, onto the stack, and so on.
You don't mention what language you want to track these in, but I found two for javascript:
Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below
import 'package:jiffy/jiffy.dart';
var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");
You can also do the following
var a = Jiffy().yMMMMd; // October 18, 2019
And you can also pass in your DateTime object, A string and an array
var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019
var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019
var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019
Try:
SELECT post_datetime
FROM post
WHERE type = 'published'
ORDER BY post_datetime DESC
LIMIT 3
Chrome since ~Sep/Oct 2014 makes fonts subject to the same CORS checks as Firefox has done https://code.google.com/p/chromium/issues/detail?id=286681. There is a discussion on this in https://groups.google.com/a/chromium.org/forum/?fromgroups=#!topic/blink-dev/TT9D5-Zfnzw
Given that for fonts the browser may do a preflight check, then your S3 policy needs the cors request header as well. You can check your page in say Safari (which at present doesn't do CORS checking for fonts) and Firefox (that does) to double check this is the problem described.
See Stack overflow answer on Amazon S3 CORS (Cross-Origin Resource Sharing) and Firefox cross-domain font loading for the Amazon S3 CORS details.
NB in general because this used to apply to Firefox only, so it may help to search for Firefox rather than Chrome.
You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
Since variable names in the BASH shell cannot contain a dot or space it is better to use an associative array in BASH like this:
#!/bin/bash
# declare an associative array
declare -A arr
# read file line by line and populate the array. Field separator is "="
while IFS='=' read -r k v; do
arr["$k"]="$v"
done < app.properties
Testing:
Use declare -p to show the result:
> declare -p arr
declare -A arr='([db.uat.passwd]="secret" [db.uat.user]="saple user" )'
You can do it using array module. array module is part of python standard library:
from array import array
from itertools import repeat
a = array("i", repeat(0, 10))
# or
a = array("i", [0]*10)
repeat function repeats 0 value 10 times. It's more memory efficient than [0]*10, since it doesn't allocate memory, but repeats returning the same number x number of times.
To sum up the other answers:
org.hibernate.annotations.Index
org.apache.openjpa.persistence.jdbc.Index
org.eclipse.persistence.annotations.Index
I would just go for one of them. It will come with JPA 2.1 anyway and should not be too hard to change in the case that you really want to switch your JPA provider.
Using $index
works perfectly well in basic cases, and @charlietfl's answer is great. But sometimes, $index
isn't enough.
Imagine you have a single array, which you're presenting in two different ng-repeat's. One of those ng-repeat's is filtered for objects that have a truthy property, and the other is filtered for a falsy property. Two different filtered arrays are being presented, which derive from a single original array. (Or, if it helps to visualize: perhaps you have a single array of people, and you want one ng-repeat for the women in that array, and another for the men in that same array.) Your goal: delete reliably from the original array, using information from the members of the filtered arrays.
In each of those filtered arrays, $index won't be the index of the item within the original array. It'll be the index in the filtered sub-array. So, you won't be able to tell the person's index in the original people
array, you'll only know the $index from the women
or men
sub-array. Try to delete using that, and you'll have items disappearing from everywhere except where you wanted. What to do?
If you're lucky enough be using a data model includes a unique identifier for each object, then use that instead of $index, to find the object and splice
it out of the main array. (Use my example below, but with that unique identifier.) But if you're not so lucky?
Angular actually augments each item in an ng-repeated array (in the main, original array) with a unique property called $$hashKey
. You can search the original array for a match on the $$hashKey
of the item you want to delete, and get rid of it that way.
Note that $$hashKey
is an implementation detail, not included in the published API for ng-repeat. They could remove support for that property at any time. But probably not. :-)
$scope.deleteFilteredItem = function(hashKey, sourceArray){
angular.forEach(sourceArray, function(obj, index){
// sourceArray is a reference to the original array passed to ng-repeat,
// rather than the filtered version.
// 1. compare the target object's hashKey to the current member of the iterable:
if (obj.$$hashKey === hashKey) {
// remove the matching item from the array
sourceArray.splice(index, 1);
// and exit the loop right away
return;
};
});
}
Invoke with:
ng-click="deleteFilteredItem(item.$$hashKey, refToSourceArray)"
EDIT: Using a function like this, which keys on the $$hashKey
instead of a model-specific property name, also has the significant added advantage of making this function reusable across different models and contexts. Provide it with your array reference, and your item reference, and it should just work.
The different answers here have two different meanings.
If you want to check whether an instance is of an exact type then
if (c.GetType() == typeof(TForm))
is the way to go.
If you want to know whether c
is an instance of TForm
or a subclass then use is
/as
:
if (c is TForm)
or
TForm form = c as TForm;
if (form != null)
It's worth being clear in your mind about which of these behaviour you actually want.
Try this code
final EditText editText = findViewById(R.id.name); // your edittext id in xml
Button submit = findViewById(R.id.submit_button); // your button id in xml
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
String string = editText.getText().toString();
Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
}
});
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
It is possible to extend the relation with query functions:
<?php
public function comments()
{
return $this->hasMany('Comment')->orderBy('column');
}
[edit after comment]
<?php
class User
{
public function comments()
{
return $this->hasMany('Comment');
}
}
class Controller
{
public function index()
{
$column = Input::get('orderBy', 'defaultColumn');
$comments = User::find(1)->comments()->orderBy($column)->get();
// use $comments in the template
}
}
default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )
This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:
When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.
$(document).ready(function() { $("input[id$='btnAwesome']").click(function() { // Do client side button click stuff here. }); });
The id$= is doing a regex match for an id ENDING with btnAwesome.
Edit:
Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.
The gist of it is you create a static method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.
$.ajax({ type: "POST", url: "PageName.aspx/MethodName", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Do something interesting here. } });
I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.
If you're finding by Contains then it'll be like this
$("input[id*='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Starts With then it'll be like this
$("input[id^='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Ends With then it'll be like this
$("input[id$='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is not a given string
$("input[id!='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which name contains a given word, delimited by spaces
$("input[name~='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen
$("input[id|='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
pip has a --no-dependencies
switch. You should use that.
For more information, run pip install -h
, where you'll see this line:
--no-deps, --no-dependencies
Ignore package dependencies
You can even set a separate right margin for HTML. Under the specified path:
File >> Settings >> Editor >> Code Style >> HTML >> Other Tab >> Right margin (columns)
This is very useful because generally HTML and JS may be usually long in one line than Python. :)
You can select the form like this:
$("#submit").click(function(){
var form = $(this).parents('form:first');
...
});
However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:
$('form#myform1').submit(function(e){
e.preventDefault(); //Prevent the normal submission action
var form = this;
// ... Handle form submission
});
To select fields inside the form, use the form context. For example:
$("input[name='somename']",form).val();
set
is what you want, so you should use set
. Trying to be clever introduces subtle bugs like forgetting to add one tomax(mylist)
! Code defensively. Worry about what's faster when you determine that it is too slow.
range(min(mylist), max(mylist) + 1) # <-- don't forget to add 1
You could use dots: ...
in your function definition.
myfun <- function(a, b, ...){
cat(a,b)
}
myfun(a=4,b=7,hello=3)
# 4 7
Nice answer by Alex and Sameer, but maybe just additional info on why is necessary to put
public $timestamps = false;
Timestamps are nicely explained on official Laravel page:
By default, Eloquent expects created_at and updated_at columns to exist on your >tables. If you do not wish to have these columns automatically managed by >Eloquent, set the $timestamps property on your model to false.
I got the similar error when install bundle
sudo apt-get install ruby-dev
Works great for me and solve the problem Mint 16 ruby1.9.3
You can create functions in react components. It is actually regular ES6 class which inherits from React.Component
. Just be careful and bind it to the correct context in onClick
event:
export default class Archive extends React.Component {
saySomething(something) {
console.log(something);
}
handleClick(e) {
this.saySomething("element clicked");
}
componentDidMount() {
this.saySomething("component did mount");
}
render() {
return <button onClick={this.handleClick.bind(this)} value="Click me" />;
}
}
Big difference between an image and an iframe is the fact that an image keeps its aspect-ratio. You could combine an image and an iframe with will result in a responsive iframe. Hope this answerers your question.
Check this link for example : http://jsfiddle.net/Masau/7WRHM/
HTML:
<div class="wrapper">
<div class="h_iframe">
<!-- a transparent image is preferable -->
<img class="ratio" src="http://placehold.it/16x9"/>
<iframe src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe>
</div>
<p>Please scale the "result" window to notice the effect.</p>
</div>
CSS:
html,body {height:100%;}
.wrapper {width:80%;height:100%;margin:0 auto;background:#CCC}
.h_iframe {position:relative;}
.h_iframe .ratio {display:block;width:100%;height:auto;}
.h_iframe iframe {position:absolute;top:0;left:0;width:100%; height:100%;}
note: This only works with a fixed aspect-ratio.
My answer comes quite late because I'm a pretty new developer. This is what you can do:
Location.select(:name, :website, :city).find(row.id)
Btw, this is Rails 4
origin/master
is an entity (since it is not a physical branch) representing the state of the master
branch on the remote origin
.
origin master
is the branch master
on the remote origin
.
So we have these:
Example (in local branch master
):
git fetch # get current state of remote repository
git merge origin/master # merge state of remote master branch into local branch
git push origin master # push local branch master to remote branch master
Updating and placing, somewhere it will be easier for others to find, ling's comment upon jur's response above.
df_diff = pd.concat([df1,df2]).drop_duplicates(keep=False)
Testing with these DataFrames:
# with import pandas as pd
df1 = pd.DataFrame({
'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24'],
'Fruit':['Banana','Orange','Apple','Celery'],
'Num':[22.1,8.6,7.6,10.2],
'Color':['Yellow','Orange','Green','Green'],
})
df2 = pd.DataFrame({
'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24','2013-11-25','2013-11-25'],
'Fruit':['Banana','Orange','Apple','Celery','Apple','Orange'],
'Num':[22.1,8.6,7.6,10.2,22.1,8.6],
'Color':['Yellow','Orange','Green','Green','Red','Orange'],
})
Results in this:
# for df1
Date Fruit Num Color
0 2013-11-24 Banana 22.1 Yellow
1 2013-11-24 Orange 8.6 Orange
2 2013-11-24 Apple 7.6 Green
3 2013-11-24 Celery 10.2 Green
# for df2
Date Fruit Num Color
0 2013-11-24 Banana 22.1 Yellow
1 2013-11-24 Orange 8.6 Orange
2 2013-11-24 Apple 7.6 Green
3 2013-11-24 Celery 10.2 Green
4 2013-11-25 Apple 22.1 Red
5 2013-11-25 Orange 8.6 Orange
# for df_diff
Date Fruit Num Color
4 2013-11-25 Apple 22.1 Red
5 2013-11-25 Orange 8.6 Orange
Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
This worked for me though:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
base.OnModelCreating(modelBuilder);
}
There several different ways to do it. But You can use the following approach:
List<DataRow> RowsToDelete = new List<DataRow>();
for (int i = 0; i < drr.Length; i++)
{
if(condition to delete the row)
{
RowsToDelete.Add(drr[i]);
}
}
foreach(var dr in RowsToDelete)
{
drr.Rows.Remove(dr);
}
The difference between these two methods is:
parseXxx()
returns the primitive typevalueOf()
returns a wrapper object reference of the type.Here are a few options:
In Perl, you can choose alternate delimiters. You're not confined to m//
. You could choose another, such as m{}
. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts that m{}
is the only alternate delimiter that ought to be used, and this is reinforced by Perl::Critic (on CPAN). While you can get away with using a variety of alternate delimiter characters, //
and {}
seem to be the clearest to decipher later on. However, if either of those choices result in too much escaping, choose whichever one lends itself best to legibility. Common examples are m(...)
, m[...]
, and m!...!
.
In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash: m/\/[^/]+$/
for example (using an alternate delimiter that could become m{/[^/]+$}
, which may read more clearly). Escaping the slash with a backslash is common enough to have earned a name and a wikipedia page: Leaning Toothpick Syndrome. In regular expressions where there's just a single instance, escaping a slash might not rise to the level of being considered a hindrance to legibility, but if it starts to get out of hand, and if your language permits alternate delimiters as Perl does, that would be the preferred solution.
package name with 0 may cause problem for sharedPreference.
(OK) con = createPackageContext("com.example.android.sf1", 0);
(Problem but no error)
con = createPackageContext("com.example.android.sf01", 0);
There is a sort that's called bogobogosort. First, it checks the first 2 elements, and bogosorts them. Next it checks the first 3, bogosorts them, and so on.
Should the list be out of order at any time, it restarts by bogosorting the first 2 again. Regular bogosort has a average complexity of O(N!)
, this algorithm has a average complexity of O(N!1!2!3!...N!)
Edit: To give you an idea of how large this number is, for 20
elements, this algorithm takes an average of 3.930093*10^158
years,well above the proposed heat death of the universe(if it happens) of 10^100
years,
whereas merge sort takes around .0000004
seconds,
bubble sort .0000016
seconds,
and bogosort takes 308
years, 139
days, 19
hours, 35
minutes, 22.306
seconds, assuming a year is 365.242 days and a computer does 250,000,000 32 bit integer operations per second.
Edit2: This algorithm is not as slow as the "algorithm" miracle sort, which probably, like this sort, will get the computer sucked in the black hole before it successfully sorts 20 elemtnts, but if it did, I would estimate an average complexity of 2^(32(the number of bits in a 32 bit integer)*N)(the number of elements)*(a number <=10^40)
years,
since gravity speeds up the chips alpha moving, and there are 2^N states, which is 2^640*10^40
, or about 5.783*10^216.762162762
years, though if the list started out sorted, its complexity would only be O(N)
, faster than merge sort, which is only N log N even at the worst case.
Edit3: This algorithm is actually slower than miracle sort as the size gets very big, say 1000, since my algorithm would have a run time of 2.83*10^1175546
years, while the miracle sort algorithm would have a run time of 1.156*10^9657
years.
Use List.Insert(0, ...)
. But are you sure a LinkedList
isn't a better fit? Each time you insert an item into an array at a position other than the array end, all existing items will have to be copied to make space for the new one.
You can also do it this way
private static string GetPaddingSequence(int padding)
{
StringBuilder SB = new StringBuilder();
for (int i = 0; i < padding; i++)
{
SB.Append("0");
}
return SB.ToString();
}
public static string FormatNumber(int number, int padding)
{
return number.ToString(GetPaddingSequence(padding));
}
Finally call the function FormatNumber
string x = FormatNumber(1,2);
Output will be 01 which is based on your padding parameter. Increasing it will increase the number of 0s
Not sure why no one has mentioned two Base R functions specifically to do this: str2lang()
and str2expression()
. These are variants of parse()
, but seem to return the expression more cleanly:
eval(str2lang("5+5"))
# > 10
eval(str2expression("5+5"))
# > 10
Also want to push back against the posters saying that anyone trying to do this is wrong. I'm reading in R expressions stored as text in a file and trying to evaluate them. These functions are perfect for this use case.
New-Symlink:
Function New-SymLink ($link, $target)
{
if (test-path -pathtype container $target)
{
$command = "cmd /c mklink /d"
}
else
{
$command = "cmd /c mklink"
}
invoke-expression "$command $link $target"
}
Remove-Symlink:
Function Remove-SymLink ($link)
{
if (test-path -pathtype container $link)
{
$command = "cmd /c rmdir"
}
else
{
$command = "cmd /c del"
}
invoke-expression "$command $link"
}
Usage:
New-Symlink "c:\foo\bar" "c:\foo\baz"
Remove-Symlink "c:\foo\bar"
Ended up using .closest() instead.
$(document).on("click", function (event) {
if($(event.target).closest(".CustomControllerMainDiv").length == 1)
alert('element is a child of the custom controller')
});
If you're using a shell, the filepath to the Download (no "s") folder is
/storage/emulated/0/Download
Here's the code I normally use to generate primes in Python:
$ python -mtimeit -s'import sieve' 'sieve.sieve(1000000)'
10 loops, best of 3: 445 msec per loop
$ cat sieve.py
from math import sqrt
def sieve(size):
prime=[True]*size
rng=xrange
limit=int(sqrt(size))
for i in rng(3,limit+1,+2):
if prime[i]:
prime[i*i::+i]=[False]*len(prime[i*i::+i])
return [2]+[i for i in rng(3,size,+2) if prime[i]]
if __name__=='__main__':
print sieve(100)
It can't compete with the faster solutions posted here, but at least it is pure python.
Thanks for posting this question. I really learnt a lot today.
This lists files recursively if they're normal files, sorts by the 7th field (which is size in my find
output; check yours), and shows just the first file.
find . -type f -ls | sort +7 | head -1
The first option to find
is the start path for the recursive search. A -type of f
searches for normal files. Note that if you try to parse this as a filename, you may fail if the filename contains spaces, newlines or other special characters. The options to sort
also vary by operating system. I'm using FreeBSD.
A "better" but more complex and heavier solution would be to have find
traverse the directories, but perhaps use stat
to get the details about the file, then perhaps use awk
to find the largest size. Note that the output of stat
also depends on your operating system.
As @Randall in his answer mentioned iOS 5.0+ UIAppearance
proxy can be used to customize the appearance of all instances of a class read more.
UILabel.appearance().font = .systemFont(ofSize: 17, weight: .regular)
document.getElementById("TestToggleRadioButtonList").rows[0].cells[0].childNodes[0].checked = true;
where TestToggleRadioButtonList
is the id of the RadioButtonList
.
I solved this problem by switching to root with sudo su.
I had this same problem a week ago.
First of all I noticed your URL has an ampersand preceding the parameter string, but it probably needs to have a question mark instead to begin the parameter string, followed by an ampersand between each additional parameter.
Now, you do need to escape your URL but also double-escape the URL parameters (title or other content you need to provide content in the Share) you are passing to the URL, as follows:
var myParams = 't=' + escape('Some title here.') + '&id=' + escape('some content ID or any other value I want to load');
var fooBar = 'http://www.facebook.com/share.php?u=' + escape('http://foobar.com/superDuperSharingPage.php?' + myParams);
Now, you need to create the above-linked superDuperSharingPage.php, which should provide the dynamic title, description, and image content you desire. Something like this should suffice:
<?php
// get our URL query parameters
$title = $_GET['t'];
$id = $_GET['id'];
// maybe we want to load some content with the id I'll pretend we loaded a
// description from some database in the sky which is magically arranged thusly:
$desciption = $databaseInTheSky[$id]['description'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $title;?></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="title" content="<?php echo $title;?>" />
<meta name="description" content="<?php echo $desciption;?>" />
<!-- the following line redirects to wherever we want the USER to land -->
<!-- Facebook won't follow it. you may or may not actually want || need this. -->
<meta http-equiv="refresh" content="1;URL=http://foobar.com" />
</head>
<body>
<p><?php echo $desciption;?></p>
<p><img src="image_a_<?php echo $id;?>.jpg" alt="Alt tags are always a good idea." /></p>
<p><img src="image_b_<?php echo $id;?>.jpg" alt="Make the web more accessible to the blind!" /></p>
</body>
</html>
Let me know if this works for you, it's essentially what did for me :)
Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala List
; it's an immutable data structure, like a Java String.
What you actually do when you "add an element to a list" in Scala is to create a new List from an existing List. (Source)
Instead of using lists for such use cases, I suggest to either use an ArrayBuffer
or a ListBuffer
. Those datastructures are designed to have new elements added.
Finally, after all your operations are done, the buffer then can be converted into a list. See the following REPL example:
scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer
scala> var fruits = new ListBuffer[String]()
fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer()
scala> fruits += "Apple"
res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple)
scala> fruits += "Banana"
res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana)
scala> fruits += "Orange"
res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange)
scala> val fruitsList = fruits.toList
fruitsList: List[String] = List(Apple, Banana, Orange)
Although the answers above seems correct, just a simple explanation to give you an idea of how it works.
Suppose that your column is set to be DECIMAL(13,4)
. This means that the column will have a total size of 13 digits where 4 of these will be used for precision representation.
So, in summary, for that column you would have a max value of: 999999999.9999
Armin's answer + a strict check for object types and non-angular keys such as $resolve
app.filter('orderObjectBy', function(){
return function(input, attribute) {
if (!angular.isObject(input)) return input;
var array = [];
for(var objectKey in input) {
if (typeof(input[objectKey]) === "object" && objectKey.charAt(0) !== "$")
array.push(input[objectKey]);
}
array.sort(function(a, b){
a = parseInt(a[attribute]);
b = parseInt(b[attribute]);
return a - b;
});
return array;
}
})
Using the MONTH and YEAR functions as suggested in most of the responses has the disadvantage that SQL Server will not be able to use any index there may be on your date column. This can kill performance on a large table.
I would be inclined to pass a DATETIME value (e.g. @StartDate) to the stored procedure which represents the first day of the month you are interested in.
You can then use
SELECT ... FROM ...
WHERE DateColumn >= @StartDate
AND DateColumn < DATEADD(month, 1, @StartDate)
If you must pass the month and year as separate parameters to the stored procedure, you can generate a DATETIME representing the first day of the month using CAST and CONVERT then proceed as above. If you do this I would recommend writing a function that generates a DATETIME from integer year, month, day values, e.g. the following from a SQL Server blog.
create function Date(@Year int, @Month int, @Day int)
returns datetime
as
begin
return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
end
go
The query then becomes:
SELECT ... FROM ...
WHERE DateColumn >= Date(@Year,@Month,1)
AND DateColumn < DATEADD(month, 1, Date(@Year,@Month,1))
Setting up a simple reverse proxy on the server, will allow the browser to use relative paths for the Ajax requests, while the server would be acting as a proxy to any remote location.
If using mod_proxy in Apache, the fundamental configuration directive to set up a reverse proxy is the ProxyPass
. It is typically used as follows:
ProxyPass /ajax/ http://other-domain.com/ajax/
In this case, the browser would be able to request /ajax/web_service.xml
as a relative URL, but the server would serve this by acting as a proxy to http://other-domain.com/ajax/web_service.xml
.
One interesting feature of the this method is that the reverse proxy can easily distribute requests towards multiple back-ends, thus acting as a load balancer.
try this:
Using jQuery:
You can reset the entire form with:
$("#myform")[0].reset();
Or just the specific field with:
$('#form-id').children('input').val('')
Using JavaScript Without jQuery
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
function submitForm() {
// Get the first form with the name
// Hopefully there is only one, but there are more, select the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit
frm.reset(); // Reset
return false; // Prevent page refresh
}
>>> import csv
>>> with open('test.csv', 'wb') as f:
... wtr = csv.writer(f, delimiter= ' ')
... wtr.writerows( [[1, 2], [2, 3], [4, 5]])
...
>>> with open('test.csv', 'r') as f:
... for line in f:
... print line,
...
1 2 <<=== Exactly what you said that you wanted.
2 3
4 5
>>>
To get it so that it can be loaded sensibly by Excel, you need to use a comma (the csv default) as the delimiter, unless you are in a locale (e.g. Europe) where you need a semicolon.
Extend HttpServletRequestWrapper
, override the header getters to return the parameters as well:
public class AddParamsToHeader extends HttpServletRequestWrapper {
public AddParamsToHeader(HttpServletRequest request) {
super(request);
}
public String getHeader(String name) {
String header = super.getHeader(name);
return (header != null) ? header : super.getParameter(name); // Note: you can't use getParameterValues() here.
}
public Enumeration getHeaderNames() {
List<String> names = Collections.list(super.getHeaderNames());
names.addAll(Collections.list(super.getParameterNames()));
return Collections.enumeration(names);
}
}
..and wrap the original request with it:
chain.doFilter(new AddParamsToHeader((HttpServletRequest) request), response);
That said, I personally find this a bad idea. Rather give it direct access to the parameters or pass the parameters to it.
You can write a method that takes the type as a generic parameter:
void GenericProcessMessage<T>(T message)
{
MessageProcessor<T> processor = messageProcessors[typeof(T)]
as MessageProcessor<T>;
// Call method processor or whatever you need to do
}
Then you need a way to call the method with the correct generic argument. You can do this with reflection:
public void ProcessMessage(object message)
{
Type messageType = message.GetType();
MethodInfo method = this.GetType().GetMethod("GenericProcessMessage");
MethodInfo closedMethod = method.MakeGenericMethod(messageType);
closedMethod.Invoke(this, new object[] {message});
}
Simple and neat with fontawesome
input[type=radio] {
-moz-appearance: none;
-webkit-appearance: none;
-o-appearance: none;
outline: none;
content: none;
margin-left: 5px;
}
input[type=radio]:before {
font-family: "FontAwesome";
content: "\f00c";
font-size: 25px;
color: transparent !important;
background: #fff;
width: 25px;
height: 25px;
border: 2px solid black;
margin-right: 5px;
}
input[type=radio]:checked:before {
color: black !important;
}
The best solution is probably: use Modernizr.
However, if you necessarily want to use $.browser property, you can do it using jQuery Migrate plugin (for JQuery >= 1.9 - in earlier versions you can just use it) and then do something like:
if($.browser.chrome) {
alert(1);
} else if ($.browser.mozilla) {
alert(2);
} else if ($.browser.msie) {
alert(3);
}
And if you need for some reason to use navigator.userAgent, then it would be:
$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
$.browser.mozilla = /firefox/.test(navigator.userAgent.toLowerCase());
If you want to use the Create Aggregate function in SQL Server, this is how to do it. Doing it this way has the benefit of being able to write clean queries. Note this this process could be adapted to calculate a Percentile value fairly easily.
Create a new Visual Studio project and set the target framework to .NET 3.5 (this is for SQL 2008, it may be different in SQL 2012). Then create a class file and put in the following code, or c# equivalent:
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.IO
<Serializable>
<SqlUserDefinedAggregate(Format.UserDefined, IsInvariantToNulls:=True, IsInvariantToDuplicates:=False, _
IsInvariantToOrder:=True, MaxByteSize:=-1, IsNullIfEmpty:=True)>
Public Class Median
Implements IBinarySerialize
Private _items As List(Of Decimal)
Public Sub Init()
_items = New List(Of Decimal)()
End Sub
Public Sub Accumulate(value As SqlDecimal)
If Not value.IsNull Then
_items.Add(value.Value)
End If
End Sub
Public Sub Merge(other As Median)
If other._items IsNot Nothing Then
_items.AddRange(other._items)
End If
End Sub
Public Function Terminate() As SqlDecimal
If _items.Count <> 0 Then
Dim result As Decimal
_items = _items.OrderBy(Function(i) i).ToList()
If _items.Count Mod 2 = 0 Then
result = ((_items((_items.Count / 2) - 1)) + (_items(_items.Count / 2))) / 2@
Else
result = _items((_items.Count - 1) / 2)
End If
Return New SqlDecimal(result)
Else
Return New SqlDecimal()
End If
End Function
Public Sub Read(r As BinaryReader) Implements IBinarySerialize.Read
'deserialize it from a string
Dim list = r.ReadString()
_items = New List(Of Decimal)
For Each value In list.Split(","c)
Dim number As Decimal
If Decimal.TryParse(value, number) Then
_items.Add(number)
End If
Next
End Sub
Public Sub Write(w As BinaryWriter) Implements IBinarySerialize.Write
'serialize the list to a string
Dim list = ""
For Each item In _items
If list <> "" Then
list += ","
End If
list += item.ToString()
Next
w.Write(list)
End Sub
End Class
Then compile it and copy the DLL and PDB file to your SQL Server machine and run the following command in SQL Server:
CREATE ASSEMBLY CustomAggregate FROM '{path to your DLL}'
WITH PERMISSION_SET=SAFE;
GO
CREATE AGGREGATE Median(@value decimal(9, 3))
RETURNS decimal(9, 3)
EXTERNAL NAME [CustomAggregate].[{namespace of your DLL}.Median];
GO
You can then write a query to calculate the median like this: SELECT dbo.Median(Field) FROM Table
Culture can be changed for a specific cell in grid view.
<%# DateTime.ParseExact(Eval("contractdate", "{0}"), "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture) %>
For more detail check the link.
The JDK provides
Collections.unmodifiableXXX
methods, but in our opinion, these can be unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.
Use @obstart
or try to use Java Script
put your obstart();
into your top of the page
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit();
}
If you use Javascript
Use window.location.href
window.location.href example:
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
echo "<script type='text/javascript'>window.location.href = 'page1.php';</script>"
exit();
}
I've found this is often a misnaming error, if you install from a package manager you bin may be called nodejs so you just need to symlink it like so
ln -s /usr/bin/nodejs /usr/bin/node
You could put a crontab file in /etc/cron.d
which would run a script that would run your command and then delete the crontab file in /etc/cron.d
. Of course, that means your script would need to run as root.
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName();
and hit return.
The above steps
conda install -c conda-forge tensorflow
will work for Windows 10 as well but the Python version should be 3.5 or above. I have used it with Anaconda Python version 3.6 as the protocol buffer format it refers to available on 3.5 or above. Thanks, Sandip
Well you can achieve this using Color State Resource. If you notice inside your NavigationView
you're using
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
Here instead of using @color/black
or @color/primary_test
, use a Color State List Resource
. For that, first create a new xml
(e.g drawer_item.xml) inside color
directory (which should be inside res
directory.) If you don't have a directory named color
already, create one.
Now inside drawer_item.xml
do something like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="checked state color" android:state_checked="true" />
<item android:color="your default color" />
</selector>
Final step would be to change your NavigationView
<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/drawer_item" // notice here
app:itemTextColor="@color/drawer_item" // and here
app:itemBackground="@android:color/transparent"// and here for setting the background color to tranparent
app:menu="@menu/menu_drawer">
Like this you can use separate Color State List Resources for IconTint
, ItemTextColor
, ItemBackground
.
Now when you set an item as checked (either in xml
or programmatically), the particular item will have different color than the unchecked ones.
Synchronized Vs Atomic Vs Volatile:
Please correct me if anything i missed.
Here is a new one (Note: in Tech Preview stage): http://www.dot42.com
It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.
Disclosure: I work for this company
UPDATE: all sources are now on https://github.com/dot42
What I normally do, similar to answer one:
var response = await httpClient.GetAsync(completeURL); // http://192.168.0.1:915/api/Controller/Object
if (response.IsSuccessStatusCode == true)
{
string res = await response.Content.ReadAsStringAsync();
var content = Json.Deserialize<Model>(res);
// do whatever you need with the JSON which is in 'content'
// ex: int id = content.Id;
Navigate();
return true;
}
else
{
await JSRuntime.Current.InvokeAsync<string>("alert", "Warning, the credentials you have entered are incorrect.");
return false;
}
Where 'model' is your C# model class.
for Lat,Long in zip(Latitudes, Longitudes):
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
A little bit easier and it looks exactly like the button in the form. Just use the input and wrap the anchor tag around it.
<a href="#"><input type="button" value="Button Text"></a>
just to add another solution, particularly useful if you are using the new pandas assessors, other solutions will replace the original pandas and lose the assessors
df.drop(df.loc[df['line_race']==0].index, inplace=True)
Clearing Cache solved the issue for me or you can open it in another browser
function myFun() {
$('h2').html("H999999");
}
<html>
<head>
<title>Reader</title>
</head>
<body>
<h2>${message}</h2>
<button id="hi" onclick="myFun();" type="submit">Hi</button>
</body>
</html>
select.list1 option.option2
{
background-color: #007700;
}
_x000D_
<select class="list1">
<option value="1">Option 1</option>
<option value="2" class="option2">Option 2</option>
</select>
_x000D_
In mvc 4 Could be rendered with Underscore(" _ ")
Razor:
@Html.ActionLink("Vote", "#", new { id = item.FileId, }, new { @class = "votes", data_fid = item.FileId, data_jid = item.JudgeID, })
Rendered Html
<a class="votes" data-fid="18587" data-jid="9" href="/Home/%23/18587">Vote</a>
As discussed in this RFE and its comments, you could call tempDir.delete()
first. Or you could use System.getProperty("java.io.tmpdir")
and create a directory there. Either way, you should remember to call tempDir.deleteOnExit()
, or the file won't be deleted after you're done.
Padding a UILabel
, full solution. Updated for 2021.
It turns out there are three things that must be done.
In the typical example below, the text unit is in a table view, stack view or similar construction, which gives it a fixed width. In the example we want padding of 60,20,20,24.
Thus, we take the "existing" intrinsicContentSize and actually add 80 to the height.
You have to literally "get" the height calculated "so far" by the engine, and change that value.
I find that process confusing, but, that is how it works. For me, Apple should expose a call named something like "preliminary height calculation".
Secondly we have to actually use the textRect#forBounds call with our new smaller size.
So in textRect#forBounds we first make the size smaller and then call super.
If you carefully investigate all the attempts and discussion on this page, that is the exact problem.
Notice some solutions "seem to usually work". This is indeed the exact reason - confusingly you must "call super afterwards", not before.
If you call super "in the wrong order", it usually works, but fails for certain specific text lengths.
Here is an exact visual example of "incorrectly doing super first":
Notice the 60,20,20,24 margins are correct BUT the size calculation is actually wrong, because it was done with the "super first" pattern in textRect#forBounds.
Fixed:
Only now does the textRect#forBounds engine know how to do the calculation properly:
Finally!
Again, in this example the UILabel is being used in the typical situation where width is fixed. So in intrinsicContentSize we have to "add" the overall extra height we want. (You don't need to "add" in any way to the width, that would be meaningless as it is fixed.)
Then in textRect#forBounds you get the bounds "suggested so far" by autolayout, you subtract your margins, and only then call again to the textRect#forBounds engine, that is to say in super, which will give you a result.
Finally and simply in drawText you of course draw in that same smaller box.
Phew!
let UIEI = UIEdgeInsets(top: 60, left: 20, bottom: 20, right: 24) // as desired
override var intrinsicContentSize:CGSize {
numberOfLines = 0 // don't forget!
var s = super.intrinsicContentSize
s.height = s.height + UIEI.top + UIEI.bottom
s.width = s.width + UIEI.left + UIEI.right
return s
}
override func drawText(in rect:CGRect) {
let r = rect.inset(by: UIEI)
super.drawText(in: r)
}
override func textRect(forBounds bounds:CGRect,
limitedToNumberOfLines n:Int) -> CGRect {
let b = bounds
let tr = b.inset(by: UIEI)
let ctr = super.textRect(forBounds: tr, limitedToNumberOfLines: 0)
// that line of code MUST be LAST in this function, NOT first
return ctr
}
Once again. Note that the answers on this and other QA that are "almost" correct suffer the problem in the first image above - the "super is in the wrong place". You must force the size bigger in intrinsicContentSize and then in textRect#forBounds you must first shrink the first-suggestion bounds and then call super.
That's the secret.
Note that you do not need to and should not need to additionally call invalidate, sizeThatFits, needsLayout or any other forcing call. A correct solution should work properly in the normal autolayout draw cycle.
My issue was having multiple AWS credentials; default and dev. Since I was trying to deploy to dev this worked:
$(aws ecr get-login --no-include-email --region eu-west-1 --profile dev | sed 's|https://||')
In my opinion this is great solution:
interface PersonRepository extends Repository<Person, UUID> {
<T> Collection<T> findByLastname(String lastname, Class<T> type);
}
and using it like so
void someMethod(PersonRepository people) {
Collection<Person> aggregates =
people.findByLastname("Matthews", Person.class);
Collection<NamesOnly> aggregates =
people.findByLastname("Matthews", NamesOnly.class);
}