I fixed the same problem with the below commands... Type python on your terminal. If you see python version 2.x then run these two commands to install pandas:
sudo python -m pip install wheel
and
sudo python -m pip install pandas
Else if you see python version 3.x then run these two commands to install pandas:
sudo python3 -m pip install wheel
and
sudo python3 -m pip install pandas
Good Luck!
You can create a subclass of Application and store your shared object there. The Application object should exist for the lifetime of your app as long as there is some active component.
From your activities, you can access the application object via getApplication()
.
If someone facing this problem when using Docker
, be sure if you are using your version of SQL.
In my case: MYSQL_VERSION=latest
changing to MYSQL_VERSION=5.7
.
Then you need to remove your unused Docker images with docker system prune -a
(docs).
Also, in your .env
you need to change DB_HOST=mysql
. And run php artisan config:clear
.
I think it will help someone.
Yes, you need the full path.
log = open(os.path.join(root, f), 'r')
Is the quick fix. As the comment pointed out, os.walk
decends into subdirs so you do need to use the current directory root rather than indir
as the base for the path join.
This is the code that provides user current location
create Maps Activty:
public class Maps extends MapActivity {
public static final String TAG = "MapActivity";
private MapView mapView;
private LocationManager locationManager;
Geocoder geocoder;
Location location;
LocationListener locationListener;
CountDownTimer locationtimer;
MapController mapController;
MapOverlay mapOverlay = new MapOverlay();
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
initComponents();
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapView.setTraffic(true);
mapView.setStreetView(true);
mapController = mapView.getController();
mapController.setZoom(16);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null) {
Toast.makeText(Maps.this, "Location Manager Not Available",
Toast.LENGTH_SHORT).show();
return;
}
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(Maps.this, "Location Are" + lat + ":" + lng,
Toast.LENGTH_SHORT).show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
locationListener = new LocationListener() {
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
public void onProviderEnabled(String arg0) {}
public void onProviderDisabled(String arg0) {}
public void onLocationChanged(Location l) {
location = l;
locationManager.removeUpdates(this);
if (l.getLatitude() == 0 || l.getLongitude() == 0) {
} else {
double lat = l.getLatitude();
double lng = l.getLongitude();
Toast.makeText(Maps.this, "Location Are" + lat + ":" + lng,
Toast.LENGTH_SHORT).show();
}
}
};
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10f, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 10f, locationListener);
locationtimer = new CountDownTimer(30000, 5000) {
@Override
public void onTick(long millisUntilFinished) {
if (location != null) locationtimer.cancel();
}
@Override
public void onFinish() {
if (location == null) {
}
}
};
locationtimer.start();
}
public MapView getMapView() {
return this.mapView;
}
private void initComponents() {
mapView = (MapView) findViewById(R.id.map_container);
ImageView ivhome = (ImageView) this.findViewById(R.id.imageView_home);
ivhome.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Maps.this, GridViewContainer.class);
startActivity(intent);
finish();
}
});
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.select_map);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:orientation="vertical" >
<com.google.android.maps.MapView
android:id="@+id/map_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="yor api key"
android:clickable="true"
android:focusable="true" />
</LinearLayout>
and define following permission in manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Use simple negative margin rather than using display table.
Updated in fiddle JS Fiddle
.container {
border-style: solid;
border-color: red;
border-width: 1px 0 0 1px;
display: inline-block;
}
.column {
float: left; overflow: hidden;
}
.cell {
border: 1px solid red; width: 120px; height: 20px;
margin:-1px 0 0 -1px;
}
.clearfix {
clear:both;
}
If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).
Eclipse Classic is basically the full featured Eclipse without the Java EE part.
If you need a progmatic solution this should work in jQuery:
$(".abc.xyz").css("width", 200);
Browser technology currently doesn't support downloading a file directly from an Ajax request. The work around is to add a hidden form and submit it behind the scenes to get the browser to trigger the Save dialog.
I'm running a standard Flux implementation so I'm not sure what the exact Redux (Reducer) code should be, but the workflow I just created for a file download goes like this...
FileDownload
. All this component does is render a hidden form and then, inside componentDidMount
, immediately submit the form and call it's onDownloadComplete
prop.Widget
, with a download button/icon (many actually... one for each item in a table). Widget
has corresponding action and store files. Widget
imports FileDownload
.Widget
has two methods related to the download: handleDownload
and handleDownloadComplete
.Widget
store has a property called downloadPath
. It's set to null
by default. When it's value is set to null
, there is no file download in progress and the Widget
component does not render the FileDownload
component.Widget
calls the handleDownload
method which triggers a downloadFile
action. The downloadFile
action does NOT make an Ajax request. It dispatches a DOWNLOAD_FILE
event to the store sending along with it the downloadPath
for the file to download. The store saves the downloadPath
and emits a change event.downloadPath
, Widget
will render FileDownload
passing in the necessary props including downloadPath
as well as the handleDownloadComplete
method as the value for onDownloadComplete
.FileDownload
is rendered and the form is submitted with method="GET"
(POST should work too) and action={downloadPath}
, the server response will now trigger the browser's Save dialog for the target download file (tested in IE 9/10, latest Firefox and Chrome).onDownloadComplete
/handleDownloadComplete
is called. This triggers another action that dispatches a DOWNLOAD_FILE
event. However, this time downloadPath
is set to null
. The store saves the downloadPath
as null
and emits a change event.downloadPath
the FileDownload
component is not rendered in Widget
and the world is a happy place.Widget.js - partial code only
import FileDownload from './FileDownload';
export default class Widget extends Component {
constructor(props) {
super(props);
this.state = widgetStore.getState().toJS();
}
handleDownload(data) {
widgetActions.downloadFile(data);
}
handleDownloadComplete() {
widgetActions.downloadFile();
}
render() {
const downloadPath = this.state.downloadPath;
return (
// button/icon with click bound to this.handleDownload goes here
{downloadPath &&
<FileDownload
actionPath={downloadPath}
onDownloadComplete={this.handleDownloadComplete}
/>
}
);
}
widgetActions.js - partial code only
export function downloadFile(data) {
let downloadPath = null;
if (data) {
downloadPath = `${apiResource}/${data.fileName}`;
}
appDispatcher.dispatch({
actionType: actionTypes.DOWNLOAD_FILE,
downloadPath
});
}
widgetStore.js - partial code only
let store = Map({
downloadPath: null,
isLoading: false,
// other store properties
});
class WidgetStore extends Store {
constructor() {
super();
this.dispatchToken = appDispatcher.register(action => {
switch (action.actionType) {
case actionTypes.DOWNLOAD_FILE:
store = store.merge({
downloadPath: action.downloadPath,
isLoading: !!action.downloadPath
});
this.emitChange();
break;
FileDownload.js
- complete, fully functional code ready for copy and paste
- React 0.14.7 with Babel 6.x ["es2015", "react", "stage-0"]
- form needs to be display: none
which is what the "hidden" className
is for
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
function getFormInputs() {
const {queryParams} = this.props;
if (queryParams === undefined) {
return null;
}
return Object.keys(queryParams).map((name, index) => {
return (
<input
key={index}
name={name}
type="hidden"
value={queryParams[name]}
/>
);
});
}
export default class FileDownload extends Component {
static propTypes = {
actionPath: PropTypes.string.isRequired,
method: PropTypes.string,
onDownloadComplete: PropTypes.func.isRequired,
queryParams: PropTypes.object
};
static defaultProps = {
method: 'GET'
};
componentDidMount() {
ReactDOM.findDOMNode(this).submit();
this.props.onDownloadComplete();
}
render() {
const {actionPath, method} = this.props;
return (
<form
action={actionPath}
className="hidden"
method={method}
>
{getFormInputs.call(this)}
</form>
);
}
}
This is a possible solution for you:
a = [15, 12, 10]
b = sorted(a)
print b # --> b = [10, 12, 15]
c = 13
for i in range(len(b)):
if b[i] > c:
break
d = b[:i] + [c] + b[i:]
print d # --> d = [10, 12, 13, 15]
In single line to print the element or array.
print $_ for (@array);
NOTE: remember that $_ is internally referring to the element of @array in loop. Any changes made in $_ will reflect in @array; ex.
my @array = qw( 1 2 3 );
for (@array) {
$_ = $_ *2 ;
}
print "@array";
output: 2 4 6
My solution: If it is correct*, update the data and viewable items without re-drawing the whole list. Else notifyDataSetChanged.
Correct - oldData size == new data size, and old data IDs and their order == new data IDs and order
How:
/**
* A View can only be used (visible) once. This class creates a map from int (position) to view, where the mapping
* is one-to-one and on.
*
*/
private static class UniqueValueSparseArray extends SparseArray<View> {
private final HashMap<View,Integer> m_valueToKey = new HashMap<View,Integer>();
@Override
public void put(int key, View value) {
final Integer previousKey = m_valueToKey.put(value,key);
if(null != previousKey) {
remove(previousKey);//re-mapping
}
super.put(key, value);
}
}
@Override
public void setData(final List<? extends DBObject> data) {
// TODO Implement 'smarter' logic, for replacing just part of the data?
if (data == m_data) return;
List<? extends DBObject> oldData = m_data;
m_data = null == data ? Collections.EMPTY_LIST : data;
if (!updateExistingViews(oldData, data)) notifyDataSetChanged();
else if (DEBUG) Log.d(TAG, "Updated without notifyDataSetChanged");
}
/**
* See if we can update the data within existing layout, without re-drawing the list.
* @param oldData
* @param newData
* @return
*/
private boolean updateExistingViews(List<? extends DBObject> oldData, List<? extends DBObject> newData) {
/**
* Iterate over new data, compare to old. If IDs out of sync, stop and return false. Else - update visible
* items.
*/
final int oldDataSize = oldData.size();
if (oldDataSize != newData.size()) return false;
DBObject newObj;
int nVisibleViews = m_visibleViews.size();
if(nVisibleViews == 0) return false;
for (int position = 0; nVisibleViews > 0 && position < oldDataSize; position++) {
newObj = newData.get(position);
if (oldData.get(position).getId() != newObj.getId()) return false;
// iterate over visible objects and see if this ID is there.
final View view = m_visibleViews.get(position);
if (null != view) {
// this position has a visible view, let's update it!
bindView(position, view, false);
nVisibleViews--;
}
}
return true;
}
and of course:
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
final View result = createViewFromResource(position, convertView, parent);
m_visibleViews.put(position, result);
return result;
}
Ignore the last param to bindView (I use it to determine whether or not I need to recycle bitmaps for ImageDrawable).
As mentioned above, the total number of 'visible' views is roughly the amount that fits on the screen (ignoring orientation changes etc), so no biggie memory-wise.
Greedy means your expression will match as large a group as possible, lazy means it will match the smallest group possible. For this string:
abcdefghijklmc
and this expression:
a.*c
A greedy match will match the whole string, and a lazy match will match just the first abc
.
Here's a version using the excellent requests library:
from requests import session
payload = {
'action': 'login',
'username': USERNAME,
'password': PASSWORD
}
with session() as c:
c.post('http://example.com/login.php', data=payload)
response = c.get('http://example.com/protected_page.php')
print(response.headers)
print(response.text)
I have a problem with merged_cells and autosize not work correctly, if you have the same problem, you can solve with the next code:
for col in worksheet.columns:
max_length = 0
column = col[0].column # Get the column name
for cell in col:
if cell.coordinate in worksheet.merged_cells: # not check merge_cells
continue
try: # Necessary to avoid error on empty cells
if len(str(cell.value)) > max_length:
max_length = len(cell.value)
except:
pass
adjusted_width = (max_length + 2) * 1.2
worksheet.column_dimensions[column].width = adjusted_width
The JSON spec says you CAN escape forward slash, but you don't have to.
You can easily do with first you can make the div flex and apply justify content right or left and your problem is solved.
<div style="display: flex;padding-bottom: 8px;justify-content: flex-end;">_x000D_
<button style="font-weight: bold;outline: none;background-color: #2764ff;border-radius: 3px;margin-left: 12px;border: none;padding: 3px 6px;color: white;text-align: center;font-family: 'Open Sans', sans-serif;text-decoration: none;margin-right: 14px;">Sense</button>_x000D_
</div>
_x000D_
YAML supports inline comments, but does not support block comments.
From Wikipedia:
Comments begin with the number sign (
#
), can start anywhere on a line, and continue until the end of the line
A comparison with JSON, also from Wikipedia:
The syntax differences are subtle and seldom arise in practice: JSON allows extended charactersets like UTF-32, YAML requires a space after separators like comma, equals, and colon while JSON does not, and some non-standard implementations of JSON extend the grammar to include Javascript's
/* ... */
comments. Handling such edge cases may require light pre-processing of the JSON before parsing as in-line YAML.
# If you want to write
# a block-commented Haiku
# you'll need three pound signs
For SpringFramework Tests, I would recommend to add the below as well
org.springframework.test.web.servlet.request.MockMvcRequestBuilders
org.springframework.test.web.servlet.request.MockMvcResponseBuilders
org.springframework.test.web.servlet.result.MockMvcResultHandlers
org.springframework.test.web.servlet.result.MockMvcResultMatchers
org.springframework.test.web.servlet.setup.MockMvcBuilders
org.mockito.Mockito
When you add above as new Type it automatically add .* to the package.
The current accepted answer is out of date. Now if you want to create a post request and add parameters to it you should user MultipartBody.Builder as Mime Craft now is deprecated.
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("somParam", "someValue")
.build();
Request request = new Request.Builder()
.url(BASE_URL + route)
.post(requestBody)
.build();
Usually occurs when you have errors in your manifest.Open AndroidManifest.xml .Click on the merged manifest tab.The errors can be seen there .Also include suggestions mentioned there.When I had a similar problem while importing com.google.android.gms.maps.model.LatLng ,it suggested me to include tools:overrideLibrary="com.google.android.gms.maps" in the application tag and the build was successful.
Faced this scenario using Git Bash.
Our repository has multiple branches and each branch has a different commit cycle and merge happens once in a while. Old_Branch was used as a parent for New_Branch
Old_Branch was updated with some changes which required to be merged with New_Branch
Was using below pull command without any branch to get all sources from all branches.
git pull origin
Strangely this doesn't pull all the commits from all the branches. Had thought it so as the indicated shows almost all branches and tags.
So to fix this had checked out the Old_Branch pulled the latest using
git checkout Old_Branch
git pull origin Old_Branch
Now checked out New_Branch
git checkout New_Branch
Pulled it to be sure
git pull origin New_Branch
git merge Old_Branch
And viola got conflicts to fix from Old_Branch to New_Branch :) which was expected
Update: The answer previously posted here linked to a custom script that is no longer available, solely because the OP indicated that date +'%s'
didn't work for him. Please see UberAlex' answer and cadrian's answer for proper solutions. In short:
For the number of seconds since the Unix epoch use date(1)
as follows:
date +'%s'
For the number of days since the Unix epoch divide the result by the number of seconds in a day (mind the double parentheses!):
echo $(($(date +%s) / 60 / 60 / 24))
This is what I did.
Note: Please check App.js for the code.
If you liked it, you can drop a star.??
Update:
import * as htmlToImage from 'html-to-image';
import download from 'downloadjs';
import logo from './logo.svg';
import './App.css';
const App = () => {
const onButtonClick = () => {
var domElement = document.getElementById('my-node');
htmlToImage.toJpeg(domElement)
.then(function (dataUrl) {
console.log(dataUrl);
download(dataUrl, 'image.jpeg');
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});
};
return (
<div className="App" id="my-node">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a><br></br>
<button onClick={onButtonClick}>Download as JPEG</button>
</header>
</div>
);
}
export default App;
The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.
This is done with something like this, attaching a handler to the window.scroll event
// Cache selectors outside callback for performance.
var $window = $(window),
$stickyEl = $('#the-sticky-div'),
elTop = $stickyEl.offset().top;
$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});
This simply adds a sticky
CSS class when the page has scrolled past it, and removes the class when it's back up.
And the CSS class looks like this
#the-sticky-div.sticky {
position: fixed;
top: 0;
}
EDIT- Modified code to cache jQuery objects, faster now.
Hi you can achieve your result with use of <marquee behavior="alternate"></marquee>
HTML
<div class="wrapper">
<marquee behavior="alternate"><span class="marquee">This is a marquee!</span></marquee>
</div>
CSS
.wrapper{
max-width: 400px;
background: green;
height: 40px;
text-align: right;
}
.marquee {
background: red;
white-space: nowrap;
-webkit-animation: rightThenLeft 4s linear;
}
see the demo:- http://jsfiddle.net/gXdMc/6/
Actually, if you do not want to delete your local .m2/repository/... and you are have a downloaded copy of Maven from Apache, you can have Eclipse /STS use that external Maven and you can edit the {maven}\conf\settings.xml to point your localRepository to a new empty location.
<localRepository>C:\java\repository</localRepository>
Of course, you will have a new repository with all of the maven source downloads in addition to your previous .m2 location.
Installing Visual C++ is a good first step, though I couldn't say for sure whether the 2010 version will work. Anyway give it a try.
Look for vcvarsall.bat
in the Visual C++ installation directory (for Visual Studio 2010 it's in ProgramFiles\Microsoft Visual Studio 10.0\VC
). Then add that directory to the system path. If you're doing this on the command line, you can try:
path %path%;c:\path\to\vs2010\bin
then try again to run whatever you were trying to run.
For more permanent effect, add it in the computer system path settings.
Taken from the ReactKonvaCore.d.ts file:
onClick?(evt: Konva.KonvaEventObject<MouseEvent>): void;
So, I'd say your event type is Konva.KonvaEventObject<MouseEvent>
Note that from Netbeans 8 there is no Run panel in the project Properties.
To do what you want I simply add the following line (example setting the locale) in my project's properties file:
run.args.extra=--locale fr:FR
It is no use putting the .fn, it will reffers to the prototype.
What you need to do is $.fancybox.close();
The thing is that you are maybe experiencing another error from js.
There are any errors on screen?
Is your fancybox and jquery the latest releases?
jquery is currently in 1.4.1 and fb in 1.3 something
Experiment putting a link inside the fancybox and put that function in it.
You probably had read that, but in any case, http://fancybox.net/api
One thing that you probably might need to do is isolate each part in order to realize what it is.
If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by
with out the need of any aggregate functions.
So the query can be simplified to this.
select * from comments_table group by commentname;
Try out the query in action here
Another option is just using head:
grep ...parameters... yourfile | head
This won't require searching the entire file - it will stop when the first ten matching lines are found. Another advantage with this approach is that will return no more than 10 lines even if you are using grep with the -o option.
For example if the file contains the following lines:
112233
223344
123123
Then this is the difference in the output:
$ grep -o '1.' yourfile | head -n2 11 12 $ grep -m2 -o '1.' 11 12 12
Using head
returns only 2 results as desired, whereas -m2 returns 3.
That depends. Is it just a variable (in a method)? Or a class-member?
If it's just a variable you'll get an error that no value has been set when trying to read from it without first assinging it a value.
If it's a class-member it will be initialized to null by the VM.
I came across HikariCP
and I was amazed by the benchmarks and I wanted to try it instead of my default choice C3P0
and to my surprise I struggled to get the configurations
right probably because the configurations differ based on what combination of tech stack you are using.
I have setup Spring Boot
project with JPA, Web, Security
starters (Using Spring Initializer) to use PostgreSQL
as a database with HikariCP
as connection pooling.
I have used Gradle
as build tool and I would like to share what worked for me for the following assumptions:
You need the following build.gradle
if you are using Gradle
or equivalent pom.xml
if you are using maven
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
group = 'com'
version = '1.0'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-aop')
// Exclude the tomcat-jdbc since it's used as default for connection pooling
// This can also be achieved by setting the spring.datasource.type to HikariCP
// datasource see application.properties below
compile('org.springframework.boot:spring-boot-starter-data-jpa') {
exclude group: 'org.apache.tomcat', module: 'tomcat-jdbc'
}
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
runtime('org.postgresql:postgresql')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.springframework.security:spring-security-test')
// Download HikariCP but, exclude hibernate-core to avoid version conflicts
compile('com.zaxxer:HikariCP:2.5.1') {
exclude group: 'org.hibernate', module: 'hibernate-core'
}
// Need this in order to get the HikariCPConnectionProvider
compile('org.hibernate:hibernate-hikaricp:5.2.11.Final') {
exclude group: 'com.zaxxer', module: 'HikariCP'
exclude group: 'org.hibernate', module: 'hibernate-core'
}
}
There are a bunch of excludes in the above build.gradle
and that's because
jdbc-tomcat
connection pool when downloading the spring-boot-starter-data-jpa
dependencies. This can be achieved by setting up the spring.datasource.type=com.zaxxer.hikari.HikariDataSource
also but, I don't want an extra dependency if I don't need it hibernate-core
when downloading com.zaxxer
dependency and that's because hibernate-core
is already downloaded by Spring Boot
and we don't want to end up with different versions. hibernate-core
when downloading hibernate-hikaricp
module which is needed in order to make HikariCP use org.hibernate.hikaricp.internal.HikariCPConnectionProvider
as connection provider instead of deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider
Once I figured out the build.gradle
and what to keep and what to not, I was ready to copy/paste a datasource
configuration into my application.properties
and expected everything to work with flying colors but, not really and I stumbled upon the following issues
com.zaxxer.hikari.hibernate.HikariConnectionProvider
key/value
in the application.properties
and was complaining about dataSource, dataSourceClassName, jdbcUrl
. I had to debug into HikariConfig, HikariConfigurationUtil, HikariCPConnectionProvider
and found out that HikariCP
could not find the properties from application.properties
because it was named differently. Anyway, this is where I had to rely on trial and error and make sure that HikariCP
is able to pick the properties (i.e. data source that's db details, as well as pooling properties) as well as Sping Boot behave as expected and I ended up with the following application.properties
file.
server.contextPath=/
debug=true
# Spring data source needed for Spring boot to behave
# Pre Spring Boot v2.0.0.M6 without below Spring Boot defaults to tomcat-jdbc connection pool included
# in spring-boot-starter-jdbc and as compiled dependency under spring-boot-starter-data-jpa
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:postgresql://localhost:5432/somedb
spring.datasource.username=dbuser
spring.datasource.password=dbpassword
# Hikari will use the above plus the following to setup connection pooling
spring.datasource.hikari.minimumIdle=5
spring.datasource.hikari.maximumPoolSize=20
spring.datasource.hikari.idleTimeout=30000
spring.datasource.hikari.poolName=SpringBootJPAHikariCP
spring.datasource.hikari.maxLifetime=2000000
spring.datasource.hikari.connectionTimeout=30000
# Without below HikariCP uses deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider
# Surprisingly enough below ConnectionProvider is in hibernate-hikaricp dependency and not hibernate-core
# So you need to pull that dependency but, make sure to exclude it's transitive dependencies or you will end up
# with different versions of hibernate-core
spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider
# JPA specific configs
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql=true
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.properties.hibernate.default_schema=dbschema
spring.jpa.properties.hibernate.search.autoregister_listeners=false
spring.jpa.properties.hibernate.bytecode.use_reflection_optimizer=false
# Enable logging to verify that HikariCP is used, the second entry is specific to HikariCP
logging.level.org.hibernate.SQL=DEBUG
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
As shown above the configurations are divided into categories based on following naming patterns
It's hard to come across a tutorial or post or some resource that shows how the above properties file is used and how the properties should be named. Well, there you have it.
Throwing the above application.properties
with build.gradle
(or at least similar) into a Spring Boot JPA project version (1.5.8) should work like a charm and connect to your pre-configured database (i.e. in my case it's PostgreSQL that both HikariCP & Spring
figure out from the spring.datasource.url
on which database driver to use).
I did not see the need to create a DataSource
bean and that's because Spring Boot is capable of doing everything for me just by looking into application.properties
and that's neat.
The article in HikariCP's github wiki shows how to setup Spring Boot with JPA but, lacks explanation and details.
The above two file is also availble as a public gist https://gist.github.com/rhamedy/b3cb936061cc03acdfe21358b86a5bc6
And this is if copying a single property to another list is needed:
targetList.AddRange(sourceList.Select(i => i.NeededProperty));
I realize my opinion is probably not the popular one, but I guess I have a hard time jumping on the Linq-y band wagon. It's nifty. It's condensed. I get that and I'm not opposed to using it where it's appropriate. Maybe it's just me, but I feel like people have stopped thinking about creating utility functions to accomplish what they want and instead prefer to litter their code with (sometimes) excessively long lines of Linq code for the sake of creating a dense 1-liner.
I'm not saying that any of the Linq answers that people have provided here are bad, but I guess I feel like there is the potential that these single lines of code can start to grow longer and more obscure as you need to handle various situations. What if your array is null? What if you want a delimited string instead of just purely concatenated? What if some of the integers in your array are double-digit and you want to pad each value with leading zeros so that the string for each element is the same length as the rest?
Taking one of the provided answers as an example:
result = arr.Aggregate(string.Empty, (s, i) => s + i.ToString());
If I need to worry about the array being null, now it becomes this:
result = (arr == null) ? null : arr.Aggregate(string.Empty, (s, i) => s + i.ToString());
If I want a comma-delimited string, now it becomes this:
result = (arr == null) ? null : arr.Skip(1).Aggregate(arr[0].ToString(), (s, i) => s + "," + i.ToString());
This is still not too bad, but I think it's not obvious at a glance what this line of code is doing.
Of course, there's nothing stopping you from throwing this line of code into your own utility function so that you don't have that long mess mixed in with your application logic, especially if you're doing it in multiple places:
public static string ToStringLinqy<T>(this T[] array, string delimiter)
{
// edit: let's replace this with a "better" version using a StringBuilder
//return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(array[0].ToString(), (s, i) => s + "," + i.ToString());
return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(new StringBuilder(array[0].ToString()), (s, i) => s.Append(delimiter).Append(i), s => s.ToString());
}
But if you're going to put it into a utility function anyway, do you really need it to be condensed down into a 1-liner? In that case why not throw in a few extra lines for clarity and take advantage of a StringBuilder so that you're not doing repeated concatenation operations:
public static string ToStringNonLinqy<T>(this T[] array, string delimiter)
{
if (array != null)
{
// edit: replaced my previous implementation to use StringBuilder
if (array.Length > 0)
{
StringBuilder builder = new StringBuilder();
builder.Append(array[0]);
for (int i = 1; i < array.Length; i++)
{
builder.Append(delimiter);
builder.Append(array[i]);
}
return builder.ToString()
}
else
{
return string.Empty;
}
}
else
{
return null;
}
}
And if you're really so concerned about performance, you could even turn it into a hybrid function that decides whether to do string.Join or to use a StringBuilder depending on how many elements are in the array (this is a micro-optimization, not worth doing in my opinion and possibly more harmful than beneficial, but I'm using it as an example for this problem):
public static string ToString<T>(this T[] array, string delimiter)
{
if (array != null)
{
// determine if the length of the array is greater than the performance threshold for using a stringbuilder
// 10 is just an arbitrary threshold value I've chosen
if (array.Length < 10)
{
// assumption is that for arrays of less than 10 elements
// this code would be more efficient than a StringBuilder.
// Note: this is a crazy/pointless micro-optimization. Don't do this.
string[] values = new string[array.Length];
for (int i = 0; i < values.Length; i++)
values[i] = array[i].ToString();
return string.Join(delimiter, values);
}
else
{
// for arrays of length 10 or longer, use a StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append(array[0]);
for (int i = 1; i < array.Length; i++)
{
sb.Append(delimiter);
sb.Append(array[i]);
}
return sb.ToString();
}
}
else
{
return null;
}
}
For this example, the performance impact is probably not worth caring about, but the point is that if you are in a situation where you actually do need to be concerned with the performance of your operations, whatever they are, then it will most likely be easier and more readable to handle that within a utility function than using a complex Linq expression.
That utility function still looks kind of clunky. Now let's ditch the hybrid stuff and do this:
// convert an enumeration of one type into an enumeration of another type
public static IEnumerable<TOut> Convert<TIn, TOut>(this IEnumerable<TIn> input, Func<TIn, TOut> conversion)
{
foreach (TIn value in input)
{
yield return conversion(value);
}
}
// concatenate the strings in an enumeration separated by the specified delimiter
public static string Delimit<T>(this IEnumerable<T> input, string delimiter)
{
IEnumerator<T> enumerator = input.GetEnumerator();
if (enumerator.MoveNext())
{
StringBuilder builder = new StringBuilder();
// start off with the first element
builder.Append(enumerator.Current);
// append the remaining elements separated by the delimiter
while (enumerator.MoveNext())
{
builder.Append(delimiter);
builder.Append(enumerator.Current);
}
return builder.ToString();
}
else
{
return string.Empty;
}
}
// concatenate all elements
public static string ToString<T>(this IEnumerable<T> input)
{
return ToString(input, string.Empty);
}
// concatenate all elements separated by a delimiter
public static string ToString<T>(this IEnumerable<T> input, string delimiter)
{
return input.Delimit(delimiter);
}
// concatenate all elements, each one left-padded to a minimum length
public static string ToString<T>(this IEnumerable<T> input, int minLength, char paddingChar)
{
return input.Convert(i => i.ToString().PadLeft(minLength, paddingChar)).Delimit(string.Empty);
}
Now we have separate and fairly compact utility functions, each of which are arguable useful on their own.
Ultimately, my point is not that you shouldn't use Linq, but rather just to say don't forget about the benefits of creating your own utility functions, even if they are small and perhaps only contain a single line that returns the result from a line of Linq code. If nothing else, you'll be able to keep your application code even more condensed than you could achieve with a line of Linq code, and if you are using it in multiple places, then using a utility function makes it easier to adjust your output in case you need to change it later.
For this problem, I'd rather just write something like this in my application code:
int[] arr = { 0, 1, 2, 3, 0, 1 };
// 012301
result = arr.ToString<int>();
// comma-separated values
// 0,1,2,3,0,1
result = arr.ToString(",");
// left-padded to 2 digits
// 000102030001
result = arr.ToString(2, '0');
This question is very helpfully BUT Don't forget to mount SD Card in your emulator, if you don't do this its doesn't work.
I lose my time before discover this.
SOLUTION
<style>
.container {
margin: 10px;
width: 115px;
height: 115px;
line-height: 115px;
text-align: center;
border: 1px solid red;
background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
</style>
<div class='container'>
</div>
<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>
<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>
I am not sure does it suit you but I noticed that tar
does not fail on changed/deleted files in pipe mode. See what I mean.
Test script:
#!/usr/bin/env bash
set -ex
tar cpf - ./files | aws s3 cp - s3://my-bucket/files.tar
echo $?
Deleting random files manually...
Output:
+ aws s3 cp - s3://my-bucket/files.tar
+ tar cpf - ./files
tar: ./files/default_images: File removed before we read it
tar: ./files: file changed as we read it
+ echo 0
0
Changing XAMPP Default Port: If you want to get XAMPP up and running, you should consider changing the port from the default 80 to say 7777.
In the XAMPP Control Panel, click on the Apache – Config button which is located next to the ‘Logs’ button.
Select ‘Apache (httpd.conf)’ from the drop down. (Notepad should open)
Do Ctrl+F to find ’80’ and change line Listen 80 to Listen 7777
Find again and change line ServerName localhost:80 to ServerName localhost:7777
Save and re-start Apache. It should be running by now.
The only demerit to this technique is, you have to explicitly include the port number in the localhost url. Rather than http://localhost
it becomes http://localhost:7777
.
To complement the accepted answer, for much better security, you could add your server certificate or your own root CA certificate to keychain( https://stackoverflow.com/a/9941559/1432048), however doing this alone won't make NSURLConnection authenticate your self-signed server automatically. You still need to add the below code to your NSURLConnection delegate, it's copied from Apple sample code AdvancedURLConnections, and you need to add two files(Credentials.h, Credentials.m) from apple sample code to your projects.
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
// if ([trustedHosts containsObject:challenge.protectionSpace.host])
OSStatus err;
NSURLProtectionSpace * protectionSpace;
SecTrustRef trust;
SecTrustResultType trustResult;
BOOL trusted;
protectionSpace = [challenge protectionSpace];
assert(protectionSpace != nil);
trust = [protectionSpace serverTrust];
assert(trust != NULL);
err = SecTrustEvaluate(trust, &trustResult);
trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultUnspecified));
// If that fails, apply our certificates as anchors and see if that helps.
//
// It's perfectly acceptable to apply all of our certificates to the SecTrust
// object, and let the SecTrust object sort out the mess. Of course, this assumes
// that the user trusts all certificates equally in all situations, which is implicit
// in our user interface; you could provide a more sophisticated user interface
// to allow the user to trust certain certificates for certain sites and so on).
if ( ! trusted ) {
err = SecTrustSetAnchorCertificates(trust, (CFArrayRef) [Credentials sharedCredentials].certificates);
if (err == noErr) {
err = SecTrustEvaluate(trust, &trustResult);
}
trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultUnspecified));
}
if(trusted)
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
If you add an abbr
instead of an alias
you'll get better auto-complete. In fish abbr
more closely matches the behavior of a bash alias.
abbr -a gco git checkout
Will -a
dd a new abbr
eviation gco
that expands to git checkout
.
Just use ||
if (A || B) { your action here }
Note: with string and number. It's more complicated.
Check this for deep understading:
You can use Google's Gson library to convert json to Hashmap. Try below code
String jsonString = "Your JSON string";
HashMap<String,String> map = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());
To summarize, we have three approaches to accomplish this:
The most portable one will be the last approach. But as mentioned by other poster, add .env into .gitignore in order not to upload the configuration to the public source repository.
More details: this article
Got tired of starting on win from command prompt then I ran across this as well. Slightly improved ver. over what josh3736. This uses an XML file to grab a few settings. For example the path to Node.exe
as well as the file to start in the default app.js. Also the environment to load (production, dev etc) that you have specified in your app.js (or server.js or whatever you called it). Essentially it adds the NODE_ENV={0}
where {0} is the name of your configuration in app.js as a var for you. You do this by modifying the "mode" element in the config.xml. You can grab the project here ==> github. Note in the Post Build events you can modify the copy paths to auto copy over your config.xml and the executable to your Nodejs
directory, just to save a step. Otherwise edit these out or your build will throw a warning.
var startInfo = new ProcessStartInfo();
startInfo.FileName = nodepath;
startInfo.Arguments = apppath;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
if(env.Length > 0)
startInfo.EnvironmentVariables.Add("NODE_ENV", env);
try
{
using (Process p = Process.Start(startInfo))
{
p.WaitForExit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Start Error", MessageBoxButtons.OK);
}
Check where your clang
is located:
which clang
It should be somewhere under /usr/bin/clang
.
In my case from old times it was coming from Miniconda that was put artificially on the command line PATH. Fix that so that clang comes from Xcode and that should bring you forward.
Just call plt.show()
at the end:
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0,50,60,80])
for i in np.arange(1,5):
z = 68 + 4 * np.random.randn(50)
zm = np.cumsum(z) / range(1,len(z)+1)
plt.plot(zm)
n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)
plt.plot(n,su,n,sl)
plt.show()
Ran into the diagram while looking at key-value coding, thought it might help someone. It helps with understanding of what IBOutlet is.
By looking at the flow, one could see that IBOutlets are only there to match the property name with a control name in the Nib file.
If you have not pushed the changes already:
git rm -r --cached .
git add .
git commit -m 'clear git cache'
git push
put this line in yor file .gradle above the Java conf.
apply plugin: 'java'
compileJava {options.encoding = "UTF-8"}
In your example one and two are char pointers, pointing to char constants. You cannot change the char constants pointed to by these pointers. So anything like:
strcat(one,two); // append string two to string one.
will not work. Instead you should have a separate variable(char array) to hold the result. Something like this:
char result[100]; // array to hold the result.
strcpy(result,one); // copy string one into the result.
strcat(result,two); // append string two to the result.
Please "include" both Controller and the module(s) where the controller and the functions called in the Controller are.
module(theModule);
stack size can indeed be unlimited. _STK_LIM
is the default, _STK_LIM_MAX
is something that differs per architecture, as can be seen from include/asm-generic/resource.h
:
/*
* RLIMIT_STACK default maximum - some architectures override it:
*/
#ifndef _STK_LIM_MAX
# define _STK_LIM_MAX RLIM_INFINITY
#endif
As can be seen from this example generic value is infinite, where RLIM_INFINITY
is, again, in generic case defined as:
/*
* SuS says limits have to be unsigned.
* Which makes a ton more sense anyway.
*
* Some architectures override this (for compatibility reasons):
*/
#ifndef RLIM_INFINITY
# define RLIM_INFINITY (~0UL)
#endif
So I guess the real answer is - stack size CAN be limited by some architecture, then unlimited stack trace will mean whatever _STK_LIM_MAX
is defined to, and in case it's infinity - it is infinite. For details on what it means to set it to infinite and what implications it might have, refer to the other answer, it's way better than mine.
I believe the original post was about removing the space between the buttons in a row, not adding space.
The trick is that the minimum space between the buttons was due to padding built into the buttons as part of the material design specification.
So, don't use buttons! But a GestureDetector instead. This widget type give the onClick
/ onTap
functionality but without the styling.
See this post for an example.
You can also create a Docker container with Alpine as the OS and the install Python and Pyspark as packages. That will have it all containerised.
Many times the problem comes because php
does not support short open tags in php.ini
file, i.e:
<?
phpinfo();
?>
You must use:
<?php
phpinfo();
?>
instead of this:
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
you could try the following using short circuiting:
style={{
textDecoration: completed && 'line-through'
}}
https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb
key bit of information from the link:
Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.
It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.
The other solutions might be more best practice, but thought it would be worth sharing.
Use PHP's popen
command, e.g.:
pclose(popen("start c:\wamp\bin\php.exe c:\wamp\www\script.php","r"));
This will create a child process and the script will excute in the background without waiting for output.
def flatten(alist):
if alist == []:
return []
elif type(alist) is not list:
return [alist]
else:
return flatten(alist[0]) + flatten(alist[1:])
PsSuspend command line utility from SysInternals
suite. It suspends / resumes a process by its id.
Many of them don't add this, especially in AWS EC2 Instance, I had the same issue and tried different solutions. Solution: one of my database URL inside the code was missing this parameter 'authSource', adding this worked for me.
mongodb://myUserName:MyPassword@ElasticIP:27017/databaseName?authSource=admin
A negative lookahead says, at this position, the following regex can not match.
Let's take a simplified example:
a(?!b(?!c))
a Match: (?!b) succeeds
ac Match: (?!b) succeeds
ab No match: (?!b(?!c)) fails
abe No match: (?!b(?!c)) fails
abc Match: (?!b(?!c)) succeeds
The last example is a double negation: it allows a b
followed by c
. The nested negative lookahead becomes a positive lookahead: the c
should be present.
In each example, only the a
is matched. The lookahead is only a condition, and does not add to the matched text.
Have you looked into rasdial?
Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network
ie
rasdial "VPN NETWORK NAME" "Username" *
it will then prompt for a password, else you can use "username" "password", this is however less secure
http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265
Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.
But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like
SELECT [columns] FROM table WHERE yearmonth = '200801'
instead of
SELECT [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')
The following answer only applies to Git version 1.x, but to Git version 2.x.
You want git add -A
:
git add -A
stages All;
git add .
stages new and modified, without deleted;
git add -u
stages modified and deleted, without new.
In my case I needed my EditText
to scroll text if no. of lines exceed maxLines
when its disabled. This implementation worked perfectly for me.
private void setIsChatEditTextEditable(boolean value)
{
if(value)
{
mEdittext.setCursorVisible(true);
mEdittext.setSelection(chat_edittext.length());
// use new EditText(getApplicationContext()).getKeyListener()) if required below
mEdittext.setKeyListener(new AppCompatEditText(getApplicationContext()).getKeyListener());
}
else
{
mEdittext.setCursorVisible(false);
mEdittext.setKeyListener(null);
}
}
You can use rebase, for instance, git rebase our-team
when you are on your branch featurex
It will move the start point of the branch at the end of your our-team
branch, merging all changes in your featurex
branch.
One thing you can do is to use raw SQL:
case class Bar(x1: Int, y1: Int, z1: Int, v1: String)
case class Foo(x2: Int, y2: Int, z2: Int, v2: String)
val bar = sqlContext.createDataFrame(sc.parallelize(
Bar(1, 1, 2, "bar") :: Bar(2, 3, 2, "bar") ::
Bar(3, 1, 2, "bar") :: Nil))
val foo = sqlContext.createDataFrame(sc.parallelize(
Foo(1, 1, 2, "foo") :: Foo(2, 1, 2, "foo") ::
Foo(3, 1, 2, "foo") :: Foo(4, 4, 4, "foo") :: Nil))
foo.registerTempTable("foo")
bar.registerTempTable("bar")
sqlContext.sql(
"SELECT * FROM foo LEFT JOIN bar ON x1 = x2 AND y1 = y2 AND z1 = z2")
Try this code. By using the parent>child selector "#productList li" it should find all li elements. Then, you can iterate through the result object using the each() method which will only alter li elements that have been found.
listItems = $("#productList li").each(function(){
var product = $(this);
var productid = product.children(".productId").val();
var productPrice = product.find(".productPrice").val();
var productMSRP = product.find(".productMSRP").val();
totalItemsHidden.val(parseInt(totalItemsHidden.val(), 10) + 1);
subtotalHidden.val(parseFloat(subtotalHidden.val()) + parseFloat(productMSRP));
savingsHidden.val(parseFloat(savingsHidden.val()) + parseFloat(productMSRP - productPrice));
totalHidden.val(parseFloat(totalHidden.val()) + parseFloat(productPrice));
});
Split a string on space, get a list, show its type, print it out:
el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"
>>> mylist = mystring.split(" ")
>>> print type(mylist)
<type 'list'>
>>> print mylist
['What', 'does', 'the', 'fox', 'say?']
If you have two delimiters next to each other, empty string is assumed:
el@apollo:~/foo$ python
>>> mystring = "its so fluffy im gonna DIE!!!"
>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']
Split a string on underscore and grab the 5th item in the list:
el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."
>>> mystring.split("_")[4]
"Kowalski's"
Collapse multiple spaces into one
el@apollo:~/foo$ python
>>> mystring = 'collapse these spaces'
>>> mycollapsedstring = ' '.join(mystring.split())
>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']
When you pass no parameter to Python's split method, the documentation states: "runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace".
Hold onto your hats boys, parse on a regular expression:
el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']
The regular expression "[a-m]+" means the lowercase letters a
through m
that occur one or more times are matched as a delimiter. re
is a library to be imported.
Or if you want to chomp the items one at a time:
el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"
>>> mytuple = mystring.partition(" ")
>>> print type(mytuple)
<type 'tuple'>
>>> print mytuple
('theres', ' ', 'coffee in that nebula')
>>> print mytuple[0]
theres
>>> print mytuple[2]
coffee in that nebula
Clone the repository as normal:
git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle
Then checkout the tag you want like so:
git checkout tags/1.1.4
This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".
To retain any changes made, move them to a new branch:
git checkout -b 1.1.4-jspooner
You can get back to the master branch by using:
git checkout master
Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:
git checkout 1.1.4
But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:
warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'
The shorthand can be safely used if the repository does not share names between branches and tags.
I have followed the below steps in Macbook.
on ubuntu /etc/phpmyadmin/config-db.php
make sure the password matches your config.inc.php for the control user
also for the blowfish too short error
edit /var/lib/phpmyadmin/blowfish_secret.inc.php and make the key longer
From the documentation:
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called
static
in your package or next to your module and it will be available at/static
on the application.To generate URLs for static files, use the special
'static'
endpoint name:url_for('static', filename='style.css')
The file has to be stored on the filesystem as
static/style.css
.
I suggest creating a test app (for dev environment only) on https://developers.facebook.com/apps and set: Website with Facebook Login
property to your localhost:[port] settings.
this option will work fine with no need to change hosts.
remember to change the appId back to your production app once you go live.
Edit - in the latest fb version you'll find it under the settings
tab.
Default access modifier - If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes).
pgrep -f process_name > any_file_name
sed -i 's/^/kill /' any_file_name
chmod 777 any_file_name
./any_file_name
for example 'pgrep -f firefox' will grep the PID of running 'firefox' and will save this PID to a file called 'any_file_name'. 'sed' command will add the 'kill' in the beginning of the PID number in 'any_file_name' file. Third line will make 'any_file_name' file executable. Now forth line will kill the PID available in the file 'any_file_name'. Writing the above four lines in a file and executing that file can do the control-C. Working absolutely fine for me.
You can try if(typeof object !== 'undefined')
sir_neanderthal has already posted a nice answer.
I just want to point out that if you would like to use different names for your inputs you can also use (or just copy the method) require_from_group method from official jQuery Validation additional-methods.js (link to CDN for version 1.13.1).
So,
$HOME
is what I need to modify.However I have been unable to find where this mythical
$HOME
variable is set so I assumed it was a Linux system version of PATH or something.
Git 2.23 (Q3 2019) is quite explicit on how HOME
is set.
See commit e12a955 (04 Jul 2019) by Karsten Blees (kblees
).
(Merged by Junio C Hamano -- gitster
-- in commit fc613d2, 19 Jul 2019)
mingw: initialize HOME on startup
HOME
initialization was historically duplicated in many different places, including/etc/profile
, launch scripts such asgit-bash.vbs
andgitk.cmd
, and (although slightly broken) in thegit-wrapper
.Even unrelated projects such as
GitExtensions
andTortoiseGit
need to implement the same logic to be able to call git directly.Initialize
HOME
in Git's own startup code so that we can eventually retire all the duplicate initialization code.
Now, mingw.c includes the following code:
/* calculate HOME if not set */ if (!getenv("HOME")) { /* * try $HOMEDRIVE$HOMEPATH - the home share may be a network * location, thus also check if the path exists (i.e. is not * disconnected) */ if ((tmp = getenv("HOMEDRIVE"))) { struct strbuf buf = STRBUF_INIT; strbuf_addstr(&buf, tmp); if ((tmp = getenv("HOMEPATH"))) { strbuf_addstr(&buf, tmp); if (is_directory(buf.buf)) setenv("HOME", buf.buf, 1); else tmp = NULL; /* use $USERPROFILE */ } strbuf_release(&buf); } /* use $USERPROFILE if the home share is not available */ if (!tmp && (tmp = getenv("USERPROFILE"))) setenv("HOME", tmp, 1); }
Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.
The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.
URL can have an Space Character in them and they will be displayed as %20 in most of the browsers, but browser encoding rules change quite often and we cannot depend on how a browser will display the URL.
So Instead you can replace the Space Character in the URL with any character that you think shall make the URL More readable and ' Pretty ' ;) ..... O so general characters that are preferred are "-","_","+" .... but these aren't the compulsions so u can use any of the character that is not supposed to be in the URL Already.
Please avoid the %,&,},{,],[,/,>,< as the URL Space Character Replacement as they can pull up an error on certain browsers and Platforms.
As you can see the Stak overflow itself uses the '-' character as Space(%20) replacement.
Have an Happy questioning.
the core functions are getBytes(String charset)
and new String(byte[] data)
. you can use these functions to do UTF-8 decoding.
UTF-8 decoding actually is a string to string conversion, the intermediate buffer is a byte array. since the target is an UTF-8 string, so the only parameter for new String()
is the byte array, which calling is equal to new String(bytes, "UTF-8")
Then the key is the parameter for input encoded string to get internal byte array, which you should know beforehand. If you don't, guess the most possible one, "ISO-8859-1" is a good guess for English user.
The decoding sentence should be
String decoded = new String(encoded.getBytes("ISO-8859-1"));
Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict
>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1
For those using Python 3
>>> list(x.keys()).index("c")
1
UPDATE Sept 2015
This answer continues to get upvotes, so I'm going to leave it here since it seems to be helpful to some people, but please check out the other answers from @reexmonkey and @Pressacco first. They may provide better results.
ORIGINAL ANSWER
Give this a shot:
That should cause those messages to disappear.
I saved my web.xsd in the root of my web folder (which might not be the best place for it, but just for demonstration purposes) and my Schemas property looks like this:
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\xml\Schemas\DotNetConfig.xsd" "Web.xsd"
The following CSS works for me - Using Bootstrap 3. You need to add this css after boostrap styles -
.modal.fade .modal-dialog{
-webkit-transition-property: transform;
-webkit-transition-duration:0 ;
transition-property: transform;
transition-duration:0 ;
}
.modal.fade {
transition: none;
}
No need to use for loop. It can be directly applied to a column of a dataframe
sleepstudy['Reaction'] = sleepstudy['Reaction'].round(1)
I faced the same error, but in my case, the problem was resolved after deleting the /target
folder and nbactions.xml
file.
As of today 11th April 2020, this is easily possible with backdrop-filter
CSS property which is now a stable feature in Chrome, Safari & Edge.
I wanted this in our Hybrid mobile app so also available in Android/Chrome Webview & Safari WebView.
Simply add the CSS property:
.my-class {
backdrop-filter: blur(30px);
background: transparent; // Make sure there is not backgorund
}
See it working in this pen or try the demo:
#main-wrapper {_x000D_
width: 300px;_x000D_
height: 300px;_x000D_
background: url("https://i.picsum.photos/id/1001/500/500.jpg") no-repeat center;_x000D_
background-size: cover;_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.my-effect {_x000D_
position: absolute;_x000D_
top: 300px;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
font-size: 22px;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
color: black;_x000D_
-webkit-backdrop-filter: blur(15px);_x000D_
backdrop-filter: blur(15px);_x000D_
transition: top 700ms;_x000D_
}_x000D_
_x000D_
#main-wrapper:hover .my-effect {_x000D_
top: 0;_x000D_
}
_x000D_
<h4>Hover over the image to see the effect</h4>_x000D_
_x000D_
<div id="main-wrapper">_x000D_
<div class="my-effect">_x000D_
Glossy effect worked!_x000D_
</div>_x000D_
</div>
_x000D_
Let's take an example of McDonald's app because it's quite colourful. I took its screenshot and added as the background in the body
of my app.
I wanted to show a text on top of it with the glossy effect. Using backdrop-filter: blur(20px);
on the overlay above it, I was able to see this:
In fact you need the # (hashtag) for non HTML5 browsers.
Otherwise they will just do an HTTP call to the server at the mentioned href. The # is an old browser shortcircuit which doesn't fire the request, which allows many js frameworks to build their own clientside rerouting on top of that.
You can use $locationProvider.html5Mode(true)
to tell angular to use HTML5 strategy if available.
Here the list of browser that support HTML5 strategy: http://caniuse.com/#feat=history
Simple way without methods
int x = 1, y = 2, z = 3;
int biggest = x;
if (y > biggest) {
biggest = y;
}
if (z > biggest) {
biggest = z;
}
System.out.println(biggest);
// System.out.println(Math.max(Math.max(x,y),z));
First off, if you want to extract count features and apply TF-IDF normalization and row-wise euclidean normalization you can do it in one operation with TfidfVectorizer
:
>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> from sklearn.datasets import fetch_20newsgroups
>>> twenty = fetch_20newsgroups()
>>> tfidf = TfidfVectorizer().fit_transform(twenty.data)
>>> tfidf
<11314x130088 sparse matrix of type '<type 'numpy.float64'>'
with 1787553 stored elements in Compressed Sparse Row format>
Now to find the cosine distances of one document (e.g. the first in the dataset) and all of the others you just need to compute the dot products of the first vector with all of the others as the tfidf vectors are already row-normalized.
As explained by Chris Clark in comments and here Cosine Similarity does not take into account the magnitude of the vectors. Row-normalised have a magnitude of 1 and so the Linear Kernel is sufficient to calculate the similarity values.
The scipy sparse matrix API is a bit weird (not as flexible as dense N-dimensional numpy arrays). To get the first vector you need to slice the matrix row-wise to get a submatrix with a single row:
>>> tfidf[0:1]
<1x130088 sparse matrix of type '<type 'numpy.float64'>'
with 89 stored elements in Compressed Sparse Row format>
scikit-learn already provides pairwise metrics (a.k.a. kernels in machine learning parlance) that work for both dense and sparse representations of vector collections. In this case we need a dot product that is also known as the linear kernel:
>>> from sklearn.metrics.pairwise import linear_kernel
>>> cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten()
>>> cosine_similarities
array([ 1. , 0.04405952, 0.11016969, ..., 0.04433602,
0.04457106, 0.03293218])
Hence to find the top 5 related documents, we can use argsort
and some negative array slicing (most related documents have highest cosine similarity values, hence at the end of the sorted indices array):
>>> related_docs_indices = cosine_similarities.argsort()[:-5:-1]
>>> related_docs_indices
array([ 0, 958, 10576, 3277])
>>> cosine_similarities[related_docs_indices]
array([ 1. , 0.54967926, 0.32902194, 0.2825788 ])
The first result is a sanity check: we find the query document as the most similar document with a cosine similarity score of 1 which has the following text:
>>> print twenty.data[0]
From: [email protected] (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15
I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.
Thanks,
- IL
---- brought to you by your neighborhood Lerxst ----
The second most similar document is a reply that quotes the original message hence has many common words:
>>> print twenty.data[958]
From: [email protected] (Robert Seymour)
Subject: Re: WHAT car is this!?
Article-I.D.: reed.1993Apr21.032905.29286
Reply-To: [email protected]
Organization: Reed College, Portland, OR
Lines: 26
In article <[email protected]> [email protected] (where's my
thing) writes:
>
> I was wondering if anyone out there could enlighten me on this car I saw
> the other day. It was a 2-door sports car, looked to be from the late 60s/
> early 70s. It was called a Bricklin. The doors were really small. In
addition,
> the front bumper was separate from the rest of the body. This is
> all I know. If anyone can tellme a model name, engine specs, years
> of production, where this car is made, history, or whatever info you
> have on this funky looking car, please e-mail.
Bricklins were manufactured in the 70s with engines from Ford. They are rather
odd looking with the encased front bumper. There aren't a lot of them around,
but Hemmings (Motor News) ususally has ten or so listed. Basically, they are a
performance Ford with new styling slapped on top.
> ---- brought to you by your neighborhood Lerxst ----
Rush fan?
--
Robert Seymour [email protected]
Physics and Philosophy, Reed College (NeXTmail accepted)
Artificial Life Project Reed College
Reed Solar Energy Project (SolTrain) Portland, OR
If you use Java and spring MVC you just need to add the following annotation to your method returning your page :
@CrossOrigin(origins = "*")
"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.
I find it easier to implement it in the XML file as it can be harder to trace the line of code in a class with hundreds of lines. For the XML you can use "null":
android:divider="@null"
<iframe id="upload_target" name="upload_target">
<textarea rows="20" cols="100" name="result" id="result" ></textarea>
<input type="text" id="txt1" />
</iframe>
You can Get value by JQuery
$(document).ready(function(){
alert($('#upload_target').contents().find('#result').html());
alert($('#upload_target').contents().find('#txt1').val());
});
work on only same domain link
xy <- data.frame(x=1:10, y=10:1)
plot <- ggplot(data = xy)+geom_point(aes(x = x, y = y))
plot
panel = grid.get("panel-3-3")
grid.newpage()
pushViewport(viewport(w=1, h=1, name="layout"))
pushViewport(viewport(w=1, h=1, name="panel-3-3"))
upViewport(1)
upViewport(1)
grid.draw(panel)
You could use IllegalArgumentException:
public void speedDown(int decrement)
{
if(speed - decrement < 0){
throw new IllegalArgumentException("Final speed can not be less than zero");
}else{
speed -= decrement;
}
}
You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...
I solved the Access-Control-Allow-Origin error modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true
$.ajax({
url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
if you are working on dynamic permissions and any permission like ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION giving error "cannot resolve method PERMISSION_NAME" in this case write you code with permission name and then rebuild your project this will regenerate the manifest(Manifest.permission) file.
Try to get the Ip using
ip = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "";
I would suggest using following
req.param('<param_name>')
req.param("") works as following
Lookup is performed in the following order:
req.params
req.body
req.query
Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.
Like the other answers you can do theTypeIs = Object.keys(myVar)[0];
to get the first key. If you are expecting more keys, you can use
Object.keys(myVar).forEach(function(k) {
if(k === "typeA") {
// do stuff
}
else if (k === "typeB") {
// do more stuff
}
else {
// do something
}
});
Git usually (when not specified) fetches all branches and/or tags (refs, see: git ls-refs
) from one or more other repositories along with the objects necessary to complete their histories. In other words it fetches the objects which are reachable by the objects that are already downloaded. See: What does git fetch
really do?
Sometimes you may have branches/tags which aren't directly connected to the current one, so git pull --all
/git fetch --all
won't help in that case, but you can list them by:
git ls-remote -h -t origin
and fetch them manually by knowing the ref names.
So to fetch them all, try:
git fetch origin --depth=10000 $(git ls-remote -h -t origin)
The --depth=10000
parameter may help if you've shallowed repository.
Then check all your branches again:
git branch -avv
If above won't help, you need to add missing branches manually to the tracked list (as they got lost somehow):
$ git remote -v show origin
...
Remote branches:
master tracked
by git remote set-branches
like:
git remote set-branches --add origin missing_branch
so it may appear under remotes/origin
after fetch:
$ git remote -v show origin
...
Remote branches:
missing_branch new (next fetch will store in remotes/origin)
$ git fetch
From github.com:Foo/Bar
* [new branch] missing_branch -> origin/missing_branch
If you still cannot get anything other than the master branch, check the followings:
git remote -v
), e.g.
git config branch.master.remote
is origin
.origin
points to the right URL via: git remote show origin
(see this post).Try this:
var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];
Create a file called config
inside ~/.ssh
. Inside the file you can add:
Host *
User buck
Or add
Host example
HostName example.net
User buck
The second example will set a username and is hostname specific, while the first example sets a username only. And when you use the second one you don't need to use ssh example.net
; ssh example
will be enough.
sp_spaceused gives you the size of all the indexes combined.
If you want the size of each index for a table, use one of these two queries:
SELECT
i.name AS IndexName,
SUM(s.used_page_count) * 8 AS IndexSizeKB
FROM sys.dm_db_partition_stats AS s
JOIN sys.indexes AS i
ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id
WHERE s.[object_id] = object_id('dbo.TableName')
GROUP BY i.name
ORDER BY i.name
SELECT
i.name AS IndexName,
SUM(page_count * 8) AS IndexSizeKB
FROM sys.dm_db_index_physical_stats(
db_id(), object_id('dbo.TableName'), NULL, NULL, 'DETAILED') AS s
JOIN sys.indexes AS i
ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id
GROUP BY i.name
ORDER BY i.name
The results are usually slightly different but within 1%.
Add a data-size property to the google recaptcha element and make it equal to "compact" in case of mobile.
Refer: google recaptcha docs
 
is the numeric reference for the entity reference
— they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.
See the Wikipedia page for the non-breaking space.
Try the CStr() function
Dim myVal as String;
Dim myNum as Integer;
myVal = "My number is:"
myVal = myVal & CStr(myNum);
Just in case anyone is in my boat where none of these answers worked exactly, here's what I did.
Perhaps our in house Bitbucket server is set up a little differently than most, but here's the URL that I'd normally go to just to view the files in the master branch:
https://<BITBUCKET_URL>/projects/<PROJECT_GROUP>/repos/<REPO_NAME>/browse
If I select a different branch than master from the drop down menu, I get this:
https://<BITBUCKET_URL>/projects/<PROJECT_GROUP>/repos/<REPO_NAME>/browse?at=refs%2Fheads%2F<BRANCH_NAME>
So I tried doing this and it worked:
https://<BITBUCKET_URL>/projects/<PROJECT_GROUP>/repos/<REPO_NAME>/browse?at=<COMMIT_ID>
Now I can browse the whole repo as it was at the time of that commit.
The first one will be implemented:
Collection.Where(x => x.Age == 10)
.Where(x => x.Name == "Fido") // applied to the result of the previous
.Where(x => x.Fat == true) // applied to the result of the previous
As opposed to the much simpler (and far fasterpresumably faster):
// all in one fell swoop
Collection.Where(x => x.Age == 10 && x.Name == "Fido" && x.Fat == true)
Use a memory stream
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, ...);
return ms.ToArray();
}
There is a parse_dates
parameter for read_csv
which allows you to define the names of the columns you want treated as dates or datetimes:
date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)
Many JavaScript libraries (especially non-recent ones) do not handle IE9 well because it breaks with IE8 in the handling of a lot of things.
JS code that sniffs for IE will fail quite frequently in IE9, unless such code is rewritten to handle IE9 specifically.
Before the JS code is updated, you should use the "X-UA-Compatible" meta tag to force your web page into IE8 mode.
EDIT: Can't believe that, 3 years later and we're onto IE11, and there are still up-votes for this. :-) Many JS libraries should now at least support IE9 natively and most support IE10, so it is unlikely that you'll need the meta tag these days, unless you don't intend to upgrade your JS library. But beware that IE10 changes things regarding to cross-domain scripting and some CDN-based library code breaks. Check your library version. For example, Dojo 1.9 on the CDN will break on IE10, but 1.9.1 solves it.
EDIT 2: You REALLY need to get your acts together now. We are now in mid-2014!!! I am STILL getting up-votes for this! Revise your sites to get rid of old-IE hard-coded dependencies!
Sigh... If I had known that this would be by far my most popular answer, I'd probably have spent more time polishing it...
EDIT 3: It is now almost 2016. Upvotes still ticking up... I guess there are lots of legacy code out there... One day our programs will out-live us...
I know this thread is a year old, but the real problem is in your working directory.
I believe that the working directory is C:\Users\Administrator\Documents\Mibot\oops\
. Please check for the file named socket.py
in this directory. Once you find it, rename or move it. When you import socket, socket.py
from the current directory is used instead of the socket.py
from Python's directory. Hope this helped. :)
Note: Never use the file names from Python's directory to save your program's file name; it will conflict with your program(s).
Use that code.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Your URL",
data: "{}",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
even simpler, adding up to String[]
,
use built-in filter filter(StringUtils::isNotEmpty)
of org.apache.commons.lang3
import org.apache.commons.lang3.StringUtils;
String test = "a\nb\n\nc\n";
String[] lines = test.split("\\n", -1);
String[] result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
System.out.println(Arrays.toString(lines));
System.out.println(Arrays.toString(result));
and output:
[a, b, , c, ]
[a, b, c]
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com/SpecificAction.php");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com/SpecificAction.php";
The reason for this error is very simple. Your AJAX is trying to call over HTTP whereas your server is running over HTTPS, so your server is denying calling your AJAX. This can be fixed by adding the following line inside the head tag of your main HTML file:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
A slow but straight forward regex solution:
std::string file = std::regex_replace(path, std::regex("(.*\\/)|(\\..*)"), "");
Using pyautogui
To install
pip install pyautogui
and to find the location of the mouse pointer
import pyautogui
print(pyautogui.position())
This will give the pixel location to which mouse pointer is at.
Hope it help. :)
const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;
I faced with the similar issue, and just knowing the arrayList is a resizable-array implementation of the List interface, I also expect you can add element to any point, but at least have the option to define the initial size. Anyway, you can create an array first and convert that to a list like:
int index = 5;
int size = 10;
Integer[] array = new Integer[size];
array[index] = value;
...
List<Integer> list = Arrays.asList(array);
or
List<Integer> list = Arrays.asList(new Integer[size]);
list.set(index, value);
you declare your function as returning boolean, but it never returns anything.
If you are building with ant (I am using ant from eclipse), you can just add the extra jar files by saying to ant to add them... Not necessarily the best method if you have a project maintained by multiple people but it works for one person project and is easy.
for example my target that was building the .jar file was:
<jar destfile="${plugin.jar}" basedir="${plugin.build.dir}">
<manifest>
<attribute name="Author" value="ntg"/>
................................
<attribute name="Plugin-Version" value="${version.entry.commit.revision}"/>
</manifest>
</jar>
I just added one line to make it:
<jar ....">
<zipgroupfileset dir="${external-lib-dir}" includes="*.jar"/>
<manifest>
................................
</manifest>
</jar>
where
<property name="external-lib-dir"
value="C:\...\eclipseWorkspace\Filter\external\...\lib" />
was the dir with the external jars. And that's it...
I think that it is better (for my expirience) to use: :first-of-type
, :nth-of-type()
, :last-of-type
. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type
, than *-child
selectors.
<customErrors defaultRedirect="~/404.aspx" mode="On">
<error statusCode="404" redirect="~/404.aspx"/>
</customErrors>
Code above is only for "Page Not Found Error-404" if file extension is known(.html,.aspx etc)
Beside it you also have set Customer Errors for extension not known or not correct as
.aspwx
or .vivaldo
. You have to add httperrors
settings in web.config
<httpErrors errorMode="Custom">
<error statusCode="404" prefixLanguageFilePath="" path="/404.aspx" responseMode="Redirect" />
</httpErrors>
<modules runAllManagedModulesForAllRequests="true"/>
it must be inside the <system.webServer>
</system.webServer>
why is my java logging not working
provides a jar file that will help you work out why your logging in not working as expected. It gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Try this:
<script>
var myWindow = window.open("ANYURL", "MyWindowName", "width=700,height=700");
this.window.close();
</script>
This worked for me in some cases in Google Chrome 50. It does not seem to work when put inside a javascript function, though.
I think when you define a function with "var foo = function() {...};
", the function is only defined after that line. In other words, try this:
var replaceHtmlEntites = (function() {
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {
"nbsp": " ",
"amp" : "&",
"quot": "\"",
"lt" : "<",
"gt" : ">"
};
return function(s) {
return ( s.replace(translate_re, function(match, entity) {
return translate[entity];
}) );
}
})();
var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
cleanText = replaceHtmlEntities(text);
Edit: Also, only use "var
" the first time you declare a variable (you're using it twice on the cleanText
variable).
Edit 2: The problem is the spelling of the function name. You have "var replaceHtmlEntites =". It should be "var replaceHtmlEntities ="
or this, I did not implement the array comparison so you will also have some fun :)
public bool CompareTables(DataTable a, DataTable b)
{
if(a.Rows.Count != b.Rows.Count)
{
// different size means different tables
return false;
}
for(int rowIndex=0; rowIndex<a.Rows.Count; ++rowIndex)
{
if(!arraysHaveSameContent(a.Rows[rowIndex].ItemArray, b.Rows[rowIndex].ItemArray,))
{
return false;
}
}
// Tables have same data
return true;
}
private bool arraysHaveSameContent(object[] a, object[] b)
{
// Here your super cool method to compare the two arrays with LINQ,
// or if you are a loser do it with a for loop :D
}
If You have configuration file, You can configure it.
Add urllib3 in loggers section:
[loggers]
keys = root, urllib3
Add logger_urllib3 section:
[logger_urllib3]
level = WARNING
handlers =
qualname = requests.packages.urllib3.connectionpool
Just use not
:
if not your_variable:
print("your_variable is empty")
and for your 0 as string
use:
if your_variable == "0":
print("your_variable is 0 (string)")
combine them:
if not your_variable or your_variable == "0":
print("your_variable is empty")
Python is about simplicity, so is this answer :)
//if i input 9 it should go to 8?
You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) - array(7).
Your code doesn't seem so ugly to me...
however, an alternative (not much better) could be e.g. :
df <- data.frame(table(yn))
colnames(df) <- c('Smoker','Freq')
df$Perc <- df$Freq / sum(df$Freq) * 100
------------------
Smoker Freq Perc
1 No 19 47.5
2 Yes 21 52.5
we can do like this:
in application.yml:
spring:
profiles:
active: test //modify here to switch between environments
include: application-${spring.profiles.active}.yml
in application-test.yml:
server:
port: 5000
and in application-local.yml:
server:
address: 0.0.0.0
port: 8080
then spring boot will start our app as we wish to.
I tried experimenting with the answers given. My personal finding came out to be:
git rm -r --cached .
And then
git add .
This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.
YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".
save and open in excel, try refresh data and excel will be monit about parameters.
You could pass in the command-line option -v
with a variable name (v
) and a value (=
) of the environment variable ("${v}"
):
% awk -vv="${v}" 'BEGIN { print v }'
123test
Or to make it clearer (with far fewer v
s):
% environment_variable=123test
% awk -vawk_variable="${environment_variable}" 'BEGIN { print awk_variable }'
123test
Use checked="checked"
attribute if you want your checkbox to be checked.
This worked for me..
select ROW_NUMBER() over (order by column_name_of your choice ) as pri_key, the other columns of the view
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
yum uses RPM, so the following command will list the contents of the installed package:
$ rpm -ql package-name
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
Assigning questionFrame.frame.size.height= screenSize.height * 0.30
will not reflect anything in the view. because it is a get-only property. If you want to change the frame of questionFrame you can use the below code.
questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)
Use a raw string:
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
Note that although it looks wrong, it's actually right. There is only one backslash in the string foo
.
This happens because when you just type foo
at the prompt, python displays the result of __repr__()
on the string. This leads to the following (notice only one backslash and no quotes around the print
ed string):
>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:
>>> foo = r'baz \'
File "<stdin>", line 1
foo = r'baz \'
^
SyntaxError: EOL while scanning single-quoted string
Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:
>>> foo = 'baz \\'
>>> print(foo)
baz \
However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath()
function:
myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)
This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.
const setTimeoutAsync = (cb, delay) =>
new Promise((resolve) => {
setTimeout(() => {
resolve(cb());
}, delay);
});
We can pass custom 'cb fxn' like this one
The correct answer is the following:
if [[ -n $var ]] ; then
blah
fi
Note the use of the [[...]]
, which correctly handles quoting the variables for you.
__FILE__
is the filename with extension of the file containing the code being executed.
In foo.rb
, __FILE__
would be "foo.rb".
If foo.rb
were in the dir /home/josh
then File.dirname(__FILE__)
would return /home/josh
.
I use both CSS and jQuery solutions when achieving this. This will change both how it appears in the browser and the data value. A simple solution, that just works.
CSS
#field {
text-transform: capitalize;
}
jQuery
$('#field').keyup(function() {
var caps = jQuery('#field').val();
caps = caps.charAt(0).toUpperCase() + caps.slice(1);
jQuery('#field').val(caps);
});
Manoj answer above is correct, but another option is to use MESSAGE.encode() or encode('utf-8') to convert to bytes. bytes and encode are mostly the same, encode is compatible with python 2. see here for more
full code:
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))
Maybe this is better:
const withQuery = require('with-query');
fetch(withQuery('https://api.github.com/search/repositories', {
q: 'query',
sort: 'stars',
order: 'asc',
}))
.then(res => res.json())
.then((json) => {
console.info(json);
})
.catch((err) => {
console.error(err);
});
As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils
module (Thanks Oliver)
Here is the proper way to do it:
#xlrd, xlutils and xlwt modules need to be installed.
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook("names.xls")
wb = copy(rb)
s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')
This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.
Public Shared SaveCommand_AltS As New RoutedCommand
SaveCommand_AltS.InputGestures.Add(New KeyGesture(Key.S, ModifierKeys.Control))
Me.CommandBindings.Add(New CommandBinding(SaveCommand_AltS, AddressOf Me.save))
No XAML is needed.
It should start again and delete all the instances of previous current activity.
No, it shouldn't.
It should update its data in place (e.g., requery()
the Cursor
). Then there will be no "instances of previous current activity" to worry about.
U cant try this
for (WordList i : words) {
words.get(words.indexOf(i));
}
Use <location>
configuration tag, and <allow users="?"/>
to allow anonymous only or <allow users="*"/>
for all:
<configuration>
<location path="Path/To/Public/Folder">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
This question belongs more on Server Fault but FWIW I'd say running Apache in front of Node.js is not a good approach in most cases.
Apache's ProxyPass is awesome for lots of things (like exposing Tomcat based services as part of a site) and if your Node.js app is just doing a specific, small role or is an internal tool that's only likely to have a limited number of users then it might be easier just to use it so you can get it working and move on, but that doesn't sound like the case here.
If you want to take advantage of the performance and scale you'll get from using Node.js - and especially if you want to use something that involves maintaining a persistent connection like web sockets - you are better off running both Apache and your Node.js on other ports (e.g. Apache on localhost:8080, Node.js on localhost:3000) and then running something like nginx, Varnish or HA proxy in front - and routing traffic that way.
With something like varnish or nginx you can route traffic based on path and/or host. They both use much less system resources and is much more scalable that using Apache to do the same thing.
My preferred way is String.format()
because its a oneliner and doesn't require third party libraries:
String message = String.format("Hello! My name is %s, I'm %s.", name, age);
I use this regularly, e.g. in exception messages like:
throw new Exception(String.format("Unable to login with email: %s", email));
Hint: You can put in as many variables as you like because format()
uses Varargs
For closing cmd window, especially after ending weblogic or JBOSS app servers console with Ctrl+C, I'm using 'call
' command instead of 'start
' in my batch files. My startWLS.cmd file then looks like:
call [BEA_HOME]\user_projects\domains\test_domain\startWebLogic.cmd
After Ctrl+C(and 'Y' answer) cmd window is automatically closed.
For compatibility and ease of use it's often better to use FIND to do this.
You must also consider if you would like to match case sensitively or case insensitively.
The method with 78 points (I believe I was referring to paxdiablo's post) will only match Case Sensitively, so you must put a separate check for every case variation for every possible iteration you may want to match.
( What a pain! At only 3 letters that means 9 different tests in order to accomplish the check! )
In addition, many times it is preferable to match command output, a variable in a loop, or the value of a pointer variable in your batch/CMD which is not as straight forward.
For these reasons this is a preferable alternative methodology:
Use: Find [/I] [/V] "Characters to Match"
[/I] (case Insensitive) [/V] (Must NOT contain the characters)
As Single Line:
ECHO.%Variable% | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )
Multi-line:
ECHO.%Variable%| FIND /I "ABC">Nul && (
Echo.Found "ABC"
) || (
Echo.Did not find "ABC"
)
As mentioned this is great for things which are not in variables which allow string substitution as well:
FOR %A IN (
"Some long string with Spaces does not contain the expected string"
oihu AljB
lojkAbCk
Something_Else
"Going to evaluate this entire string for ABC as well!"
) DO (
ECHO.%~A| FIND /I "ABC">Nul && (
Echo.Found "ABC" in "%A"
) || ( Echo.Did not find "ABC" )
)
Output From a command:
NLTest | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )
As you can see this is the superior way to handle the check for multiple reasons.
.dex file
Compiled Android application code file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.
// for 3 x 5 array
new Array(3).fill(new Array(5).fill(0))
Backup
..PLAIN
for Format USE INSERT COMMANDS
Use Column Inserts
if you want column names in your inserts.Backup
buttonJarret Hardie is correct. Or, first merge your changes back into master and then try the push. By default, git push
pushes all branches that have names that match on the remote -- and no others. So those are your two choices -- either specify it explicitly like Jarret said or merge back to a common branch and then push.
There's been talk about this on the Git mail list and it's clear that this behavior is not about to change anytime soon -- many developers rely on this behavior in their workflows.
Edit/Clarification
Assuming your upstreammaster
branch is ready to push then you could do this:
Pull in any changes from the upstream.
$ git pull upstream master
Switch to my local master branch
$ git checkout master
Merge changes in from upstreammaster
$ git merge upstreammaster
Push my changes up
$ git push upstream
Another thing that you may want to do before pushing is to rebase
your changes against upstream/master so that your commits are all together. You can either do that as a separate step between #1 and #2 above (git rebase upstream/master
) or you can do it as part of your pull (git pull --rebase upstream master
)
You can use StringUtils
:
import org.apache.commons.lang3.StringUtils;
if (StringUtils.isBlank(str)) {
System.out.println("String is empty");
} else {
System.out.println("String is not empty");
}
Have a look here also: StringUtils.isBlank() vs String.isEmpty()
isBlank
examples:
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
webpack.config.js
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
}
anyfile.html
<img src={image_name.jpg} />
You can stop a macro by pressing ctrl + break but if you don't have the break key you could use this autohotkey (open source) code:
+ESC:: SendInput {CtrlBreak} return
Pressing shift + Escape will be like pressing ctrl + break and thus will stop your macro.
All the glory to this page
Another reason this can happen is if you send the wrong appId. This can happen in early development if you have a development app and a production app. If you hard-code the appId for dev and push to prod, this will show up.
Both commands are correct
php_value post_max_size 30M
php_value upload_max_filesize 30M
BUT to use the .htaccess
you have to enable rewrite_module
in Apache config file. In httpd.conf
find this line:
# LoadModule rewrite_module modules/mod_rewrite.so
and remove the #
.
BE CAREFUL!!!
One should try to avoid calling a function by string in JavaScript for two reasons:
Reason 1: Some code obfuscators will wreck your code as they will change the function names, making the string invalid.
Reason 2: It is much harder to maintain code that uses this methodology as it is much harder to locate usages of the methods called by a string.
You can also get an EntityManager using PersistenceContext or Autowired annotation, but be aware that it will not be thread-safe.
@PersistenceContext
private EntityManager entityManager;
SELECT * FROM `calendar` WHERE DATE_FORMAT(startTime, "%Y-%m-%d") = '2010-04-29'"
OR
SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'
On Linux, Tomcat7 has a configuration file located at:
/etc/sysconfig/tomcat7
... which is where server specific configurations should be made. You can set the JAVA_HOME env variable here w/o needing to create a profile.d/ script.
This worked for me.
There is a commercial product with an interesting logo which lets you see all kind of traffic between server and client named charles.
Another open source tools include: Live HttpHeaders, Wireshark or Firebug.
"if(true)" will always be true and it will never make it to the else. If you want it to work correctly you have to do this:
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "HELLO");
} else {
JOptionPane.showMessageDialog(null, "GOODBYE");
System.exit(0);
}
if you need a performance trick use below:
$(".yourclass", this);
find() method makes a search everytime in selector.
As @Steven points out, a better way would be:
public void writeToFile(def directory, def fileName, def extension, def infoList) {
new File("$directory/$fileName$extension").withWriter { out ->
infoList.each {
out.println it
}
}
}
As this handles the line separator for you, and handles closing the writer as well
(and doesn't open and close the file each time you write a line, which could be slow in your original version)
You could also try this:
SELECT DISTINCT (DATE(dateadded)) AS unique_date, COUNT(*) AS amount
FROM table
GROUP BY unique_date
ORDER BY unique_date ASC
If you're using SQL Server, after your query you can select the @@RowCount function (or if your result set might have more than 2 billion rows use the RowCount_Big() function). This will return the number of rows selected by the previous statement or number of rows affected by an insert/update/delete statement.
SELECT my_table.my_col
FROM my_table
WHERE my_table.foo = 'bar'
SELECT @@Rowcount
Or if you want to row count included in the result sent similar to Approach #2, you can use the the OVER clause.
SELECT my_table.my_col,
count(*) OVER(PARTITION BY my_table.foo) AS 'Count'
FROM my_table
WHERE my_table.foo = 'bar'
Using the OVER clause will have much better performance than using a subquery to get the row count. Using the @@RowCount will have the best performance because the there won't be any query cost for the select @@RowCount statement
Update in response to comment: The example I gave would give the # of rows in partition - defined in this case by "PARTITION BY my_table.foo". The value of the column in each row is the # of rows with the same value of my_table.foo. Since your example query had the clause "WHERE my_table.foo = 'bar'", all rows in the resultset will have the same value of my_table.foo and therefore the value in the column will be the same for all rows and equal (in this case) this the # of rows in the query.
Here is a better/simpler example of how to include a column in each row that is the total # of rows in the resultset. Simply remove the optional Partition By clause.
SELECT my_table.my_col, count(*) OVER() AS 'Count'
FROM my_table
WHERE my_table.foo = 'bar'
I think there is a better solution. Make your div to print cover the entire document, but only when it's printed:
@media print {
.myDivToPrint {
background-color: white;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 15px;
font-size: 14px;
line-height: 18px;
}
}
Add between <head>
tags:
<style>
td {background: #ffddaa; width: 20%;}
</style>
and in the body:
<div style="background: black; border-radius: 12px;">
<table width="100%" style="cell-spacing: 1px;">
<tr>
<td style="border-top-left-radius: 10px;">
Noordwest
</td>
<td> </td>
<td>Noord</td>
<td> </td>
<td style="border-top-right-radius: 10px;">
Noordoost
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>West</td>
<td> </td>
<td>Centrum</td>
<td> </td>
<td>Oost</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td style="border-bottom-left-radius: 10px;">
Zuidwest
</td>
<td> </td>
<td>Zuid</td>
<td> </td>
<td style="border-bottom-right-radius: 10px;">
Zuidoost
</td>
</tr>
</table>
</div>
The cell color, contents and formatting are of course for example;
it's about spacing color-filled cells within a div.
Doing so, the black cell borders/table border are actually the div background color.
Note that you'll need to set the div-border-radius about 2 values greater than the separate cell corner border radii, to take a smooth rounded corner effect.
a much more practical way for those who do not want to use regex:
$data = filter_var($data, FILTER_SANITIZE_NUMBER_INT);
note: it works with phone numbers too.
I found another solution that worked for me follow this link
https://stackoverflow.com/a/42687397/4559365
It basically overrides the method canScrollHorizontally
to disable swiping by finger. Howsoever setCurrentItem
still works.
if you want to run spring boot without a servlet container, but with one on the classpath (e.g. for tests), use the following, as described in the spring boot documentation:
@Configuration
@EnableAutoConfiguration
public class MyClass{
public static void main(String[] args) throws JAXBException {
SpringApplication app = new SpringApplication(MyClass.class);
app.setWebEnvironment(false); //<<<<<<<<<
ConfigurableApplicationContext ctx = app.run(args);
}
}
also, I just stumbled across this property:
spring.main.web-environment=false
You are missing the selector in the .on
function:
.on(eventType, selector, function)
This selector is very important!
If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler
See jQuery 1.9 .live() is not a function for more details.
Create your own class Customer
as following:
import import java.io.Serializable;
public class Customer implements Serializable
{
private String name;
private String city;
public Customer()
{
}
public Customer(String name, String city)
{
this.name= name;
this.city=city;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city= city;
}
}
In your onCreate()
method
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top);
Customer cust=new Customer();
cust.setName("abc");
cust.setCity("xyz");
Intent intent=new Intent(abc.this,xyz.class);
intent.putExtra("bundle",cust);
startActivity(intent);
}
In xyz activity
class you need to use the following code:
Intent intent=getIntent();
Customer cust=(Customer)intent.getSerializableExtra("bundle");
textViewName.setText(cust.getName());
textViewCity.setText(cust.getCity());
<span style="text-align:center; display:block;">
<a href="http://news.awaissoft.com">Awaissoft</a>
</span>
Since Express 4.0, there's a dedicated sendStatus
function:
res.sendStatus(404);
If you're using an earlier version of Express, use the status
function instead.
res.status(404).send('Not found');
I used this approach in a recent project and I was pretty happy with the result:
.select-wrapper {
position: relative;
&::after {
position: absolute;
top: 0;
right: 0;
width: 100px;
height: 100%;
content: "";
background: linear-gradient(to right, transparent, white);
pointer-events: none;
}
}
Basically, wrap the select in a div and insert a pseudo element to overlay the end of the text to create the appearance that the text fades out.
Neither main()
or void main()
are standard C. The former is allowed as it has an implicit int
return value, making it the same as int main()
. The purpose of main
's return value is to return an exit status to the operating system.
In standard C, the only valid signatures for main
are:
int main(void)
and
int main(int argc, char **argv)
The form you're using: int main()
is an old style declaration that indicates main
takes an unspecified number of arguments. Don't use it - choose one of those above.
<ul>
<li ng-repeat=interface in interfaces>
<img src='green-checkmark.png' ng-show="interface=='UP'" />
<img src='big-black-X.png' ng-show="interface=='DOWN'" />
</li>
</ul>
The question, is the provided example just an "example" or exact what you looking for? There are many mixed answers here, and I dont understand the complexibility of the accepted one.
To find out if ANY content of the array of needles exists in the string, and quickly return true or false:
$string = 'abcdefg';
if(str_replace(array('a', 'c', 'd'), '', $string) != $string){
echo 'at least one of the needles where found';
};
If, so, please give @Leon credit for that.
To find out if ALL values of the array of needles exists in the string, as in this case, all three 'a', 'b'
and 'c'
MUST be present, like you mention as your "for example"
echo 'All the letters are found in the string!';
Many answers here is out of that context, but I doubt that the intension of the question as you marked as resolved. E.g. The accepted answer is a needle of
$array = array('burger', 'melon', 'cheese', 'milk');
What if all those words MUST be found in the string?
Then you try out some "not accepted answers"
on this page.
First Rename your AndroidManifest.xml file
android:label="Your App Name"
Second
Rename Your Application Name in Pubspec.yaml file
name: Your Application Name
Third Change Your Application logo
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/path/your Application logo.formate"
Fourth Run
flutter pub pub run flutter_launcher_icons:main
If you have administrator permissions, Right Click to Visual Studio icon > properties and then advanced, "Run as administrator" check. You can run visaul studio as administrator directly anymore. This way, formal and so basic.