One simple way is to wrap your Spinner + Drop Down Arrow Image inside a Layout. Set the background of Spinner as transparent so that the default arrow icon gets hidden. Something like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/background"
android:orientation="horizontal">
<Spinner
android:id="@+id/spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="4"
android:gravity="center"
android:background="@android:color/transparent"
android:spinnerMode="dropdown" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:onClick="showDropDown"
android:src="@drawable/ic_chevron_down_blue" />
</LinearLayout>
Here background.xml is a drawable to produce a box type background.
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<corners android:radius="2dp" />
<stroke
android:width="1dp"
android:color="#BDBDBD" />
</shape>
The above code produces this type of a Spinner and icon.
Sublime Text -> Preferences -> Setting:
Write your style in right screen:
The case
values are just codeless "goto" points that can share the same entry point:
case text1:
case text4:
//blah
break;
Note that the braces are redundant.
My mongo (3.2.9) was installed on Ubuntu, and my log file had the following lines:
2016-09-28T11:32:07.821+0100 E STORAGE [initandlisten] WiredTiger (13) [1475058727:821829][6785:0x7fa9684ecc80], file:WiredTiger.wt, connection: /var/lib/mongodb/WiredTiger.turtle: handle-open: open: Permission denied
2016-09-28T11:32:07.822+0100 I - [initandlisten] Assertion: 28595:13: Permission denied
2016-09-28T11:32:07.822+0100 I STORAGE [initandlisten] exception in initAndListen: 28595 13: Permission denied, terminating
2016-09-28T11:32:07.822+0100 I CONTROL [initandlisten] dbexit: rc: 100
So the problem was in permissions on /var/lib/mongodb folder.
sudo chown -R mongodb:mongodb /var/lib/mongodb/
sudo chmod -R 755 /var/lib/mongodb
Fixed it, although I do realise that may be not too secure (it's my own dev box I'm in my case), bit following the change both db and authentication worked.
No need to pass anything in. The function used for addEventListener
will automatically have this
bound to the current element. Simply use this
in your function:
productLineSelect.addEventListener('change', getSelection, false);
function getSelection() {
var value = this.options[this.selectedIndex].value;
alert(value);
}
Here's the fiddle: http://jsfiddle.net/dJ4Wm/
If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:
productLineSelect.addEventListener('change', function() {
foo('bar');
}, false);
function foo(message) {
alert(message);
}
Here's the fiddle: http://jsfiddle.net/t4Gun/
If you want to set the value of this
manually, you can use the call
method to call the function:
var self = this;
productLineSelect.addEventListener('change', function() {
getSelection.call(self);
// This'll set the `this` value inside of `getSelection` to `self`
}, false);
function getSelection() {
var value = this.options[this.selectedIndex].value;
alert(value);
}
In order to remove any URL within a string in Python, you can use this RegEx function :
import re
def remove_URL(text):
"""Remove URLs from a text string"""
return re.sub(r"http\S+", "", text)
You can use following as well
<string name="spelatonertext3"> "-4, 5, -5, 6, -6, "> </string>
Put anything in " "
(quotation) with space, and it should work
Simple to me is like this:
$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables
If you have a lot of columns, then create a variable like $NewRow
like:
$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).
$NewRow | Add-Content -Path $File # Keep no space between content variables
Please note the difference between Set-Content
(overwrites the existing contents) and Add-Content
(appends to the existing contents) of the file.
For Asp.Net MVC
@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList,
new {
@class = "chosen-select form-control"
})
or
@Html.ListBoxFor(model => model.parameterName,
ViewBag.ParameterValueList as MultiSelectList,
new{
data_placeholder = "Select Options ",
@class = "chosen-select form-control"
})
We can also use Exists
:
string[] array = { "cat", "dog", "perl" };
// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perl");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));
You might find this wiki article interesting : http://ajaxpatterns.org/On-Demand_Javascript
It explains how and when to use such technique.
Handles spaces in filenames well — not that you should use those!
$ find . -type f -not -path '*/\.*' -printf '%TY.%Tm.%Td %THh%TM %Ta %p\n' |sort -nr |head -n 10
2017.01.28 07h00 Sat ./recent
2017.01.21 10h49 Sat ./hgb
2017.01.16 07h44 Mon ./swx
2017.01.10 18h24 Tue ./update-stations
2017.01.09 10h38 Mon ./stations.json
More find
galore can be found by following the link.
Try this
string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };
var t = lines.ToList().Find(c => c.Contains(stringToCheck));
It will return you the line with the first incidence of the text that you are looking for.
Perhaps using the "~" selector of CSS?
.myclass {
background: red;
}
.myclass~.myclass {
background: yellow;
}
.myclass~.myclass~.myclass {
background: green;
}
See my example on jsfiddle
Here is a simple clean implementation which is consistent with Pattern#split
and works with variable length patterns, which look behind cannot support, and it is easier to use. It is similar to the solution provided by @cletus.
public static String[] split(CharSequence input, String pattern) {
return split(input, Pattern.compile(pattern));
}
public static String[] split(CharSequence input, Pattern pattern) {
Matcher matcher = pattern.matcher(input);
int start = 0;
List<String> result = new ArrayList<>();
while (matcher.find()) {
result.add(input.subSequence(start, matcher.start()).toString());
result.add(matcher.group());
start = matcher.end();
}
if (start != input.length()) result.add(input.subSequence(start, input.length()).toString());
return result.toArray(new String[0]);
}
I don't do null checks here, Pattern#split
doesn't, why should I. I don't like the if
at the end but it is required for consistency with the Pattern#split
. Otherwise I would unconditionally append, resulting in an empty string as the last element of the result if the input string ends with the pattern.
I convert to String[] for consistency with Pattern#split
, I use new String[0]
rather than new String[result.size()]
, see here for why.
Here are my tests:
@Test
public void splitsVariableLengthPattern() {
String[] result = Split.split("/foo/$bar/bas", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "/foo/", "$bar", "/bas" }, result);
}
@Test
public void splitsEndingWithPattern() {
String[] result = Split.split("/foo/$bar", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "/foo/", "$bar" }, result);
}
@Test
public void splitsStartingWithPattern() {
String[] result = Split.split("$foo/bar", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "", "$foo", "/bar" }, result);
}
@Test
public void splitsNoMatchesPattern() {
String[] result = Split.split("/foo/bar", "\\$\\w+");
Assert.assertArrayEquals(new String[] { "/foo/bar" }, result);
}
You can use the explode
function, using "\n
" as separator:
$your_array = explode("\n", $your_string_from_db);
For instance, if you have this piece of code:
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
var_dump($arr);
You'd get this output:
array
0 => string 'My text1' (length=8)
1 => string 'My text2' (length=8)
2 => string 'My text3' (length=8)
Note that you have to use a double-quoted string, so \n
is actually interpreted as a line-break.
(See that manual page for more details.)
var arr = new Array();
$('li').each(function() {
arr.push(this.innerHTML);
})
In Colum widget Text alignment will be centred automatically, so use crossAxisAlignment: CrossAxisAlignment.start
to align start.
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(""),
Text(""),
]);
Your logic is correct but you have 2 mistakes apparently everyone missed:
just change if(Number(i) = 'NaN')
to if(Number(i) == NaN)
NaN
is a constant and you should use double equality signs to compare, a single one is used to assign values to variables.
I want to leave this here because I struggled with this when compiling for Android in Windows with the Android SDK.
CMake distinguishes between TARGET and HOST platform.
My TARGET was Android so the variables like CMAKE_SYSTEM_NAME had the value "Android" and the variable WIN32 from the other answer here was not defined. But I wanted to know if my HOST system was Windows because I needed to do a few things differently when compiling on either Windows or Linux or IOs. To do that I used CMAKE_HOST_SYSTEM_NAME which I found is barely known or mentioned anywhere because for most people TARGEt and HOST are the same or they don't care.
Hope this helps someone somewhere...
If you don't like libraries, how about this?
Note that you should not use this function on the whole URL, instead you should use this on the components...e.g. just the "a b" component, as you build up the URL - otherwise the computer won't know what characters are supposed to have a special meaning and which ones are supposed to have a literal meaning.
/** Converts a string into something you can safely insert into a URL. */
public static String encodeURIcomponent(String s)
{
StringBuilder o = new StringBuilder();
for (char ch : s.toCharArray()) {
if (isUnsafe(ch)) {
o.append('%');
o.append(toHex(ch / 16));
o.append(toHex(ch % 16));
}
else o.append(ch);
}
return o.toString();
}
private static char toHex(int ch)
{
return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private static boolean isUnsafe(char ch)
{
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
}
Since you already have <Tags>
component calling a function on its parent, you do not need additional state: simply pass the filter to the <Tags>
component as a prop, and use this in rendering your buttons. Like so:
Change your render function inside your <Tags>
component to:
render: function() {
return <div className = "tags">
<button className = {this._checkActiveBtn('')} onClick = {this.setFilter.bind(this, '')}>All</button>
<button className = {this._checkActiveBtn('male')} onClick = {this.setFilter.bind(this, 'male')}>male</button>
<button className = {this._checkActiveBtn('female')} onClick = {this.setFilter.bind(this, 'female')}>female</button>
<button className = {this._checkActiveBtn('blonde')} onClick = {this.setFilter.bind(this, 'blonde')}>blonde</button>
</div>
},
And add a function inside <Tags>
:
_checkActiveBtn: function(filterName) {
return (filterName == this.props.activeFilter) ? "btn active" : "btn";
}
And inside your <List>
component, pass the filter state to the <tags>
component as a prop:
return <div>
<h2>Kids Finder</h2>
<Tags filter = {this.state.filter} onChangeFilter = {this.changeFilter} />
{list}
</div>
Then it should work as intended. Codepen here (hope the link works)
First of all, remove video's "controls" attribute.
For iOS, we could hide video's buildin play button by adding the following CSS pseudo selector:
video::-webkit-media-controls-start-playback-button {
display: none;
}
Just cast one of the two operands to a float first.
v = (float)s / t;
The cast has higher precedence than the division, so happens before the division.
The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. Java Language Specification, §4.2.4 and §15.17
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
The distinction between TO, CC and BCC occurs only in the text headers. At the SMTP level, everybody is a recipient.
TO - There is a TO: header with this recipient's address
CC - There is a CC: header with this recipient's address
BCC - This recipient isn't mentioned in the headers at all, but is still a recipient.
If you have
TO: [email protected]
CC: [email protected]
BCC: [email protected]
You have three recipients. The headers in the email body will include only the TO: and CC:
You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.
Here you can find a nice tutorial (for MonoTouch, but you can use the information for Non-MonoTouch-projects, too):
http://redth.info/get-your-monotouch-apps-ready-for-iphone-5-ios-6-today/
Create a new image for your splash/default screen (640 x 1136 pixel) with the name "[email protected]"
In the iOS Simulator, go to the Hardware -> Device menu, and select "iPhone (Retina 4-inch)"
Create other images, e.g. background images
public static bool IsTall
{
get {
return UIDevice.currentDevice.userInterfaceIdiom
== UIUserInterfaceIdiomPhone
&& UIScreen.mainScreen.bounds.size.height
* UIScreen.mainScreen.scale >= 1136;
}
}
private static string tallMagic = "-568h@2x";
public static UIImage FromBundle16x9(string path)
{
//adopt the -568h@2x naming convention
if(IsTall())
{
var imagePath = Path.GetDirectoryName(path.ToString());
var imageFile = Path.GetFileNameWithoutExtension(path.ToString());
var imageExt = Path.GetExtension(path.ToString());
imageFile = imageFile + tallMagic + imageExt;
return UIImage.FromFile(Path.Combine(imagePath,imageFile));
}
else
{
return UIImage.FromBundle(path.ToString());
}
}
I had the same problem. I solve it when I convert string to factor. In your case, check the class of variable and check if they are numeric and 'train and test' should be factor.
The practical use of this construct? It is a javascript replaceAll() on strings.
var s = 'stackoverflow_is_cool';
s = s.split('_').join(' ');
console.log(s);
will output:
stackoverflow is cool
If you are using Prototype there is Form.serialize
If you are using jQuery there is Ajax/serialize
I do not know of any independent functions to accomplish this, though, but a google search for it turned up some promising options if you aren't currently using a library. If you're not, though, you really should because they are heaven.
Yes; change your where to be:
where T:BaseFruit, new()
However, this only works with parameterless constructors. You'll have to have some other means of setting your property (setting the property itself or something similar).
For the record, the spring.jpa.hibernate.ddl-auto
property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto
.
The values create
, create-drop
, validate
, and update
basically influence how the schema tool management will manipulate the database schema at startup.
For example, the update
operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.
The update
operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.
Typically in test case scenarios, you'll likely use create-drop
so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.
In development, it's often common to see developers use update
to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.
In production, it's often highly recommended you use none
or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.
one of the easy way to do that is use landa function without any problem like
userControl_Material1.simpleButton4.Click += (s, ee) =>
{
Save_mat(mat_global);
};
To add to the current answers, here is a playlist of videos which works with separate subtitle files. At the end of the playlist, it will go to endPage
<video id="video" controls autoplay preload="metadata">
<source src="vid1.mp4" type="mp4">
<track id="subs" label="English" kind="subtitles" srclang="en" src="sub1.vtt" default>
</video>
<script type="text/javascript">
var endPage = "duckduckgo.com";
var playlist = [
{
'file': 'vid2.mp4',
'subtitle': 'sub2.vtt'
},{
'file': 'vid3.mp4',
'subtitle': 'sub3.vtt'
}
]
var i = 0;
var videoPlayer = document.getElementById('video');
var subtitles = document.getElementById('subs');
videoPlayer.onended = function(){
if(i < playlist.length){
videoPlayer.src = playlist[i].file;
subtitles.src = playlist[i].subtitle;
i++;
} else {
console.log("We are leaving")
document.location.href = endPage;
}
}
</script>
You've already done it correctly by using a DateTime
parameter with the value from the DateTime
, so it should already work. Forget about ToString()
- since that isn't used here.
If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).
I have a table and the date-times in it are in the format:
2011-07-01 15:17:33.357
Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281
. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
I tried doing something similar, which took me a lot of time before I could figure out the collect() function. So you can have something this way:
collect($items)->sum('amount');
This will give you the sum total of all the items.
In Visual Studio 2017 with a .NET Core console application do the following:
Right click on the Project in the Solution window, select "Properties", Debug (on the left side), and enter the arguments into the field "Application Arguments".
Note that they should be space-separated.
It depends on how you access the data:
Go for Option 1:
Go for Option 2:
P.S.: As a rule of the thumb, go for the option which requires fewer queries on most of your use cases.
I was having this same issue - I am using Selectize with Rails and wanted to Selectize an association field - I wanted the name of the associated record to show up in the dropdown, but I needed the value of each option to be the id of the record, since Rails uses the value
to set associations.
I solved this by setting a coffeescript var of @valueAttr
to the id
of each object and a var of @dataAttr
to the name
of the record. Then I went through each option and set:
opts.labelField = @dataAttr
opts.valueField = @valueAttr
It helps to see the full diff: https://github.com/18F/C2/pull/912/files
Make it simply use: PDO::lastInsertId
If no other option in this thread works, you can try the steps given in this guide (see below): https://blogs.msdn.microsoft.com/heaths/2015/07/14/how-to-install-visual-studio-to-another-directory-when-a-pre-release-is-installed/
Open an elevated PowerShell command prompt and run the following to discover which products have installed the key shared component:
get-msicomponentinfo '{777CBCAC-12AB-4A57-A753-4A7D23B484D3}' | get-msiproductinfo
If you’re fine with uninstalling all the listed products (especially given that you’re probably going to install RTM next), run the following:
get-msicomponentinfo '{777CBCAC-12AB-4A57-A753-4A7D23B484D3}' | get-msiproductinfo | uninstall-msiproduct -properties IGNOREDEPENDENCIES=ALL
Personally, this worked for me. I forgot that I had some old files laying around on an old drive, which appearantly later on messed something up in the registry (I think..?). Anyway, with everything clean, it installed just fine!
Note: if you have issues with importing the PSMSI-tools in PowerShell, check this out: https://msdn.microsoft.com/en-us/library/dn568022.aspx
In summary, you may need to run the command
Set-ExecutionPolicy RemoteSigned
to be allowed to import the software.
Hope this helps someone in need!
It should be legal to put a semicolon directly before the WITH keyword.
The solution for me was:
<mat-form-field>
<mat-select #monedaSelect formControlName="monedaDebito" [attr.disabled]="isLoading" [placeholder]="monedaLabel | async ">
<mat-option *ngFor="let moneda of monedasList" [value]="moneda.id">{{moneda.detalle}}</mat-option>
</mat-select>
TS:
@ViewChild('monedaSelect') public monedaSelect: MatSelect;
this.genericService.getOpciones().subscribe(res => {
this.monedasList = res;
this.monedaSelect._onChange(res[0].id);
});
Using object: {id: number, detalle: string}
If you add to RelativeLayout, don't forget to set imageView's position. For instance:
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(200, 200);
lp.addRule(RelativeLayout.CENTER_IN_PARENT); // A position in layout.
ImageView imageView = new ImageView(this); // initialize ImageView
imageView.setLayoutParams(lp);
// imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(R.drawable.photo);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
layout.addView(imageView);
EDIT: several years since this question was first answered, as noted in a newer answer, there is now a command for this:
nvm now has a command to update npm. It's
nvm install-latest-npm
ornvm install --latest-npm
.
nvm install-latest-npm
: Attempt to upgrade to the latest working npm
on the current node version
nvm install --latest-npm
: After installing, attempt to upgrade to the latest working npm on the given node version
Below are previous revisions of the correct answer to this question.
Over three years after this question was first asked, it seems like the answer is much simpler now. Just update the version that nvm installed, which lives in ~/.nvm/versions/node/[your-version]/lib/node_modules/npm
.
I just installed node 4.2.2, which comes with npm 2.14.7, but I want to use npm 3. So I did:
cd ~/.nvm/versions/node/v4.2.2/lib
npm install npm
Easy!
And yes, this should work for any module, not just npm, that you want to be "global" for a specific version of node.
EDIT 1: In the newest version, npm -g
is smart and installs modules into the path above instead of the system global path.
Thanks @philraj for pointing this out in a comment.
It fails "when trying to execute the function manually
" because you have a different 'this'. This will refer not to the thing you have in mind when invoking the method manually, but something else, probably the window object, or whatever context object you have when invoking manually.
This is kind of overkill but let's give it a go. First lets use statsmodel to find out what the p-values should be
import pandas as pd
import numpy as np
from sklearn import datasets, linear_model
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
from scipy import stats
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
X2 = sm.add_constant(X)
est = sm.OLS(y, X2)
est2 = est.fit()
print(est2.summary())
and we get
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.518
Model: OLS Adj. R-squared: 0.507
Method: Least Squares F-statistic: 46.27
Date: Wed, 08 Mar 2017 Prob (F-statistic): 3.83e-62
Time: 10:08:24 Log-Likelihood: -2386.0
No. Observations: 442 AIC: 4794.
Df Residuals: 431 BIC: 4839.
Df Model: 10
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 152.1335 2.576 59.061 0.000 147.071 157.196
x1 -10.0122 59.749 -0.168 0.867 -127.448 107.424
x2 -239.8191 61.222 -3.917 0.000 -360.151 -119.488
x3 519.8398 66.534 7.813 0.000 389.069 650.610
x4 324.3904 65.422 4.958 0.000 195.805 452.976
x5 -792.1842 416.684 -1.901 0.058 -1611.169 26.801
x6 476.7458 339.035 1.406 0.160 -189.621 1143.113
x7 101.0446 212.533 0.475 0.635 -316.685 518.774
x8 177.0642 161.476 1.097 0.273 -140.313 494.442
x9 751.2793 171.902 4.370 0.000 413.409 1089.150
x10 67.6254 65.984 1.025 0.306 -62.065 197.316
==============================================================================
Omnibus: 1.506 Durbin-Watson: 2.029
Prob(Omnibus): 0.471 Jarque-Bera (JB): 1.404
Skew: 0.017 Prob(JB): 0.496
Kurtosis: 2.726 Cond. No. 227.
==============================================================================
Ok, let's reproduce this. It is kind of overkill as we are almost reproducing a linear regression analysis using Matrix Algebra. But what the heck.
lm = LinearRegression()
lm.fit(X,y)
params = np.append(lm.intercept_,lm.coef_)
predictions = lm.predict(X)
newX = pd.DataFrame({"Constant":np.ones(len(X))}).join(pd.DataFrame(X))
MSE = (sum((y-predictions)**2))/(len(newX)-len(newX.columns))
# Note if you don't want to use a DataFrame replace the two lines above with
# newX = np.append(np.ones((len(X),1)), X, axis=1)
# MSE = (sum((y-predictions)**2))/(len(newX)-len(newX[0]))
var_b = MSE*(np.linalg.inv(np.dot(newX.T,newX)).diagonal())
sd_b = np.sqrt(var_b)
ts_b = params/ sd_b
p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-len(newX[0])))) for i in ts_b]
sd_b = np.round(sd_b,3)
ts_b = np.round(ts_b,3)
p_values = np.round(p_values,3)
params = np.round(params,4)
myDF3 = pd.DataFrame()
myDF3["Coefficients"],myDF3["Standard Errors"],myDF3["t values"],myDF3["Probabilities"] = [params,sd_b,ts_b,p_values]
print(myDF3)
And this gives us.
Coefficients Standard Errors t values Probabilities
0 152.1335 2.576 59.061 0.000
1 -10.0122 59.749 -0.168 0.867
2 -239.8191 61.222 -3.917 0.000
3 519.8398 66.534 7.813 0.000
4 324.3904 65.422 4.958 0.000
5 -792.1842 416.684 -1.901 0.058
6 476.7458 339.035 1.406 0.160
7 101.0446 212.533 0.475 0.635
8 177.0642 161.476 1.097 0.273
9 751.2793 171.902 4.370 0.000
10 67.6254 65.984 1.025 0.306
So we can reproduce the values from statsmodel.
Should it be LIBRARY_PATH
instead of LD_LIBRARY_PATH
.
gcc checks for LIBRARY_PATH
which can be seen with -v
option
You could finish your Activity by calling Activity.finish(). However take care of the Android Activity life-cycle.
You have included a dependency on the SLF4J API, which is what you use in your application for logging, but you must also include an implementation that does the real logging work.
For example to log through Log4J you would add this dependency:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.2</version>
</dependency>
The recommended implementation would be logback-classic, which is the successor of Log4j, made by the same guys that made SLF4J and Log4J:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.24</version>
</dependency>
Note: The versions may be incorrect.
An extensionmethod like this would do it...
public static bool In<T>(this T item, params T[] items)
{
return items.Contains(item);
}
Use it like this:
Console.WriteLine(1.In(1,2,3));
Console.WriteLine("a".In("a", "b"));
.aar is a standard zip archive, the same one used in .jar. Just change the extension and, assuming it's not corrupt or anything, it should be fine.
If you needed to, you could extract it to your filesystem and then repackage it as a jar.
1) Rename it to .jar
2) Extract: jar xf filename.jar
3) Repackage: jar cf output.jar input-file(s)
You can load the content from the file. Consider the file is present in asset folder.
public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
AssetManager am = context.getAssets();
try {
InputStream is = am.open(fileName);
return is;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String loadContentFromFile(Context context, String path){
String content = null;
try {
InputStream is = loadInputStreamFromAssetFile(context, path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return content;
}
Now you can get the content by calling the function as follow
String json= FileUtil.loadContentFromFile(context, "data.json");
Considering the data.json is stored at Application\app\src\main\assets\data.json
Cloudera and Hortonworks are the best tools to start up with the HDFS in Microsoft Windows. You can also use VMWare or VBox to initiate Virtual Machine to establish build to your HDFS and Spark, Hive, HBase, Pig, Hadoop with Scala, R, Java, Python.
You can't download the file directly via ajax.
You can put a link on the page with the URL to your file (returned from the ajax call) or another way is to use a hidden iframe
and set the URL of the source of that iframe
dynamically. This way you can download the file without refreshing the page.
Here is the code
$.ajax({
url : "yourURL.php",
type : "GET",
success : function(data) {
$("#iframeID").attr('src', 'downloadFileURL');
}
});
This is also working both the filter and normal list. The first thing to create a new filter for the sum of all values from the list, and also given solution for a sum of the total quantity. In details code check it fiddler link.
angular.module("sampleApp", [])
.filter('sumOfValue', function () {
return function (data, key) {
if (angular.isUndefined(data) || angular.isUndefined(key))
return 0;
var sum = 0;
angular.forEach(data,function(value){
sum = sum + parseInt(value[key], 10);
});
return sum;
}
}).filter('totalSumPriceQty', function () {
return function (data, key1, key2) {
if (angular.isUndefined(data) || angular.isUndefined(key1) || angular.isUndefined(key2))
return 0;
var sum = 0;
angular.forEach(data,function(value){
sum = sum + (parseInt(value[key1], 10) * parseInt(value[key2], 10));
});
return sum;
}
}).controller("sampleController", function ($scope) {
$scope.items = [
{"id": 1,"details": "test11","quantity": 2,"price": 100},
{"id": 2,"details": "test12","quantity": 5,"price": 120},
{"id": 3,"details": "test3","quantity": 6,"price": 170},
{"id": 4,"details": "test4","quantity": 8,"price": 70}
];
});
<div ng-app="sampleApp">
<div ng-controller="sampleController">
<div class="col-md-12 col-lg-12 col-sm-12 col-xsml-12">
<label>Search</label>
<input type="text" class="form-control" ng-model="searchFilter" />
</div>
<div class="col-md-12 col-lg-12 col-sm-12 col-xsml-12">
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2">
<h4>Id</h4>
</div>
<div class="col-md-4 col-lg-4 col-sm-4 col-xsml-4">
<h4>Details</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>Quantity</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>Price</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>Total</h4>
</div>
<div ng-repeat="item in resultValue=(items | filter:{'details':searchFilter})">
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2">{{item.id}}</div>
<div class="col-md-4 col-lg-4 col-sm-4 col-xsml-4">{{item.details}}</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">{{item.quantity}}</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">{{item.price}}</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">{{item.quantity * item.price}}</div>
</div>
<div colspan='3' class="col-md-8 col-lg-8 col-sm-8 col-xsml-8 text-right">
<h4>{{resultValue | sumOfValue:'quantity'}}</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>{{resultValue | sumOfValue:'price'}}</h4>
</div>
<div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
<h4>{{resultValue | totalSumPriceQty:'quantity':'price'}}</h4>
</div>
</div>
</div>
</div>
check this Fiddle Link
I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().
// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();
These methods can also be called on a Collection for example
// <= Laravel 5.1
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->lists('word_one');
// >= Laravel 5.2
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->pluck('word_one');
You can place an AP overlay like...
#overlay {
position: absolute;
top: -79px;
left: -60px;
height: 80px;
width: 380px;
z-index: 2;
background: url(fake.gif);
}
<div id="overlay"></div>
just put it over where you dont want ie cliked. Works in all.
Simple version:
for /F "delims==, tokens=4" %a IN ('ping -n 2 127.0.0.1 ^| findstr /R "^Packets: Sent =.$"') DO (
if %a EQU 2 (
echo Success
) ELSE (
echo FAIL
)
)
But sometimes first ping just fail and second one work (or vice versa) right? So we want to get success when at least one ICMP reply has been returned successfully:
for /F "delims==, tokens=4" %a IN ('ping -n 2 192.168.1.1 ^| findstr /R "^Packets: Sent =.$"') DO (
if %a EQU 2 (
echo Success
) ELSE (
if %a EQU 1 (
echo Success
) ELSE (
echo FAIL
)
)
)
You can't use primitive types as generic arguments in Java. Use instead:
Map<String, Integer> myMap = new HashMap<String, Integer>();
With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:
myMap.put("foo", 3);
instead of:
myMap.put("foo", new Integer(3));
Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:
int i = myMap.get("foo");
instead of:
int i = myMap.get("foo").intValue();
The implicit call to intValue()
means if the key isn't found it will generate a NullPointerException
, for example:
int i = myMap.get("bar"); // NullPointerException
The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:
Integer i = (Integer)myMap.get("foo");
To give you an example, this code is perfectly legal:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");
I kept using this all this time
Import-module .\build_functions.ps1 -Force
another option (in place, any combination of indices):
_marker = object()
for i in indices:
my_list[i] = _marker # marked for deletion
obj[:] = [v for v in my_list if v is not _marker]
find location -ctime time_period
Examples of time_period:
More than 30 days ago: -ctime +30
Less than 30 days ago: -ctime -30
Exactly 30 days ago: -ctime 30
with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center
You can use the below statement to get the inserted Id to a variable-like thing.
INSERT INTO YOUR_TABLE(ID) VALUES ('10') returning ID into :Inserted_Value;
Now you can retrieve the value using the below statement
SELECT :Inserted_Value FROM DUAL;
Disabled HTML forms elements aren't sent along with the post/get values when you submit the form. So if you disable your submit button once clicked and that this submit button have the name
attribute set, It will not be sent in the post/get values since the element is now disabled. This is normal behavior.
One of the way to overcome this problem is using hidden form elements.
I doubt the standard library supports this.
But you can use the google maps utility library:
http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker = new MarkerWithLabel({
position: myLatlng,
map: map,
draggable: true,
raiseOnDrag: true,
labelContent: "A",
labelAnchor: new google.maps.Point(3, 30),
labelClass: "labels", // the CSS class for the label
labelInBackground: false
});
The basics about marker can be found here: https://developers.google.com/maps/documentation/javascript/overlays#Markers
on windows: Go to "Add or remove programs" in control panel (or open the start menu and search for "remove program")
Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask
to schedule a task to set a stopExecution
flag, and also .interrupt()
your thread.
With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).
It may be bacause you do not have jre installed. Thus go to http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html and download it.
Something like this might be the easiest way.
<a href="mailto:?subject=I wanted you to see this site&body=Check out this site http://www.website.com."
title="Share by Email">
<img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>
You could find another email image and add that if you wanted.
The syntax '%' in %matplotlib inline
is recognized by iPython (where it is set up to handle the magic methods), but not Python itself, which gives a SyntaxError.
Here is given one solution.
In English:
It's a
List
of some type that extends the classHasWord
, includingHasWord
In general the ?
in generics means any class. And the extends SomeClass
specifies that that object must extend SomeClass
(or be that class).
VBA does not have an internal implementation of a dictionary, but from VBA you can still use the dictionary object from MS Scripting Runtime Library.
Dim d
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "aaa"
d.Add "b", "bbb"
d.Add "c", "ccc"
If d.Exists("c") Then
MsgBox d("c")
End If
The syntax you wrote as first is not valid. You can achieve something using the follow:
var map = {"aaa": "rrr", "bbb": "ppp" /* etc */ };
The server directive has to be in the http directive. It should not be outside of it.
Incase if you need detailed information, refer this.
You need to add the "Maven Dependency" in the Deployment Assembly
Rebuild and deploy again
Note: This is also applicable for non maven project.
The general approach to write to any stream (not only MemoryStream
) is to use BinaryWriter
:
static void Write(Stream s, Byte[] bytes)
{
using (var writer = new BinaryWriter(s))
{
writer.Write(bytes);
}
}
2015 update with dplyr:
df %>% group_by(dive) %>% summarise(percentage = mean(speed))
Source: local data frame [2 x 2]
dive percentage
1 dive1 0.4777462
2 dive2 0.6726483
You can also use Url.Action for the path instead like so:
$.ajax({
url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",
type: "GET",
success: function (partialViewResult) {
$("#refTable").html(partialViewResult);
}
});
Official FAQ ( https://reactjs.org/docs/hooks-faq.html#is-there-something-like-forceupdate ) now recommends this way if you really need to do it:
const [ignored, forceUpdate] = useReducer(x => x + 1, 0);
function handleClick() {
forceUpdate();
}
string filePath = HttpContext.Current.Server.MapPath("~/folderName/filename.extension");
OR
string filePath = HttpContext.Server.MapPath("~/folderName/filename.extension");
You can essentially do this 2 ways:
Add a file called .htaccess
in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:
Put the following in your .htaccess instead: (note the leading slash)
FallbackResource /index.php
This will tell it to run your index.php
for all files it cannot normally find in your site. In there you can then for example:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
if(empty($elements[0])) { // No path elements means home
ShowHomepage();
} else switch(array_shift($elements)) // Pop off first item and switch
{
case 'Some-text-goes-here':
ShowPicture($elements); // passes rest of parameters to internal function
break;
case 'more':
...
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess
will do fine though.
A very simple way to do so with IPython that worked for me in Visual Studio Code is to add the following:
{
"key": "ctrl+space",
"command": "jupyter.runallcells"
}
to the keybindings.json that you can access by typing F1 and 'open keyboard shortcuts'.
-
WHERE SUBSTR('Hello world', -4)
I don't have enough reputation to comment on any answer. In one of the comments, someone has asked how to ignore the hidden folders in the list. Below is how you can do this.
dir /b /AD-H
Here's another one:
PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate
Name LockedOut LastLogonDate
---- --------- -------------
Yxxxxxxx True 14/11/2014 10:19:20
Bxxxxxxx True 18/11/2014 08:38:34
Administrator True 03/11/2014 20:32:05
Other parameters worth mentioning:
Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive
Get-Help Search-ADAccount -ShowWindow
Exit
[construct], and intelisense will tell you which one(s) are valid in a particular place.
Simply quote your variable:
[ -e "$VAR" ]
This evaluates to [ -e "" ]
if $VAR
is empty.
Your version does not work because it evaluates to [ -e ]
. Now in this case, bash simply checks if the single argument (-e
) is a non-empty string.
From the manpage:
test and [ evaluate conditional expressions using a set of rules based on the number of arguments. ...
1 argument
The expression is true if and only if the argument is not null.
(Also, this solution has the additional benefit of working with filenames containing spaces)
This would require a sort (O(n log n)) but is very simple and flexible. Another advantage is being able to use it with LINQ to SQL:
var maxObject = list.OrderByDescending(item => item.Height).First();
Note that this has the advantage of enumerating the list
sequence just once. While it might not matter if list
is a List<T>
that doesn't change in the meantime, it could matter for arbitrary IEnumerable<T>
objects. Nothing guarantees that the sequence doesn't change in different enumerations so methods that are doing it multiple times can be dangerous (and inefficient, depending on the nature of the sequence). However, it's still a less than ideal solution for large sequences. I suggest writing your own MaxObject
extension manually if you have a large set of items to be able to do it in one pass without sorting and other stuff whatsoever (O(n)):
static class EnumerableExtensions {
public static T MaxObject<T,U>(this IEnumerable<T> source, Func<T,U> selector)
where U : IComparable<U> {
if (source == null) throw new ArgumentNullException("source");
bool first = true;
T maxObj = default(T);
U maxKey = default(U);
foreach (var item in source) {
if (first) {
maxObj = item;
maxKey = selector(maxObj);
first = false;
} else {
U currentKey = selector(item);
if (currentKey.CompareTo(maxKey) > 0) {
maxKey = currentKey;
maxObj = item;
}
}
}
if (first) throw new InvalidOperationException("Sequence is empty.");
return maxObj;
}
}
and use it with:
var maxObject = list.MaxObject(item => item.Height);
I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by
method accepts multiple arguments, you could easily chain them:
ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):
>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name
:
>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
...
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)
And now the combined order_by
call:
>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
As you can see it is the same result as the first one, meaning it doesn't work as you would expect.
parseInt()
with radix is a best solution (as was told by many):
But if you want to implement it without parseInt, here is an implementation:
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
If you want to use the same mapping for renaming both columns and index you can do:
mapping = {0:'Date', 1:'SM'}
df.index.names = list(map(lambda name: mapping.get(name, name), df.index.names))
df.rename(columns=mapping, inplace=True)
If you have imported your project from Eclipse.
1. The select project
2. Go to File -> **Project Structure**
3. Select app in **module** section on left hand panel
4. Select **Dependency** tab
5. Your able to see jars you have added in eclipse project for v4 and v13.
6. Remove that jar by clicking on minus sign at bottom after selection
7. Click on Plus sign select **Library Dependency**
8. Choose V4 and V13 if added
9. Press Ok and Clean and Rebuild your project
The scenario I have faced after importing Eclipse project to Android studio.
Hope this helps..
You can use XmlDocument. Also some XPath can be useful.
Just a simple example
XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
// use node variable here for your beeds
}
use $timeout and run a function to search in "results" array
app.controller("Search", function ($scope, $timeout) {
var foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
$timeout(function () {
for (var i = 0; i < foo.results.length; i++) {
if (foo.results[i].id=== 2) {
$scope.name = foo.results[i].name;
}
}
}, 10);
});
You may also use the .jquery property as described here: http://api.jquery.com/jquery-2/
var a = { what: "A regular JS object" },
b = $('body');
if ( a.jquery ) { // falsy, since it's undefined
alert(' a is a jQuery object! ');
}
if ( b.jquery ) { // truthy, since it's a string
alert(' b is a jQuery object! ');
}
You can fix the errors by validating your input, which is something you should do regardless of course.
The following typechecks correctly, via type guarding validations
const DNATranscriber = {
G: 'C',
C: 'G',
T: 'A',
A: 'U'
};
export default class Transcriptor {
toRna(dna: string) {
const codons = [...dna];
if (!isValidSequence(codons)) {
throw Error('invalid sequence');
}
const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
return transcribedRNA;
}
}
function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
return value in DNATranscriber;
}
It is worth mentioning that you seem to be under the misapprehention that converting JavaScript to TypeScript involves using classes.
In the following, more idiomatic version, we leverage TypeScript to improve clarity and gain stronger typing of base pair mappings without changing the implementation. We use a function
, just like the original, because it makes sense. This is important! Converting JavaScript to TypeScript has nothing to do with classes, it has to do with static types.
const DNATranscriber = {
G = 'C',
C = 'G',
T = 'A',
A = 'U'
};
export default function toRna(dna: string) {
const codons = [...dna];
if (!isValidSequence(codons)) {
throw Error('invalid sequence');
}
const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
return transcribedRNA;
}
function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
return value in DNATranscriber;
}
Update:
Since TypeScript 3.7, we can write this more expressively, formalizing the correspondence between input validation and its type implication using assertion signatures.
const DNATranscriber = {
G = 'C',
C = 'G',
T = 'A',
A = 'U'
} as const;
type DNACodon = keyof typeof DNATranscriber;
type RNACodon = typeof DNATranscriber[DNACodon];
export default function toRna(dna: string): RNACodon[] {
const codons = [...dna];
validateSequence(codons);
const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
return transcribedRNA;
}
function validateSequence(values: string[]): asserts values is DNACodon[] {
if (!values.every(isValidCodon)) {
throw Error('invalid sequence');
}
}
function isValidCodon(value: string): value is DNACodon {
return value in DNATranscriber;
}
You can read more about assertion signatures in the TypeScript 3.7 release notes.
add this to your form:
<form id="regform" action="insert.php" method="post">
add this to your function:
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
}
else {
alert("Passwords Match!!!");
document.getElementById("regForm").submit();
}
}
</script>
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
If you are using Jackson, then you can use the @JsonProperty
annotation to customize the name of a given JSON property.
Therefore, you just have to annotate the entity fields with the @JsonProperty
annotation and provide a custom JSON property name, like this:
@Entity
public class City {
@Id
@JsonProperty("value")
private Long id;
@JsonProperty("label")
private String name;
//Getters and setters omitted for brevity
}
JSON-B is the standard binding layer for converting Java objects to and from JSON. If you are using JSON-B, then you can override the JSON property name via the @JsonbProperty
annotation:
@Entity
public class City {
@Id
@JsonbProperty("value")
private Long id;
@JsonbProperty("label")
private String name;
//Getters and setters omitted for brevity
}
Had the same problem when Load external without cache using Javascript
Load external <script> without cache using Javascript
Had a good solution for cache problem here:
But this happend: Uncaught TypeError: Cannot read property 'appendChild' of null.
Here is good explanation: https://stackoverflow.com/a/58824439/14491024
As it said your script tag is in the head, the JavaScript is loaded before your HTML.
In Visual Studio by C# this problem is solved like this by adding Guid:
Here is how it looks in the View page source:
You can consider using the C-Style while
loop instead. This works just fine in Swift 3:
var i = 5
while i > 0 {
print(i)
i -= 1
}
I had read yesterday that the issue was fixed for someone when that person cleared cookies. I had tried that but it did not work for me.
Checking the following section in DatabaseInterface.class.php,
define(
'PMA_MYSQL_INT_VERSION',
PMA_Util::cacheGet('PMA_MYSQL_INT_VERSION', true)
);
I figured that somehow cache is the problem. So, I remembered that I was restarting the service instead of doing a start
and stop
.
# restart the service
systemd restart php-fpm
# start and stop the service
systemd stop php-fpm
systemd start php-fpm
Doing a stop
followed by a start
fixed the issue for me.
I simple add a dupe check as follows:
private void OnChanged(object source, FileSystemEventArgs e)
{
string sTabName = Path.GetFileNameWithoutExtension(e.Name);
string sLastLine = ReadLastLine(e.FullPath);
if(sLastLine != _dupeCheck)
{
TabPage tp = tcLogs.TabPages[sTabName];
TextBox tbLog = (TextBox)tp.Controls[0] as TextBox;
tbLog.Invoke(new Action(() => tbLog.AppendText(sLastLine + Environment.NewLine)));
tbLog.Invoke(new Action(() => tbLog.SelectionStart = tbLog.Text.Length));
tbLog.Invoke(new Action(() => tbLog.ScrollToCaret()));
_dupeCheck = sLastLine;
}
}
public static String ReadLastLine(string path)
{
return ReadLastLine(path, Encoding.Default, "\n");
}
public static String ReadLastLine(string path, Encoding encoding, string newline)
{
int charsize = encoding.GetByteCount("\n");
byte[] buffer = encoding.GetBytes(newline);
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
long endpos = stream.Length / charsize;
for (long pos = charsize; pos < endpos; pos += charsize)
{
stream.Seek(-pos, SeekOrigin.End);
stream.Read(buffer, 0, buffer.Length);
if (encoding.GetString(buffer) == newline)
{
buffer = new byte[stream.Length - stream.Position];
stream.Read(buffer, 0, buffer.Length);
return encoding.GetString(buffer);
}
}
}
return null;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
private const int WM_VSCROLL = 0x115;
private const int SB_BOTTOM = 7;
/// <summary>
/// Scrolls the vertical scroll bar of a multi-line text box to the bottom.
/// </summary>
/// <param name="tb">The text box to scroll</param>
public static void ScrollToBottom(TextBox tb)
{
SendMessage(tb.Handle, WM_VSCROLL, (IntPtr)SB_BOTTOM, IntPtr.Zero);
}
The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename
method. See this deprecation note in the documentation for more detail.
This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg
method.
These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.
Before we get there, let's create a four column DataFrame.
df = pd.DataFrame({'A' : list('wwwwxxxx'),
'B':list('yyzzyyzz'),
'C':np.random.rand(8),
'D':np.random.rand(8)})
A B C D
0 w y 0.643784 0.828486
1 w y 0.308682 0.994078
2 w z 0.518000 0.725663
3 w z 0.486656 0.259547
4 x y 0.089913 0.238452
5 x y 0.688177 0.753107
6 x z 0.955035 0.462677
7 x z 0.892066 0.368850
Let's say we want to group by columns A, B
and aggregate column C
with mean
and median
and aggregate column D
with max
. The following code would do this.
df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})
D C
max mean median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:
df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'},
'D':{'D_max': 'max'}})
D C
D_max C_mean C_median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0)
.
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
check the below code.
Reading from a file in the filesystem.
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
// READ STRING OF UNKNOWN LENGTH
StringBuilder sb = new StringBuilder();
char[] inputBuffer = new char[2048];
int l;
// FILL BUFFER WITH DATA
while ((l = isr.read(inputBuffer)) != -1) {
sb.append(inputBuffer, 0, l);
}
// CONVERT BYTES TO STRING
String readString = sb.toString();
fis.close();
catch (Exception e) {
} finally {
if (fis != null) {
fis = null;
}
}
below code is to write the file in to internal filesystem.
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(stringdatatobestoredinfile.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
I think this will help you.
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
for /f "tokens=8 delims=\" %a in ('reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist" ^| find "UsrClass.dat"') do echo %a
It looks like there's not a straightforward solution for HTTPS-based cloning regarding GitLab. Therefore if you want a SSH-based cloning, you should take account these three forthcoming steps:
Create properly an SSH key using your email used to sign up. I would use the default filename to key for Windows. Don't forget to introduce a password!
$ ssh-keygen -t rsa -C "[email protected]" -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key ($PWD/.ssh/id_rsa): [\n]
Enter passphrase (empty for no passphrase):[your password]
Enter same passphrase again: [your password]
Your identification has been saved in $PWD/.ssh/id_rsa.
Your public key has been saved in $PWD/.ssh/id_rsa.pub.
Copy and paste all content from the recently id_rsa.pub
generated into Setting>SSH keys>Key from your GitLab profile.
Get locally connected:
$ ssh -i $PWD/.ssh/id_rsa [email protected]
Enter passphrase for key "$PWD/.ssh/id_rsa": [your password]
PTY allocation request failed on channel 0
Welcome to GitLab, you!
Connection to gitlab.com closed.
Finally, clone any private or internal GitLab repository!
$ git clone https://git.metabarcoding.org/obitools/ROBIBarcodes.git
Cloning into 'ROBIBarcodes'...
remote: Counting objects: 69, done.
remote: Compressing objects: 100% (65/65), done.
remote: Total 69 (delta 14), reused 0 (delta 0)
Unpacking objects: 100% (69/69), done.
The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:
CODE:
import codecs
path="D:\\Users\\html\\abc.html"
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)
If this is MS Sql Server then what you have should work fine... In fact, technically, you don;t need the Begin & End at all, snce there's only one statement in the begin-End Block... (I assume @Classes is a table variable ?)
If @Term = 3
INSERT INTO @Classes
SELECT XXXXXX
FROM XXXX blah blah blah
-- -----------------------------
-- This next should always run, if the first code did not throw an exception...
INSERT INTO @Classes
SELECT XXXXXXXX
FROM XXXXXX (more code)
Slight tweak to answer from @divbyzero above to fix sonar security warnings
CloseableHttpClient getInsecureHttpClient() throws GeneralSecurityException {
TrustStrategy trustStrategy = (chain, authType) -> true;
HostnameVerifier hostnameVerifier = (hostname, session) -> hostname.equalsIgnoreCase(session.getPeerHost());
return HttpClients.custom()
.setSSLSocketFactory(new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(trustStrategy).build(), hostnameVerifier))
.build();
}
The methods readAsArrayBuffer and readAsText from a FileReader object converts a Blob object to an ArrayBuffer or to a DOMString asynchronous.
A Blob object type can be created from a raw text or byte array, for example.
let blob = new Blob([text], { type: "text/plain" });
let reader = new FileReader();
reader.onload = event =>
{
let buffer = event.target.result;
};
reader.readAsArrayBuffer(blob);
I think it's better to pack up this in a promise:
function textToByteArray(text)
{
let blob = new Blob([text], { type: "text/plain" });
let reader = new FileReader();
let done = function() { };
reader.onload = event =>
{
done(new Uint8Array(event.target.result));
};
reader.readAsArrayBuffer(blob);
return { done: function(callback) { done = callback; } }
}
function byteArrayToText(bytes, encoding)
{
let blob = new Blob([bytes], { type: "application/octet-stream" });
let reader = new FileReader();
let done = function() { };
reader.onload = event =>
{
done(event.target.result);
};
if(encoding) { reader.readAsText(blob, encoding); } else { reader.readAsText(blob); }
return { done: function(callback) { done = callback; } }
}
let text = "\uD83D\uDCA9 = \u2661";
textToByteArray(text).done(bytes =>
{
console.log(bytes);
byteArrayToText(bytes, 'UTF-8').done(text =>
{
console.log(text); // = ?
});
});
Import moment js:
var fulldate = new Date(1370001284000);
var converted_date = moment(fulldate).format(");
In rails 4.2 the above methods didn't work.
To Run all the tasks in that file assign the following inside the same file and run rake all
task :all => [:iqmedier, :euroads, :mikkelsen, :orville ] do #This will print all the tasks o/p on the screen
end
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
The problem is that you are passing a nullable type to a non-nullable type.
You can do any of the following solution:
A. Declare your dt
as nullable
DateTime? dt = dateTime;
B. Use Value
property of the the DateTime? datetime
DateTime dt = datetime.Value;
C. Cast it
DateTime dt = (DateTime) datetime;
Nobody seems to address the case of summing elements of a vector that can have NaN values in it, e.g. numerical_limits<double>::quite_NaN()
I usually loop through the elements and bluntly check.
vector<double> x;
//...
size_t n = x.size();
double sum = 0;
for (size_t i = 0; i < n; i++){
sum += (x[i] == x[i] ? x[i] : 0);
}
It's not fancy at all, i.e. no iterators or any other tricks but I this is how I do it. Some times if there are other things to do inside the loop and I want the code to be more readable I write
double val = x[i];
sum += (val == val ? val : 0);
//...
inside the loop and re-use val
if needed.
If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform
property:
.myclass {
text-transform: lowercase;
}
See https://developer.mozilla.org/en/CSS/text-transform for more info.
However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.
var arr=[{"username":"sai","email":"[email protected],"}]
localStorage.setItem('logInArr', JSON.stringfy(arr))
Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from
"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*
to
"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*
(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.
I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).
I just checked the status of the response object:
$promise.then( function successCallback(response) {
console.log(response);
if (response.status === 200) { ... }
});
if you have a string of date, then you should try this.
const FORMAT = "YYYY ddd MMM DD HH:mm";
const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300
const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019
or try this :
const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);
Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('http://example.com/upload', function() {
window.location = 'http://google.com';
});
return false;
});
});
</script>
timedeltas have a days
and seconds
attribute .. you can convert them yourself with ease.
Register your handler with signal.signal
like this:
#!/usr/bin/env python
import signal
import sys
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
Code adapted from here.
More documentation on signal
can be found here.
Some of the solutions listed on this page have some side-effects:
Here is a solution which keeps the position of the key in the same place and is compatible in IE9+, but has to create a new object and may not be the fastest solution:
function renameObjectKey(oldObj, oldName, newName) {
const newObj = {};
Object.keys(oldObj).forEach(key => {
const value = oldObj[key];
if (key === oldName) {
newObj[newName] = value;
} else {
newObj[key] = value;
}
});
return newObj;
}
Please note: IE9 may not support forEach in strict mode
This obviously does not work if the blank lines contain tabs or blanks. Many web pages (e.g. http://www.guardian.co.uk/) contain these white lines, as a result of a faulty HTML editor.
Remove white space using regular expression as follows:
change pattern: [\t ]+$ into nothing.
where [\t ] matches either tab or space. '+' matches one or more occurrences, and '$' marks the end of line.
Then use notepad++/textFX to remove single or extra empty lines. Be sure that these blank lines are not significant in the given context.
If that is the case, I think you need to use a better way of creating a class name or a class name convention. For example, like you said you want the .container
class to have different color according to a specific usage or appearance. You can do this:
SCSS
.container {
background: red;
&--desc {
background: blue;
}
// or you can do a more specific name
&--blue {
background: blue;
}
&--red {
background: red;
}
}
CSS
.container {
background: red;
}
.container--desc {
background: blue;
}
.container--blue {
background: blue;
}
.container--red {
background: red;
}
The code above is based on BEM Methodology in class naming conventions. You can check this link: BEM — Block Element Modifier Methodology
If you are using jQuery you can use the extend function to add new items.
var olddata = {"fruit":{"apples":10,"pears":21}};
var newdata = {};
newdata['vegetables'] = {"carrots": 2, "potatoes" : 5};
$.extend(true, olddata, newdata);
This will generate:
{"fruit":{"apples":10,"pears":21}, "vegetables":{"carrots":2,"potatoes":5}};
Sending Data:
First make your serializable data by implement Serializable
to your data class
public class YourDataClass implements Serializable {
String someText="Some text";
}
Then put it into intent
YourDataClass yourDataClass=new YourDataClass();
Intent intent = new Intent(getApplicationContext(),ReceivingActivity.class);
intent.putExtra("value",yourDataClass);
startActivity(intent);
Receiving Data:
YourDataClass yourDataClass=(YourDataClass)getIntent().getSerializableExtra("value");
None of the existing answers worked for me, but I found what did work for me by comparing the .csproj
files of different projects. The following manual edit to the .csproj
XML-file solved the Razor-intellisense problem for me, maybe this can help someone else who has tried all the other answers to no avail. Key is to remove any instances of <Private>False</Private>
in the <Reference>
's:
<ItemGroup>
<Reference Include="Foo">
<HintPath>path\to\Foo</HintPath>
<!-- <Private>False</Private> -->
</Reference>
<Reference Include="Bar">
<HintPath>path\to\Bar</HintPath>
<!-- <Private>True</Private> -->
</Reference>
</ItemGroup>
I don't know how those got there or exactly what they do, maybe someone smarter than me can add that information. I was just happy to finally solve this problem.
You can use mplayer.
mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi
The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.
In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.
There is another suggestion maybe for the slow guys like me =) Put the .gitignore file into your repository root not in .git folder. Cheers!
Try with regular expression and default parameters argument
public static int parseIntWithDefault(String str, int defaultInt) {
return str.matches("-?\\d+") ? Integer.parseInt(str) : defaultInt;
}
int testId = parseIntWithDefault("1001", 0);
System.out.print(testId); // 1001
int testId = parseIntWithDefault("test1001", 0);
System.out.print(testId); // 1001
int testId = parseIntWithDefault("-1001", 0);
System.out.print(testId); // -1001
int testId = parseIntWithDefault("test", 0);
System.out.print(testId); // 0
if you're using apache.commons.lang3 then by using NumberUtils:
int testId = NumberUtils.toInt("test", 0);
System.out.print(testId); // 0
Change the property WindowState
to System.Windows.Forms.FormWindowState.Maximized
, in some cases if the older answers doesn't works.
So the window will be maximized, and the other parts are in the other answers.
Take the terminal and type
fuser 8081/tcp
You will get a Process id which is using port 8081 Now kill the process
kill <pid>
You need to use javascript for this.
<form id="form1" action="showMessage.jsp" method="post">
<a href="javascript:;" onclick="document.getElementById('form1').submit();"><%=n%></a>
<input type="hidden" name="mess" value=<%=n%>/>
</form>
your can query woocommerce programatically you can even add a product to your shopping cart. I'm sure you can figure out how to interact with woocommerce cart once you read the code. how to interact with woocommerce cart programatically
====================================
<?php
add_action('wp_loaded', 'add_product_to_cart');
function add_product_to_cart()
{
global $wpdb;
if (!is_admin()) {
$product_id = wc_get_product_id_by_sku('L3-670115');
$found = false;
if (is_user_logged_in()) {
if (sizeof(WC()->cart->get_cart()) > 0) {
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if ($_product->get_id() == $product_id)
WC()->cart->remove_cart_item($cart_item_key);
}
}
} else {
if (sizeof(WC()->cart->get_cart()) > 0) {
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if ($_product->id == $product_id)
$found = true;
}
// if product not found, add it
if (!$found)
WC()->cart->add_to_cart($product_id);
} else {
// if no products in cart, add it
WC()->cart->add_to_cart($product_id);
}
}
}
}
All answers are quite old. Since the beginning of 2013 Mongoose started to support promises gradually for all queries, so that would be the recommended way of structuring several async calls in the required order going forward I guess.
More precisely, you have to force the addition of the tag, then push with option --tags and -f:
git tag -f -a <tagname>
git push -f --tags
My well intended answer is to use this tiny bit of JS: https://github.com/rhroyston/clock-js
clock.now --> 1462248501241
clock.time --> 11:08 PM
clock.weekday --> monday
clock.day --> 2
clock.month --> may
clock.year --> 2016
clock.since(1462245888784) --> 44 minutes
clock.until(1462255888784) --> 2 hours
clock.what.time(1462245888784) --> 10:24 PM
clock.what.weekday(1461968554458) --> friday
clock.what.day('14622458887 84') --> 2
clock.what.month(1461968554458) --> april
clock.what.year('1461968554458') --> 2016
clock.what.time() --> 11:11 PM
clock.what.weekday('14619685abcd') --> clock.js error : expected unix timestamp as argument
clock.unit.seconds --> 1000
clock.unit.minutes --> 60000
clock.unit.hours --> 3600000
clock.unit.days --> 86400000
clock.unit.weeks --> 604800000
clock.unit.months --> 2628002880
clock.unit.years --> 31536000000
This is a modification to @user3360260 answer. It has the following new features
MyEnum fromString(const string&)
supportUsage:
SMART_ENUM(MyEnum, ONE=1, TWO, THREE, TEN=10, ELEVEN)
MyEnum foo = MyEnum::TWO;
cout << MyEnum::toString(foo); // static method
cout << foo.toString(); // member method
cout << MyEnum::toString(MyEnum::TWO);
cout << MyEnum::toString(10);
MyEnum foo = myEnum::fromString("TWO");
// C++11 iteration over all values
for( auto x : MyEnum::allValues() )
{
cout << x.toString() << endl;
}
Here's the code
#define SMART_ENUM(EnumName, ...) \
class EnumName \
{ \
public: \
EnumName() : value(0) {} \
EnumName(int x) : value(x) {} \
public: \
enum {__VA_ARGS__}; \
private: \
static void initMap(std::map<int, std::string>& tmp) \
{ \
using namespace std; \
\
int val = 0; \
string buf_1, buf_2, str = #__VA_ARGS__; \
replace(str.begin(), str.end(), '=', ' '); \
stringstream stream(str); \
vector<string> strings; \
while (getline(stream, buf_1, ',')) \
strings.push_back(buf_1); \
for(vector<string>::iterator it = strings.begin(); \
it != strings.end(); \
++it) \
{ \
buf_1.clear(); buf_2.clear(); \
stringstream localStream(*it); \
localStream>> buf_1 >> buf_2; \
if(buf_2.size() > 0) \
val = atoi(buf_2.c_str()); \
tmp[val++] = buf_1; \
} \
} \
int value; \
public: \
operator int () const { return value; } \
std::string toString(void) const { \
return toString(value); \
} \
static std::string toString(int aInt) \
{ \
return nameMap()[aInt]; \
} \
static EnumName fromString(const std::string& s) \
{ \
auto it = find_if(nameMap().begin(), nameMap().end(), [s](const std::pair<int,std::string>& p) { \
return p.second == s; \
}); \
if (it == nameMap().end()) { \
/*value not found*/ \
throw EnumName::Exception(); \
} else { \
return EnumName(it->first); \
} \
} \
class Exception : public std::exception {}; \
static std::map<int,std::string>& nameMap() { \
static std::map<int,std::string> nameMap0; \
if (nameMap0.size() ==0) initMap(nameMap0); \
return nameMap0; \
} \
static std::vector<EnumName> allValues() { \
std::vector<EnumName> x{ __VA_ARGS__ }; \
return x; \
} \
bool operator<(const EnumName a) const { return (int)*this < (int)a; } \
};
Note that the conversion toString is a fast has lookup, while the conversion fromString is a slow linear search. But strings are so expensive anyways(and the associated file IO), I didn't feel the need to optimize or use a bimap.
you can measure how long your program works. The following functions help measure the CPU time since the start of the program:
my reference: Algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics
so you can add this line of code after your algorithm
cout << (double)clock() / CLOCKS_PER_SEC ;
Expected Output: the output representing the number of clock ticks per second
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
Anyone who is just starting with Haskell and trying to print an Int, use:
module Lib
( someFunc
) where
someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)
There is no performance difference between importing the package or using the fully qualified class name. The import directive is not converted to Java byte code, consequently there is no effect on runtime performance. The only difference is that it saves you time in case you are using the imported class multiple times. This is a good read here
There is the semicolon missing (;) after the "50%"
but you should also notice that the percentage of your div is connected to the div that contains it.
for instance:
<div id="wrapper">
<div class="container">
adsf
</div>
</div>
#wrapper {
height:100px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.
if you have:
adsf
#wrapper {
height:400px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
then you .container will be 200px. 50% of the wrapper.
So you may want to look at the divs "wrapping" your ".container"...
Try the below code
HttpRequest req = System.Web.HttpContext.Current.Request
string browserName = req.Browser.Browser;
As the only reliable source for domain suffixes are the domain registrars, you can't find the subdomain without their knowledge. There is a list with all domain suffixes at https://publicsuffix.org. This site also links to a PHP library: https://github.com/jeremykendall/php-domain-parser.
Please find an example below. I also added the sample for en.test.co.uk which is a domain with a multi suffix (co.uk).
<?php
require_once 'vendor/autoload.php';
$pslManager = new Pdp\PublicSuffixListManager();
$parser = new Pdp\Parser($pslManager->getList());
$host = 'http://en.example.com';
$url = $parser->parseUrl($host);
echo $url->host->subdomain;
$host = 'http://en.test.co.uk';
$url = $parser->parseUrl($host);
echo $url->host->subdomain;
alter table Employee alter column salary numeric(22,5)
The answer below is taken from Reading from Console: JAVA Scanner vs BufferedReader
When read an input from console, there are two options exists to achieve that. First using Scanner
, another using BufferedReader
. Both of them have different characteristics. It means differences how to use it.
Scanner treated given input as token. BufferedReader just read line by line given input as string. Scanner it self provide parsing capabilities just like nextInt(), nextFloat().
But, what is others differences between?
Scanner come with since JDK version 1.5 higher.
When should use Scanner, or Buffered Reader?
Look at the main differences between both of them, one using tokenized, others using stream line. When you need parsing capabilities, use Scanner instead. But, i am more comfortable with BufferedReader. When you need to read from a File, use BufferedReader, because it’s use buffer when read a file. Or you can use BufferedReader as input to Scanner.
As of Python 2.7 (or 3.1 respectively) you can write
with open('a', 'w') as a, open('b', 'w') as b:
do_something()
In earlier versions of Python, you can sometimes use
contextlib.nested()
to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.
In the rare case that you want to open a variable number of files all at the same time, you can use contextlib.ExitStack
, starting from Python version 3.3:
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Do something with "files"
Most of the time you have a variable set of files, you likely want to open them one after the other, though.
Since archiver
is not compatible with the new version of webpack for a long time, I recommend using zip-lib.
var zl = require("zip-lib");
zl.archiveFolder("path/to/folder", "path/to/target.zip").then(function () {
console.log("done");
}, function (err) {
console.log(err);
});
I needed to apply a translation to the Ok and Cancel buttons. I modified the code to except dynamic text (calls my translation function)
$.extend({_x000D_
confirm: function(message, title, okAction) {_x000D_
$("<div></div>").dialog({_x000D_
// Remove the closing 'X' from the dialog_x000D_
open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },_x000D_
width: 500,_x000D_
buttons: [{_x000D_
text: localizationInstance.translate("Ok"),_x000D_
click: function () {_x000D_
$(this).dialog("close");_x000D_
okAction();_x000D_
}_x000D_
},_x000D_
{_x000D_
text: localizationInstance.translate("Cancel"),_x000D_
click: function() {_x000D_
$(this).dialog("close");_x000D_
}_x000D_
}],_x000D_
close: function(event, ui) { $(this).remove(); },_x000D_
resizable: false,_x000D_
title: title,_x000D_
modal: true_x000D_
}).text(message);_x000D_
}_x000D_
});
_x000D_
You could use is()
instead of hasClass()
:
if ($('html').is('.m320, .m768')) { ... }
You can use findIndex to find the index in the array of the object and replace it as required:
var item = {...}
var items = [{id:2}, {id:2}, {id:2}];
var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;
This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:
items.forEach((element, index) => {
if(element.id === item.id) {
items[index] = item;
}
});
Fun fact!
The 'modulus' operation is defined as:
a % n ==> a - (a/n) * n
So you could roll your own, although it will be FAR slower than the built in % operator:
public static int Mod(int a, int n)
{
return a - (int)((double)a / n) * n;
}
Edit: wow, misspoke rather badly here originally, thanks @joren for catching me
Now here I'm relying on the fact that division + cast-to-int in C# is equivalent to Math.Floor
(i.e., it drops the fraction), but a "true" implementation would instead be something like:
public static int Mod(int a, int n)
{
return a - (int)Math.Floor((double)a / n) * n;
}
In fact, you can see the differences between % and "true modulus" with the following:
var modTest =
from a in Enumerable.Range(-3, 6)
from b in Enumerable.Range(-3, 6)
where b != 0
let op = (a % b)
let mod = Mod(a,b)
let areSame = op == mod
select new
{
A = a,
B = b,
Operator = op,
Mod = mod,
Same = areSame
};
Console.WriteLine("A B A%B Mod(A,B) Equal?");
Console.WriteLine("-----------------------------------");
foreach (var result in modTest)
{
Console.WriteLine(
"{0,-3} | {1,-3} | {2,-5} | {3,-10} | {4,-6}",
result.A,
result.B,
result.Operator,
result.Mod,
result.Same);
}
Results:
A B A%B Mod(A,B) Equal?
-----------------------------------
-3 | -3 | 0 | 0 | True
-3 | -2 | -1 | -1 | True
-3 | -1 | 0 | 0 | True
-3 | 1 | 0 | 0 | True
-3 | 2 | -1 | 1 | False
-2 | -3 | -2 | -2 | True
-2 | -2 | 0 | 0 | True
-2 | -1 | 0 | 0 | True
-2 | 1 | 0 | 0 | True
-2 | 2 | 0 | 0 | True
-1 | -3 | -1 | -1 | True
-1 | -2 | -1 | -1 | True
-1 | -1 | 0 | 0 | True
-1 | 1 | 0 | 0 | True
-1 | 2 | -1 | 1 | False
0 | -3 | 0 | 0 | True
0 | -2 | 0 | 0 | True
0 | -1 | 0 | 0 | True
0 | 1 | 0 | 0 | True
0 | 2 | 0 | 0 | True
1 | -3 | 1 | -2 | False
1 | -2 | 1 | -1 | False
1 | -1 | 0 | 0 | True
1 | 1 | 0 | 0 | True
1 | 2 | 1 | 1 | True
2 | -3 | 2 | -1 | False
2 | -2 | 0 | 0 | True
2 | -1 | 0 | 0 | True
2 | 1 | 0 | 0 | True
2 | 2 | 0 | 0 | True
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
You can try also with userInput.bat which uses the html input element.
This will assign the input to the value jstackId:
call userInput.bat jstackId
echo %jstackId%
This will just print the input value which eventually you can capture with FOR /F
:
call userInput.bat
I recently got this message, too, after I switched the data center location of a web application sending through Google SMTP.
The URL that apparently Google means is: https://support.google.com/mail/answer/78754. At that link, one of the steps is to reset your password. Not coincidentally, I also received an email from google with a subject of "Suspicious sign in prevented" that instructed me to change my password.
After resetting my password, I was back to using Google SMTP as usual.
Use this plugin http://multidatespickr.sourceforge.net
Thank you #DangerDave this solved my problem on Magento 2, and this is how I did
I am on a vps
root@myvps [~]# cd /var/lib/mysql/mydatabasename/
root@myvps [~]# ls
check for tables with no .frm fie (only .idb) and delete them,
rm customer_grid_flat.ibd
System will regenerate tables after running index:reindex command
Find timestamp from DateTime:
private long ConvertToTimestamp(DateTime value)
{
TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
TimeZone localZone = TimeZone.CurrentTimeZone;
System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
NyTime = NyTime.AddHours(-1);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
TimeSpan span = (NyTime - epoch);
return (long)Convert.ToDouble(span.TotalSeconds);
}
In my case, the reason was a simple typo.
<parent>
<groupId>org.sringframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
A missing character in the groupId
org.s(p)ringframework lead to this error.
@Html.TextBoxFor(model => model.IssueDate, new { @class = "form-control", name = "inv_issue_date", id = "inv_issue_date", title = "Select Invoice Issue Date", placeholder = "dd/mm/yyyy", style = "text-align:center;" })
Following should work
$d = strtotime("+1 months",strtotime("2015-05-25"));
echo date("Y-m-d",$d); // This will print **2015-06-25**
If this is a long calculation then I would go background worker. It has progress support. It also has support for cancel.
http://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx
Here I have a TextBox bound to contents.
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Debug.Write("backgroundWorker_RunWorkerCompleted");
if (e.Cancelled)
{
contents = "Cancelled get contents.";
NotifyPropertyChanged("Contents");
}
else if (e.Error != null)
{
contents = "An Error Occured in get contents";
NotifyPropertyChanged("Contents");
}
else
{
contents = (string)e.Result;
if (contentTabSelectd) NotifyPropertyChanged("Contents");
}
}
Is it possible to do it this way, as opposed to using something like Raphael or jQuery SVG?
Definitely.
If it is possible, what's the technique?
This annotated code snippet works:
<!DOCTYPE html>
<html>
<head>
<title>SVG Illustrator Test</title>
</head>
<body>
<object data="alpha.svg" type="image/svg+xml"
id="alphasvg" width="100%" height="100%"></object>
<script>
var a = document.getElementById("alphasvg");
// It's important to add an load event listener to the object,
// as it will load the svg doc asynchronously
a.addEventListener("load",function(){
// get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
// get the inner element by id
var delta = svgDoc.getElementById("delta");
// add behaviour
delta.addEventListener("mousedown",function(){
alert('hello world!')
}, false);
}, false);
</script>
</body>
</html>
Note that a limitation of this technique is that it is restricted by the same-origin policy, so alpha.svg
must be hosted on the same domain as the .html
file, otherwise the inner DOM of the object will be inaccessible.
Important thing to run this HTML, you need host HTML file to web server like IIS, Tomcat
topn = function(vector, n){
maxs=c()
ind=c()
for (i in 1:n){
biggest=match(max(vector), vector)
ind[i]=biggest
maxs[i]=max(vector)
vector=vector[-biggest]
}
mat=cbind(maxs, ind)
return(mat)
}
this function will return a matrix with the top n values and their indices. hope it helps VDevi-Chou
Do you mean design as in 'graphic representation of tables' or just plain old 'engineering kind of design'. If it's the latter, use FlameRobin, version 0.9.0 has just been released.
If it's the former, then use DBDesigner. Yup, that uses Java.
Or maybe you meant something more like MS Access. Then Kexi should be right for you.
So Soumyaansh's Revo Uninstaller Pro fix worked for me :) ( After 2 days of troubleshooting other options {screams internally 😀} ).
I did run into the an issue with his method though, "Could not find a suitable SDK to target" even though I selected to install Visual Studio with custom settings and selected the SDK I wanted to install. You may need to download the Windows 10 Standalone SDK to resolved this, in order to develop UWP apps if you see this same error after reinstalling Visual Studio.
To do this
Windows 10 SDK (WINDOWS_VERSION_NUMBER_HERE)
-> Windows 10 SDK (14393) etc . . .). If there are no SDKs on your system go to step 2!Roman Samoylenko's answer was correct except the function has changed. The correct answer is
Glide.with(context)
.load(yourImage)
.apply(RequestOptions.circleCropTransform())
.into(imageView);
Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren't used in SQL, but that can vary from database to database.
Stick to using single quotes.
That's the primary use anyway. You can use single quotes for a column alias — where you want the column name you reference in your application code to be something other than what the column is actually called in the database. For example: PRODUCT.id
would be more readable as product_id
, so you use either of the following:
SELECT PRODUCT.id AS product_id
SELECT PRODUCT.id 'product_id'
Either works in Oracle, SQL Server, MySQL… but I know some have said that the TOAD IDE seems to give some grief when using the single quotes approach.
You do have to use single quotes when the column alias includes a space character, e.g., product id
, but it's not recommended practice for a column alias to be more than one word.
public partial class Form1 : Form
{
public static Form1 gui;
public Form1()
{
InitializeComponent();
gui = this;
}
public void WriteLog(string log)
{
this.Invoke(new Action(() => { txtbx_test1.Text += log; }));
}
}
public class SomeAnotherClass
{
public void Test()
{
Form1.gui.WriteLog("1234");
}
}
I like this solution.
you can try this in the stylesheet:
@page{size:auto; margin-bottom:5mm;}
But this also removes the page number
TRY THIS ONE
mysql_connect('localhost','dbuser','dbpass');
$query = "SELECT username FROM Users WHERE username='".$username."'";
mysql_select_db('dbname');
$result=mysql_query($query);
if (mysql_num_rows($query) != 0)
{
echo "Username already exists";
}
else
{
...
}
The code snippet in the linked proposed duplicate reads user input.
ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?:
The user can type as many letters as they want, and it will go into the delBuild variable.
If you want to avoid collisions you may want to use a secure hash like SHA-256. There are several JavaScript SHA-256 implementations.
I wrote tests to compare several hash implementations, see https://github.com/brillout/test-javascript-hash-implementations.
Or go to http://brillout.github.io/test-javascript-hash-implementations/, to run the tests.
This question is really old, but I came across this page when I was looking for the easiest and quickest way to do this. Using Webpack is much simpler:
install webpack-dev-server
npm i -g webpack-dev-server
start webpack-dev-server with https
webpack-dev-server --https
This is my configuration for sublime-keymap:
[
{
"keys": [",+=+="],
"command": "reindent",
"args": {
"single_line": false
}
}
]
For vim people, just use ,==
to reindent the whole file.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Here $users
is a PDOStatement
object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach
is essentially shorthand for:
while ($row = $users->fetch()) ...
Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
Here all results are being output by the first loop. The call to fetch
will return false
, since you have already exhausted the result set (see above), so you get an error trying to loop over false
.
In the last example you are simply fetching the first result row and are looping over it.
As a more brute force method that I found worked for me:
First wrap the text inside the button in a span, and then apply this css to that span
var spanStyle = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)"
}
*above setup for inline styling
just add container element befor your img element just to be sure that your intersted element not the first one, tested in ie,ff
I know this very old but for future's sake:
I also used a dynamic dns provider. Wanted to test the website (IIS) BEHIND my (home) router. So i thought i use something like this:
my.dynamic.dnss.ip:8080 (because my router's port 80 was used to admin it).
So this seemed to be the only solution.
But: Paypal seemed to not like port 8080: only port 80 and 443 are allowed (don't know why!!)
If you know the key which you unset then put directly by comma separated
unset($attr['placeholder'], $attr['autocomplete']);
If you're looking to paginate results, use the integrated paginator, it works great!
$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages
Even this will serve the purpose
Sample data
declare @t table(id int, name varchar(20),somecolumn varchar(MAX))
insert into @t
select 1,'ABC','X' union all
select 1,'ABC','Y' union all
select 1,'ABC','Z' union all
select 2,'MNO','R' union all
select 2,'MNO','S'
Query:
SELECT ID,Name,
STUFF((SELECT ',' + CAST(T2.SomeColumn AS VARCHAR(MAX))
FROM @T T2 WHERE T1.id = T2.id AND T1.name = T2.name
FOR XML PATH('')),1,1,'') SOMECOLUMN
FROM @T T1
GROUP BY id,Name
Output:
ID Name SomeColumn
1 ABC X,Y,Z
2 MNO R,S
I came across a similar situation after publishing a ClickOnce application, and one of my colleagues on a different domain reported that it fails to launch.
To find out what was going on, I added a try catch statement inside the MainWindow method as @BradleyDotNET mentioned in one comment on the original post, and then published again.
public MainWindow()
{
try
{
InitializeComponent();
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
Then my colleague reported to me the exception detail, and it was a missing reference of a third party framework dll file.
Added the reference and problem solved.
Try this:
SET TERMOUT OFF;
spool M:\Documents\test;
select * from employees;
/
spool off;
Further to PhoneixS answer to get the correct length of string in bytes - Since mb_strlen()
is slower than strlen()
, for the best performance one can check "mbstring.func_overload" ini setting so that mb_strlen()
is used only when it is really required:
$content_length = ini_get('mbstring.func_overload') ? mb_strlen($content , '8bit') : strlen($content);
For those who are using Gradle, as @Billda mentioned, you can get the package name via:
BuildConfig.APPLICATION_ID
This gives you the package name declared in your app gradle:
android {
defaultConfig {
applicationId "com.domain.www"
}
}
If you are interested to get the package name used by your java classes (which sometimes is different than applicationId
), you can use
BuildConfig.class.getPackage().toString()
If you are confused which one to use, read here:
Note: The application ID used to be directly tied to your code's package name; so some Android APIs use the term "package name" in their method names and parameter names, but this is actually your application ID. For example, the Context.getPackageName() method returns your application ID. There's no need to ever share your code's true package name outside your app code.
Look up CPUID for one option. There might be some issues with multi-CPU systems.
Try this:
@Echo off
Set _File=file.txt
Set /a _Lines=0
For /f %%j in ('Find "" /v /c ^< %_File%') Do Set /a _Lines=%%j
Echo %_File% has %_Lines% lines.
It eliminates the extra FindStr and doesn't need expansion.
- edited to use ChrisJJ's redirect suggestion. Removal of the TYPE
command makes it three times faster.
you can use
@Html.Raw(str)
See MSDN for more
Returns markup that is not HTML encoded.
This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.
Some lambda function :
import org.junit.Test;
import java.awt.event.ActionListener;
import java.util.function.Function;
public class TestLambda {
@Test
public void testLambda() {
System.out.println("test some lambda function");
////////////////////////////////////////////
//1-any input | any output:
//lambda define:
Runnable lambda1 = () -> System.out.println("no parameter");
//lambda execute:
lambda1.run();
////////////////////////////////////////////
//2-one input(as ActionEvent) | any output:
//lambda define:
ActionListener lambda2 = (p) -> System.out.println("One parameter as action");
//lambda execute:
lambda2.actionPerformed(null);
////////////////////////////////////////////
//3-one input | by output(as Integer):
//lambda define:
Function<String, Integer> lambda3 = (p1) -> {
System.out.println("one parameters: " + p1);
return 10;
};
//lambda execute:
lambda3.apply("test");
////////////////////////////////////////////
//4-two input | any output
//lambda define:
TwoParameterFunctionWithoutReturn<String, Integer> lambda4 = (p1, p2) -> {
System.out.println("two parameters: " + p1 + ", " + p2);
};
//lambda execute:
lambda4.apply("param1", 10);
////////////////////////////////////////////
//5-two input | by output(as Integer)
//lambda define:
TwoParameterFunctionByReturn<Integer, Integer> lambda5 = (p1, p2) -> {
System.out.println("two parameters: " + p1 + ", " + p2);
return p1 + p2;
};
//lambda execute:
lambda5.apply(10, 20);
////////////////////////////////////////////
//6-three input(Integer,Integer,String) | by output(as Integer)
//lambda define:
ThreeParameterFunctionByReturn<Integer, Integer, Integer> lambda6 = (p1, p2, p3) -> {
System.out.println("three parameters: " + p1 + ", " + p2 + ", " + p3);
return p1 + p2 + p3;
};
//lambda execute:
lambda6.apply(10, 20, 30);
}
@FunctionalInterface
public interface TwoParameterFunctionWithoutReturn<T, U> {
public void apply(T t, U u);
}
@FunctionalInterface
public interface TwoParameterFunctionByReturn<T, U> {
public T apply(T t, U u);
}
@FunctionalInterface
public interface ThreeParameterFunctionByReturn<M, N, O> {
public Integer apply(M m, N n, O o);
}
}
Assuming you're using a std::ofstream
to write to file, the following snippet will write a std::string
to file in human readable form:
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
1) "Unnecessarily complicated" is IMHO to create first an unmodifiable List before adding its elements to the ArrayList.
2) The solution matches exact the question: "Is there a way to define an ArrayList with the double type?"
double type:
double[] arr = new double[] {1.38, 2.56, 4.3};
ArrayList:
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( new Supplier<ArrayList<Double>>() {
public ArrayList<Double> get() {
return( new ArrayList<Double>() );
}
} ) );
…and this creates the same compact and fast compilation as its Java 1.8 short-form:
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( ArrayList::new ) );
it because it apply flex. you can use this code
@media (min-width: 992px){
.navbar-expand-lg .navbar-collapse {
display: -ms-flexbox!important;
display: flex!important;
-ms-flex-preferred-size: auto;
flex-basis: auto;
justify-content: center;
}
in my case it workded correctly.
This is an old question, but I found the code useful and saved me three minutes of thinking :) So I am adding a small expansion to @opsb's answer.
If you wanted to convert this arc into a slice (to allow for fill) we can modify the code slightly:
function describeArc(x, y, radius, spread, startAngle, endAngle){_x000D_
var innerStart = polarToCartesian(x, y, radius, endAngle);_x000D_
var innerEnd = polarToCartesian(x, y, radius, startAngle);_x000D_
var outerStart = polarToCartesian(x, y, radius + spread, endAngle);_x000D_
var outerEnd = polarToCartesian(x, y, radius + spread, startAngle);_x000D_
_x000D_
var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";_x000D_
_x000D_
var d = [_x000D_
"M", outerStart.x, outerStart.y,_x000D_
"A", radius + spread, radius + spread, 0, largeArcFlag, 0, outerEnd.x, outerEnd.y,_x000D_
"L", innerEnd.x, innerEnd.y, _x000D_
"A", radius, radius, 0, largeArcFlag, 1, innerStart.x, innerStart.y, _x000D_
"L", outerStart.x, outerStart.y, "Z"_x000D_
].join(" ");_x000D_
_x000D_
return d;_x000D_
}_x000D_
_x000D_
function polarToCartesian(centerX, centerY, radius, angleInDegrees) {_x000D_
var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;_x000D_
_x000D_
return {_x000D_
x: centerX + (radius * Math.cos(angleInRadians)),_x000D_
y: centerY + (radius * Math.sin(angleInRadians))_x000D_
};_x000D_
}_x000D_
_x000D_
var path = describeArc(150, 150, 50, 30, 0, 50)_x000D_
document.getElementById("p").innerHTML = path_x000D_
document.getElementById("path").setAttribute('d',path)
_x000D_
<p id="p">_x000D_
</p>_x000D_
<svg width="300" height="300" style="border:1px gray solid">_x000D_
<path id="path" fill="blue" stroke="cyan"></path>_x000D_
</svg>
_x000D_
and there you go!
adb shell
su
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
This assumes your /system is yaffs2 and that it's at /dev/block/mtdblock3 the easier/better way to do this on most Android phones is:
adb shell
su
mount -o remount,rw /system
Done. This just says remount /system read-write, you don't have to specify filesystem or mount location.
Using dplyr you can:
df <- df %>% dplyr:: select(grep("ABC", names(df)), grep("XYZ", names(df)))
Assuming the ID is unique:
var result = xmldoc.Element("Customers")
.Elements("Customer")
.Single(x => (int?)x.Attribute("ID") == 2);
You could also use First
, FirstOrDefault
, SingleOrDefault
or Where
, instead of Single
for different circumstances.
Many solution here with lot of upvotes didn't work for me, even the accepted answer. I solved it by setting the scaleY, but isn't a good solution if you need too much height because the drawable comes pixelated.
Programmatically:
progressBar.setScaleY(2f);
XML Layout:
android:scaleY="2"
To list installed Python packages, you can use yolk -l
. You'll need to use easy_install yolk
first though.
Check out the contents of your array with
echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';
You could use Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode
and Microsoft.AspNetCore.Http.StatusCodes
to form your response, if you don't wish to hardcode specific numbers.
return StatusCode(StatusCodes.Status500InternalServerError);
UPDATE: Aug 2019
Perhaps not directly related to the original question but when trying to achieve the same result with Microsoft Azure Functions
I found that I had to construct a new StatusCodeResult
object found in the Microsoft.AspNetCore.Mvc.Core
assembly. My code now looks like this;
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
onClick you should call function, thats called your function toggle.
onClick={() => this.toggle()}
You can do this by using following code.
$('#dropDownId').val();
If you want to get the selected value from the select list`s options. This will do the trick.
$('#dropDownId option:selected').text();
window.top.location.href = "http://example.com";
window.top
refers to the window object of the page at the top of the frames hierarchy.