if mylist != []:
print(mylist[0])
else:
print(None)
Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.
The compiler wants you to write this:
private static List<String> list = new ArrayList<String>();
because otherwise, you could add any type you like into list
, making the instantiation as new ArrayList<String>()
pointless. Java generics are a compile-time feature only, so an object created with new ArrayList<String>()
will happily accept Integer
or JFrame
elements if assigned to a reference of the "raw type" List
- the object itself knows nothing about what types it's supposed to contain, only the compiler does.
It worked for me, but only with ssh key and not with username and password.
After i added the ssh key to sourcetree, i changed the settings under Tools -> Options -> SSH-Client to work with PuTTY/Plink.
I run into trouble after i added the ssh key, because i forgot to restart sourceTree. "this is necessary so that there is an instance of ssh-agent running that SourceTree can talk to with your key loaded." See here: https://answers.atlassian.com/questions/189412/sourcetree-with-gitlab-ssh-not-working
It is caused by a lack of precision with doubles / decimals (i.e. - the function will not always give the result you expect).
See the following link: MSDN on Math.Round
Here is the relevant quote:
Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter.This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.
Adding to the above answers: To find the package name of installed apps on any android device: Go to Storage/Android/data/< package-name >
Compact all collections in current database
db.getCollectionNames().forEach(function (collectionName) {
print('Compacting: ' + collectionName);
db.runCommand({ compact: collectionName });
});
To collaborate with the question and show an example of replacing it with an empty Container()
.
Here's the example below:
import "package:flutter/material.dart";
void main() {
runApp(new ControlleApp());
}
class ControlleApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "My App",
home: new HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
bool visibilityTag = false;
bool visibilityObs = false;
void _changed(bool visibility, String field) {
setState(() {
if (field == "tag"){
visibilityTag = visibility;
}
if (field == "obs"){
visibilityObs = visibility;
}
});
}
@override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(backgroundColor: new Color(0xFF26C6DA)),
body: new ListView(
children: <Widget>[
new Container(
margin: new EdgeInsets.all(20.0),
child: new FlutterLogo(size: 100.0, colors: Colors.blue),
),
new Container(
margin: new EdgeInsets.only(left: 16.0, right: 16.0),
child: new Column(
children: <Widget>[
visibilityObs ? new Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
new Expanded(
flex: 11,
child: new TextField(
maxLines: 1,
style: Theme.of(context).textTheme.title,
decoration: new InputDecoration(
labelText: "Observation",
isDense: true
),
),
),
new Expanded(
flex: 1,
child: new IconButton(
color: Colors.grey[400],
icon: const Icon(Icons.cancel, size: 22.0,),
onPressed: () {
_changed(false, "obs");
},
),
),
],
) : new Container(),
visibilityTag ? new Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
new Expanded(
flex: 11,
child: new TextField(
maxLines: 1,
style: Theme.of(context).textTheme.title,
decoration: new InputDecoration(
labelText: "Tags",
isDense: true
),
),
),
new Expanded(
flex: 1,
child: new IconButton(
color: Colors.grey[400],
icon: const Icon(Icons.cancel, size: 22.0,),
onPressed: () {
_changed(false, "tag");
},
),
),
],
) : new Container(),
],
)
),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new InkWell(
onTap: () {
visibilityObs ? null : _changed(true, "obs");
},
child: new Container(
margin: new EdgeInsets.only(top: 16.0),
child: new Column(
children: <Widget>[
new Icon(Icons.comment, color: visibilityObs ? Colors.grey[400] : Colors.grey[600]),
new Container(
margin: const EdgeInsets.only(top: 8.0),
child: new Text(
"Observation",
style: new TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w400,
color: visibilityObs ? Colors.grey[400] : Colors.grey[600],
),
),
),
],
),
)
),
new SizedBox(width: 24.0),
new InkWell(
onTap: () {
visibilityTag ? null : _changed(true, "tag");
},
child: new Container(
margin: new EdgeInsets.only(top: 16.0),
child: new Column(
children: <Widget>[
new Icon(Icons.local_offer, color: visibilityTag ? Colors.grey[400] : Colors.grey[600]),
new Container(
margin: const EdgeInsets.only(top: 8.0),
child: new Text(
"Tags",
style: new TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w400,
color: visibilityTag ? Colors.grey[400] : Colors.grey[600],
),
),
),
],
),
)
),
],
)
],
)
);
}
}
Run your container with --privileged flag.
docker run -it --privileged ...
Collections.sort(teamsName.subList(1, teamsName.size()));
The code above will reflect the actual sublist of your original list sorted.
To reset form (but not clear the form) just trigger reset
event:
$('#form').trigger("reset");
To clear a form see other answers.
In the specific case of a String array you could initialize the array using the Split Function as it returns a String array rather than a Variant array:
Dim arrWsNames() As String
arrWsNames = Split("Value1,Value2,Value3", ",")
This allows you to avoid using the Variant data type and preserve the desired type for arrWsNames.
I just added custom headers to the Web.config and it worked like a charm.
On configuration - system.webServer:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
I have the front end app and the backend on the same solution. For this to work, I need to set the web services project (Backend) as the default for this to work.
I was using ReST, haven't tried with anything else.
Actually, to query the team_name
, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.
from urllib2 import urlopen
import json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)
for i in json_obj['team']:
print i['team_name']
The same thing was happening for me. All I had to do was uninstalled Java Update 8
Google Chrome does not allow to load local resources because of the security. Chrome need http url. Internet Explorer and Edge allows to load local resources, but Safari, Chrome, and Firefox doesn't allows to load local resources.
Go to file location and start the Python Server from there.
python -m SimpleHttpServer
then put that url into function:
function run(){
var URL = "http://172.271.1.20:8000/" /* http://0.0.0.0:8000/ or http://127.0.0.1:8000/; */
window.open(URL, null);
}
#include<stdio.h>
#include<string.h>
main()
{
int i=0,n;
int j=0;
char str[]=" Nar ayan singh ";
char *ptr,*ptr1;
printf("sizeof str:%ld\n",strlen(str));
while(str[i]==' ')
{
memcpy (str,str+1,strlen(str)+1);
}
printf("sizeof str:%ld\n",strlen(str));
n=strlen(str);
while(str[n]==' ' || str[n]=='\0')
n--;
str[n+1]='\0';
printf("str:%s ",str);
printf("sizeof str:%ld\n",strlen(str));
}
You probably want to look into the observer pattern.
Here's some sample code to get yourself started:
import java.util.*;
// An interface to be implemented by everyone interested in "Hello" events
interface HelloListener {
void someoneSaidHello();
}
// Someone who says "Hello"
class Initiater {
private List<HelloListener> listeners = new ArrayList<HelloListener>();
public void addListener(HelloListener toAdd) {
listeners.add(toAdd);
}
public void sayHello() {
System.out.println("Hello!!");
// Notify everybody that may be interested.
for (HelloListener hl : listeners)
hl.someoneSaidHello();
}
}
// Someone interested in "Hello" events
class Responder implements HelloListener {
@Override
public void someoneSaidHello() {
System.out.println("Hello there...");
}
}
class Test {
public static void main(String[] args) {
Initiater initiater = new Initiater();
Responder responder = new Responder();
initiater.addListener(responder);
initiater.sayHello(); // Prints "Hello!!!" and "Hello there..."
}
}
Related article: Java: Creating a custom event
Asked question title is general, but authors use case stated in the body of the question is specific. So any other answers may be used.
But in order to fully answer the title question it should be clarified that it seems like all of the approaches may fail in some cases and require some rework. I reviewed all of them (and some additional) in decreasing of reliability order (in my opinion):
==
(accepted answer).Despite the fact that this is accepted answer and has most upvotes count, I think this method should not be used at all. Because in fact this approach is discouraged in python as mentioned several times here.
But if one still want to use it - should be aware of some pandas-specific dtypes like pd.CategoricalDType
, pd.PeriodDtype
, or pd.IntervalDtype
. Here one have to use extra type( )
in order to recognize dtype correctly:
s = pd.Series([pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')])
s
s.dtype == pd.PeriodDtype # Not working
type(s.dtype) == pd.PeriodDtype # working
>>> 0 2002-03-01
>>> 1 2012-02-01
>>> dtype: period[D]
>>> False
>>> True
Another caveat here is that type should be pointed out precisely:
s = pd.Series([1,2])
s
s.dtype == np.int64 # Working
s.dtype == np.int32 # Not working
>>> 0 1
>>> 1 2
>>> dtype: int64
>>> True
>>> False
isinstance()
approach.This method has not been mentioned in answers so far.
So if direct comparing of types is not a good idea - lets try built-in python function for this purpose, namely - isinstance()
.
It fails just in the beginning, because assumes that we have some objects, but pd.Series
or pd.DataFrame
may be used as just empty containers with predefined dtype
but no objects in it:
s = pd.Series([], dtype=bool)
s
>>> Series([], dtype: bool)
But if one somehow overcome this issue, and wants to access each object, for example, in the first row and checks its dtype like something like that:
df = pd.DataFrame({'int': [12, 2], 'dt': [pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')]},
index = ['A', 'B'])
for col in df.columns:
df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)
>>> (dtype('int64'), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
It will be misleading in the case of mixed type of data in single column:
df2 = pd.DataFrame({'data': [12, pd.Timestamp('2013-01-02')]},
index = ['A', 'B'])
for col in df2.columns:
df2[col].dtype, 'is_int64 = %s' % isinstance(df2.loc['A', col], np.int64)
>>> (dtype('O'), 'is_int64 = False')
And last but not least - this method cannot directly recognize Category
dtype. As stated in docs:
Returning a single item from categorical data will also return the value, not a categorical of length “1”.
df['int'] = df['int'].astype('category')
for col in df.columns:
df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)
>>> (CategoricalDtype(categories=[2, 12], ordered=False), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
So this method is also almost inapplicable.
df.dtype.kind
approach.This method yet may work with empty pd.Series
or pd.DataFrames
but has another problems.
First - it is unable to differ some dtypes:
df = pd.DataFrame({'prd' :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
'str' :['s1', 's2'],
'cat' :[1, -1]})
df['cat'] = df['cat'].astype('category')
for col in df:
# kind will define all columns as 'Object'
print (df[col].dtype, df[col].dtype.kind)
>>> period[D] O
>>> object O
>>> category O
Second, what is actually still unclear for me, it even returns on some dtypes None.
df.select_dtypes
approach.This is almost what we want. This method designed inside pandas so it handles most corner cases mentioned earlier - empty DataFrames, differs numpy or pandas-specific dtypes well. It works well with single dtype like .select_dtypes('bool')
. It may be used even for selecting groups of columns based on dtype:
test = pd.DataFrame({'bool' :[False, True], 'int64':[-1,2], 'int32':[-1,2],'float': [-2.5, 3.4],
'compl':np.array([1-1j, 5]),
'dt' :[pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')],
'td' :[pd.Timestamp('2012-03-02')- pd.Timestamp('2016-10-20'),
pd.Timestamp('2010-07-12')- pd.Timestamp('2000-11-10')],
'prd' :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
'intrv':pd.arrays.IntervalArray([pd.Interval(0, 0.1), pd.Interval(1, 5)]),
'str' :['s1', 's2'],
'cat' :[1, -1],
'obj' :[[1,2,3], [5435,35,-52,14]]
})
test['int32'] = test['int32'].astype(np.int32)
test['cat'] = test['cat'].astype('category')
Like so, as stated in the docs:
test.select_dtypes('number')
>>> int64 int32 float compl td
>>> 0 -1 -1 -2.5 (1-1j) -1693 days
>>> 1 2 2 3.4 (5+0j) 3531 days
On may think that here we see first unexpected (at used to be for me: question) results - TimeDelta
is included into output DataFrame
. But as answered in contrary it should be so, but one have to be aware of it. Note that bool
dtype is skipped, that may be also undesired for someone, but it's due to bool
and number
are in different "subtrees" of numpy dtypes. In case with bool, we may use test.select_dtypes(['bool'])
here.
Next restriction of this method is that for current version of pandas (0.24.2), this code: test.select_dtypes('period')
will raise NotImplementedError
.
And another thing is that it's unable to differ strings from other objects:
test.select_dtypes('object')
>>> str obj
>>> 0 s1 [1, 2, 3]
>>> 1 s2 [5435, 35, -52, 14]
But this is, first - already mentioned in the docs. And second - is not the problem of this method, rather the way strings are stored in DataFrame
. But anyway this case have to have some post processing.
df.api.types.is_XXX_dtype
approach.This one is intended to be most robust and native way to achieve dtype recognition (path of the module where functions resides says by itself) as i suppose. And it works almost perfectly, but still have at least one caveat and still have to somehow distinguish string columns.
Besides, this may be subjective, but this approach also has more 'human-understandable' number
dtypes group processing comparing with .select_dtypes('number')
:
for col in test.columns:
if pd.api.types.is_numeric_dtype(test[col]):
print (test[col].dtype)
>>> bool
>>> int64
>>> int32
>>> float64
>>> complex128
No timedelta
and bool
is included. Perfect.
My pipeline exploits exactly this functionality at this moment of time, plus a bit of post hand processing.
Hope I was able to argument the main point - that all discussed approaches may be used, but only pd.DataFrame.select_dtypes()
and pd.api.types.is_XXX_dtype
should be really considered as the applicable ones.
I had the same issue while installing mysqlclient
for the Django project.
In my case, it's the system architecture mismatch causing the issue. I have Windows 7 64bit version on my system. But, I had installed Python 3.7.2 32 bit version by mistake.
So, I re-installed Python interpreter (64bit) and ran the command
pip install mysqlclient
I hope this would work with other Python packages as well.
For %d
part refer to this How does this program work? and for decimal places use %.2f
Check this out. It's free one.
http://irfaann.blogspot.com/2009/07/ajax-based-multiselect-dropdown-control.html
HTH,
take mongodb backup for particular db and delete 7 days old backup using bin sh command :-
#!/bin/bash
MONGO_DATABASE="nexgtv_16"
APP_NAME="test"
MONGO_HOST="127.0.0.1"
MONGO_PORT="27017"
TIMESTAMP=`date +%F-%H%M`
MONGODUMP_PATH="/usr/bin/mongodump"
BACKUPS_DIR="/home/mongodbbackups/backups/$APP_NAME"
BACKUP_NAME="$APP_NAME-$TIMESTAMP"
$MONGODUMP_PATH -d $MONGO_DATABASE
mkdir -p $BACKUPS_DIR
mv dump $BACKUP_NAME
tar -zcvf $BACKUPS_DIR/$BACKUP_NAME.tgz $BACKUP_NAME
rm -rf $BACKUP_NAME
find /home/mongodbbackups/backups/test/ -mindepth 1 -mtime +7 -delete
I tried this:
label1.Content = Directory.GetCurrentDirectory();
and get also the directory.
Amyuni PDF Converter .Net can also be used for this. And it will also allow you to modify existing files, apply OCR to them and extract text, create raster images (for thumbnails generation for example), optimize the output PDF for web viewing, etc.
Usual disclaimer applies.
Iterate through the list of keys and values, then add them.
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
for (String key : myHashMap.keySet()){
reversedHashMap.put(myHashMap.get(key), key);
}
ssh -t 'command; bash -l'
will execute the command and then start up a login shell when it completes. For example:
ssh -t [email protected] 'cd /some/path; bash -l'
create the new name from scratch and delete the old one.
You actually need to pass a function inside the window.setTimeout()
which you want to execute after 5000 milliseconds, like this:
$(document).ready(function () {
// Handler for .ready() called.
window.setTimeout(function () {
location.href = "https://www.google.co.in";
}, 5000);
});
For More info: .setTimeout()
This worked for me perfectly fine.
select name, orderno from (
select name, orderno, row_number() over(partition by
orderno order by created_date desc) as rn from orders
) O where rn =1;
You could check whether the value of your selectOneMenu
component belongs to the list of subjects.
Namely:
public void subjectSelectionChanged() {
// Cancel if subject is manually written
if (!subjectList.contains(aktNachricht.subject)) { return; }
// Write your code here in case the user selected (or wrote) an item of the list
// ....
}
Supposedly subjectList
is a collection type, like ArrayList
. Of course here your code will run in case the user writes an item of your selectOneMenu
list.
You can also use a linear gradient and an image: http://codepen.io/anon/pen/RPweox
.background{
background: linear-gradient(rgba(0,0,0,.5), rgba(0,0,0,.5)),
url('http://www.imageurl.com');
}
This is because the linear gradient function creates an Image which is added to the background stack. https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
First, convert the string into a timestamp:
$timestamp = strtotime($string);
Then do a
date("Y-m-d H:i:s", $timestamp);
From my limited experience, this happens for two main reasons:
The simple solution here is to use an error handler ending with Resume Next
If your lookup_value
is a variable you can enclose it with TRIM()
cellNum = wsFunc.VLookup(TRIM(currName), rngLook, 13, False)
No need to use jQuery, querystring
or manually assemble the payload. URLSearchParams
is a way to go and here is one of the most concise answers with the full request example:
fetch('https://example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'param': 'Some value',
'another_param': 'Another value'
})
})
.then(res => {
// Do stuff with the result
});
Yes, you can use Axios or whatever you want instead of fetch
.
P.S. URLSearchParams
is not supported in IE.
Just for an additional reference.
All of the above answers will work in case of a data frame. But if you are using lambda while creating / modify a column this won't work, Because there it is considered as a int attribute instead of pandas series. You have to use str( target_attribute ) to make it as a string. Please refer the below example.
def add_zero_in_prefix(df):
if(df['Hour']<10):
return '0' + str(df['Hour'])
data['str_hr'] = data.apply(add_zero_in_prefix, axis=1)
Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.
An alternative option is to set it in the machine level web.config, so its not even in the web site folder.
To generate it do it just like the linked article in David's answer.
There is a way to remove the line.
1) Follow this tutorial: android-tabs-with-fragments
2) Then apply the RelativeLayout change that Leaudro suggested above (apply the layout props to all FrameLayouts).
You can also add an ImageView to the tab.xml in item #1 and get a very iPhone like look to the tabs.
Here is a screenshot of what I'm working on right now. I still have some work to do, mainly make a selector for the icons and ensure equal horizontal distribution, but you get the idea. In my case, I'm using fragments, but the same principals should apply to a standard tab view.
First, get Pdftk:
sudo apt-get install pdftk
Now, as shown on example page, use
pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf
for merging pdf files into one.
jQuery offers $.inArray
:
Note that inArray returns the index of the element found, so 0
indicates the element is the first in the array. -1
indicates the element was not found.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;_x000D_
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Edit 3.5 years later
$.inArray
is effectively a wrapper for Array.prototype.indexOf
in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype
, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.indexOf('specialword') > -1;_x000D_
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
Edit another 3 years later
Gosh, 6.5 years?!
The best option for this in modern Javascript is Array.prototype.includes
:
var found = categories.includes('specialword');
No comparisons and no confusing -1
results. It does what we want: it returns true
or false
. For older browsers it's polyfillable using the code at MDN.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.includes('specialword');_x000D_
var foundNotPresent = categoriesNotPresent.includes('specialword');_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
How about this?
List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();
I found a working splitter, http://www.dreamchain.com/split-pane/, which works with jQuery v1.9. Note I had to add the following CSS code to get it working with a fixed bootstrap
navigation bar.
fixed-left {
position: absolute !important; /* to override relative */
height: auto !important;
top: 55px; /* Fixed navbar height */
bottom: 0px;
}
This is a more comprehensive version that will match as much as I can think of as well as give you group matching for country, region, first, and last.
(?<number>(\+?(?<country>(\d{1,3}))(\s|-|\.)?)?(\(?(?<region>(\d{3}))\)?(\s|-|\.)?)((?<first>(\d{3}))(\s|-|\.)?)((?<last>(\d{4}))))
One note for people who might not have the set password for sysdba or sys and regularly use a third party client. Here's some info about logging into command line sqlplus without a password that helped me. I am using fedora 21 by the way.
locate sqlplus
In my case, sqlplus is located here:
/u01/app/oracle/product/11.2.0/xe/config/scripts/sqlplus.sh
Now run
cd /u01/app/oracle/product/11.2.0/xe/config/scripts
./sqlplus.sh / as sysdba
Now you need to connect to database with your old credentials. You can find Oracle provided template in your output:
Use "connect username/password@XE" to connect to the database.
In my case I have user "oracle" with password "oracle" so my input looks like
connect oracle/oracle@XE
Done. Now type your new password twice. Then if you don't want your password to expire anymore you could run
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
If you are debugging or similar - In chrome developer tools, you can simply use
$x('/html/.//div[@id="text"]')
Try DataGridView.CurrentCellAddress.
Returns: A Point that represents the row and column indexes of the currently active cell.
E.G. Select the first column and the fifth row, and you'll get back: Point( X=1, Y=5 )
You can use Double.parseDouble()
to convert a String
to a double
:
String text = "12.34"; // example String
double value = Double.parseDouble(text);
For your case it looks like you want:
double total = Double.parseDouble(jlbTotal.getText());
double price = Double.parseDouble(jlbPrice.getText());
I wanted to specify two points which kept causing me problems.
body {
margin: 0;
padding: 0;
background: url('img/background.jpg') repeat;
}
body:before {
content: " ";
width: 100%;
height: 100%;
position: absolute;
z-index: -1;
top: 0;
left: 0;
background: -webkit-radial-gradient(top center, ellipse cover, rgba(255,255,255,0.2) 0%,rgba(0,0,0,0.5) 100%);
}
PLEASE NOTE: This only using webkit so it will only work in webkit browsers.
try :
-moz-linear-gradient = (Firefox)
-ms-linear-gradient = (IE)
-o-linear-gradient = (Opera)
-webkit-linear-gradient = (Chrome & safari)
This thread says you can't do send private messages to a group of friends on facebook but I found this https://developers.facebook.com/docs/sharing/reference/send-dialog
alloca () is nice and efficient... but it is also deeply broken.
In most cases you can replace it using local variables and majorant size. If it's used for large objects, putting them on the heap is usually a safer idea.
If you really need it C you can use VLA (no vla in C++, too bad). They are much better than alloca() regarding scope behavior and consistency. As I see it VLA are a kind of alloca() made right.
Of course a local structure or array using a majorant of the needed space is still better, and if you don't have such majorant heap allocation using plain malloc() is probably sane. I see no sane use case where you really really need either alloca() or VLA.
If you set CURLOPT_RETURNTRANSFER
to true
or 1
then the return value from curl_exec
will be the actual result from the successful operation. In other words it will not return TRUE
on success. Although it will return FALSE
on failure.
As described in the Return Values section of curl-exec
PHP manual page: http://php.net/manual/function.curl-exec.php
You should enable the CURLOPT_FOLLOWLOCATION
option for redirects but this would be a problem if your server is in safe_mode
and/or open_basedir
is in effect which can cause issues with curl as well.
Instead of looking at the source code, you should read the javadoc String.format() and Formatter syntax.
You specify the format of the value after the %. For instance for decimal integer it is d
, and for String it is s
:
String aString = "world";
int aInt = 20;
String.format("Hello, %s on line %d", aString, aInt );
Output:
Hello, world on line 20
To do what you tried (use an argument index), you use: *n*$
,
String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );
Output:
Line:20. Value:world. Result: Hello world at line 20
Simply $("#3").remove();
would be enough. But 3
isn't a good id (I think it's even illegal, as it starts with a digit).
Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.
List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();
You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.
an example that worked for me:
$query = "some buggy sql statement";
$this->db->db_debug = false;
if(!@$this->db->query($query))
{
$error = $this->db->error();
// do something in error case
}else{
// do something in success case
}
...
Best
Just do this:
var $div = $('div');
var a = 0;
setInterval(function() {
a++;
$div.stop(true,true).css("left", a);
}, 1000 / 30);
Inactive browser tabs buffer some of the setInterval
or setTimeout
functions.
stop(true,true)
will stop all buffered events and execute immediatly only the last animation.
The window.setTimeout()
method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).
None of these worked for me. I am using git-bash on windows. Found out the problem was with my file path formatting.
WRONG:
git clone F:\DEV\MY_REPO\.git
CORRECT:
git clone /F/DEV/MY_REPO/.git
These commands are done from the folder you want the repo folder to appear in.
I have been puzzled a lot with this problem, since I am relively new in Python. I cannot apply the solution to the code given by the questioned, since it's not self executable. So I bring a very simple code:
from turtle import *
ts = Screen(); tu = Turtle()
def move(x,y):
print "move()"
tu.goto(100,100)
ts.listen();
ts.onclick(move)
done()
As you can see, the solution consists in using two (dummy) arguments, even if they are not used either by the function itself or in calling it! It sounds crazy, but I believe there must be a reason for it (hidden from the novice!).
I have tried a lot of other ways ('self' included). It's the only one that works (for me, at least).
Remember load jquery before bootstrap js
In 2020, this is still not possible on Mobile Safari.
The next best solution is to show instructions on the steps to adding your page to the homescreen.
Picture is from this great article which covers that an many other tips on how to make your PWA feel iOS native.
From git stash --help
Recovering stashes that were cleared/dropped erroneously
If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
following incantation to get a list of stashes that are still in your repository, but not reachable any more:
git fsck --unreachable |
grep commit | cut -d\ -f3 |
xargs git log --merges --no-walk --grep=WIP
This helped me better than the accepted answer with the same scenario.
System.in.read() is a read input method for System.in class which is "Standard Input file" or 0 in conventional OS.
Since the column is of type VARCHAR, you should convert the input parameter to a string rather than converting the column value to a number:
select * from exception where exception_value = to_char(105);
Differences in SOAP versions
Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.
The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.
The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.
In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.
SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.
There is not difine POST AND GET method for particular android....but all here is differance
GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.
What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.
POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.
I am not very sure whether it will make any difference in performance of my API.
Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async
" considerations in my article on async
ASP.NET.
I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.
As far as the code goes, this is not asynchronous:
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
return Task.FromResult(response);
}
You'd need a truly asynchronous implementation to get the scalability benefits of async
:
public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}
Or (if your logic in this method really is just a pass-through):
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}
Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync
). Then let the async
trickle up, making your controller actions asynchronous as the last step.
And under no circumstances should you use Task.Run
in this scenario.
Pass object from one activity to another activity.
(1) source activity
Intent ii = new Intent(examreport_select.this,
BarChartActivity.class);
ii.putExtra("IntentExamResultDetail",
(Serializable) your List<ArraList<String>> object here);
startActivity(ii);
(2) destination acitivity
List<ArrayList<String>> aa = (List<ArrayList<String>>) getIntent()
.getSerializableExtra("IntentExamResultDetail");
We're using Install4J to build installers for windows or unix environments.
It's easily customizable up to the point where you want to write scripts for special actions that cannot be done with standard dialogues. But even though we're setting up windows services with it, we're only using standard components.
I think Launch4J is from the same company (just the launcher - no installer).
PS: sadly i'm not getting paid for this endorsement. I just like that tool.
It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:
-XX:MaxPermSize=256m
-Xms256m -Xmx512M
If you are not using any server, you can type the following on the command line before you run your code:
java -Xms64m -Xmx256m HelloWorld
More information on increasing the heap size can be found here
class ShadowContainer extends StatelessWidget {
ShadowContainer({
Key key,
this.margin = const EdgeInsets.fromLTRB(0, 10, 0, 8),
this.padding = const EdgeInsets.symmetric(horizontal: 8),
this.circular = 4,
this.shadowColor = const Color.fromARGB(
128, 158, 158, 158), //Colors.grey.withOpacity(0.5),
this.backgroundColor = Colors.white,
this.spreadRadius = 1,
this.blurRadius = 3,
this.offset = const Offset(0, 1),
@required this.child,
}) : super(key: key);
final Widget child;
final EdgeInsetsGeometry margin;
final EdgeInsetsGeometry padding;
final double circular;
final Color shadowColor;
final double spreadRadius;
final double blurRadius;
final Offset offset;
final Color backgroundColor;
@override
Widget build(BuildContext context) {
return Container(
margin: margin,
padding: padding,
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(circular),
boxShadow: [
BoxShadow(
color: shadowColor,
spreadRadius: spreadRadius,
blurRadius: blurRadius,
offset: offset,
),
],
),
child: child,
);
}
}
If width:100%
works in any cases, just use that, otherwise you can use vw
in this case which is relative to 1% of the width of the viewport.
That means if you want to cover off the width, just use 100vw
.
Look at the image I draw for you here:
Try the snippet I created for you as below:
.full-width {_x000D_
width: 100vw;_x000D_
height: 100px;_x000D_
margin-bottom: 40px;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.one-vw-width {_x000D_
width: 1vw;_x000D_
height: 100px;_x000D_
background-color: red;_x000D_
}
_x000D_
<div class="full-width"></div>_x000D_
<div class="one-vw-width"></div>
_x000D_
Prefix the call with Module2 (ex. Module2.IDLE
). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.
How about using os.kill? See the docs here: http://docs.python.org/library/os.html#os.kill
--============= FIRST WAY (Shows as Multiple Row) ===============
SELECT 'tblProducts' [TableName], COUNT(P.Id) [RowCount] FROM tblProducts P
UNION ALL
SELECT 'tblProductSales' [TableName], COUNT(S.Id) [RowCount] FROM tblProductSales S
--============== SECOND WAY (Shows in a Single Row) =============
SELECT
(SELECT COUNT(Id) FROM tblProducts) AS ProductCount,
(SELECT COUNT(Id) FROM tblProductSales) AS SalesCount
I'm running BS3 on a dev site and the following produces the effect/layout you're requesting. Of course you'll need the glyphicons set up in BS3.
<div class="navbar navbar-inverse navbar-static-top" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" rel="home" href="/" title="Aahan Krish's Blog - Homepage">ITSMEEE</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="/topic/notes/">/notes</a></li>
<li><a href="/topic/dev/">/dev</a></li>
<li><a href="/topic/good-reads/">/good-reads</a></li>
<li><a href="/topic/art/">/art</a></li>
<li><a href="/topic/bookmarks/">/bookmarks</a></li>
<li><a href="/all-topics/">/all</a></li>
</ul>
<div class="col-sm-3 col-md-3 pull-right">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</div>
</div>
UPDATE: See JSFiddle
You are correct in that it's not "right" to add files to the tags folder.
You've correctly guessed that copy
is the operation to use; it lets Subversion keep track of the history of these files, and also (I assume) store them much more efficiently.
In my experience, it's best to do copies ("snapshots") of entire projects, i.e. all files from the root check-out location. That way the snapshot can stand on its own, as a true representation of the entire project's state at a particular point in time.
This part of "the book" shows how the command is typically used.
Below query can work :
SELECT user_id, value, date , row_number() OVER (PARTITION BY user_id ORDER BY date desc) AS rn
FROM table_name
WHERE rn= 1
No, this is very incorrect.
HTTP is an application protocol. 200 implies that the response contains a payload that represents the status of the requested resource. An error message usually is not a representation of that resource.
If something goes wrong while processing GET, the right status code is 4xx ("you messed up") or 5xx ("I messed up").
This is going to return the keys with max value in a Map<Integer, Integer>
public Set<Integer> getMaxKeys(Map<Integer, Integer> map) {
if (map.isEmpty()) {
return Collections.emptySet();
}
return map
.entrySet()
.stream()
.collect(
groupingBy(
Map.Entry::getValue, TreeMap::new, mapping(Map.Entry::getKey, toSet())
)
)
.lastEntry()
.getValue();
}
According to theory its the same things. Recursion and loop with the same O() complexity will work with the same theoretical speed, but of course real speed depends on language, compiler and processor. Example with power of number can be coded in iteration way with O(ln(n)):
int power(int t, int k) {
int res = 1;
while (k) {
if (k & 1) res *= t;
t *= t;
k >>= 1;
}
return res;
}
For floating point data, you can use the new ismembertol
function, which computes set membership with a specified tolerance. This is similar to the ismemberf
function found in the File Exchange except that it is now built-in to MATLAB. Example:
>> pi_estimate = 3.14159;
>> abs(pi_estimate - pi)
ans =
5.3590e-08
>> tol = 1e-7;
>> ismembertol(pi,pi_estimate,tol)
ans =
1
Try using additional condition in join:
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1
INNER JOIN Table2
ON (Table1.Col1 = Table2.Col1
OR (Table1.Col1 IS NULL AND Table2.Col1 IS NULL)
)
This problem can also happen in Windows. Cmake looks into the registry and sometimes python values are not set. For those with similar problem:
http://ericsilva.org/2012/10/11/restoring-your-python-registry-in-windows/
Just create a .reg file to set the necessary keys and edit accordingly to match your setup.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Python]
[HKEY_CURRENT_USER\Software\Python\Pythoncore]
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.6]
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.6\InstallPath]
@="C:\\python26"
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.6\PythonPath]
@="C:\\python26;C:\\python26\\Lib\\;C:\\python26\\DLLs\\"
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.7]
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.7\InstallPath]
@="C:\\python27"
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.7\PythonPath]
@="C:\\python27;C:\\python27\\Lib\\;C:\\python27\\DLLs\\"
This was the only thing that worked for me on Armbian:
dmesg | grep -oE 'mac=.*\w+' | cut -b '5-'
foreach($images as $key => $image)
{
if(in_array($image, array(
'http://i27.tinypic.com/29ykt1f.gif',
'http://img3.abload.de/img/10nxjl0fhco.gif',
'http://i42.tinypic.com/9pp2tx.gif',
))
{
unset($images[$key]);
}
}
public static string FormatXml(string xml)
{
try
{
var doc = XDocument.Parse(xml);
return doc.ToString();
}
catch (Exception)
{
return xml;
}
}
a = ('x', 'y')
b = a + ('z',)
print(b)
a = ('x', 'y')
b = a + tuple('b')
print(b)
(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:
$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();
Oh, also: count()
instead if exists
but this could be something used after get
.
Use this:
document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');
I got the same error the first time I wanted to install LightGBM on python (GPU version).
You can simply fix it with this command line :
sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev
the boost libraries will be installed and you'll be fine to continue your installation process.
In mycase, with tree command
Relative path
tree -ifF ./dir | grep -v '^./dir$' | grep -v '.*/$' | grep '\./.*' | while read file; do
echo $file
done
Absolute path
tree -ifF ./dir | grep -v '^./dir$' | grep -v '.*/$' | grep '\./.*' | while read file; do
echo $file | sed -e "s|^.|$PWD|g"
done
We see this constantly, all over our app, using Crashlytics. The crash usually happens way down in platform code. A small sampling:
android.database.CursorWindow.finalize() timed out after 10 seconds
java.util.regex.Matcher.finalize() timed out after 10 seconds
android.graphics.Bitmap$BitmapFinalizer.finalize() timed out after 10 seconds
org.apache.http.impl.conn.SingleClientConnManager.finalize() timed out after 10 seconds
java.util.concurrent.ThreadPoolExecutor.finalize() timed out after 10 seconds
android.os.BinderProxy.finalize() timed out after 10 seconds
android.graphics.Path.finalize() timed out after 10 seconds
The devices on which this happens are overwhelmingly (but not exclusively) devices manufactured by Samsung. That could just mean that most of our users are using Samsung devices; alternately it could indicate a problem with Samsung devices. I'm not really sure.
I suppose this doesn't really answer your questions, but I just wanted to reinforce that this seems quite common, and is not specific to your application.
use this: (?<=beginningstringname)(.*\n?)(?=endstringname)
If you are using Jenkins pipelines and want to checkout a specific tag (eg: a TAG
parameter of your build), here is what you can do:
stage('Checkout') {
steps {
checkout scm: [$class: 'GitSCM', userRemoteConfigs: [[url: 'YOUR_GIT_REPO_URL.git', credentialsId: 'YOUR_GIT_CREDENTIALS_ID' ]], branches: [[name: 'refs/tags/${TAG}']]], poll: false
}
}
None of the above work on OSX.
Do the following:
perl -pi -w -e 's/SEARCH_FOR/REPLACE_WITH/g;' *.txt
This is based on Jim's answer,
SELECT
@field_text + SPACE(@pad_length - LEN(@field_text)) AS RightPad
,SPACE(@pad_length - LEN(@field_text)) + @field_text AS LeftPad
Advantages
Disadvantages
I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.
There are many possible options for specifying your log4j configuration. One is for the file to be named exactly "log4j.properties" and be in your classpath. Another is to name it however you want and add a System property to the command line when you start Java, like this:
-Dlog4j.configuration=file:///path/to/your/log4j.properties
All of them are outlined here http://logging.apache.org/log4j/1.2/manual.html#defaultInit
here is a link to generate a short list of options available to npm; it filters on the keywords unused packages
Overloading: In Real world, overloading means assigning some extra stuff to someone. As as in real world Overloading in PHP means calling extra functions. In other way You can say it have slimier function with different parameter.In PHP you can use overloading with magic functions e.g. __get, __set, __call etc.
Example of Overloading:
class Shape {
const Pi = 3.142 ; // constant value
function __call($functionname, $argument){
if($functionname == 'area')
switch(count($argument)){
case 0 : return 0 ;
case 1 : return self::Pi * $argument[0] ; // 3.14 * 5
case 2 : return $argument[0] * $argument[1]; // 5 * 10
}
}
}
$circle = new Shape();`enter code here`
echo "Area of circle:".$circle->area()."</br>"; // display the area of circle Output 0
echo "Area of circle:".$circle->area(5)."</br>"; // display the area of circle
$rect = new Shape();
echo "Area of rectangle:".$rect->area(5,10); // display area of rectangle
Overriding : In object oriented programming overriding is to replace parent method in child class.In overriding you can re-declare parent class method in child class. So, basically the purpose of overriding is to change the behavior of your parent class method.
Example of overriding :
class parent_class
{
public function text() //text() is a parent class method
{
echo "Hello!! everyone I am parent class text method"."</br>";
}
public function test()
{
echo "Hello!! I am second method of parent class"."</br>";
}
}
class child extends parent_class
{
public function text() // Text() parent class method which is override by child
class
{
echo "Hello!! Everyone i am child class";
}
}
$obj= new parent_class();
$obj->text(); // display the parent class method echo
$obj= new parent_class();
$obj->test();
$obj= new child();
$obj->text(); // display the child class method echo
One common error is leaving a space before the class names. Even if this was the correct syntax:
.menu a:hover .main-nav-item
it never would have worked.
Therefore, you would not write
.menu a .main-nav-item:hover
it would be
.menu a.main-nav-item:hover
For a popup javascript is required. Put this in your header:
<script>
function myFunction()
{
alert("I am an alert box!"); // this is the message in ""
}
</script>
And this in your body:
<input type="button" onclick="myFunction()" value="Show alert box">
When the button is pressed a box pops up with the message set in the header.
This can be put in any html or php file without the php tags.
-----EDIT-----
To display it using php try this:
<?php echo '<script>myfunction()</script>'; ?>
It may not be 100% correct but the principle is the same.
To display different messages you can either create lots of functions or you can pass a variable in to the function when you call it.
You can do a simple return of the .length
here:
function areAnyChecked(formID) {
return !!$('#'+formID+' input[type=checkbox]:checked').length;
}
This look for checkboxes in the given form, sees if any are :checked
and returns true
if they are (since the length would be 0 otherwise). To make it a bit clearer, here's the non boolean converted version:
function howManyAreChecked(formID) {
return $('#'+formID+' input[type=checkbox]:checked').length;
}
This would return a count of how many were checked.
CharField
has max_length of 255
characters while TextField
can hold more than 255
characters. Use TextField
when you have a large string as input. It is good to know that when the max_length
parameter is passed into a TextField
it passes the length validation to the TextArea
widget.
Make sure you are injecting the repository into the service's constructor. That solved it for me. ::smacks forehead::
I suppose you don't want your textarea-content to be parsed as HTML. In this case, you can just set it as plaintext so the browser doesn't treat it as HTML and doesn't remove newlines No CSS or preprocessing required.
<script>_x000D_
function copycontent(){_x000D_
var content = document.getElementById('ta').value;_x000D_
document.getElementById('target').innerText = content;_x000D_
}_x000D_
</script>_x000D_
<textarea id='ta' rows='3'>_x000D_
line 1_x000D_
line 2_x000D_
line 3_x000D_
</textarea>_x000D_
<button id='btn' onclick='copycontent();'>_x000D_
Copy_x000D_
</button>_x000D_
<p id='target'></p>
_x000D_
Something like this should do the trick (However, read after the snippet for more info)
CREATE PROCEDURE GetFilteredData()
BEGIN
DECLARE bDone INT;
DECLARE var1 CHAR(16); -- or approriate type
DECLARE Var2 INT;
DECLARE Var3 VARCHAR(50);
DECLARE curs CURSOR FOR SELECT something FROM somewhere WHERE some stuff;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DROP TEMPORARY TABLE IF EXISTS tblResults;
CREATE TEMPORARY TABLE IF NOT EXISTS tblResults (
--Fld1 type,
--Fld2 type,
--...
);
OPEN curs;
SET bDone = 0;
REPEAT
FETCH curs INTO var1,, b;
IF whatever_filtering_desired
-- here for whatever_transformation_may_be_desired
INSERT INTO tblResults VALUES (var1, var2, var3 ...);
END IF;
UNTIL bDone END REPEAT;
CLOSE curs;
SELECT * FROM tblResults;
END
A few things to consider...
Concerning the snippet above:
More generally: trying to avoid needing a cursor.
I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.
Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.
I have been developing and designing iOS apps for a while and This is the best iOS design cheat sheet out there!
have fun :)!
Update: For iOS 8+, and the new devices (iPhone 6, 6 Plus, iPad Air) see this updated link.
Meta update: Iphone 6s/6s Plus have the same resolutions as iPhone 6/6 Plus respectively
This is an image from the new version of the article:
On Postgres 10:
SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)
The way you do it is pretty standard. You can define a utility clamp
function:
/**
* Returns a number whose value is limited to the given range.
*
* Example: limit the output of this computation to between 0 and 255
* (x * 255).clamp(0, 255)
*
* @param {Number} min The lower boundary of the output range
* @param {Number} max The upper boundary of the output range
* @returns A number in the range [min, max]
* @type Number
*/
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
(Although extending language built-ins is generally frowned upon)
Put the <label>
outside the form-group
:
<form class="form-inline">
<label for="rg-from">Ab: </label>
<div class="form-group">
<input type="text" id="rg-from" name="rg-from" value="" class="form-control">
</div>
<!-- rest of form -->
</form>
Diff command in Unix is used to find the differences between files(all types). Since directory is also a type of file, the differences between two directories can easily be figure out by using diff commands. For more option use man diff on your unix box.
-b Ignores trailing blanks (spaces and tabs)
and treats other strings of blanks as
equivalent.
-i Ignores the case of letters. For example,
`A' will compare equal to `a'.
-t Expands <TAB> characters in output lines.
Normal or -c output adds character(s) to the
front of each line that may adversely affect
the indentation of the original source lines
and make the output lines difficult to
interpret. This option will preserve the
original source's indentation.
-w Ignores all blanks (<SPACE> and <TAB> char-
acters) and treats all other strings of
blanks as equivalent. For example,
`if ( a == b )' will compare equal to
`if(a==b)'.
and there are many more.
This is an expansion of @Michael Tiller's excellent answer. His answer works for initializing variables from the view by injecting the $attrs
object into the controller. The problem occurs if the same controller is called from $routeProvider
when you navigate by routing. Then you get injector error Unknown provider : $attrsProvider
because $attrs
is only available for injection when the view is compiled. The solution is to pass the variable (foo) through $routeParams
when initializing controller from route and by $attrs
when initializing controller from view. Here's my solution.
From Route
$routeProvider.
when('/mypage/:foo', {
templateUrl: 'templates/mypage.html',
controller: 'MyPageController',
caseInsensitiveMatch: true,
resolve: {
$attrs: function () {
return {};
}
}
});
This handles a url such as '/mypage/bar'
. As you can see foo is passed by url param and we provide the $injector
with a blank object for $attrs
so no injector errors.
From View
<div ng-controller="MyPageController" data-foo="bar">
</div>
Now the controller
var app = angular.module('myapp', []);
app.controller('MyPageController',['$scope', '$attrs', '$routeParams'], function($scope, $attrs, $routeParams) {
//now you can initialize foo. If $attrs contains foo, it's been initialized from view
//else find it from $routeParams
var foo = $attrs.foo? $attrs.foo : $routeParams.foo;
console.log(foo); //prints 'bar'
});
Pass the string and replace space with line break, it gives you desired result.
select replace('shailendra kumar',' ',chr(10)) from dual;
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
In my macOS (10.13.3), I got it solved after reinstalling Node version manager.
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
source ~/.bashrc
You can have a constructor in the abstract class that accepts the init parameters. The Java spec only specifies that the anonymous class, which is the offspring of the (optionally) abstract class or implementation of an interface, can not have a constructor by her own right.
The following is absolutely legal and possible:
static abstract class Q{
int z;
Q(int z){ this.z=z;}
void h(){
Q me = new Q(1) {
};
}
}
If you have the possibility to write the abstract class yourself, put such a constructor there and use fluent API where there is no better solution. You can this way override the constructor of your original class creating an named sibling class with a constructor with parameters and use that to instantiate your anonymous class.
@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.
WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;
Hope this helps... :D
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
<a href="#test100">Test link</a>
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?
<h1><span>This is</span> a Headline</h1>
h1 { font-weight: normal; text-transform: uppercase; }
h1 span { font-weight: bold; }
I'm not sure if it was just for the sake of showing us, but as a side note, you should always set uppercase text with CSS :)
You can try macro also.
#define NONE 0x00
#define DBG 0x1F
#define INFO 0x0F
#define ERR 0x07
#define EMR 0x03
#define CRIT 0x01
#define DEBUG_LEVEL ERR
#define WHERESTR "[FILE : %s, FUNC : %s, LINE : %d]: "
#define WHEREARG __FILE__,__func__,__LINE__
#define DEBUG(...) fprintf(stderr, __VA_ARGS__)
#define DEBUG_PRINT(X, _fmt, ...) if((DEBUG_LEVEL & X) == X) \
DEBUG(WHERESTR _fmt, WHEREARG,__VA_ARGS__)
int main()
{
int x=10;
DEBUG_PRINT(DBG, "i am x %d\n", x);
return 0;
}
\b
matches at word boundaries (without actually matching any characters), so the following should do what you want:
\bstackoverflow\b
You can get last N records simply by using last method:
Record.last(N)
Example:
User.last(5)
Returns 5 users in descending order by their id.
An active record query like this I think would get you what you want ('Something' is the model name):
Something.find(:all, :order => "id desc", :limit => 5).reverse
edit: As noted in the comments, another way:
result = Something.find(:all, :order => "id desc", :limit => 5)
while !result.empty?
puts result.pop
end
$.when
doesn't work for me, callback(x)
instead of return x
worked as described here: https://stackoverflow.com/a/13455253/10357604
That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null
or undefined
here, so don't complain about the possibility of it being null
or undefined
." Sometimes the type checker is unable to make that determination itself.
It is explained here:
A new
!
post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operationx!
produces a value of the type ofx
withnull
andundefined
excluded. Similar to type assertions of the forms<T>x
andx as T
, the!
non-null assertion operator is simply removed in the emitted JavaScript code.
I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.
Short oneliner for CamelCases when you have spaces also included (doesn't work correctly if you have a word inbetween with small starting-letter):
a = "Test String"
a.gsub(' ', '').underscore
=> "test_string"
- We can add a page break tag with style "page-break-after: always" at the point where we want to introduce the pagebreak in the html page.
- "page-break-before" also works
Example:
HTML_BLOCK_1
<p style="page-break-after: always"></p>
HTML_BLOCK_2
<p style="page-break-after: always"></p>
HTML_BLOCK_3
While printing the html file with the above code, the print preview will show three pages (one for each html block "HTML_BLOCK_n" ) where as in the browser all the three blocks appear sequentially one after the other.
The uriVariables are also expanded in the query string. For example, the following call will expand values for both, account and name:
restTemplate.exchange("http://my-rest-url.org/rest/account/{account}?name={name}",
HttpMethod.GET,
httpEntity,
clazz,
"my-account",
"my-name"
);
so the actual request url will be
http://my-rest-url.org/rest/account/my-account?name=my-name
Look at HierarchicalUriComponents.expandInternal(UriTemplateVariables) for more details. Version of Spring is 3.1.3.
Here is one way you could do it...
find . -type f -name "*_peaks.bed" | egrep -v "^(./tmp/|./scripts/)"
The following code works perfectly
public Comparator<Map<String, String>> mapComparator = new Comparator<Map<String, String>>() {
public int compare(Map<String, String> m1, Map<String, String> m2) {
return m1.get("name").compareTo(m2.get("name"));
}
}
Collections.sort(list, mapComparator);
But your maps should probably be instances of a specific class.
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax
kwarg to tell fig.colorbar
to use the new axes.
For example:
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()
I've written the tests that compare using regular expressions (as per other answers) against not using regular expressions. Tests done on a quad core OSX10.8 machine running Java 1.6
Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2()
function is marginally faster than isAlphanumeric()
. One supports the case where extended Unicode numbers are allowed, and the other is for when only standard ASCII numbers are allowed.
public class QuickTest extends TestCase {
private final int reps = 1000000;
public void testRegexp() {
for(int i = 0; i < reps; i++)
("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
}
public void testIsAlphanumeric() {
for(int i = 0; i < reps; i++)
isAlphanumeric("ab4r3rgf"+i);
}
public void testIsAlphanumeric2() {
for(int i = 0; i < reps; i++)
isAlphanumeric2("ab4r3rgf"+i);
}
public boolean isAlphanumeric(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
public boolean isAlphanumeric2(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
}
For bootstrap 4 just add this class:
w-100
Start GDB on your project.
Go to project directory, where you've already compiled the project executable. Issue the command gdb and the name of the executable as below:
gdb projectExecutablename
This starts up gdb, prints the following: GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. ................................................. Type "apropos word" to search for commands related to "word"... Reading symbols from projectExecutablename...done. (gdb)
Before you start your program running, you want to set up your breakpoints. The break command allows you to do so. To set a breakpoint at the beginning of the function named main:
(gdb) b main
Once you've have the (gdb) prompt, the run command starts the executable running. If the program you are debugging requires any command-line arguments, you specify them to the run command. If you wanted to run my program on the "xfiles" file (which is in a folder "mulder" in the project directory), you'd do the following:
(gdb) r mulder/xfiles
Hope this helps.
Disclaimer: This solution is not mine, it is adapted from https://web.stanford.edu/class/cs107/guide_gdb.html This short guide to gdb was, most probably, developed at Stanford University.
DECLARE @DDate date -- To store the current date
DECLARE @DTime time -- To store the current time
DECLARE @DateTime datetime -- To store the result of the concatenation
;
SET @DDate = GETDATE() -- Getting the current date
SET @DTime = GETDATE() -- Getting the current time
SET @DateTime = CONVERT(datetime, CONVERT(varchar(19), LTRIM(@DDate) + ' ' + LTRIM(@DTime) ));
;
/*
1. LTRIM the date and time do an automatic conversion of both types to string.
2. The inside CONVERT to varchar(19) is needed, because you cannot do a direct conversion to datetime
3. Once the inside conversion is done, the second do the final conversion to datetime.
*/
-- The following select shows the initial variables and the result of the concatenation
SELECT @DDate, @DTime, @DateTime
Follow this steps:
-Build
-Generate Signed Apk
-Create new
Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)
I wouldn't recommend any of these methods. Instead, put it within its own namespace.
class Post < ActiveRecord::Base
def clean_input
self.input = Helpers.sanitize(self.input, :tags => %w(b i u))
end
module Helpers
extend ActionView::Helpers::SanitizeHelper
end
end
Although it doesn't make much difference on the way in, it does on the way back.
Sure you can use either '/' or '\' in new File(String path), but File.getPath() will only give you one of them.
I noticed that there are few example of using Java 8 stream to solve your problem but I think that this is the simplest one:
int[] intTab = String.valueOf(number).chars().map(Character::getNumericValue).toArray();
To be clear:
You use String.valueOf(number)
to convert int to String, then chars()
method to get an IntStream (each char from your string is now an Ascii number), then you need to run map()
method to get a numeric values of the Ascii number. At the end you use toArray()
method to change your stream into an int[] array.
I use:
Install Node.js. and npm. npm is installed with Node.js
Placed inside the root project directory
$ cd <your_angularjs_project>
The next command creates package.json
$ npm init
Install express ==> Fast, unopinionated, minimalist for node:
$ npm install express --save
Install morgan ==> HTTP request logger middleware for node.js
$ npm install morgan --save
create file server.js
add the following code in server.js file
// Required Modules
var express = require("express");
var morgan = require("morgan");
var app = express();
var port = process.env.PORT || 3002;
app.use(morgan("dev"));
app.use(express.static("./"));
app.get("/", function(req, res) {
res.sendFile("./index.html"); //index.html file of your angularjs application
});
// Start Server
app.listen(port, function () {
console.log( "Express server listening on port " + port);
});
Finally run your AngularJS project in localhost server:
$ node server.js
Tried this out quickly in the interactive shell:
>>> l = ['a', 'ab', 'abc', 'bac']
>>> [x for x in l if 'ab' in x]
['ab', 'abc']
>>>
Why does this work? Because the in
operator is defined for strings to mean: "is substring of".
Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:
l = ['a', 'ab', 'abc', 'bac']
result = []
for s in l:
if 'ab' in s:
result.append(s)
numpy.dot(a, b, out=None)
Dot product of two arrays.
For N dimensions it is a sum product over the last axis of a
and the second-to-last of b
.
Documentation: numpy.dot.
This will get you a string array of all the resources:
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
To reduce memory consumption and to speed up the search you may use -ReadCount option of Get-Content cmdlet (https://technet.microsoft.com/ru-ru/library/hh849787.aspx).
This may save hours when you working with large files.
Here is an example:
$n = 60699010
$src = 'hugefile.csv'
$batch = 100
$timer = [Diagnostics.Stopwatch]::StartNew()
$count = 0
Get-Content $src -ReadCount $batch -TotalCount $n | % {
$count += $_.Length
if ($count -ge $n ) {
$_[($n - $count + $_.Length - 1)]
}
}
$timer.Stop()
$timer.Elapsed
This prints $n'th line and elapsed time.
I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr
), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:
```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```
Then all the images will be written as PDF files, and LaTeX will be happy.
Your second problem is you are mixing up the HTML units with LaTeX units in out.width
/ out.height
. LaTeX and HTML are very different technologies. You should not expect \maxwidth
to work in HTML, or 200px
in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width
/ out.height
(use fig.width
/ fig.height
and let LaTeX use the original size).
Just throw any RuntimeException
from a method marked as @Transactional
.
By default all RuntimeException
s rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor()
and noRollbackFor()
annotation parameters:
@Transactional(rollbackFor=Exception.class)
This will rollback transaction after throwing any exception.
Acording to your first code snipet seems ok, but I've got similar behavior caused by bad programing. Have you checked the "options" variable is not null before the put call?
I'm using Struts2 (2.3.3) webapp and use a HashMap for displaying results. When is executed (in a class initialized by an Action class) :
if(value != null) pdfMap.put("date",value.toString());
else pdfMap.put("date","");
Got this error:
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
File: aoc/psisclient/samples/PDFValidation.java
Line number: 155
Stacktraces
java.lang.NullPointerException
aoc.psisclient.samples.PDFValidation.getRevisionsDetail(PDFValidation.java:155)
aoc.action.signature.PDFUpload.execute(PDFUpload.java:66)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
...
Seems the NullPointerException points to the put method (Line number 155), but the problem was that de Map hasn't been initialized before. It compiled ok since the variable is out of the method that set the value.
If you're using on a web page, you can also use CSS:
style="text-transform:capitalize;"
Here is MySQL version which prints only one entry where there are duplicates MAX(datetime) in a group.
You could test here http://www.sqlfiddle.com/#!2/0a4ae/1
mysql> SELECT * from topten;
+------+------+---------------------+--------+----------+
| id | home | datetime | player | resource |
+------+------+---------------------+--------+----------+
| 1 | 10 | 2009-04-03 00:00:00 | john | 399 |
| 2 | 11 | 2009-04-03 00:00:00 | juliet | 244 |
| 3 | 10 | 2009-03-03 00:00:00 | john | 300 |
| 4 | 11 | 2009-03-03 00:00:00 | juliet | 200 |
| 5 | 12 | 2009-04-03 00:00:00 | borat | 555 |
| 6 | 12 | 2009-03-03 00:00:00 | borat | 500 |
| 7 | 13 | 2008-12-24 00:00:00 | borat | 600 |
| 8 | 13 | 2009-01-01 00:00:00 | borat | 700 |
| 9 | 10 | 2009-04-03 00:00:00 | borat | 700 |
| 10 | 11 | 2009-04-03 00:00:00 | borat | 700 |
| 12 | 12 | 2009-04-03 00:00:00 | borat | 700 |
+------+------+---------------------+--------+----------+
SELECT *
FROM (
SELECT ord.*,
IF (@prev_home = ord.home, 0, 1) AS is_first_appear,
@prev_home := ord.home
FROM (
SELECT t1.id, t1.home, t1.player, t1.resource
FROM topten t1
INNER JOIN (
SELECT home, MAX(datetime) AS mx_dt
FROM topten
GROUP BY home
) x ON t1.home = x.home AND t1.datetime = x.mx_dt
ORDER BY home
) ord, (SELECT @prev_home := 0, @seq := 0) init
) y
WHERE is_first_appear = 1;
+------+------+--------+----------+-----------------+------------------------+
| id | home | player | resource | is_first_appear | @prev_home := ord.home |
+------+------+--------+----------+-----------------+------------------------+
| 9 | 10 | borat | 700 | 1 | 10 |
| 10 | 11 | borat | 700 | 1 | 11 |
| 12 | 12 | borat | 700 | 1 | 12 |
| 8 | 13 | borat | 700 | 1 | 13 |
+------+------+--------+----------+-----------------+------------------------+
4 rows in set (0.00 sec)
SELECT tt.*
FROM topten tt
INNER JOIN
(
SELECT home, MAX(datetime) AS MaxDateTime
FROM topten
GROUP BY home
) groupedtt ON tt.home = groupedtt.home AND tt.datetime = groupedtt.MaxDateTime
+------+------+---------------------+--------+----------+
| id | home | datetime | player | resource |
+------+------+---------------------+--------+----------+
| 1 | 10 | 2009-04-03 00:00:00 | john | 399 |
| 2 | 11 | 2009-04-03 00:00:00 | juliet | 244 |
| 5 | 12 | 2009-04-03 00:00:00 | borat | 555 |
| 8 | 13 | 2009-01-01 00:00:00 | borat | 700 |
| 9 | 10 | 2009-04-03 00:00:00 | borat | 700 |
| 10 | 11 | 2009-04-03 00:00:00 | borat | 700 |
| 12 | 12 | 2009-04-03 00:00:00 | borat | 700 |
+------+------+---------------------+--------+----------+
7 rows in set (0.00 sec)
You can use the variables name itself to check if a value is an integer. for example:
#include <iostream>
using namespace std;
int main (){
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
if(firstvariable && secondvariable){
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
cout << "\n[ERROR\tINVALID INPUT]\n";
return 1;
}
return 0;
}
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class DoSomethingInAThread implements Runnable
{
public static void main(String[] args) throws ExecutionException, InterruptedException
{
//limit the number of actual threads
int poolSize = 10;
ExecutorService service = Executors.newFixedThreadPool(poolSize);
List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>();
for (int n = 0; n < 1000; n++)
{
Future f = service.submit(new DoSomethingInAThread());
futures.add(f);
}
// wait for all tasks to complete before continuing
for (Future<Runnable> f : futures)
{
f.get();
}
//shut down the executor service so that this thread can exit
service.shutdownNow();
}
public void run()
{
// do something here
}
}
Dim sHostName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
To your first question, you can't really do any query through YQL to get data for all companies. It's more oriented towards obtaining data for a smaller query. (I.e., it's not going to give you a full data dump of the whole Yahoo! Finance database.)
To your second question, here's how you can get started exploring the Yahoo! Finance tables in YQL:
finance
in the search fieldThen you can try some example queries like the following:
select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")
Update 2016-04-04: Here's a current screenshot showing the location of the Show Community Tables checkbox which must be clicked to see these finance tables:
You can set an ENV if you want your Time.now
and DateTime.now
to respond in UTC time.
require 'date'
Time.now #=> 2015-11-30 11:37:14 -0800
DateTime.now.to_s #=> "2015-11-30T11:37:25-08:00"
ENV['TZ'] = 'UTC'
Time.now #=> 2015-11-30 19:37:38 +0000
DateTime.now.to_s #=> "2015-11-30T19:37:36+00:00"
We also need to mention default schema for SQSERVER: dbo
<property name="hibernate.default_schema">dbo</property>
Tested with hibernate 4
Chrome doesn't seem to understand true
and false
.
Use autostart="1"
and autostart="0"
instead.
Source: (Google Groups: https://productforums.google.com/forum/#!topic/chrome/LkA8FoBoleU)
you must have record in table or array record in database.
example:
SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);
You can use bind method to attach function to several events. Just pass the event names and the handler function as in this code:
$('#foo').bind('mouseenter mouseleave', function() {
$(this).toggleClass('entered');
});
Another option is to use chaining support of jquery api.
$_ is an variable which iterates over each object/element passed from the previous | (pipe).
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an __init__.py
file.
Allowing implicit namespace packages means that the requirement to provide an
__init__.py
file can be dropped completely, and affected ... .
The old way with __init__.py
files still works as in Python 2.
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
The difference between gcc and g++ are:
gcc | g++
compiles c source | compiles c++ source
use g++ instead of gcc to compile you c++ source.
My solution:
I have created wrapper over Object.assign to fix typing issues.
export function assign<T>(...args: T[] | Partial<T>[]): T {
return Object.assign.apply(Object, [{}, ...args]);
}
Usage:
env.base.ts
export interface EnvironmentValues {
export interface EnvironmentValues {
isBrowser: boolean;
apiURL: string;
}
export const enviromentBaseValues: Partial<EnvironmentValues> = {
isBrowser: typeof window !== 'undefined',
};
export default enviromentBaseValues;
env.dev.ts
import { EnvironmentValues, enviromentBaseValues } from './env.base';
import { assign } from '../utilities';
export const enviromentDevValues: EnvironmentValues = assign<EnvironmentValues>(
{
apiURL: '/api',
},
enviromentBaseValues
);
export default enviromentDevValues;
What is the difference between abstract class and interface in Python?
An interface, for an object, is a set of methods and attributes on that object.
In Python, we can use an abstract base class to define and enforce an interface.
For example, say we want to use one of the abstract base classes from the collections
module:
import collections
class MySet(collections.Set):
pass
If we try to use it, we get an TypeError
because the class we created does not support the expected behavior of sets:
>>> MySet()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MySet with abstract methods
__contains__, __iter__, __len__
So we are required to implement at least __contains__
, __iter__
, and __len__
. Let's use this implementation example from the documentation:
class ListBasedSet(collections.Set):
"""Alternate set implementation favoring space over speed
and not requiring the set elements to be hashable.
"""
def __init__(self, iterable):
self.elements = lst = []
for value in iterable:
if value not in lst:
lst.append(value)
def __iter__(self):
return iter(self.elements)
def __contains__(self, value):
return value in self.elements
def __len__(self):
return len(self.elements)
s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2
We can create our own Abstract Base Class by setting the metaclass to abc.ABCMeta
and using the abc.abstractmethod
decorator on relevant methods. The metaclass will be add the decorated functions to the __abstractmethods__
attribute, preventing instantiation until those are defined.
import abc
For example, "effable" is defined as something that can be expressed in words. Say we wanted to define an abstract base class that is effable, in Python 2:
class Effable(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __str__(self):
raise NotImplementedError('users must define __str__ to use this base class')
Or in Python 3, with the slight change in metaclass declaration:
class Effable(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def __str__(self):
raise NotImplementedError('users must define __str__ to use this base class')
Now if we try to create an effable object without implementing the interface:
class MyEffable(Effable):
pass
and attempt to instantiate it:
>>> MyEffable()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyEffable with abstract methods __str__
We are told that we haven't finished the job.
Now if we comply by providing the expected interface:
class MyEffable(Effable):
def __str__(self):
return 'expressable!'
we are then able to use the concrete version of the class derived from the abstract one:
>>> me = MyEffable()
>>> print(me)
expressable!
There are other things we could do with this, like register virtual subclasses that already implement these interfaces, but I think that is beyond the scope of this question. The other methods demonstrated here would have to adapt this method using the abc
module to do so, however.
We have demonstrated that the creation of an Abstract Base Class defines interfaces for custom objects in Python.
You can use ClassLoader.getResource
method to get the correct resource.
URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();
OR
Although this may not work all the time, a simpler solution -
You can create a File
object and use getAbsolutePath
method:
File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();
Is it possible that you can avoid using wsdl2java? You can straight away use CXF FrontEnd APIs to invoke your SOAP Webservice. The only catch is that you need to create your SEI and VOs on your client end. Here is a sample code.
package com.aranin.weblog4j.client;
import com.aranin.weblog4j.services.BookShelfService;
import com.aranin.weblog4j.vo.BookVO;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class DemoClient {
public static void main(String[] args){
String serviceUrl = "http://localhost:8080/weblog4jdemo/bookshelfservice";
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(BookShelfService.class);
factory.setAddress(serviceUrl);
BookShelfService bookService = (BookShelfService) factory.create();
//insert book
BookVO bookVO = new BookVO();
bookVO.setAuthor("Issac Asimov");
bookVO.setBookName("Foundation and Earth");
String result = bookService.insertBook(bookVO);
System.out.println("result : " + result);
bookVO = new BookVO();
bookVO.setAuthor("Issac Asimov");
bookVO.setBookName("Foundation and Empire");
result = bookService.insertBook(bookVO);
System.out.println("result : " + result);
bookVO = new BookVO();
bookVO.setAuthor("Arthur C Clarke");
bookVO.setBookName("Rama Revealed");
result = bookService.insertBook(bookVO);
System.out.println("result : " + result);
//retrieve book
bookVO = bookService.getBook("Foundation and Earth");
System.out.println("book name : " + bookVO.getBookName());
System.out.println("book author : " + bookVO.getAuthor());
}
}
You can see the full tutorial here http://weblog4j.com/2012/05/01/developing-soap-web-service-using-apache-cxf/
Change this (CURRENT_TIMESTAMP-30)
To This: DateADD(mi, -30, Current_TimeStamp)
To get the current date use GetDate().
MSDN Link to DateAdd Function
MSDN Link to Get Date Function
As I was researching this I found my answer, but can't find the answer on the internet, so I thought I'd share this:
I fixed my issue by modifying my applicationhost.config file. My file was saved in the "\My Documents\IISExpress\config" folder.
It seems that VS2013 was ignoring my web.config file and applying different authentication methods.
I had to modify this portion of the file to look like the below. In truth, I only modified the anonymousAuthentication to be false and the windowsAuthentication mode to true.
<authentication>
<anonymousAuthentication enabled="false" userName="" />
<basicAuthentication enabled="false" />
<clientCertificateMappingAuthentication enabled="false" />
<digestAuthentication enabled="false" />
<iisClientCertificateMappingAuthentication enabled="false">
</iisClientCertificateMappingAuthentication>
<windowsAuthentication enabled="true">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
</authentication>
Perhaps use plt.annotate:
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show()
Collapse All is Fold All in Visual Studio Code.
Press Ctrl + K + S for All Settings. Assign a key which you want for Fold All. By default it's Ctrl + K + 0.
I've tried a lot of solutions, but on Ubuntu 20.04 only this worked for me:
export PATH="$HOME/.composer/vendor/bin:$PATH"
This terminal command:
open /Applications/Python\ 3.7/Install\ Certificates.command
Found here: https://stackoverflow.com/a/57614113/6207266
Resolved it for me. With my config
pip install --upgrade certifi
had no impact.
I understand this post is old but if anybody is still searching and has not found a solution to the intellisense issue even after re-installing, applying the cumulative updates, or other methods, then I hope I may be of assistance.
I have Applied SQL 2008 R2 Service Pack 1 which you can download here
http://www.microsoft.com/download/en/details.aspx?id=26727
32 Bit: SQLServer2008R2SP1-KB2528583-x86-ENU.exe
64 Bit: SQLServer2008R2SP1-KB2528583-x64-ENU.exe
I have applied this SP1 and now my intellisense works again. I hope this helps! (:
Since this is a rather popular topic and answers differ, I had to take a fresh look on the problem.
Testing env: EF 6.1.3, SQL Server, 300k records
Table model:
class TestTable
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
Test code:
class Program
{
static void Main()
{
using (var context = new TestContext())
{
context.Database.Log = Console.WriteLine;
context.TestTables.Where(x => x.Surname.Contains("Surname")).Any(x => x.Id > 1000);
context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Any(x => x.Id > 1000);
context.TestTables.Where(x => x.Surname.Contains("Surname")).Count(x => x.Id > 1000);
context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Count(x => x.Id > 1000);
Console.ReadLine();
}
}
}
Results:
Any() ~ 3ms
Count() ~ 230ms for first query, ~ 400ms for second
Remarks:
For my case, EF didn't generate SQL like @Ben mentioned in his post.
ul {
/* Remove default list icon */
list-style: none;
padding: 0;
/* Small width and margin to demonstrate the text wrapping */
width: 200px;
border:1px solid red;
}
li{
/* Make sure the text is properly wrpped (not spilling in the image area) */
display: flex;
}
li:before {
content: url(https://via.placeholder.com/10/0000FF/808080/?text=*);
display: inline-block;
vertical-align: middle;
/* If you want some space between icon and text: */
margin-right: 2em;
}
Command to get the database backup from linux machine terminal.
sqlcmd -S localhost -U SA -Q "BACKUP DATABASE [demodb] TO DISK = N'/var/opt/mssql/data/demodb.bak' WITH NOFORMAT, NOINIT, NAME = 'demodb-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10"
You need to find the selected option:
$(this).find(':selected').data('id')
or
$(this).find(':selected').attr('data-id')
although the first method is preferred.
If you have some params, you can do this.
$results = DB::table('rooms')
->distinct()
->leftJoin('bookings', function($join) use ($param1, $param2)
{
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on('arrival','=',DB::raw("'".$param1."'"));
$join->on('arrival','=',DB::raw("'".$param2."'"));
})
->where('bookings.room_type_id', '=', NULL)
->get();
and then return your query
return $results;
Updated 2018
For the original question based on Bootstrap 3, the solution was to use push-pull.
In Bootstrap 4 it's now possible to change the order, even when the columns are full-width stacked vertically, thanks to Bootstrap 4 flexbox. OFC, the push pull method will still work, but now there are other ways to change column order in Bootstrap 4, making it possible to re-order full-width columns.
Method 1 - Use flex-column-reverse
for xs
screens:
<div class="row flex-column-reverse flex-md-row">
<div class="col-md-3">
sidebar
</div>
<div class="col-md-9">
main
</div>
</div>
Method 2 - Use order-first
for xs
screens:
<div class="row">
<div class="col-md-3">
sidebar
</div>
<div class="col-md-9 order-first order-md-last">
main
</div>
</div>
Bootstrap 4(alpha 6): http://www.codeply.com/go/bBMOsvtJhD
Bootstrap 4.1: https://www.codeply.com/go/e0v77yGtcr
Original 3.x Answer
For the original question based on Bootstrap 3, the solution was to use push-pull for the larger widths, and then the columns will show is their natural order on smaller (xs) widths. (A-B reverse to B-A).
<div class="container">
<div class="row">
<div class="col-md-9 col-md-push-3">
main
</div>
<div class="col-md-3 col-md-pull-9">
sidebar
</div>
</div>
</div>
Bootstrap 3: http://www.codeply.com/go/wgzJXs3gel
@emre stated, "You cannot change the order of columns in smaller screens but you can do that in large screens". However, this should be clarified to state: "You cannot change the order of full-width "stacked" columns.." in Bootstrap 3.
A more eye-friendly solution using dplyr
would be
require(dplyr)
## fake blank cells
iris[1,1]=""
## define a helper function
empty_as_na <- function(x){
if("factor" %in% class(x)) x <- as.character(x) ## since ifelse wont work with factors
ifelse(as.character(x)!="", x, NA)
}
## transform all columns
iris %>% mutate_each(funs(empty_as_na))
To apply the correction to just a subset of columns you can specify columns of interest using dplyr's column matching syntax. Example:mutate_each(funs(empty_as_na), matches("Width"), Species)
In case you table contains dates you should consider using a more typesafe version of ifelse
Since iOS 8 came out, this problem does not exist any more. The scroll event is now fired smoothly in iOS Safari as well.
So, if you register the scroll
event handler and check window.pageYOffset
inside that event handler, everything works just fine.
There are 2 potential issues that I see:
1 - IE has had trouble with position:fixed in the past. If you are using IE7+ with a valid doctype or a non-IE browser this isn't part of the problem
2 - You need to specify a width for the footer if you want the footer object to be centered. Otherwise it defaults to the full width of the page and the auto margin for the left and right get set to 0. If you want the footer bar to take up the width (like the StackOverflow notice bar) and center the text, then you need to add "text-align: center" to your definition.
Try this one:
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Create a calendar object with today date. Calendar is in java.util pakage.
Calendar calendar = Calendar.getInstance();
// Move calendar to yesterday
calendar.add(Calendar.DATE, -1);
// Get current date of calendar which point to the yesterday now
Date yesterday = calendar.getTime();
return dateFormat.format(yesterday).toString();
}
If you are experienced with SQL Server, I would recommend ASP.NET.
ADO.NET gives you good access to SQL Server, and with SMO, you will also have just about the best access to SQL Server features. You can access SQL Server from other environments, but nothing is quite as integrated or predictable.
You can call your stored procs with SqlCommand and process the results the SqlDataReader and you'll be in business.
What are you trying to do?
The InterruptedException
is thrown when a thread is waiting or sleeping and another thread interrupts it using the interrupt
method in class Thread
. So if you catch this exception, it means that the thread has been interrupted. Usually there is no point in calling Thread.currentThread().interrupt();
again, unless you want to check the "interrupted" status of the thread from somewhere else.
Regarding your other option of throwing a RuntimeException
, it does not seem a very wise thing to do (who will catch this? how will it be handled?) but it is difficult to tell more without additional information.
Kibana is also a good solution. It is a data visualization platform for Elastic.If installed it runs by default on port 5601.
Out of the many things it provides. It has "Dev Tools" where we can do your debugging.
For example you can check your available indexes here using the command
GET /_cat/indices
if($query)
{
// try to export to excel the whole data ---
//initialize php excel first
ob_end_clean();
//--- create php excel object ---
$objPHPExcel = new PHPExcel();
//define cachemethod
ini_set('memory_limit', '3500M');
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
$cacheSettings = array('memoryCacheSize' => '800MB');
//set php excel settings
PHPExcel_Settings::setCacheStorageMethod(
$cacheMethod,$cacheSettings
);
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
$objPHPExcel->setActiveSheetIndex(0);
// Field names in the first row
$fields = $query->list_fields();
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
// Fetching the table data
$row = 2;
foreach($query->result() as $data)
{
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
$col++;
}
$row++;
}
$objPHPExcel->setActiveSheetIndex(0);
//redirect to cleint browser
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename=Provinces.xlsx');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
change your code to this
$start_date = new DateTime( "@" . $dbResult->db_timestamp );
and it will work fine
Always specify the minimum required version of cmake
cmake_minimum_required(VERSION 3.9)
You should declare a project. cmake
says it is mandatory and it will define convenient variables PROJECT_NAME
, PROJECT_VERSION
and PROJECT_DESCRIPTION
(this latter variable necessitate cmake 3.9):
project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")
Declare a new library target. Please avoid the use of file(GLOB ...)
. This feature does not provide attended mastery of the compilation process. If you are lazy, copy-paste output of ls -1 sources/*.cpp
:
add_library(mylib SHARED
sources/animation.cpp
sources/buffers.cpp
[...]
)
Set VERSION
property (optional but it is a good practice):
set_target_properties(mylib PROPERTIES VERSION ${PROJECT_VERSION})
You can also set SOVERSION
to a major number of VERSION
. So libmylib.so.1
will be a symlink to libmylib.so.1.0.0
.
set_target_properties(mylib PROPERTIES SOVERSION 1)
Declare public API of your library. This API will be installed for the third-party application. It is a good practice to isolate it in your project tree (like placing it include/
directory). Notice that, private headers should not be installed and I strongly suggest to place them with the source files.
set_target_properties(mylib PROPERTIES PUBLIC_HEADER include/mylib.h)
If you work with subdirectories, it is not very convenient to include relative paths like "../include/mylib.h"
. So, pass a top directory in included directories:
target_include_directories(mylib PRIVATE .)
or
target_include_directories(mylib PRIVATE include)
target_include_directories(mylib PRIVATE src)
Create an install rule for your library. I suggest to use variables CMAKE_INSTALL_*DIR
defined in GNUInstallDirs
:
include(GNUInstallDirs)
And declare files to install:
install(TARGETS mylib
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
You may also export a pkg-config
file. This file allows a third-party application to easily import your library:
pkg-config
PKG_CHECK_MODULES
pkg_check_modules
Create a template file named mylib.pc.in
(see pc(5) manpage for more information):
prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=@CMAKE_INSTALL_PREFIX@
libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
Name: @PROJECT_NAME@
Description: @PROJECT_DESCRIPTION@
Version: @PROJECT_VERSION@
Requires:
Libs: -L${libdir} -lmylib
Cflags: -I${includedir}
In your CMakeLists.txt
, add a rule to expand @
macros (@ONLY
ask to cmake to not expand variables of the form ${VAR}
):
configure_file(mylib.pc.in mylib.pc @ONLY)
And finally, install generated file:
install(FILES ${CMAKE_BINARY_DIR}/mylib.pc DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)
You may also use cmake EXPORT
feature. However, this feature is only compatible with cmake
and I find it difficult to use.
Finally the entire CMakeLists.txt
should looks like:
cmake_minimum_required(VERSION 3.9)
project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")
include(GNUInstallDirs)
add_library(mylib SHARED src/mylib.c)
set_target_properties(mylib PROPERTIES
VERSION ${PROJECT_VERSION}
SOVERSION 1
PUBLIC_HEADER api/mylib.h)
configure_file(mylib.pc.in mylib.pc @ONLY)
target_include_directories(mylib PRIVATE .)
install(TARGETS mylib
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES ${CMAKE_BINARY_DIR}/mylib.pc
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)
You can use customValidity
$(function(){ var elements = document.getElementsByTagName("input"); for (var i = 0; i < elements.length; i++) { elements[i].oninvalid = function(e) { e.target.setCustomValidity("This can't be left blank!"); }; } });
I think that will work on at least Chrome and FF, I'm not sure about other browsers
No:
http://www.w3.org/TR/css3-background/#the-box-shadow
You can verify this in Chrome and Firefox by checking the list of computed styles. Other properties that have shorthand methods (like border-radius
) have their variations defined in the spec.
As with most missing "long-hand" CSS properties, CSS variables can solve this problem:
#el {
--box-shadow-color: palegoldenrod;
box-shadow: 1px 2px 3px var(--box-shadow-color);
}
#el:hover {
--box-shadow-color: goldenrod;
}
I don't think finding dialog stuff using $('.any-selector') from the whole DOM is so bright.
Try
$('<div />').dialog({
open: function(event, ui){
var ins = $(this).dialog('instance');
var overlay = ins.overlay;
overlay.off('click').on('click', {$dialog: $(this)}, function(event){
event.data.$dialog.dialog('close');
});
}
});
You're really getting the overlay from the dialog instance it belongs to, things will never go wrong this way.
I find Visual Studio Code is awesome for debugging Django apps. The standard python launch.json parameters run python manage.py
with the debugger attached, so you can set breakpoints and step through your code as you like.
One of the easiest ways to achiever what is mentioned in the question is by using CONTAINS with NEAR or '~'. For example the following queries would give us all the columns that specifically include word1, word2 and word3.
SELECT * FROM MyTable WHERE CONTAINS(Column1, 'word1 NEAR word2 NEAR word3')
SELECT * FROM MyTable WHERE CONTAINS(Column1, 'word1 ~ word2 ~ word3')
In addition, CONTAINSTABLE returns a rank for each document based on the proximity of "word1", "word2" and "word3". For example, if a document contains the sentence, "The word1 is word2 and word3," its ranking would be high because the terms are closer to one another than in other documents.
One other thing that I would like to add is that we can also use proximity_term to find columns where the words are inside a specific distance between them inside the column phrase.
You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules
For details on Scope of variables
refer this link
Please copy the below code into any module, save the workbook and then run the code.
Here is what code does
The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.
I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
folderPath = ThisWorkbook.Path & "\"
fileNm1 = "file1.xlsx"
fileNm2 = "file2.xlsx"
filePath1 = folderPath & fileNm1
filePath2 = folderPath & fileNm2
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Using Prompt to select the file use below code.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
Dim filePath As String
cmdBrowse_Click filePath, 1
filePath1 = filePath
'reset the variable
filePath = vbNullString
cmdBrowse_Click filePath, 2
filePath2 = filePath
fileNm1 = GetFileName(filePath1, "\")
fileNm2 = GetFileName(filePath2, "\")
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select workbook " & num
fd.InitialView = msoFileDialogViewSmallIcons
Dim FileChosen As Integer
FileChosen = fd.Show
fd.Filters.Clear
fd.Filters.Add "Excel macros", "*.xlsx"
fd.FilterIndex = 1
If FileChosen <> -1 Then
MsgBox "You chose cancel"
filePath = ""
Else
filePath = fd.SelectedItems(1)
End If
End Sub
Function GetFileName(fullName As String, pathSeparator As String) As String
Dim i As Integer
Dim iFNLenght As Integer
iFNLenght = Len(fullName)
For i = iFNLenght To 1 Step -1
If Mid(fullName, i, 1) = pathSeparator Then Exit For
Next
GetFileName = Right(fullName, iFNLenght - i)
End Function
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
java.exe
is the console app while javaw.exe
is windows app (console-less). You can't have Console
with javaw.exe
.
Try this statement:
exit 1
Replace 1
with appropriate error codes. See also Exit Codes With Special Meanings.