Your port 80 is being used by the system.
And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.
Before I start, please let me emphasize that the size of the file must be checked on the server side. If not checked on server side, malicious users can override your client side limits, and upload huge files to your server. DO NOT TRUST THE USERS.
I played a bit with PHP's MAX_FILE_SIZE, it seemed to work only after the file was uploaded, which makes it irrelevant (again, malicious user can override it quite easily).
The javascript code below (tested in Firefox and Chrome), based on Matthew's post, will warn the user (the good, innocent one) a priori to uploading a large file, saving both traffic and the user's time:
<form method="post" enctype="multipart/form-data"
onsubmit="return checkSize(2097152)">
<input type="file" id="upload" />
<input type="submit" />
<script type="text/javascript">
function checkSize(max_img_size)
{
var input = document.getElementById("upload");
// check for browser support (may need to be modified)
if(input.files && input.files.length == 1)
{
if (input.files[0].size > max_img_size)
{
alert("The file must be less than " + (max_img_size/1024/1024) + "MB");
return false;
}
}
return true;
}
</script>
When you run a .ps1 PowerShell script you might get the message saying “.ps1 is not digitally signed. The script will not execute on the system.” To fix it you have to run the command below to run Set-ExecutionPolicy and change the Execution Policy setting.
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.
int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
case 0: yourBool = false; break;
case 1: yourBool = true; break;
default:
throw new InvalidOperationException("Integer value is not valid");
}
The out-of-the-box Convert
won't check this; nor will yourInteger (==|!=) (0|1)
.
Just spotted this thread while searching for this very answer. I just made a small jQuery function, hope this helps, works like a charm:
JAVASCRIPT
var maxHeight = 0;
$('.inner').each(function() {
maxHeight = Math.max(maxHeight, $(this).height());
});
$('.lhs_content .inner, .rhs_content .inner').css({height:maxHeight + 'px'});
HTML
<div class="lhs_content">
<div class="inner">
Content in here
</div>
</div>
<div class="rhs_content">
<div class="inner">
More content in here
</div>
</div>
This is for vmware workstation 6.5
It is pretty far down.
select Create new virtual machine ->
select custom ->
on compatibility page take defaults ->
check I will install os later
-> click through several pages choosing other for OS, give it a name, make sure it IS NOT in the same folder as the VMDK file. Choose bridged network.
You will now see a screen asking to select disk, select existing virual disk. then browse and select the VMDK file
I'm on windows, and had to install Redis from here and then run redis-server.exe
.
From the top of this SO question.
System variables can be set through CMD and registry For ex. reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH
All the commonly used CMD codes and system variables are given here: Set Windows system environment variables using CMD.
Open CMD and type Set
You will get all the values of system variable.
Type set java to know the path details of java installed on your window OS.
>/dev/null 2>&1
will mute both stdout
and stderr
yum install nano >/dev/null 2>&1
Before couple of months, I created GPSTracker library to help me to get GPS locations. In case you need to view GPSTracker > getLocation
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geo_locations);
// check if GPS enabled
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.getIsGPSTrackingEnabled())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView)findViewById(R.id.fieldLatitude);
textview.setText(stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
textview = (TextView)findViewById(R.id.fieldLongitude);
textview.setText(stringLongitude);
String country = gpsTracker.getCountryName(this);
textview = (TextView)findViewById(R.id.fieldCountry);
textview.setText(country);
String city = gpsTracker.getLocality(this);
textview = (TextView)findViewById(R.id.fieldCity);
textview.setText(city);
String postalCode = gpsTracker.getPostalCode(this);
textview = (TextView)findViewById(R.id.fieldPostalCode);
textview.setText(postalCode);
String addressLine = gpsTracker.getAddressLine(this);
textview = (TextView)findViewById(R.id.fieldAddressLine);
textview.setText(addressLine);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);
return true;
}
}
GPS Tracker
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
/**
* Create this Class from tutorial :
* http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
*
* For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
*
*/
public class GPSTracker extends Service implements LocationListener {
// Get Class Name
private static String TAG = GPSTracker.class.getName();
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;
Location location;
double latitude;
double longitude;
// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Try to get my current location by GPS or Network Provider
*/
public void getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Try to get location if you GPS Service is enabled
if (isGPSEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use GPS Service");
/*
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
* a location fix.
*/
provider_info = LocationManager.GPS_PROVIDER;
} else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use Network State to get GPS coordinates");
/*
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
*/
provider_info = LocationManager.NETWORK_PROVIDER;
}
// Application can use GPS or Network Provider
if (!provider_info.isEmpty()) {
locationManager.requestLocationUpdates(
provider_info,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider_info);
updateGPSCoordinates();
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to LocationManager", e);
}
}
/**
* Update GPSTracker latitude and longitude
*/
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* GPSTracker latitude getter and setter
* @return latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* GPSTracker longitude getter and setter
* @return
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* GPSTracker isGPSTrackingEnabled getter.
* Check GPS/wifi is enabled
*/
public boolean getIsGPSTrackingEnabled() {
return this.isGPSTrackingEnabled;
}
/**
* Stop using GPS listener
* Calling this method will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* @return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* @return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
* @return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* @return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* @return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
If the method / answer doesn't work. You need to use the official Google Provider: FusedLocationProviderApi.
Article: Getting the Last Known Location
Yes, it's possible to use inline if-expressions:
{{ 'Update' if files else 'Continue' }}
You can get this error if you use wrong mode when opening the file. For example:
with open(output, 'wb') as output_file:
print output_file.read()
In that code, I want to read the file, but I use mode wb
instead of r
or r+
To put it short 'value' is not an valid attribute of div. So it's absolutely correct to return undefined.
What you could do was something in the line of using one of the HTML5 attributes 'data-*'
<div id="demo" align="center" data-value="1">
And the script would be:
var val = document.getElementById('demo').getAttribute('data-value');
This should work in most modern browsers
Just remember to put your doctype as <!DOCTYPE html>
to get it valid
It seems that when this error appears it is an indication that the selenium-java plugin for maven is out-of-date.
Changing the version in the pom.xml should fix the problem
There is no need to include a bulky library such as Moment.js to fix such a simple issue.
The issue you are facing is not with formatting, but with parsing.
As John Shammas mentions in another answer, the Date
constructor (and Date.parse
) are picky about the input. Your 2016-01-04 10:34:23
may work in one JavaScript implementation, but not necessarily in the other.
According to the specification of ECMAScript 5.1, Date.parse
supports (a simplification of) ISO 8601. That's good news, because your date is already very ISO 8601-like.
All you have to do is change the input format just a little. Swap the space for a T
: 2016-01-04T10:34:23
; and optionally add a time zone (2016-01-04T10:34:23+01:00
), otherwise UTC is assumed.
If you know the number of elements per "row" and the width of the container you can use a selector to add a margin to the elements you need to cause a justified look.
I had rows of three divs I wanted justified so used the:
.tile:nth-child(3n+2) { margin: 0 10px }
this allows the center div in each row to have a margin that forces the 1st and 3rd div to the outside edges of the container
Also great for other things like borders background colors etc
var: Declare a variable, value initialization optional.
let: Declare a local variable with block scope.
const: Declare a read-only named constant.
Ex:
var a;
a = 1;
a = 2;//re-initialize possible
var a = 3;//re-declare
console.log(a);//3
let b;
b = 5;
b = 6;//re-initiliaze possible
// let b = 7; //re-declare not possible
console.log(b);
// const c;
// c = 9; //initialization and declaration at same place
const c = 9;
// const c = 9;// re-declare and initialization is not possible
console.log(c);//9
// NOTE: Constants can be declared with uppercase or lowercase, but a common
// convention is to use all-uppercase letters.
You can use a Union.
This will return the results of the queries in separate rows.
First you must make sure that both queries return identical columns.
Then you can do :
SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS Number
FROM tableD
RIGHT OUTER JOIN [tableB]
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id
GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl
UNION
SELECT tableA.Id, tableA.Name, '' AS Owner, '' AS ImageUrl, '' AS CompanyImageUrl, COUNT([tableC].Id) AS Number
FROM
[tableC]
RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id GROUP BY tableA.Id, tableA.Name
As has been mentioned, both queries return quite different data. You would probably only want to do this if both queries return data that could be considered similar.
SO
You can use a Join
If there is some data that is shared between the two queries. This will put the results of both queries into a single row joined by the id, which is probably more what you want to be doing here...
You could do :
SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS NumberOfUsers, query2.NumberOfPlans
FROM tableD
RIGHT OUTER JOIN [tableB]
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id
INNER JOIN
(SELECT tableA.Id, COUNT([tableC].Id) AS NumberOfPlans
FROM [tableC]
RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id
GROUP BY tableA.Id, tableA.Name) AS query2
ON query2.Id = tableA.Id
GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl
To check that the file you're trying to open actually exists, you can change directories in terminal using cd
. To change to ~/Desktop/sass/css
: cd ~/Desktop/sass/css
. To see what files are in the directory: ls
.
If you want information about either of those commands, use the man
page: man cd
or man ls
, for example.
Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.
On Mac OS X, you can also use open
to open a finder window: open .
will open the current directory in finder. (open ~/Desktop/sass/css
will open the ~/Desktop/sass/css
).
I know this is old, but I was having this same issue, found this post, and while it didn't explain exactly what was wrong, it helped me to the right answer - so hopefully my answer helps someone else who might be having a similar problem to mine.
I had an element I wanted rotated vertical, so naturally I added the filter: for IE8 and then the -ms-transform property for IE9. What I found is that having the -ms-transform property AND the filter applied to the same element causes IE9 to render the element very poorly. My solution:
If you are using the transform-origin property, add one for MS too (-ms-transform-origin: left bottom;). If you don't see your element, it could be that it's rotating on it's middle axis and thus leaving the page somehow - so double check that.
Move the filter: property for IE7&8 to a separate style sheet and use an IE conditional to insert that style sheet for browsers less than IE9. This way it doesn't affect the IE9 styles and all should work fine.
Make sure to use the correct DOCTYPE tag as well; if you have it wrong IE9 will not work properly.
Try this:
result <- df %>%
group_by(A, B) %>%
filter(value == max(value)) %>%
arrange(A,B,C)
Seems to work:
identical(
as.data.frame(result),
ddply(df, .(A, B), function(x) x[which.max(x$value),])
)
#[1] TRUE
As pointed out in the comments, slice
may be preferred here as per @RoyalITS' answer below if you strictly only want 1 row per group. This answer will return multiple rows if there are multiple with an identical maximum value.
HSQLDB is a good candidate (the fact that it is used in OpenOffice may convinced some of you), but for such a small personnal application, why not using an object database (instead of a classic relationnal database) ?
I used DB4O in one of my projects, and I'm very satisfied with it. Being object-oriented, you don't need the whole Hibernate layer, and can directly insert/update/delete/query objects ! Moreover, you don't need to worry about the schema, you directly work with the objects and DB4O does the rest !
I agree that it may take some time to get used to this new type of database, but check the DB40 tutorial to see how easy it makes working with the DB !
EDIT: As said in the comments, DB4O handles automatically the newer versions of the classes. Moreover, a tool for browsing and updating the database outside of the application is available here : http://code.google.com/p/db4o-om/
Got an easy progress bar function that i wrote the other day:
#!/bin/bash
# 1. Create ProgressBar function
# 1.1 Input is currentState($1) and totalState($2)
function ProgressBar {
# Process data
let _progress=(${1}*100/${2}*100)/100
let _done=(${_progress}*4)/10
let _left=40-$_done
# Build progressbar string lengths
_fill=$(printf "%${_done}s")
_empty=$(printf "%${_left}s")
# 1.2 Build progressbar strings and print the ProgressBar line
# 1.2.1 Output example:
# 1.2.1.1 Progress : [########################################] 100%
printf "\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%"
}
# Variables
_start=1
# This accounts as the "totalState" variable for the ProgressBar function
_end=100
# Proof of concept
for number in $(seq ${_start} ${_end})
do
sleep 0.1
ProgressBar ${number} ${_end}
done
printf '\nFinished!\n'
Or snag it from,
https://github.com/fearside/ProgressBar/
Specifically if you want to clear your text box in VB.NET or VB 6.0, write this code:
TextBox1.Items.Clear()
If you are using VBA, then the use this code :
TextBox1.Text = ""
or
TextBox1.Clear()
Click to green checkbox on installed tensorflow and choose needed version
EXECUTE dbms_mview.refresh('view name','cf');
What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:
div {
position: absolute;
top: 300px;
bottom: 0px;
left: 30px;
right: 30px;
}
This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom. Add an overflow:auto;
to handle cases where the content is larger than the div.
You could use tr
, like this:
tr " " .
Example:
# echo "hello world" | tr " " .
hello.world
From man tr
:
DESCRIPTION
Translate, squeeze, and/or delete characters from standard input, writ- ing to standard output.
Another approach is to add a toString()
method to your Car
class and just let the toString()
method of ArrayList do all the work.
@Override
public String toString()
{
return "Car{" +
"make=" + make +
", registration='" + registration + '\'' +
'}';
}
You don't get one car per line in the output, but it is quick and easy if you just want to see what is in the array.
List<Car> cars = c1.getAll();
System.out.println(cars);
Output would be something like this:
[Car{make=FORD, registration='ABC 123'},
Car{make=TOYOTA, registration='ZYZ 999'}]
maybe this can solve the problem: matplotlib, define size of a grid on a plot
ax.grid(True, which='both')
The truth is that the grid is working, but there's only one v-grid in 00:00 and no grid in others. I meet the same problem that there's only one grid in Nov 1 among many days.
Another way (depending on your actual needs): If you want to pop the first n characters and save both the popped characters and the modified string:
s = 'lipsum'
n = 3
a, s = s[:n], s[n:]
print(a)
# lip
print(s)
# sum
I agree that a data structure like a List is the best way to go:
List<Integer> values = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values.add(value);
} while (value >= 1) && (value <= 100);
Or you can just allocate an array of a max size and load values into it:
int maxValues = 100;
int [] values = new int[maxValues];
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values[numValues++] = value;
} while (value >= 1) && (value <= 100) && (numValues < maxValues);
A longer but more robust version of the accepted answer:
perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\})?;substr($1,0,int(length($1)/2)).($2&&length($1)%2?$2:$ENV{$3||$4});eg' template.txt
This expands all instances of $VAR
or ${VAR}
to their environment values (or, if they're undefined, the empty string).
It properly escapes backslashes, and accepts a backslash-escaped $ to inhibit substitution (unlike envsubst, which, it turns out, doesn't do this).
So, if your environment is:
FOO=bar
BAZ=kenny
TARGET=backslashes
NOPE=engi
and your template is:
Two ${TARGET} walk into a \\$FOO. \\\\
\\\$FOO says, "Delete C:\\Windows\\System32, it's a virus."
$BAZ replies, "\${NOPE}s."
the result would be:
Two backslashes walk into a \bar. \\
\$FOO says, "Delete C:\Windows\System32, it's a virus."
kenny replies, "${NOPE}s."
If you only want to escape backslashes before $ (you could write "C:\Windows\System32" in a template unchanged), use this slightly-modified version:
perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\});substr($1,0,int(length($1)/2)).(length($1)%2?$2:$ENV{$3||$4});eg' template.txt
Here's an example of using the HttpWebRequest
class to fetch a URL
private void buttonl_Click(object sender, EventArgs e)
{
String url = TextBox_url.Text;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
}
The shortcut for the integrated terminal is ctrl + `, then type node <filename>
.
Alternatively you can create a task. This is the only code in my tasks.json:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "node",
"isShellCommand": true,
"args": ["${file}"],
"showOutput": "always"
}
From here create a shortcut. This is my keybindings.json:
// Place your key bindings in this file to overwrite the defaults
[
{ "key": "cmd+r",
"command": "workbench.action.tasks.runTask"
},
{ "key": "cmd+e",
"command": "workbench.action.output.toggleOutput"
}
]
This will open 'run' in the Command Pallete, but you still have to type or select with the mouse the task you want to run, in this case node. The second shortcut toggles the output panel, there's already a shortcut for it but these keys are next to each other and easier to work with.
E = exponent expression, simply means power(10, n) or 10 ^ n
F = fraction expression, default 6 digits precision
G = gerneral expression, somehow smart to show the number in a concise way (but really?)
See the below example,
The code
void main(int argc, char* argv[])
{
double a = 4.5;
printf("=>>>> below is the example for printf 4.5\n");
printf("%%e %e\n",a);
printf("%%f %f\n",a);
printf("%%g %g\n",a);
printf("%%E %E\n",a);
printf("%%F %F\n",a);
printf("%%G %G\n",a);
double b = 1.79e308;
printf("=>>>> below is the exbmple for printf 1.79*10^308\n");
printf("%%e %e\n",b);
printf("%%f %f\n",b);
printf("%%g %g\n",b);
printf("%%E %E\n",b);
printf("%%F %F\n",b);
printf("%%G %G\n",b);
double d = 2.25074e-308;
printf("=>>>> below is the example for printf 2.25074*10^-308\n");
printf("%%e %e\n",d);
printf("%%f %f\n",d);
printf("%%g %g\n",d);
printf("%%E %E\n",d);
printf("%%F %F\n",d);
printf("%%G %G\n",d);
}
The output
=>>>> below is the example for printf 4.5
%e 4.500000e+00
%f 4.500000
%g 4.5
%E 4.500000E+00
%F 4.500000
%G 4.5
=>>>> below is the exbmple for printf 1.79*10^308
%e 1.790000e+308
%f 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%g 1.79e+308
%E 1.790000E+308
%F 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%G 1.79E+308
=>>>> below is the example for printf 2.25074*10^-308
%e 2.250740e-308
%f 0.000000
%g 2.25074e-308
%E 2.250740E-308
%F 0.000000
%G 2.25074E-308
Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//These variable are initalized here as they need to be used in more than one methid
private double currentLatitude; //lat of user
private double currentLongitude; //long of user
private double latitudeVillageApartmets= 53.385952001750184;
private double longitudeVillageApartments= -6.599087119102478;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
/*These methods all have to do with the map and wht happens if the activity is paused etc*/
//contains lat and lon of another marker
private void setUpMap() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
mMap.addMarker(marker); // adding marker
}
//contains your lat and lon
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("You are here");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
@Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.
I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.
The fasted way is:
SQL Server has a PIVOT command that might be what you are looking for.
select * from Tag
pivot (MAX(Value) for TagID in ([A1],[A2],[A3],[A4])) as TagTime;
If the columns are not constant, you'll have to combine this with some dynamic SQL.
DECLARE @columns AS VARCHAR(MAX);
DECLARE @sql AS VARCHAR(MAX);
select @columns = substring((Select DISTINCT ',' + QUOTENAME(TagID) FROM Tag FOR XML PATH ('')),2, 1000);
SELECT @sql =
'SELECT *
FROM TAG
PIVOT
(
MAX(Value)
FOR TagID IN( ' + @columns + ' )) as TagTime;';
execute(@sql);
if your project maven based, you can also try updating your project maven config by selecting project. Right click project> Maven>Update Project option. it will update your project config.
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
While this doesn't directly answer the question, there is great book available for free which will help you learn the basics called ProGit. If you would prefer the dead-wood version to a collection of bits you can purchase it from Amazon.
Just as an addendum to OP accepted answer:
If you having issues with
fatal: bad object xxxxx
that's because you don't have access to that commit. Which means you don't have that repo stored locally. Then:
git remote add LABEL_FOR_THE_REPO REPO_YOU_WANT_THE_COMMIT_FROM
git fetch LABEL_FOR_THE_REPO
git cherry-pick xxxxxxx
Where xxxxxxx is the commit hash you want.
This is nowhere definied in the JDBC API contract, but if you're lucky, the JDBC driver in question may return the complete SQL by just calling PreparedStatement#toString()
. I.e.
System.out.println(preparedStatement);
To my experience, the ones which do so are at least the PostgreSQL 8.x and MySQL 5.x JDBC drivers. For the case your JDBC driver doesn't support it, your best bet is using a statement wrapper which logs all setXxx()
methods and finally populates a SQL string on toString()
based on the logged information. For example Log4jdbc or P6Spy.
You can see the errors after stopping debbuging by choosing the option to display ASP.NET Core Web Server output in the output window. In my case I was pointing to a different templateUrl.
As others have said, you can't do that either using alert()
or confirm()
.
You can, however, create an external HTML document containing your error message and an OK
button, set its <title>
element to whatever you want, then display it in a modal dialog box using showModalDialog().
your code would be
a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [a[1],a[5],a[7]]
print(ind_pos)
you get [88, 85, 16]
Use the matplotlib savefig
function with the keyword argument transparent=True
to save the image as a png file.
In [30]: x = np.linspace(0,6,31)
In [31]: y = np.exp(-0.5*x) * np.sin(x)
In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]
In [33]: savefig('demo.png', transparent=True)
Result:
Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display
command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.
I based my answer on the title of your post only, as I don't know C# and didn't understand the given query. But in MySQL I suggest you try subselects. First get a set of primary keys of interesting columns then select data from those rows:
SELECT somecolumn, anothercolumn
FROM sometable
WHERE id IN (
SELECT min(id)
FROM sometable
GROUP BY somecolumn
);
Since Python 3.7 and no external libraries, you can use the strptime function from the datetime module:
datetime.datetime.strptime('2019-01-04T16:41:24+0200', "%Y-%m-%dT%H:%M:%S%z")
For more formatting options, see here.
Python 2 doesn't support the %z
format specifier, so it's best to explicitly use Zulu time everywhere if possible:
datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")
Here are several options for getting the "tail" items of an iterable:
Given
n = 9
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Desired Output
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Code
We get the latter output using any of the following options:
from collections import deque
import itertools
import more_itertools
# A: Slicing
iterable[-n:]
# B: Implement an itertools recipe
def tail(n, iterable):
"""Return an iterator over the last *n* items of *iterable*.
>>> t = tail(3, 'ABCDEFG')
>>> list(t)
['E', 'F', 'G']
"""
return iter(deque(iterable, maxlen=n))
list(tail(n, iterable))
# C: Use an implemented recipe, via more_itertools
list(more_itertools.tail(n, iterable))
# D: islice, via itertools
list(itertools.islice(iterable, len(iterable)-n, None))
# E: Negative islice, via more_itertools
list(more_itertools.islice_extended(iterable, -n, None))
Details
iter(iterable)
. itertools
recipe. It is generalized to work on any iterable and resolves the iterator issue in the last solution. This recipe must be implemented manually as it is not officially included in the itertools
module.more_itertools
(install via > pip install more-itertools
); see more_itertools.tail
.itertools
library. Note, itertools.islice
does not support negative slicing. more_itertools
that generalizes itertools.islice
to support negative slicing; see more_itertools.islice_extended
.Which one do I use?
It depends. In most cases, slicing (option A, as mentioned in other answers) is most simple option as it built into the language and supports most iterable types. For more general iterators, use any of the remaining options. Note, options C and E require installing a third-party library, which some users may find useful.
In MySQL:
start transaction;
savepoint sp1;
delete from customer where ID=1;
savepoint sp2;
delete from customer where ID=2;
rollback to sp2;
rollback to sp1;
In my implementation, the cell I was referencing could have been several options. I used the following format where 'ws' is the current worksheet being edited
For each ws in Activeworkbook.Worksheets
For i…
For j...
...
ws.Cells(i, j).Value = "=HYPERLINK(""#'" & SHEET-REF-VAR & "'!" & CELL-REF-VAR & """,""" & SHEET-REF-VAR & """)"
I would assume so, I have Python 2.4, 2.5 and 2.6 installed side-by-side on the same computer.
You can easily solve that in 2 steps:
1- Reach the child element using querySelector like that:
var target = element[0].querySelector('tbody tr:first-child td')
2- Transform it to an angular.element
object again by doing:
var targetElement = angular.element(target)
You will then have access to all expected methods on the targetElement
variable.
Another convenient way to copy the values from src ArrayList to dest Arraylist is as follows:
ArrayList<String> src = new ArrayList<String>();
src.add("test string1");
src.add("test string2");
ArrayList<String> dest= new ArrayList<String>();
dest.addAll(src);
This is actual copying of values and not just copying of reference.
Another way is to use a copy of your arrayList just for iteration:
List<Object> l = ...
List<Object> iterationList = ImmutableList.copyOf(l);
for (Object curr : iterationList) {
if (condition(curr)) {
l.remove(curr);
}
}
You can use Google Gson like this
UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);
Gson gson = new Gson();
String jsonStr = gson.toJson(user);
You can't. All you can do is to make that image as small as possible and set some cache invalidation headers (Expires
, Cache-Control
) far in the future. Here's what Yahoo! has to say about favicon.ico requests.
I was curious to see the results of the methods provided in the question as well as the accepted answer, so I put it to the test.
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
class Worker
{
public int Id;
public int SleepTimeout;
public async Task DoWork(DateTime testStart)
{
var workerStart = DateTime.Now;
Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
Id, Thread.CurrentThread.ManagedThreadId, (workerStart-testStart).TotalSeconds.ToString("F2"));
await Task.Run(() => Thread.Sleep(SleepTimeout));
var workerEnd = DateTime.Now;
Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
Id, (workerEnd-workerStart).TotalSeconds.ToString("F2"), (workerEnd-testStart).TotalSeconds.ToString("F2"));
}
}
static void Main(string[] args)
{
var workers = new List<Worker>
{
new Worker { Id = 1, SleepTimeout = 1000 },
new Worker { Id = 2, SleepTimeout = 2000 },
new Worker { Id = 3, SleepTimeout = 3000 },
new Worker { Id = 4, SleepTimeout = 4000 },
new Worker { Id = 5, SleepTimeout = 5000 },
};
var startTime = DateTime.Now;
Console.WriteLine("Starting test: Parallel.ForEach...");
PerformTest_ParallelForEach(workers, startTime);
var endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WaitAll...");
PerformTest_TaskWaitAll(workers, startTime);
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
startTime = DateTime.Now;
Console.WriteLine("Starting test: Task.WhenAll...");
var task = PerformTest_TaskWhenAll(workers, startTime);
task.Wait();
endTime = DateTime.Now;
Console.WriteLine("Test finished after {0} seconds.\n",
(endTime - startTime).TotalSeconds.ToString("F2"));
Console.ReadKey();
}
static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
{
Parallel.ForEach(workers, worker => worker.DoWork(testStart).Wait());
}
static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
{
Task.WaitAll(workers.Select(worker => worker.DoWork(testStart)).ToArray());
}
static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
{
return Task.WhenAll(workers.Select(worker => worker.DoWork(testStart)));
}
}
}
And the resulting output:
Starting test: Parallel.ForEach...
Worker 1 started on thread 1, beginning 0.21 seconds after test start.
Worker 4 started on thread 5, beginning 0.21 seconds after test start.
Worker 2 started on thread 3, beginning 0.21 seconds after test start.
Worker 5 started on thread 6, beginning 0.21 seconds after test start.
Worker 3 started on thread 4, beginning 0.21 seconds after test start.
Worker 1 stopped; the worker took 1.90 seconds, and it finished 2.11 seconds after the test start.
Worker 2 stopped; the worker took 3.89 seconds, and it finished 4.10 seconds after the test start.
Worker 3 stopped; the worker took 5.89 seconds, and it finished 6.10 seconds after the test start.
Worker 4 stopped; the worker took 5.90 seconds, and it finished 6.11 seconds after the test start.
Worker 5 stopped; the worker took 8.89 seconds, and it finished 9.10 seconds after the test start.
Test finished after 9.10 seconds.
Starting test: Task.WaitAll...
Worker 1 started on thread 1, beginning 0.01 seconds after test start.
Worker 2 started on thread 1, beginning 0.01 seconds after test start.
Worker 3 started on thread 1, beginning 0.01 seconds after test start.
Worker 4 started on thread 1, beginning 0.01 seconds after test start.
Worker 5 started on thread 1, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.
Starting test: Task.WhenAll...
Worker 1 started on thread 1, beginning 0.00 seconds after test start.
Worker 2 started on thread 1, beginning 0.00 seconds after test start.
Worker 3 started on thread 1, beginning 0.00 seconds after test start.
Worker 4 started on thread 1, beginning 0.00 seconds after test start.
Worker 5 started on thread 1, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.00 seconds after the test start.
Test finished after 5.00 seconds.
In my case, I had the wrong IP Address in the virtual host file. The listen was 443, and the stanza was <VirtualHost 192.168.0.1:443>
but the server did not have the 192.168.0.1 address!
You don't need external library:
Integer[] input = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(input, (a, b) -> b - a); // reverse order
return Arrays.stream(input).mapToInt(Integer::intValue).toArray();
Using
<a href="foo.html"><div class="xyz"></div></a>
works in browsers, even though it violates current HTML specifications. It is permitted according to HTML5 drafts.
When you say that it does not work, you should explain exactly what you did (including jsfiddle code is a good idea), what you expected, and how the behavior different from your expectations.
It is unclear what you mean by “all the content in that div is in the css”, but I suppose it means that the content is really empty in HTML markup and you have CSS like
.xyz:before { content: "Hello world"; }
The entire block is then clickable, with the content text looking like link text there. Isn’t this what you expected?
Valid longitudes are from -180 to 180 degrees.
Latitudes are supposed to be from -90 degrees to 90 degrees, but areas very near to the poles are not indexable.
So exact limits, as specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 are the following:
map()
doesn't return a list, it returns a map
object.
You need to call list(map)
if you want it to be a list again.
Even better,
from itertools import imap
payIntList = list(imap(int, payList))
Won't take up a bunch of memory creating an intermediate object, it will just pass the ints
out as it creates them.
Also, you can do if choice.lower() == 'n':
so you don't have to do it twice.
Python supports +=
: you can do payIntList[i] += 1000
and numElements += 1
if you want.
If you really want to be tricky:
from itertools import count
for numElements in count(1):
payList.append(raw_input("Enter the pay amount: "))
if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
break
and / or
for payInt in payIntList:
payInt += 1000
print payInt
Also, four spaces is the standard indent amount in Python.
#include <memory>
#include <iostream>
class SharedMemory {
public:
SharedMemory(int* x):_capture(x){}
int* get() { return (_capture.get()); }
protected:
std::shared_ptr<int> _capture;
};
int main(int , char**){
SharedMemory *_obj1= new SharedMemory(new int(10));
SharedMemory *_obj2 = new SharedMemory(*_obj1);
std::cout << " _obj1: " << *_obj1->get() << " _obj2: " << *_obj2->get()
<< std::endl;
delete _obj2;
std::cout << " _obj1: " << *_obj1->get() << std::endl;
delete _obj1;
std::cout << " done " << std::endl;
}
This is an example of shared_ptr in action. _obj2 was deleted but pointer is still valid. output is, ./test _obj1: 10 _obj2: 10 _obj2: 10 done
What about using numpy.count_nonzero
, something like
>>> import numpy as np
>>> y = np.array([1, 2, 2, 2, 2, 0, 2, 3, 3, 3, 0, 0, 2, 2, 0])
>>> np.count_nonzero(y == 1)
1
>>> np.count_nonzero(y == 2)
7
>>> np.count_nonzero(y == 3)
3
The generally excellent C5 Generic Collection Library has several different tree-based data structures, including sets, bags and dictionaries. Source code is available if you want to study their implementation details. (I have used C5 collections in production code with good results, although I haven't used any of the tree structures specifically.)
All answers so far only tell you how to print an array of integers, but we can also print any arbitrary structure, given that we know its size. The example below creates such structure and iterates a pointer through its bytes, printing them to the output:
#include <iostream>
#include <iomanip>
#include <cstring>
using std::cout;
using std::endl;
using std::hex;
using std::setfill;
using std::setw;
using u64 = unsigned long long;
using u16 = unsigned short;
using f64 = double;
struct Header {
u16 version;
u16 msgSize;
};
struct Example {
Header header;
u64 someId;
u64 anotherId;
bool isFoo;
bool isBar;
f64 floatingPointValue;
};
int main () {
Example example;
// fill with zeros so padding regions don't contain garbage
memset(&example, 0, sizeof(Example));
example.header.version = 5;
example.header.msgSize = sizeof(Example) - sizeof(Header);
example.someId = 0x1234;
example.anotherId = 0x5678;
example.isFoo = true;
example.isBar = true;
example.floatingPointValue = 1.1;
cout << hex << setfill('0'); // needs to be set only once
auto *ptr = reinterpret_cast<unsigned char *>(&example);
for (int i = 0; i < sizeof(Example); i++, ptr++) {
if (i % sizeof(u64) == 0) {
cout << endl;
}
cout << setw(2) << static_cast<unsigned>(*ptr) << " ";
}
return 0;
}
And here's the output:
05 00 24 00 00 00 00 00
34 12 00 00 00 00 00 00
78 56 00 00 00 00 00 00
01 01 00 00 00 00 00 00
9a 99 99 99 99 99 f1 3f
Notice this example also illustrates memory alignment working. We see version
occupying 2 bytes (05 00
), followed by msgSize
with 2 more bytes (24 00
) and then 4 bytes of padding, after which comes someId
(34 12 00 00 00 00 00 00
) and anotherId
(78 56 00 00 00 00 00 00
). Then isFoo
, which occupies 1 byte (01
) and isBar
, another byte (01
), followed by 6 bytes of padding, finally ending with the IEEE 754 standard representation of the double field floatingPointValue
.
Also notice that all values are represented as little endian (least significant bytes come first), since this was compiled and run on an Intel platform.
Delete every things (jar, pom.xml, etc) under your local ~/.m2/repository/phonegap/1.1.0/
directory if you are using a linux OS.
Check out the AsyncImageView
provided over here. Some good example code, and might even be usable right "out of the box" for you.
Keep your prototype clean.
function val2key(val,array){
for (var key in array) {
if(array[key] == val){
return key;
}
}
return false;
}
Example:
var map = {"first" : 1, "second" : 2};
var key = val2key(2,map); /*returns "second"*/
you can use static constructor to initializes static fields. It runs at an indeterminate time before those fields are used. Microsoft's documentation and many developers warn that static constructors on a type impose a substantial overhead.
It is best to avoid static constructors for maximum performance.
update: you can't use more than one static constructor in the same class, however you can use other instance constructors with (maximum) one static constructor.
My issue was that it was in my init(). Probably the "weak self" killed him while the init wasn't finished. I moved it from the init and it solved my issue.
You can use some different schemes for that. I've always tested for arguments.length:
function myFunc(requiredArg, optionalArg){
optionalArg = myFunc.arguments.length<2 ? 'defaultValue' : optionalArg;
...
-- doing so, it can't possibly fail, but I don't know if your way has any chance of failing, just now I can't think up a scenario, where it actually would fail ...
And then Paul provided one failing scenario !-)
You should put a semicolon at the end of select * from v$version;
.
Like this you will get all info you need...
If you are looking just for Oracle for example you can do as:
SQL> select * from v$version where banner like 'Oracle%';
If you want to run the scripts in parallel and give them different arguments you can do like below.
import os
os.system("python script.py arg1 arg2 & python script.py arg11 arg22")
I don't understand why Nick is using margin-left: 200px;
instead off floating the other div
to the left
or right
, I've just tweaked his markup, you can use float
for both elements instead of using margin-left
.
#main {
margin: auto;
width: 400px;
}
#sidebar {
width: 100px;
min-height: 400px;
background: red;
float: left;
}
#page-wrap {
width: 300px;
background: #0f0;
min-height: 400px;
float: left;
}
.clear:after {
clear: both;
display: table;
content: "";
}
Also, I've used .clear:after
which am calling on the parent element, just to self clear the parent.
Couldn't you just call the following replaceing the {zipcode} with the zip code or city and state http://maps.googleapis.com/maps/api/geocode/json?address={zipcode}
Here is a link with a How To Geocode using JavaScript: Geocode walk-thru. If you need the specific lat/lng numbers call geometry.location.lat() or geometry.location.lng() (API for google.maps.LatLng class)
EXAMPLE to get lat/lng:
var lat = '';
var lng = '';
var address = {zipcode} or {city and state};
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
alert('Latitude: ' + lat + ' Logitude: ' + lng);
The correct answer will be to add
android:backgroundTint="#ff00ff"
to the tool bar
with
android:background="@android:color/white"
If you use other color then white for the background it will remove the shadow. Nice one Google!
Putting the "#" symbol as the href for something means that it points not to a different URL, but rather to another id or name tag on the same page. For example:
<a href="#bottomOfPage">Click to go to the bottom of the page</a>
blah blah
blah blah
...
<a id="bottomOfPage"></a>
However, if there is no id or name then it goes "no where."
Here's another similar question asked HTML Anchors with 'name' or 'id'?
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
your event is triggered only once... so this code may work try this
$(".addproduct,.addproduct,.addproduct,.addproduct,.addproduct").click(function(){//do something fired 5 times});
Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.
The :nth-child
CSS3 selector is in fact more capable than you ever imagined!
For example, this will select the last 2 elements of #container
:
#container :nth-last-child(-n+2) {}
But this is just the beginning of a beautiful friendship.
#container :nth-last-child(-n+2) {
background-color: cyan;
}
_x000D_
<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div>
<div>SELECT THIS</div>
</div>
_x000D_
You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.
- each side with the same color
:root{
--color: #f0f;
}
div {
display: flex;
flex-flow: row nowrap;
align-items: center;
justify-content: center;
box-sizing: border-box;
margin: 50px auto;
width: 200px;
height: 100px;
background: #ccc;
}
.four-sides-with-same-color {
box-shadow: 0px 0px 10px 5px var(--color);
}
_x000D_
<div class="four-sides-with-same-color"></div>
_x000D_
- each side with a different color
:root{
--color1: #00ff4e;
--color2: #ff004e;
--color3: #b716e6;
--color4: #FF5722;
}
div {
display: flex;
flex-flow: row nowrap;
align-items: center;
justify-content: center;
box-sizing: border-box;
margin: 50px auto;
width: 200px;
height: 100px;
background-color: rgba(255,255,0,0.7);
}
.four-sides-with-different-color {
box-shadow:
10px 0px 5px 0px var(--color1),
0px 10px 5px 0px var(--color2),
-10px 0px 5px 0px var(--color3),
0px -10px 5px 0px var(--color4);
}
_x000D_
<div class="four-sides-with-different-color"></div>
_x000D_
Let's me give a more detail example. As to the below struct:
struct Count{
uint32_t c;
Count(uint32_t i=0):c(i){}
uint32_t getCount(){
return c;
}
uint32_t add(const Count& count){
uint32_t total = c + count.getCount();
return total;
}
};
As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object
. In the method add
count
is declared as const object, but the method getCount
is not const method, so count.getCount()
may change the members in count
.
Compile error as below(core message in my compiler):
error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]
To solve the above problem, you can:
uint32_t getCount(){...}
to uint32_t getCount() const {...}
. So count.getCount()
won't change the members in count
.or
uint32_t add(const Count& count){...}
to uint32_t add(Count& count){...}
. So count
don't care about changing members in it.As to you problem, objects in the std::set are stored as const StudentT, but the method getId
and getName
are not const, so you give the above error.
You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.
select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b
where table_name='YOUR_TABLE' and a.table_name = b.name;
This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value
). Else, if default partition is defined, it would go there.
EDIT:
I presume, your TABLE DDL would be like this.
CREATE TABLE HE0_DT_INF_INTERFAZ_MES
(
COD_PAIS NUMBER,
FEC_DATA NUMBER,
INTERFAZ VARCHAR2(100)
)
partition BY RANGE(COD_PAIS, FEC_DATA)
(
PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
);
Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);
That is first COD_PAIS <= 98
and Also FEC_DATA < 20091024
Combinations And Result:
98, 20091024 FAIL
98, 20091023 PASS
99, ******** FAIL
97, ******** PASS
< 98, ******** PASS
So the below INSERT
fails with ORA-14400; because (98,20091024)
in INSERT
is EQUAL to the one in DDL
but NOT less than it.
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
VALUES(98, 20091024, 'CTA'); 2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
*
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition
But, we I attempt (97,20091024), it goes through
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
2 VALUES(97, 20091024, 'CTA');
1 row created.
This solution matches the process name more strictly:
ps -Ac -o pid,comm | awk '/^ *[0-9]+ Dropbox$/ {print $1}'
This solution has the following advantages:
tail -f ~/Dropbox
~/Dropbox/foo.sh
~/DropboxUID.sh
I'm wondering whether you meant "recursive". Here is a simple example of a recursive function to compute the factorial function:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
The two key elements of a recursive algorithm are:
n == 0
factorial(n - 1)
As @alucic mentioned, use:
composer require vendor/package:version
or you can use:
composer update vendor/package:version
You should probably review this StackOverflow post about differences between composer install and composer update.
Related to question about version numbers, you can review Composer documentation on versions, but here in short:
So, with Tilde you will get automatic updates of patches but minor and major versions will not be updated. However, if you use Caret you will get patches and minor versions, but you will not get major (breaking changes) versions.
Tilde Version is considered a "safer" approach, but if you are using reliable dependencies (well-maintained libraries) you should not have any problems with Caret Version (because minor changes should not be breaking changes.
I could figure out the problem. I was getting following warning on startup of eclipse.
The Maven Integration requires that Eclipse be running in a JDK, because a number of Maven core plugins are using jars from the JDk.
Please make sure the -vm option in eclipse.ini is pointing to a JDK and verify that
Installed JRE's are also using JDK installs
I changed eclipse.ini file and added following and restarted eclipse
-vm
C:/Program Files/java/jdk1.6.0_21/bin/javaw.exe
Now I can see "Maven Dependency" library included automatically in java build path.
This works in both SQL 2005 and 2008:
declare @source varbinary(max);
set @source = 0x21232F297A57A5A743894A0E4A801FC3;
select cast('' as xml).value('xs:hexBinary(sql:variable("@source"))', 'varchar(max)');
In addition to what TaskManager shows, if you use ProcessExplorer from Sysinternals, you can tell when you right-click on the process name and select Properties. In the Image tab, there is a field toward the bottom that says Image. It says 32-bit for a 32 bit application and 64 bit for the 64 bit application.
I found a website with a "simple" tutorial: http://www.winprog.org/tutorial/start.html
MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]
. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.
To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED
.
You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.
Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:
"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*
As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.
You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts
and the second is named ProductsOverTenDollars
.
WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
SELECT
CategoryID,
CategoryName,
(SELECT COUNT(1) FROM Products p
WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
FROM Categories c
),
ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
SELECT
ProductID,
CategoryID,
ProductName,
UnitPrice
FROM Products p
WHERE UnitPrice > 10.0
)
SELECT c.CategoryName, c.NumberOfProducts,
p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
INNER JOIN CategoryAndNumberOfProducts c ON
p.CategoryID = c.CategoryID
ORDER BY ProductName
If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:
$('#container').text(xmlString);
Here's how you'd do it with standard DOM methods:
document.getElementById('container')
.appendChild(document.createTextNode(xmlString));
If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).
Thread is a class, not an instance; currentThread() is a static method that returns the Thread instance corresponding to the calling thread.
Use (2). interrupt() is a bit brutal for normal use.
This will depend on the logging configuration. The default value will depend on the framework being used. The idea is that later on by changing a configuration setting from INFO to DEBUG you will see a ton of more (or less if the other way around) lines printed without recompiling the whole application.
If you think which one to use then it boils down to thinking what you want to see on which level. For other levels for example in Log4J look at the API, http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Level.html
Firstly install ffmpeg-php
project (http://ffmpeg-php.sourceforge.net/)
And then you can use of this simple code:
<?php
$frame = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';
$mov = new ffmpeg_movie($movie);
$frame = $mov->getFrame($frame);
if ($frame) {
$gd_image = $frame->toGDImage();
if ($gd_image) {
imagepng($gd_image, $thumbnail);
imagedestroy($gd_image);
echo '<img src="'.$thumbnail.'">';
}
}
?>
Description: This project use binary extension .so
file, It's very old and last update was for 2008. So, maybe don't works with newer version of FFMpeg
or PHP
.
Firstly install PHP-FFMpeg
project (https://github.com/PHP-FFMpeg/PHP-FFMpeg)
(just run for install: composer require php-ffmpeg/php-ffmpeg
)
And then you can use of this simple code:
<?php
require 'vendor/autoload.php';
$sec = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($movie);
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($sec));
$frame->save($thumbnail);
echo '<img src="'.$thumbnail.'">';
Description: It's newer and more modern project and works with latest version of FFMpeg
and PHP
. Note that it's required to proc_open()
PHP function.
If all else fails (including not having the timeout
command) the concept in this shell script will work:
#!/bin/bash
set -u
ssh $1 "sleep 10 ; uptime" > /tmp/outputfile 2>&1 & PIDssh=$!
Count=0
while test $Count -lt 5 && ps -p $PIDssh > /dev/null
do
echo -n .
sleep 1
Count=$((Count+1))
done
echo ""
if ps -p $PIDssh > /dev/null
then
echo "ssh still running, killing it"
kill -HUP $PIDssh
else
echo "Exited"
fi
If I have to use an API that doesn't support Generics.. I try and isolate those calls in wrapper routines with as few lines as possible. I then use the SuppressWarnings annotation and also add the type-safety casts at the same time.
This is just a personal preference to keep things as neat as possible.
you can use it.
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
Overview of the services used by all sessions provides the distionary view v$session
(or gv$session
for RAC databases) in the column SERVICE_NAME
.
To limit the information to the connected session use the SID from the view V$MYSTAT
:
select SERVICE_NAME from gv$session where sid in (
select sid from V$MYSTAT)
If the name is SYS$USERS
the session is connected to a default service, i.e. in the connection string no explicit service_name was specified.
To see what services are available in the database use following queries:
select name from V$SERVICES;
select name from V$ACTIVE_SERVICES;
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
Since GDB 7.5 you can use these native Convenience Functions:
$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)
Seems quite less problematic than having to execute a "foreign" strcmp()
on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.
Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running
show configuration
inside GDB and searching for--with-python
. This little oneliner does the trick, too:$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python' --with-python=/usr (relocatable)
For your demo case, the usage would be
break <where> if $_streq(x, "hello")
or, if your breakpoint already exists and you just want to add the condition to it
condition <breakpoint number> $_streq(x, "hello")
$_streq
only matches the whole string, so if you want something more cunning you should use $_regex
, which supports the Python regular expression syntax.
Just add a transition to the element you are messing with. Be aware that there could be some effects when the page loads. Like if you made a border radius change, you will see it when the dom loads.
.element {_x000D_
width: 100px;_x000D_
transition: all ease-in-out 0.5s;_x000D_
}_x000D_
_x000D_
.element:hover {_x000D_
width: 200px;_x000D_
transition: all ease-in-out 0.5s;_x000D_
}
_x000D_
You can revert uncommitted changes only to particular file or directory:
git checkout [some_dir|file.txt]
If you are developing an existing theme, it's possible that the theme has a custom list style.
So if you cant't change the list style using list-style: none;
in ul or li tags, first check with !important
, because maybe some other line of style is overwriting your style. If !important
fixed it, you should find a more specific selector and clear out the !important
.
li {
list-style: none !important;
}
If it's not the case, then check the li:before
. If it contains the content, then do:
li:before {
display: none;
}
I liked the "START /W" answer, though for my situation I found something even more basic. My processes were console applications. And in my ignorance I thought I would need something special in BAT syntax to make sure that the 1st one completed before the 2nd one started. However BAT appears to make a distinction between console apps and windows apps, and it executes them a little differently. The OP shows that window apps will get launched as an asynchronous call from BAT. But for console apps, that are invoked synchronously, inside the same command window as the BAT itself is running in.
For me it was actually better not to use "START /W", because everything could run inside one command window. The annoying thing about "START /W" is that it will spawn a new command window to execute your console application in.
probably it is better to use NSString and load html document as follows:
Objective-C
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];
Swift
let htmlFile = NSBundle.mainBundle().pathForResource("fileName", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(html!, baseURL: nil)
Swift 3 has few changes:
let htmlFile = Bundle.main.path(forResource: "intro", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
webView.loadHTMLString(html!, baseURL: nil)
Did you try?
Also check that the resource was found by pathForResource:ofType:inDirectory
call.
@Micheal
Slightly revised version of your code:
catch (Exception ex)
{
Type exType = ex.GetType();
if (exType == typeof(System.FormatException) ||
exType == typeof(System.OverflowException)
{
WebId = Guid.Empty;
} else {
throw;
}
}
String comparisons are ugly and slow.
Borrowing from Michael Jasper's and Jon Hendershot's solutions, I offer the following:
$('address').each(function() {
var text = $(this).text();
var q = $.trim(text).replace(/\r?\n/, ',').replace(/\s+/g, ' ');
var link = '<a href="http://maps.google.com/maps?q=' + encodeURIComponent(q) + '" target="_blank"></a>';
return $(this).wrapInner(link);
});
This solution offers the following benefits over solutions previously offered:
<br>
tags) within <address>
, so formatting is preserved<a><address></address></a>
which is invalid because block-level elements such as <address>
are not permitted within inline elements such as <a>
.Caveat: If your <address>
tag contains block-level elements like <p>
or <div>
, then this JavaScript code will produce in invalid markup (because the <a>
tag will contain those block-level elements). But if you're just doing stuff like this:
<address>
The White House
<br>
1600 Pennsylvania Ave NW
<br>
Washington, D.C. 20500
</address>
Then it'll work just fine.
Class.isAssignableFrom()
- works for interfaces as well. If you don't want that, you'll have to call getSuperclass()
and test until you reach Object
.
If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm
A funny way to remove all spaces from a variable is to use printf:
$ myvar='a cool variable with lots of spaces in it'
$ printf -v myvar '%s' $myvar
$ echo "$myvar"
acoolvariablewithlotsofspacesinit
It turns out it's slightly more efficient than myvar="${myvar// /}"
, but not safe regarding globs (*
) that can appear in the string. So don't use it in production code.
If you really really want to use this method and are really worried about the globbing thing (and you really should), you can use set -f
(which disables globbing altogether):
$ ls
file1 file2
$ myvar=' a cool variable with spaces and oh! no! there is a glob * in it'
$ echo "$myvar"
a cool variable with spaces and oh! no! there is a glob * in it
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglobfile1file2init
$ # See the trouble? Let's fix it with set -f:
$ set -f
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglob*init
$ # Since we like globbing, we unset the f option:
$ set +f
I posted this answer just because it's funny, not to use it in practice.
I always prefer let
to an instance variable for a couple of reasons:
nil
, which can lead to subtle bugs and false positives. Since let
creates a method, you'll get a NameError
when you misspell it, which I find preferable. It makes it easier to refactor specs, too.before(:each)
hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined by let
, the initialization code only runs if the example calls it.@
).let
and keeping my it
block nice and short.A related link can be found here: http://www.betterspecs.org/#let
See this answer: Source
If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone. If TZ is not defined or is not any of the time zone names known to PostgreSQL, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime(). The default time zone is selected as the closest match among PostgreSQL's known time zones. (These rules are also used to choose the default value of log_timezone, if not specified.) source
This means that if you do not define a timezone, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().
If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone.
It seems to have the System's timezone to be set is possible indeed.
Get the OS local time zone from the shell. In psql:
=> \! date +%Z
You use a singleton when you need to manage a shared resource. For instance a printer spooler. Your application should only have a single instance of the spooler in order to avoid conflicting request for the same resource.
Or a database connection or a file manager etc.
Another reason might be that the git server has reached its resource limits, and there's nothing wrong with your local git setup.
I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect
<?php
$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion = $_POST['seccion'];
$precio = $_POST['precio'];
$fecha = $_POST['fecha'];
$importado = $_POST['importado'];
$paisdeorigen = $_POST['paisdeorigen'];
try {
$server = 'mysql: host=localhost; dbname=usuarios';
$user = 'root';
$pass = '';
$base = new PDO($server, $user, $pass);
$base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$base->query("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$base->exec("SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'");
$sql = "
INSERT INTO productos
(CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
VALUES
(:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
$result = $base->prepare($sql);
// se pasan por parametros aqui
$result->bindParam(':c_art', $codigoarticulo);
$result->bindParam(':n_art', $nombrearticulo);
$result->bindParam(':sec', $seccion);
$result->bindParam(':pre', $precio);
$result->bindParam(':fecha_art', $fecha);
$result->bindParam(':import', $importado);
$result->bindParam(':p_orig', $paisdeorigen);
$result->execute();
echo 'Articulo agregado';
} catch (Exception $e) {
echo 'Error';
echo $e->getMessage();
} finally {
}
?>
Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :
</body>
<script>require('../script/viewLog.js')</script>
after :
<script>require('../script/viewLog.js')</script>
</body>
If you want to stick with the same sort of loop then this will work:
Option Explicit
Sub selectColumns()
Dim topSelection As Integer
Dim endSelection As Integer
topSelection = 2
endSelection = 10
Dim columnSelected As Integer
columnSelected = 1
Do
With Excel.ThisWorkbook.ActiveSheet
.Range(.Cells(columnSelected, columnSelected), .Cells(endSelection, columnSelected)).Select
End With
columnSelected = columnSelected + 1
Loop Until columnSelected > 10
End Sub
EDIT
If in reality you just want to loop through every cell in an area of the spreadsheet then use something like this:
Sub loopThroughCells()
'=============
'this is the starting point
Dim rwMin As Integer
Dim colMin As Integer
rwMin = 2
colMin = 2
'=============
'=============
'this is the ending point
Dim rwMax As Integer
Dim colMax As Integer
rwMax = 10
colMax = 5
'=============
'=============
'iterator
Dim rwIndex As Integer
Dim colIndex As Integer
'=============
For rwIndex = rwMin To rwMax
For colIndex = colMin To colMax
Cells(rwIndex, colIndex).Select
Next colIndex
Next rwIndex
End Sub
If you have output that can have errors, you may want to use an ampersand and a greater than, as follows:
my_task &> 'Users/Name/Desktop/task_output.log'
this will redirect both stderr and stdout to the log file (instead of stdout only).
SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...
class Trie:
head = {}
def add(self,word):
cur = self.head
for ch in word:
if ch not in cur:
cur[ch] = {}
cur = cur[ch]
cur['*'] = True
def search(self,word):
cur = self.head
for ch in word:
if ch not in cur:
return False
cur = cur[ch]
if '*' in cur:
return True
else:
return False
def printf(self):
print (self.head)
dictionary = Trie()
dictionary.add("hi")
#dictionary.add("hello")
#dictionary.add("eye")
#dictionary.add("hey")
print(dictionary.search("hi"))
print(dictionary.search("hello"))
print(dictionary.search("hel"))
print(dictionary.search("he"))
dictionary.printf()
Out
True
False
False
False
{'h': {'i': {'*': True}}}
Is it not possible in your case to do the AND on several matching results? in pseudocode
regexp_match(pattern1, data) && regexp_match(pattern2, data) && ...
In a nutshell, a schema is the definition for the entire database, so it includes tables, views, stored procedures, indexes, primary and foreign keys, etc.
No, actually the same result would be:
$('#contents')[0]
jQuery does not know how many results would be returned from the query. What you get back is a special jQuery object which is a collection of all the controls that matched the query.
Part of what makes jQuery so convenient is that MOST methods called on this object that look like they are meant for one control, are actually in a loop called on all the members int he collection
When you use the [0] syntax you take the first element from the inner collection. At this point you get a DOM object
Array(n).map((value, index) ....) is 80% of the way there. But for some odd reason it does not work. But there is a workaround.
Array(n).map((v,i) => i) // does not work
Array(n).fill().map((v,i) => i) // does dork
For a range
Array(end-start+1).fill().map((v,i) => i + start) // gives you a range
Odd, these two iterators return the same result: Array(end-start+1).entries()
and Array(end-start+1).fill().entries()
I would recommend doing the following:
foreach ($fields as $key => $field) {
if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
$fields[$key]['value'] = "Some error";
}
}
So basically use $field
when you need the values, and $fields[$key]
when you need to change the data.
@prateek thank you for your help. I rewrote the function with comments for use in a program. Increase 8 for more bits (up to 32 for an integer).
std::vector <bool> bits_from_int (int integer) // discern which bits of PLC codes are true
{
std::vector <bool> bool_bits;
// continously divide the integer by 2, if there is no remainder, the bit is 1, else it's 0
for (int i = 0; i < 8; i++)
{
bool_bits.push_back (integer%2); // remainder of dividing by 2
integer /= 2; // integer equals itself divided by 2
}
return bool_bits;
}
I use the following method to calculate age:
$oDateNow = new DateTime();
$oDateBirth = new DateTime($sDateBirth);
// New interval
$oDateIntervall = $oDateNow->diff($oDateBirth);
// Output
echo $oDateIntervall->y;
<input type="text" autocomplete="off" />
All the parent elements in the hierarchy should have height 100%. Just give max-height:100% to the element and max-height:calc(100% - 90px) to the immediate parent element.
It worked for me on IE also.
html,
body {
height: 100%
}
parent-element {
max-height: calc(100% - 90px);
}
element {
height:100%;
}
The Rendering in IE fails due to failure of Calc when the window is resized or data loaded in DOM. But this method mentioned above worked for me even in IE.
Before you start implementing any vibration code, you have to give your application the permission to vibrate:
<uses-permission android:name="android.permission.VIBRATE"/>
Make sure to include this line in your AndroidManifest.xml file.
Most IDEs will do this for you, but here is the import statement if yours doesn't:
import android.os.Vibrator;
Make sure this in the activity where you want the vibration to occur.
In most circumstances, you'll be wanting to vibrate the device for a short, predetermined amount of time. You can achieve this by using the vibrate(long milliseconds)
method. Here is a quick example:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
v.vibrate(400);
That's it, simple!
It may be the case that you want the device to continue vibrating indefinitely. For this, we use the vibrate(long[] pattern, int repeat)
method:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};
// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, 0);
When you're ready to stop the vibration, just call the cancel()
method:
v.cancel();
If you want a more bespoke vibration, you can attempt to create your own vibration patterns:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Each element then alternates between vibrate, sleep, vibrate, sleep...
long[] pattern = {0, 100, 1000, 300, 200, 100, 500, 200, 100};
// The '-1' here means to vibrate once, as '-1' is out of bounds in the pattern array
v.vibrate(pattern, -1);
There are multiple SDKs that offer a more comprehensive range of haptic feedback. One that I use for special effects is Immersion's Haptic Development Platform for Android.
If your device won't vibrate, first make sure that it can vibrate:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Output yes if can vibrate, no otherwise
if (v.hasVibrator()) {
Log.v("Can Vibrate", "YES");
} else {
Log.v("Can Vibrate", "NO");
}
Secondly, please ensure that you've given your application the permission to vibrate! Refer back to the first point.
Assuming you're using winforms, default panel components does not offer you a way to disable the horizontal scrolling components. A workaround of this is to disable the auto scrolling and add a scrollbar yourself:
ScrollBar vScrollBar1 = new VScrollBar();
vScrollBar1.Dock = DockStyle.Right;
vScrollBar1.Scroll += (sender, e) => { panel1.VerticalScroll.Value = vScrollBar1.Value; };
panel1.Controls.Add(vScrollBar1);
Detailed discussion here.
For those who want to just copy and paste the fastest implementation of shift, there is a benchmark and conclusion(see the end). In addition, I introduce fill_value parameter and fix some bugs.
import numpy as np
import timeit
# enhanced from IronManMark20 version
def shift1(arr, num, fill_value=np.nan):
arr = np.roll(arr,num)
if num < 0:
arr[num:] = fill_value
elif num > 0:
arr[:num] = fill_value
return arr
# use np.roll and np.put by IronManMark20
def shift2(arr,num):
arr=np.roll(arr,num)
if num<0:
np.put(arr,range(len(arr)+num,len(arr)),np.nan)
elif num > 0:
np.put(arr,range(num),np.nan)
return arr
# use np.pad and slice by me.
def shift3(arr, num, fill_value=np.nan):
l = len(arr)
if num < 0:
arr = np.pad(arr, (0, abs(num)), mode='constant', constant_values=(fill_value,))[:-num]
elif num > 0:
arr = np.pad(arr, (num, 0), mode='constant', constant_values=(fill_value,))[:-num]
return arr
# use np.concatenate and np.full by chrisaycock
def shift4(arr, num, fill_value=np.nan):
if num >= 0:
return np.concatenate((np.full(num, fill_value), arr[:-num]))
else:
return np.concatenate((arr[-num:], np.full(-num, fill_value)))
# preallocate empty array and assign slice by chrisaycock
def shift5(arr, num, fill_value=np.nan):
result = np.empty_like(arr)
if num > 0:
result[:num] = fill_value
result[num:] = arr[:-num]
elif num < 0:
result[num:] = fill_value
result[:num] = arr[-num:]
else:
result[:] = arr
return result
arr = np.arange(2000).astype(float)
def benchmark_shift1():
shift1(arr, 3)
def benchmark_shift2():
shift2(arr, 3)
def benchmark_shift3():
shift3(arr, 3)
def benchmark_shift4():
shift4(arr, 3)
def benchmark_shift5():
shift5(arr, 3)
benchmark_set = ['benchmark_shift1', 'benchmark_shift2', 'benchmark_shift3', 'benchmark_shift4', 'benchmark_shift5']
for x in benchmark_set:
number = 10000
t = timeit.timeit('%s()' % x, 'from __main__ import %s' % x, number=number)
print '%s time: %f' % (x, t)
benchmark result:
benchmark_shift1 time: 0.265238
benchmark_shift2 time: 0.285175
benchmark_shift3 time: 0.473890
benchmark_shift4 time: 0.099049
benchmark_shift5 time: 0.052836
shift5 is winner! It's OP's third solution.
I know this is an old thread and that you've picked an answer, but I thought I'd post this as it is relevant for anyone else that is currently looking.
There is no reason to create new CSS rules, simply undo the current rules and the borders will disappear.
.table>tbody>tr>th, .table>tbody>tr>td { border-top: 0; }
going forward, anything styled with
.table
will show no borders.
You can use the BlockingCollection and ConcurrentQueue in the System.Collections.Concurrent Namespace
public class ProducerConsumerQueue<T> : BlockingCollection<T>
{
/// <summary>
/// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
/// </summary>
public ProducerConsumerQueue()
: base(new ConcurrentQueue<T>())
{
}
/// <summary>
/// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
/// </summary>
/// <param name="maxSize"></param>
public ProducerConsumerQueue(int maxSize)
: base(new ConcurrentQueue<T>(), maxSize)
{
}
}
actions.js
const axios = require('axios');
const types = require('./types');
export const actions = {
GET_CONTENT({commit}){
axios.get(`${URL}`)
.then(doc =>{
const content = doc.data;
commit(types.SET_CONTENT , content);
setTimeout(() =>{
commit(types.IS_LOADING , false);
} , 1000);
}).catch(err =>{
console.log(err);
});
},
}
home.vue
<script>
import {value , onCreated} from "vue-function-api";
import {useState, useStore} from "@u3u/vue-hooks";
export default {
name: 'home',
setup(){
const store = useStore();
const state = {
...useState(["content" , "isLoading"])
};
onCreated(() =>{
store.value.dispatch("GET_CONTENT" );
});
return{
...state,
}
}
};
</script>
Create a BufferedImage from file and make it TYPE_INT_RGB
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
public static void main(String args[]){
try{
BufferedImage img = new BufferedImage(
500, 500, BufferedImage.TYPE_INT_RGB );
File f = new File("MyFile.png");
int r = 5;
int g = 25;
int b = 255;
int col = (r << 16) | (g << 8) | b;
for(int x = 0; x < 500; x++){
for(int y = 20; y < 300; y++){
img.setRGB(x, y, col);
}
}
ImageIO.write(img, "PNG", f);
}
catch(Exception e){
e.printStackTrace();
}
}
}
This paints a big blue streak across the top.
If you want it ARGB, do it like this:
try{
BufferedImage img = new BufferedImage(
500, 500, BufferedImage.TYPE_INT_ARGB );
File f = new File("MyFile.png");
int r = 255;
int g = 10;
int b = 57;
int alpha = 255;
int col = (alpha << 24) | (r << 16) | (g << 8) | b;
for(int x = 0; x < 500; x++){
for(int y = 20; y < 30; y++){
img.setRGB(x, y, col);
}
}
ImageIO.write(img, "PNG", f);
}
catch(Exception e){
e.printStackTrace();
}
Open up MyFile.png, it has a red streak across the top.
After struggling much with the npm link
command (suggested solution for developing local modules without publishing them to a registry or maintaining a separate copy in the node_modules folder), I built a small npm module to help with this issue.
The fix requires two easy steps.
First:
npm install lib-manager --save-dev
Second, add this to your package.json
:
{
"name": "yourModuleName",
// ...
"scripts": {
"postinstall": "./node_modules/.bin/local-link"
}
}
More details at https://www.npmjs.com/package/lib-manager. Hope it helps someone.
I do it this way:
NET SESSION
IF %ERRORLEVEL% NEQ 0 GOTO ELEVATE
GOTO ADMINTASKS
:ELEVATE
CD /d %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
EXIT
:ADMINTASKS
(Do whatever you need to do here)
EXIT
This way it's simple and use only windows default commands. It's great if you need to redistribute you batch file.
CD /d %~dp0
Sets the current directory to the file's current directory (if it is not already, regardless of the drive the file is in, thanks to the /d
option).
%~nx0
Returns the current filename with extension (If you don't include the extension and there is an exe with the same name on the folder, it will call the exe).
There are so many replies on this post I don't even know if my reply will be seen.
Anyway, I find this way simpler than the other solutions proposed on the other answers, I hope it helps someone.
I think it's better to use the symmetric difference operation of sets to do that Here is the link to the doc.
>>> dict1 = {1:'donkey', 2:'chicken', 3:'dog'}
>>> dict2 = {1:'donkey', 2:'chimpansee', 4:'chicken'}
>>> set1 = set(dict1.items())
>>> set2 = set(dict2.items())
>>> set1 ^ set2
{(2, 'chimpansee'), (4, 'chicken'), (2, 'chicken'), (3, 'dog')}
It is symmetric because:
>>> set2 ^ set1
{(2, 'chimpansee'), (4, 'chicken'), (2, 'chicken'), (3, 'dog')}
This is not the case when using the difference operator.
>>> set1 - set2
{(2, 'chicken'), (3, 'dog')}
>>> set2 - set1
{(2, 'chimpansee'), (4, 'chicken')}
However it may not be a good idea to convert the resulting set to a dictionary because you may lose information:
>>> dict(set1 ^ set2)
{2: 'chicken', 3: 'dog', 4: 'chicken'}
The solution that fixed mine was that I had inadvertently applied different keys to Encryption and Decryption methods.
If you want your scripts to load after page has been rendered, you can use:
function getScript(a, b) {
var c = document.createElement("script");
c.src = a;
var d = document.getElementsByTagName("head")[0],
done = false;
c.onload = c.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
b();
c.onload = c.onreadystatechange = null;
d.removeChild(c)
}
};
d.appendChild(c)
}
//call the function
getScript("http://www.google-analytics.com/ga.js", function() {
// do stuff after the script has loaded
});
You need to check out the attr
method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src
with the string specified in the 2nd parameter.
A better way to approach replacing a series of images source would be to loop through each and check it's source.
Example:
$('img').each(function () {
var curSrc = $(this).attr('src');
if ( curSrc === 'http://example.com/smith.gif' ) {
$(this).attr('src', 'http://example.com/johnson.gif');
}
if ( curSrc === 'http://example.com/williams.gif' ) {
$(this).attr('src', 'http://example.com/brown.gif');
}
});
Convert a number to a hexadecimal string with:
hexString = yourNumber.toString(16);
And reverse the process with:
yourNumber = parseInt(hexString, 16);
Joining fails if the DataFrames have some column names in common. The simplest way around it is to include an lsuffix
or rsuffix
keyword like so:
restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")
This way, the columns have distinct names. The documentation addresses this very problem.
Or, you could get around this by simply deleting the offending columns before you join. If, for example, the stars in restaurant_ids_dataframe
are redundant to the stars in restaurant_review_frame
, you could del restaurant_ids_dataframe['stars']
.
Another way to do this would be to add before adding lines in your output, the following line :
output.writerow(dict(zip(dr.fieldnames, dr.fieldnames)))
The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.
I saw a lot of people use an image tag. I prefer to use a background image because I can manipulate it. For example, I can:
background-size: cover;
" property.The HTML/CSS:
.overlay-box {_x000D_
background-color: #f5f5f5;_x000D_
height: 100%;_x000D_
background-repeat: no-repeat;_x000D_
background-size: cover;_x000D_
}_x000D_
_x000D_
.overlay-box:hover .desc,_x000D_
.overlay-box:focus .desc {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
/* opacity 0.01 for accessibility */_x000D_
/* adjust the styles like height,padding to match your design*/_x000D_
.overlay-box .desc {_x000D_
opacity: 0.01;_x000D_
min-height: 355px;_x000D_
font-size: 1rem;_x000D_
height: 100%;_x000D_
padding: 30px 25px 20px;_x000D_
transition: all 0.3s ease;_x000D_
background: rgba(0, 0, 0, 0.7);_x000D_
color: #fff;_x000D_
}
_x000D_
<div class="overlay-box" style="background-image: url('https://via.placeholder.com/768x768');">_x000D_
<div class="desc">_x000D_
<p>Place your text here</p>_x000D_
<ul>_x000D_
<li>lorem ipsum dolor</li>_x000D_
<li>lorem lipsum</li>_x000D_
<li>lorem</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>
_x000D_
The rolling mean returns a Series
you only have to add it as a new column of your DataFrame
(MA
) as described below.
For information, the rolling_mean
function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.
Warning Prior to version 0.18.0,
pd.rolling_*
,pd.expanding_*
, andpd.ewm*
were module level functions and are now deprecated. These are replaced by using theRolling
,Expanding
andEWM.
objects and a corresponding method call.
df['MA'] = df.rolling(window=5).mean()
print(df)
# Value MA
# Date
# 1989-01-02 6.11 NaN
# 1989-01-03 6.08 NaN
# 1989-01-04 6.11 NaN
# 1989-01-05 6.15 NaN
# 1989-01-09 6.25 6.14
# 1989-01-10 6.24 6.17
# 1989-01-11 6.26 6.20
# 1989-01-12 6.23 6.23
# 1989-01-13 6.28 6.25
# 1989-01-16 6.31 6.27
In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").
Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).
Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.
HTH.
I believe this will only appear when running the page locally in this particular case, i.e. you should not see this when loading the apge from a web server.
However if you have permission to do so, you could turn off the prompt for Internet Explorer by following Tools (menu) → Internet Options → Security (tab) → Custom Level (button) → and Disable Automatic prompting for ActiveX controls.
This will of course, only affect your browser.
Try this.
public function getDownload()
{
//PDF file is stored under project/public/download/info.pdf
$file= public_path(). "/download/info.pdf";
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, 'filename.pdf', $headers);
}
"./download/info.pdf"
will not work as you have to give full physical path.
Update 20/05/2016
Laravel 5, 5.1, 5.2 or 5.* users can use the following method instead of Response
facade. However, my previous answer will work for both Laravel 4 or 5. (the $header
array structure change to associative array =>
- the colon after 'Content-Type' was deleted - if we don't do those changes then headers will be added in wrong way: the name of header wil be number started from 0,1,...)
$headers = [
'Content-Type' => 'application/pdf',
];
return response()->download($file, 'filename.pdf', $headers);
tl;dr:
commit()
writes the data synchronously (blocking the thread its called from). It then informs you about the success of the operation.apply()
schedules the data to be written asynchronously. It does not inform you about the success of the operation.apply()
and immediately read via any getX-method, the new value will be returned!apply()
at some point and it's still executing, any calls to commit()
will block until all past apply-calls and the current commit-call are finished.More in-depth information from the SharedPreferences.Editor Documentation:
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.
As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.
The SharedPreferences.Editor interface isn't expected to be implemented directly. However, if you previously did implement it and are now getting errors about missing apply(), you can simply call commit() from apply().
r := strings(byteData)
This also works to turn []byte
into io.Reader
$('.selectpicker').selectpicker('val', YOUR_VALUE);
I believe this has a straightforward answer. Why don't you check it from the people who developed that function in their systems?
If you are a MS SQL developer, here is the answer directly from Microsoft.
IN
:
Determines whether a specified value matches any value in a subquery or a list.
Specifies a subquery to test for the existence of rows.
You would need to use a reinterpret_cast<>
as the two types you are casting between are unrelated to each other.
You can use Collections.sort
as follows:
private static void order(List<Person> persons) {
Collections.sort(persons, new Comparator() {
public int compare(Object o1, Object o2) {
String x1 = ((Person) o1).getName();
String x2 = ((Person) o2).getName();
int sComp = x1.compareTo(x2);
if (sComp != 0) {
return sComp;
}
Integer x1 = ((Person) o1).getAge();
Integer x2 = ((Person) o2).getAge();
return x1.compareTo(x2);
}});
}
List<Persons>
is now sorted by name, then by age.
String.compareTo
"Compares two strings lexicographically" - from the docs.
Collections.sort
is a static method in the native Collections library. It does the actual sorting, you just need to provide a Comparator which defines how two elements in your list should be compared: this is achieved by providing your own implementation of the compare
method.
I have came across this issue few times during the development of one complex Excel VBA app. Sometimes Excel started to break VBA object quite randomly. And the only remedy was to reboot machine. After reboot, Excel usually started to act normally.
Soon I have found out that possible solution to this issue is to hit CTRL+Break once when macro is NOT running. Maybe this can help to you too.
The best way to get filetype-specific indentation is to use filetype plugin indent on
in your vimrc. Then you can specify things like set sw=4 sts=4 et
in .vim/ftplugin/c.vim, for example, without having to make those global for all files being edited and other non-C type syntaxes will get indented correctly, too (even lisps).
The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.
Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)
How to convert array to json String in swift 2.3
var yourString : String = ""
do
{
if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(yourArray, options: NSJSONWritingOptions.PrettyPrinted)
{
yourString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
}
}
catch
{
print(error)
}
And now you can use yourSting as JSON string..
Yes you can use .is(':visible')
in jquery. But while the code is running under the safari browser
.is(':visible')
is won't work.
So please use the below code
if( $(".example").offset().top > 0 )
The above line will work both IE as well as safari also.
I've created a gist testing some different ways of resolving promises, with results. It may be helpful to see the options that work.
Here is a bash script that returns the IP (v4 and v6) ranges using @WorkWise's answer:
domainsToDig=$(dig @8.8.8.8 _spf.google.com TXT +short | \
sed \
-e 's/"v=spf1//' \
-e 's/ ~all"//' \
-e 's/ include:/\n/g' | \
tail -n+2)
for domain in $domainsToDig ; do
dig @8.8.8.8 $domain TXT +short | \
sed \
-e 's/"v=spf1//' \
-e 's/ ~all"//' \
-e 's/ ip.:/\n/g' | \
tail -n+2
done
It looks like you're using python 3.x. In python3, filter
, map
, zip
, etc return an object which is iterable, but not a list. In other words,
filter(func,data) #python 2.x
is equivalent to:
list(filter(func,data)) #python 3.x
I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.
If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:
( x for x in data if func(x) )
As opposed to:
[ x for x in data if func(x) ]
in python 2.x
You can create a wrapper function that takes in a promise and returns an array with data if no error and the error if there was an error.
function safePromise(promise) {
return promise.then(data => [ data ]).catch(error => [ null, error ]);
}
Use it like this in ES7 and in an async function:
async function checkItem() {
const [ item, error ] = await safePromise(getItem(id));
if (error) { return null; } // handle error and return
return item; // no error so safe to use item
}
Try [attr.style]="changeBackground()"
Some time we require to style some element from a component but if we have to display that component only ones or the style is so less then instead of using the CSS class we go for the inline style in react js. reactjs inline style is as same as HTML inline style just the property names are a little bit different
Write your style in any tag using style={{prop:"value"}}
import React, { Component } from "react";
import { Redirect } from "react-router";
class InlineStyle extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<div>
<div
style={{
color: "red",
fontSize: 40,
background: "green"
}}// this is inline style in reactjs
>
</div>
</div>
</div>
);
}
}
export default InlineStyle;
You need to do:
import sqlitedbx
def main():
db = sqlitedbx.SqliteDBzz()
db.connect()
if __name__ == "__main__":
main()
Even though this question is very old, many must be facing the same issue, so I would like to state how I fixed this.
The problem is classpath 'com.android.tools.build:gradle:0.13.2'
By above line in build.gradle you are asking it to find a particular version of gradle but this version is not there in your machine. The best it to change the above line to
classpath 'com.android.tools.build:gradle:+'
I found some detailed instructions here: http://digitallibraryworld.com/?p=6
The key piece of advice seems to be, don't use the 64-bit ASP.DLL (found in system32) if you've configured the app pool to run 32-bit applications (instead, use the 32-bit ASP.DLL).
Add a script map using the following setting:
Request Path: *.asp
Executable: C:\Windows\system32\inetsrv\asp.dll
Name: whatever you want. I named my Classic ASPThe executable above is 64 BIT ASP handler for your asp script. If you want your ASP script to be handled in 32 bit environment, you need to use executable from this location:
C:\Windows\SysWOW64\inetsrv\asp.dll
.
Of course, if you don't need to load any 32-bit libraries (or data providers, etc.), just make your life easier by running the 64-bit ASP.DLL!
It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".
Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
Jeigen https://github.com/hughperkins/jeigen
A quick test, by multiplying two dense matrices, ie:
import static jeigen.MatrixUtil.*;
int K = 100;
int N = 100000;
DenseMatrix A = rand(N, K);
DenseMatrix B = rand(K, N);
Timer timer = new Timer();
DenseMatrix C = B.mmul(A);
timer.printTimeCheckMilliseconds();
Results:
Jama: 4090 ms
Jblas: 1594 ms
Ojalgo: 2381 ms (using two threads)
Jeigen: 2514 ms
Something like
SELECT * FROM tablename where visible=1 ORDER BY COALESCE(position, 999999999) ASC, id DESC
Replace 999999999 with what ever the max value for the field is
I take it you can modify MyScript.ps1
. Then try to change it like so:
$(
Here is your current script
) *>&1 > output.txt
I just tried this with PowerShell 3. You can use all the redirect options as in Nathan Hartley's answer.
1.open the terminal.
2.backup your database with following command
your postgres bin - /opt/PostgreSQL/9.1/bin/
your source database server - 192.168.1.111
your backup file location and name - /home/dinesh/db/mydb.backup
your source db name - mydatabase
/opt/PostgreSQL/9.1/bin/pg_dump --host '192.168.1.111' --port 5432 --username "postgres" --no-password --format custom --blobs --file "/home/dinesh/db/mydb.backup" "mydatabase"
3.restore mydb.backup file into destination.
your destination server - localhost
your destination database name - mydatabase
create database for restore the backup.
/opt/PostgreSQL/9.1/bin/psql -h 'localhost' -p 5432 -U postgres -c "CREATE DATABASE mydatabase"
restore the backup.
/opt/PostgreSQL/9.1/bin/pg_restore --host 'localhost' --port 5432 --username "postgres" --dbname "mydatabase" --no-password --clean "/home/dinesh/db/mydb.backup"
I agree with Petar Ivanov but it is best if we implement in following way:
public String replace(String str, int index, char replace){
if(str==null){
return str;
}else if(index<0 || index>=str.length()){
return str;
}
char[] chars = str.toCharArray();
chars[index] = replace;
return String.valueOf(chars);
}
All the above answers really help me to construct my answer, because of this I voted for all the answers that other users put it out: But I finally put together my own answer to exact problem I was dealing with:
As question clearly defined I had to access some of the siblings and its children in a dom structure: This solution will iterate over the images in the dom structure and construct image name using product title and save the image to the local directory.
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
from BeautifulSoup import BeautifulSoup as bs
import requests
def getImages(url):
#Download the images
r = requests.get(url)
html = r.text
soup = bs(html)
output_folder = '~/amazon'
#extracting the images that in div(s)
for div in soup.findAll('div', attrs={'class':'image'}):
modified_file_name = None
try:
#getting the data div using findNext
nextDiv = div.findNext('div', attrs={'class':'data'})
#use findNext again on previous object to get to the anchor tag
fileName = nextDiv.findNext('a').text
modified_file_name = fileName.replace(' ','-') + '.jpg'
except TypeError:
print 'skip'
imageUrl = div.find('img')['src']
outputPath = os.path.join(output_folder, modified_file_name)
urlretrieve(imageUrl, outputPath)
if __name__=='__main__':
url = r'http://www.amazon.com/s/ref=sr_pg_1?rh=n%3A172282%2Ck%3Adigital+camera&keywords=digital+camera&ie=UTF8&qid=1343600585'
getImages(url)
Share : Text
@IBAction func shareOnlyText(_ sender: UIButton) {
let text = "This is the text....."
let textShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
}
Share : Image
@IBAction func shareOnlyImage(_ sender: UIButton) {
let image = UIImage(named: "Product")
let imageShare = [ image! ]
let activityViewController = UIActivityViewController(activityItems: imageShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
Share : Text - Image - URL
@IBAction func shareAll(_ sender: UIButton) {
let text = "This is the text...."
let image = UIImage(named: "Product")
let myWebsite = NSURL(string:"https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile")
let shareAll= [text , image! , myWebsite]
let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.
In my case, it was because I was only catching specific types of exceptions:
try
{
get-item -Force -LiteralPath $Path -ErrorAction Stop
#if file exists
if ($Path -like '\\*') {$fileType = 'n'} #Network
elseif ($Path -like '?:\*') {$fileType = 'l'} #Local
else {$fileType = 'u'} #Unknown File Type
}
catch [System.UnauthorizedAccessException] {$fileType = 'i'} #Inaccessible
catch [System.Management.Automation.ItemNotFoundException]{$fileType = 'x'} #Doesn't Exist
Added these to handle additional the exception causing the terminating error, as well as unexpected exceptions
catch [System.Management.Automation.DriveNotFoundException]{$fileType = 'x'} #Doesn't Exist
catch {$fileType='u'} #Unknown
Tested in IE 8 and Chrome 13.
<table style="table-layout: fixed; width: 100%">
<tr>
<td>
<div style="word-wrap: break-word;">
longtexthere
</div>
</td>
<td><span style="display: inline;">Foo</span></td>
</tr>
</table>
This causes the table to fit the width of the page and each column to take up 50% of the width.
If you prefer the first column to take up more of the page, add a width: 80%
to the td
as in the following example, replacing 80% with the percentage of your choice.
<table style="table-layout: fixed; width: 100%">
<tr>
<td style="width:80%">
<div style="word-wrap: break-word;">
longtexthere
</div>
</td>
<td><span style="display: inline;">Foo</span></td>
</tr>
</table>
For what its worth I got the following error trying to ssh into my local machine, running Ubuntu 16.04 Xenial, from a vm.
ssh: connect to host 192.168.144.18 port 22: Connection refused
It got immediately fixed with:
sudo apt-get install ssh
Take note, Before fix: 'which sshd' returned nothing and 'which ssh' returned
/usr/bin/ssh
And After the fix: 'which sshd' returned
/usr/sbin/sshd
My issue was also solved by sifting through the Process Explorer. However, the process I had to kill was the MySQL Notifier.exe that was still running after closing all VS and SQL applications.
Here is the Groovy way of accessing object properties:
this.class.simpleName # returns the simple name of the current class
The best easiest way I found to reset settings:
Open Settings page (Ctrl+Shift+P):
Go onto your desire setting section to reset, click on icon and then Reset Setting :
If, for some reason, you don't want to (or can't) run a .click()
on the checkbox element, you can simply change its value directly via its .checked property (an IDL attribute of <input type="checkbox">
).
Note that doing so does not fire the normally related event (change) so you'll need to manually fire it to have a complete solution that works with any related event handlers.
Here's a functional example in raw javascript (ES6):
class ButtonCheck {_x000D_
constructor() {_x000D_
let ourCheckBox = null;_x000D_
this.ourCheckBox = document.querySelector('#checkboxID');_x000D_
_x000D_
let checkBoxButton = null;_x000D_
this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');_x000D_
_x000D_
let checkEvent = new Event('change');_x000D_
_x000D_
this.checkBoxButton.addEventListener('click', function() {_x000D_
let checkBox = this.ourCheckBox;_x000D_
_x000D_
//toggle the checkbox: invert its state!_x000D_
checkBox.checked = !checkBox.checked;_x000D_
_x000D_
//let other things know the checkbox changed_x000D_
checkBox.dispatchEvent(checkEvent);_x000D_
}.bind(this), true);_x000D_
_x000D_
this.eventHandler = function(e) {_x000D_
document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
//demonstration: we will see change events regardless of whether the checkbox is clicked or the button_x000D_
_x000D_
this.ourCheckBox.addEventListener('change', function(e) {_x000D_
this.eventHandler(e);_x000D_
}.bind(this), true);_x000D_
_x000D_
//demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox_x000D_
_x000D_
this.ourCheckBox.addEventListener('click', function(e) {_x000D_
this.eventHandler(e);_x000D_
}.bind(this), true);_x000D_
_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
var init = function() {_x000D_
const checkIt = new ButtonCheck();_x000D_
}_x000D_
_x000D_
if (document.readyState != 'loading') {_x000D_
init;_x000D_
} else {_x000D_
document.addEventListener('DOMContentLoaded', init);_x000D_
}
_x000D_
<input type="checkbox" id="checkboxID" />_x000D_
_x000D_
<button aria-label="checkboxID">Change the checkbox!</button>_x000D_
_x000D_
<div class="checkboxfeedback">No changes yet!</div>
_x000D_
If you run this and click on both the checkbox and the button you should get a sense of how this works.
Note that I used document.querySelector for brevity/simplicity, but this could easily be built out to either have a given ID passed to the constructor, or it could apply to all buttons that act as aria-labels for a checkbox (note that I didn't bother setting an id on the button and giving the checkbox an aria-labelledby, which should be done if using this method) or any number of other ways to expand this. The last two addEventListener
s are just to demo how it works.
Your selector is a little off, it's missing the trailing ]
var mySelect = $('select[name=' + name + ']')
you may also need to put quotes around the name, like so:
var mySelect = $('select[name="' + name + '"]')
In addition to the other answers, there is a big benefit to using the DisplayAttribute
when you want to localize the fields. You can lookup the name in a localization database using the DisplayAttribute and it will use whatever translation you wish.
Also, you can let MVC generate the templates for you by using Html.EditorForModel()
and it will generate the correct label for you.
Ultimately, it's up to you. But the MVC is very "Model-centric", which is why data attributes are applied to models, so that metadata exists in a single place. It's not like it's a huge amount of extra typing you have to do.
list_1.insert(0,ur_data)
make sure that ur_data is of string type
so if u have data= int(5)
convert it to ur_data = str(data)
For those who are using Oracle 12.1.0 for development purposes:
I found that the above methods would have no effect on the db user: "system", because the account_status would remain in the expired-grace period.
The easiest solution was for me to use SQL Developer:
within SQL Developer, I had to go to: View / DBA / Security and then Users / System and then on the right side: Actions / Expire pw and then: Actions / Edit and I could untick the option for expired.
This cleared the account_status, it shows OPEN again, and the SQL Developer is no longer showing the ORA-28002 message.
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
This is what I used to copy some resource files: the copy-files is an empty target to ignore errors
add_custom_target(copy-files ALL
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_BINARY_DIR}/SOURCEDIRECTORY
${CMAKE_BINARY_DIR}/DESTINATIONDIRECTORY
)