The good practice is to use like this:
$.ajax({
type: "POST",
url: "/ajax/request.html",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
console.log(response.blablabla);
// put on console what server sent back...
}
});
and the php part is:
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
echo json_encode(array("blablabla"=>$variable));
}
?>
I will second madExcept and similar tools, like Eurekalog, but I think you can come a good way with FastMM also. With full debugmode enabled, it should give you some clues of whats wrong.
Anyway, even though Delphi uses FastMM as default, it's worth getting the full FastMM for it's additional control over logging.
Excellent post : http://www.carlosble.com/2010/12/understanding-python-and-unicode/
# -*- coding: utf-8 -*-
def __if_number_get_string(number):
converted_str = number
if isinstance(number, int) or \
isinstance(number, float):
converted_str = str(number)
return converted_str
def get_unicode(strOrUnicode, encoding='utf-8'):
strOrUnicode = __if_number_get_string(strOrUnicode)
if isinstance(strOrUnicode, unicode):
return strOrUnicode
return unicode(strOrUnicode, encoding, errors='ignore')
def get_string(strOrUnicode, encoding='utf-8'):
strOrUnicode = __if_number_get_string(strOrUnicode)
if isinstance(strOrUnicode, unicode):
return strOrUnicode.encode(encoding)
return strOrUnicode
Check this:
if (
MessageBox.Show(@"Are you Alright?", @"My Message Box",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//YES ---> Ok IM ALRIGHHT
}
else
{
//NO --->NO IM STUCK
}
Regards
<style>
div
{
height:200px;
width:200px;
-webkit-animation: spin 2s infinite linear;
}
@-webkit-keyframes spin {
0% {-webkit-transform: rotate(0deg);}
100% {-webkit-transform: rotate(360deg);}
}
</style>
</head>
<body>
<div><img src="1.png" height="200px" width="200px"/></div>
</body>
When using aggregate functions to filter, you must use a HAVING statement.
SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500
If you have a block of code+html that appears on several pages and is sort of independent of that page (say a block of latest news items), you could copy/paste the code to every page.
It is however better to put that code in its own block and just include that block on every page that needs it. That "block" is an ascx file.
This is the shortest way.
var now = new Date().toLocaleTimeString();
console.log(now)
Here is also a way through string manipulation that was not mentioned.
var now = new Date()
console.log(now.toString().substr(16,8))
A very unique solution for this problem is using git log:
git log -p -M --follow --stat -- path/to/your/file
As explained by Andre here
Try the tools TCPView (GUI) and Tcpvcon (command line) by Sysinternals/Microsoft.
https://docs.microsoft.com/en-us/sysinternals/downloads/tcpview
Best of both worlds [@DiddiZ, @Chalkos]: this one mainly builds upon @Chalkos method, but fixes a bug (ifst.next()), and improves initial checks (taken from @DiddiZ) as well as removes the need to copy the first collection (just removes items from a copy of the second collection).
Not requiring a hashing function or sorting, and enabling an early exist on un-equality, this is the most efficient implementation yet. That is unless you have a collection length in the thousands or more, and a very simple hashing function.
public static <T> boolean isCollectionMatch(Collection<T> one, Collection<T> two) {
if (one == two)
return true;
// If either list is null, return whether the other is empty
if (one == null)
return two.isEmpty();
if (two == null)
return one.isEmpty();
// If lengths are not equal, they can't possibly match
if (one.size() != two.size())
return false;
// copy the second list, so it can be modified
final List<T> ctwo = new ArrayList<>(two);
for (T itm : one) {
Iterator<T> it = ctwo.iterator();
boolean gotEq = false;
while (it.hasNext()) {
if (itm.equals(it.next())) {
it.remove();
gotEq = true;
break;
}
}
if (!gotEq) return false;
}
// All elements in one were found in two, and they're the same size.
return true;
}
Cors change the request method before it's done, from POST to OPTIONS, so, your post data will not be sent. The way that worked to handle this cors issue, is performing the request with ajax, which does not support the OPTIONS method. example code:
$.ajax({
type: "POST",
crossdomain: true,
url: "http://localhost:1415/anything",
dataType: "json",
data: JSON.stringify({
anydata1: "any1",
anydata2: "any2",
}),
success: function (result) {
console.log(result)
},
error: function (xhr, status, err) {
console.error(xhr, status, err);
}
});
with this headers on c# server:
if (request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
response.AddHeader("Access-Control-Max-Age", "1728000");
}
response.AppendHeader("Access-Control-Allow-Origin", "*");
The proper way to do it is using the ng-options
directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/Admin/GetTestAccounts',
data: { applicationId: 3 }
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to ensure angular is run on your html and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
What is the "Visual C#"? There is no such thing. Just C#, or .NET C# :)
Also, Python's convention for constants CONSTANT_NAME
is not very common in C#. We are usually using CamelCase according to MSDN standards, e.g. public const string ExtractedMagicString = "vs2019";
Source: Defining constants in C#
nanoid achieves exactly the same thing that you want.
Example usage:
const { nanoid } = require("nanoid")
console.log(nanoid())
//=> "n340M4XJjATNzrEl5Qvsh"
get_meta_tags
will help you with all but the title. To get the title just use a regex.
$url = 'http://some.url.com';
preg_match("/<title>(.+)<\/title>/siU", file_get_contents($url), $matches);
$title = $matches[1];
Hope that helps.
Webview - Single & Multiple files choose
you needs two minutes to implement this code:
build.gradle
implementation 'com.github.angads25:filepicker:1.1.1'
java code:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.bivoiclient.utils.Constants;
import com.github.angads25.filepicker.controller.DialogSelectionListener;
import com.github.angads25.filepicker.model.DialogConfigs;
import com.github.angads25.filepicker.model.DialogProperties;
import com.github.angads25.filepicker.view.FilePickerDialog;
import java.io.File;
public class WebBrowserScreen extends Activity {
private WebView webView;
private ValueCallback<Uri[]> mUploadMessage;
private FilePickerDialog dialog;
private String LOG_TAG = "DREG";
private Uri[] results;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complain);
webView = findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setAppCacheEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAllowFileAccess(true);
webView.setWebViewClient(new PQClient());
webView.setWebChromeClient(new PQChromeClient());
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.loadUrl(Constants.COMPLAIN_URL);
}
private void openFileSelectionDialog() {
if (null != dialog && dialog.isShowing()) {
dialog.dismiss();
}
//Create a DialogProperties object.
final DialogProperties properties = new DialogProperties();
//Instantiate FilePickerDialog with Context and DialogProperties.
dialog = new FilePickerDialog(WebBrowserScreen.this, properties);
dialog.setTitle("Select a File");
dialog.setPositiveBtnName("Select");
dialog.setNegativeBtnName("Cancel");
properties.selection_mode = DialogConfigs.MULTI_MODE; // for multiple files
// properties.selection_mode = DialogConfigs.SINGLE_MODE; // for single file
properties.selection_type = DialogConfigs.FILE_SELECT;
//Method handle selected files.
dialog.setDialogSelectionListener(new DialogSelectionListener() {
@Override
public void onSelectedFilePaths(String[] files) {
results = new Uri[files.length];
for (int i = 0; i < files.length; i++) {
String filePath = new File(files[i]).getAbsolutePath();
if (!filePath.startsWith("file://")) {
filePath = "file://" + filePath;
}
results[i] = Uri.parse(filePath);
Log.d(LOG_TAG, "file path: " + filePath);
Log.d(LOG_TAG, "file uri: " + String.valueOf(results[i]));
}
mUploadMessage.onReceiveValue(results);
mUploadMessage = null;
}
});
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
if (null != mUploadMessage) {
if (null != results && results.length >= 1) {
mUploadMessage.onReceiveValue(results);
} else {
mUploadMessage.onReceiveValue(null);
}
}
mUploadMessage = null;
}
});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
if (null != mUploadMessage) {
if (null != results && results.length >= 1) {
mUploadMessage.onReceiveValue(results);
} else {
mUploadMessage.onReceiveValue(null);
}
}
mUploadMessage = null;
}
});
dialog.show();
}
public class PQChromeClient extends WebChromeClient {
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = filePathCallback;
openFileSelectionDialog();
return true;
}
}
//Add this method to show Dialog when the required permission has been granted to the app.
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case FilePickerDialog.EXTERNAL_READ_PERMISSION_GRANT: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (dialog != null) {
openFileSelectionDialog();
}
} else {
//Permission has not been granted. Notify the user.
Toast.makeText(WebBrowserScreen.this, "Permission is Required for getting list of files", Toast.LENGTH_SHORT).show();
}
}
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
public class PQClient extends WebViewClient {
ProgressBar progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// If url contains mailto link then open Mail Intent
if (url.contains("mailto:")) {
// Could be cleverer and use a regex
//Open links in new browser
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// Here we can open new activity
return true;
} else {
// Stay within this webview and load url
view.loadUrl(url);
return true;
}
}
// Show loader on url load
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Then show progress Dialog
// in standard case YourActivity.this
if (progressDialog == null) {
progressDialog = findViewById(R.id.progressBar);
progressDialog.setVisibility(View.VISIBLE);
}
}
// Called when all page resources loaded
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:(function(){ " +
"document.getElementById('android-app').style.display='none';})()");
try {
// Close progressDialog
progressDialog.setVisibility(View.GONE);
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
From Wikipedia Media type,
A media type is composed of a type, a subtype, and optional parameters. As an example, an HTML file might be designated text/html; charset=UTF-8.
Media type consists of top-level type name and sub-type name, which is further structured into so-called "trees".
top-level type name / subtype name [ ; parameters ]
top-level type name / [ tree. ] subtype name [ +suffix ] [ ; parameters ]
All media types should be registered using the IANA registration procedures. Currently the following trees are created: standard
, vendor
, personal
or vanity
, unregistered x.
Standard:
Media types in the standards tree do not use any tree facet (prefix).
type / media type name [+suffix]
Examples: "application/xhtml+xml", "image/png"
Vendor:
Vendor tree is used for media types associated with publicly available products. It uses
vnd.
facet.
type / vnd. media type name [+suffix] - used in the case of well-known producer
type / vnd. producer's name followed by media type name [+suffix] - producer's name must be approved by IANA
type / vnd. producer's name followed by product's name [+suffix] - producer's name must be approved by IANA
Personal or Vanity tree:
Personal or Vanity tree includes media types created experimentally or as part of products that are not distributed commercially. It uses
prs.
facet.
type / prs. media type name [+suffix]
Unregistered x. tree:
The "x." tree may be used for media types intended exclusively for use in private, local environments and only with the active agreement of the parties exchanging them. Types in this tree cannot be registered.
According to the previous version of RFC 6838 - obsoleted RFC 2048 (published in November 1996) it should rarely, if ever, be necessary to use unregistered experimental types, and as such use of both "x-" and "x." forms is discouraged. Previous versions of that RFC - RFC 1590 and RFC 1521 stated that the use of "x-" notation for the sub-type name may be used for unregistered and private sub-types, but this recommendation was obsoleted in November 1996.
type / x. media type name [+suffix]
So its clear that the standard type MIME type application/pdf
is the appropriate one to use while you should avoid using the obsolete and unregistered x-
media type as stated in RFC 2048 and RFC 6838.
def func(*args):
pass
When you define a function this way, *args
will be array of arguments passed to the function. This allows your function to work without knowing ahead of time how many arguments are going to be passed to it.
You do this with keyword arguments too, using **kwargs
:
def func2(**kwargs):
pass
In your case, you've defined a class which is acting like a dictionary. The dict.pop
method is defined as pop(key[, default])
.
Your method doesn't use the default
parameter. But, by defining your method with *args
and passing *args
to dict.pop()
, you are allowing the caller to use the default
parameter.
In other words, you should be able to use your class's pop
method like dict.pop
:
my_a = a()
value1 = my_a.pop('key1') # throw an exception if key1 isn't in the dict
value2 = my_a.pop('key2', None) # return None if key2 isn't in the dict
This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.
wp_users
, add a key, like abc123 to the
user_activation
column. All versions of Git since v1.7.8 understand git fetch
with a refspec, whereas since v1.9.0 the --tags
option overrides the --prune
option. For a general purpose solution, try this:
$ git --version
git version 2.1.3
$ git fetch --prune origin "+refs/tags/*:refs/tags/*"
From ssh://xxx
x [deleted] (none) -> rel_test
For further reading on how the "--tags" with "--prune" behavior changed in Git v1.9.0, see: https://github.com/git/git/commit/e66ef7ae6f31f246dead62f574cc2acb75fd001c
Actually, using read.csv()
to read a file with text content is not a good idea, disable the quote as set quote=""
is only a temporary solution, it only worked with Separate quotation marks. There are other reasons would cause the warning, such as some special characters.
The permanent solution(using read.csv()
), finding out what those special characters are and use a regular expression to eliminate them is an idea.
Have you ever think of installing the package {data.table}
and use fread()
to read the file. it is much faster and would not bother you with this EOF warning. Note that the file it loads it will be stored as a data.table object but not a data.frame object. The class data.table has many good features, but anyway, you can transform it using as.data.frame()
if needed.
Let us call the sample code posted here the redirector and the other program the redirected. If it were me then I would probably write a test redirected program that can be used to duplicate the problem.
So I did. For test data I used the ECMA-334 C# Language Specificationv PDF; it is about 5MB. The following is the important part of that.
StreamReader stream = null;
try { stream = new StreamReader(Path); }
catch (Exception ex)
{
Console.Error.WriteLine("Input open error: " + ex.Message);
return;
}
Console.SetIn(stream);
int datasize = 0;
try
{
string record = Console.ReadLine();
while (record != null)
{
datasize += record.Length + 2;
record = Console.ReadLine();
Console.WriteLine(record);
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {ex.Message}");
return;
}
The datasize value does not match the actual file size but that does not matter. It is not clear if a PDF file always uses both CR and LF at the end of lines but that does not matter for this. You can use any other large text file to test with.
Using that the sample redirector code hangs when I write the large amount of data but not when I write a small amount.
I tried very much to somehow trace the execution of that code and I could not. I commented out the lines of the redirected program that disabled creation of a console for the redirected program to try to get a separate console window but I could not.
Then I found How to start a console app in a new window, the parent’s window, or no window. So apparently we cannot (easily) have a separate console when one console program starts another console program without ShellExecute and since ShellExecute does not support redirection we must share a console, even if we specify no window for the other process.
I assume that if the redirected program fills up a buffer somewhere then it must wait for the data to be read and if at that point no data is read by the redirector then it is a deadlock.
The solution is to not use ReadToEnd and to read the data while the data is being written but it is not necessary to use asynchronous reads. The solution can be quite simple. The following works for me with the 5 MB PDF.
ProcessStartInfo info = new ProcessStartInfo(TheProgram);
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);
string record = p.StandardOutput.ReadLine();
while (record != null)
{
Console.WriteLine(record);
record = p.StandardOutput.ReadLine();
}
p.WaitForExit();
Another possibility is to use a GUI program to do the redirection. The preceding code works in a WPF application except with obvious modifications.
Error reporting will have not included notices on the previous server which is why you haven't seen the errors.
You should be checking whether the index s
actually exists in the $_GET
array before attempting to use it.
Something like this would be suffice:
if (isset($_GET['s'])) {
if ($_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
else if ($_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
else if ($_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
} else {
echo "<body>";
}
It may be beneficial (if you plan on adding more cases) to use a switch
statement to make your code more readable.
switch ((isset($_GET['s']) ? $_GET['s'] : '')) {
case 'jwshxnsyllabus':
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
break;
case 'aquinas':
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
break;
case 'POP2':
echo "<body onload=\"loadSyllabi('POP2')\">";
break;
default:
echo "<body>";
break;
}
EDIT: BTW, the first set of code I wrote mimics what yours is meant to do in it's entirety. Is the expected outcome of an unexpected value in ?s=
meant to output no <body>
tag or was this an oversight? Note that the switch will fix this by always defaulting to <body>
.
It is not clear to me what you mean by "escape an executable which is running", but ctrl-z will put a process into the background and return control to the command line. You can then use the fg command to bring the program back into the foreground.
You're passing a pointer(address location) by value.
It's like saying "here's the place with the data I want you to update."
I was facing the same problem and found a solution to get the code to work.
The code given in the android-Sdk/samples/android-?/ApiDemos
works fine. Copy paste each folder in the android project and then in the MediaPlayerDemo_Video.java put the path of the video you want to stream in the path variable. It is left blank in the code.
The following video stream worked for me: http://www.pocketjourney.com/downloads/pj/video/famous.3gp
I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.
I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.
I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.
I hope this helps..
If I understand your question correctly, then you probably want a density estimate along with the histogram:
X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE) # prob=TRUE for probabilities not counts
lines(density(X)) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted") # add another "smoother" density
Edit a long while later:
Here is a slightly more dressed-up version:
X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2)
along with the graph it produces:
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
Make sure you Double-Check that the version you refer to in the child-pom is the same as that in the parent-pom. For me, I'd bumped version in the parent and had it as 3.1.0.0-RELEASE, but in the child-pom, I was still referring to the previous version via relativePath, and had it defined as 2.0.0.0-SNAPSHOT. It did not make any difference if I included just the parent directory, or had the "pom.xml" appended to the directory:
<parent>
<artifactId>eric-project-parent</artifactId>
<groupId>com.eric.common</groupId>
<!-- Should be 3.1.0.0-RELEASE -->
<version>2.0.0.0-SNAPSHOT</version>
<relativePath>
../../EricParentAsset/projects/eric-project-parent</relativePath>
</parent>
Try run mysqladmin reload
, which is located in /usr/loca/mysql/bin/
on mac.
Just an addition to the solved answer:
This COULD be a problem with Android Studio's Instant Run feature, for example, if you realized you forgot to add the line of code: finish()
to your activity after opening another one, and you already re-opened the activity you shouldn't have reopened (which the finish()
solved), then you add finish()
and Instant Run occurs, then the app will crash since the logic has been broken.
TL:DR;
This is not necessarily a code problem, just an Instant Run problem
I may also add, that nowadays it is possible to decompile Android application online, no software needed!
Here are 2 options for you:
It is in Firefox since version 51 (January 26, 2017), but it is not activated by default (yet)
To activate it:
about:config
dom.forms.datetime -> set to true
https://developer.mozilla.org/en-US/Firefox/Experimental_features
You have to do this:
class Bar : public Foo
{
// ...
}
The default inheritance type of a class
in C++ is private
, so any public
and protected
members from the base class are limited to private
. struct
inheritance on the other hand is public
by default.
in your device you want to run app on Go to settings About device >> Build number triple clicks or more and back to settings you will found "Developer options" appear go to and click on "USB debugging" Done
To avoid x !instance of Long
prob
Add
<property name="openjpa.Compatibility" value="StrictIdentityValues=false"/>
in your persistence.xml
Maybe adding an empty directory seems like it would be the path of least resistance because you have scripts that expect that directory to exist (maybe because it is a target for generated binaries). Another approach would be to modify your scripts to create the directory as needed.
mkdir --parents .generated/bin ## create a folder for storing generated binaries
mv myprogram1 myprogram2 .generated/bin ## populate the directory as needed
In this example, you might check in a (broken) symbolic link to the directory so that you can access it without the ".generated" prefix (but this is optional).
ln -sf .generated/bin bin
git add bin
When you want to clean up your source tree you can just:
rm -rf .generated ## this should be in a "clean" script or in a makefile
If you take the oft-suggested approach of checking in an almost-empty folder, you have the minor complexity of deleting the contents without also deleting the ".gitignore" file.
You can ignore all of your generated files by adding the following to your root .gitignore:
.generated
an alternative would be to do something like:
SELECT
CAST(P0.seconds as bigint) as seconds
FROM
(
SELECT
seconds
FROM
TableName
WHERE
ISNUMERIC(seconds) = 1
) P0
I had the opposite problem and finally had to create my own bash shell script for the company to migrate the hundred of repos from Github to Gitlab due to a change in the company policy.
The script use the Gitlab API to remotely create a repo, and push the Github repo into it.
There is no README.md file yet, but the sh is well documented.
The same thing can be done opposite way I imagine. Hope this could help.
https://github.com/mahmalsami/migrate-github-gitlab/blob/master/migrate.sh
Use std::string
and find
.
std::string str = "/user/desktop/abc/post/";
bool exists = str.find("/abc/") != std::string::npos;
Suggest the following simplification: capture return value from Workbooks.Add
instead of subscripting Windows()
afterward, as follows:
Set wkb = Workbooks.Add
wkb.SaveAs ...
wkb.Activate ' instead of Windows(expression).Activate
General Philosophy Advice:
Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.
Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.
Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection
During and within macros do not rely on these built-in names, instead capture return values, e.g.
Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate
Also, try to use qualified expressions, e.g.
wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"
or
Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"
Use qualified expressions, e.g.
newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar"
These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.
Also please note that you'll likely find that you don't need to .Activate
nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate
could simply be eliminated instead of even being replaced by wkb.Activate
.
(Also note: I think the .Select statements you show are not contributing and can be omitted.)
(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)
Might also be interesting for you to know that you can use:
{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)
to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)
The META-INF folder is the home for the MANIFEST.MF file. This file contains meta data about the contents of the JAR. For example, there is an entry called Main-Class that specifies the name of the Java class with the static main() for executable JAR files.
$('li[rel=7]').siblings().andSelf();
// or:
$('li[rel=7]').parent().children();
Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:
var rels = [];
$('ul').each(function() {
var localRels = [];
$(this).find('li').each(function(){
localRels.push( $(this).attr('rel') );
});
rels.push(localRels);
});
Sometimes you need to grep the process by name - in that case:
ps aux | grep simple-scan
Example output:
simple-scan 1090 0.0 0.1 4248 1432 ? S Jun11 0:00
MERGE INTO target
USING
(
--Source data
SELECT id, some_value, 0 deleteMe FROM source
--And anything that has been deleted from the source
UNION ALL
SELECT id, null some_value, 1 deleteMe
FROM
(
SELECT id FROM target
MINUS
SELECT id FROM source
)
) source
ON (target.ID = source.ID)
WHEN MATCHED THEN
--Requires a lot of ugly CASE statements, to prevent updating deleted data
UPDATE SET target.some_value =
CASE WHEN deleteMe=1 THEN target.some_value ELSE source.some_value end
,isDeleted = deleteMe
WHEN NOT MATCHED THEN
INSERT (id, some_value, isDeleted) VALUES (source.id, source.some_value, 0)
--Test data
create table target as
select 1 ID, 'old value 1' some_value, 0 isDeleted from dual union all
select 2 ID, 'old value 2' some_value, 0 isDeleted from dual;
create table source as
select 1 ID, 'new value 1' some_value, 0 isDeleted from dual union all
select 3 ID, 'new value 3' some_value, 0 isDeleted from dual;
--Results:
select * from target;
ID SOME_VALUE ISDELETED
1 new value 1 0
2 old value 2 1
3 new value 3 0
Bootstrap 3 requires span tag not i
<span class="glyphicon glyphicon-search"></span>`
Maybe you want more simple and short approach. This will clear all TextBoxes too. (Except TextBoxes inside Panel or GroupBox).
foreach (TextBox textBox in Controls.OfType<TextBox>())
textBox.Text = "";
request.META.get('HTTP_AUTHORIZATION')
/python3.6/site-packages/rest_framework/authentication.py
you can get that from this file though...
This is a very frequent task in linux. I use grep -rn '' . all the time to do this. -r for recursive (folder and subfolders) -n so it gives the line numbers, the dot stands for the current directory.
grep -rn '<word or regex>' <location>
do a
man grep
for more options
Changing the log level is simple; modifying other portions of the configuration will pose a more in depth approach.
LogManager.getRootLogger().setLevel(Level.DEBUG);
The changes are permanent through the life cyle of the Logger
. On reinitialization the configuration will be read and used as setting the level at runtime does not persist the level change.
UPDATE: If you are using Log4j 2 you should remove the calls to setLevel
per the documentation as this can be achieved via implementation classes.
Calls to logger.setLevel() or similar methods are not supported in the API. Applications should remove these. Equivalent functionality is provided in the Log4j 2 implementation classes but may leave the application susceptible to changes in Log4j 2 internals.
From the Official documentation,
For example, to set the background color to orange:
<meta name="theme-color" content="#db5945">
In addition, Chrome will show beautiful high-res favicons when they’re provided. Chrome for Android picks the highest res icon that you provide, and we recommend providing a 192×192px PNG file. For example:
<link rel="icon" sizes="192x192" href="nice-highres.png">
IMHO the simplest way is to use new control inherited from Hyperlink
:
/// <summary>
/// Opens <see cref="Hyperlink.NavigateUri"/> in a default system browser
/// </summary>
public class ExternalBrowserHyperlink : Hyperlink
{
public ExternalBrowserHyperlink()
{
RequestNavigate += OnRequestNavigate;
}
private void OnRequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
}
If using TextViews in tabs this selector definition worked for me (tried Klaus Balduino's but it did not):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Active tab -->
<item
android:state_selected="true"
android:state_focused="false"
android:state_pressed="false"
android:color="#000000" />
<!-- Inactive tab -->
<item
android:state_selected="false"
android:state_focused="false"
android:state_pressed="false"
android:color="#FFFFFF" />
</selector>
you just need to make background transparent of list divider and make height according to your needed gap.
<ListView
android:id="@+id/custom_list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:divider="#00ffffff"
android:dividerHeight="20dp"/>
Giving flex a value solved the problem for me, e.g.
flex: 1 0 auto
You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:
document.getElementById('sel').value = 'bike';??????????
If you sent a pull request on a repository where you don't have the rights to close it, you can delete the branch from where the pull request originated. That will cancel the pull request.
To install a Python package you've downloaded, you extract the archive and run the setup.py script inside:
python setup.py install
To me, this has always felt odd. It would be more natural to point a package manager at the download, as one would do in Ruby and Nodejs, eg. gem install rails-4.1.1.gem
A package manager is more comfortable too, because it's familiar and reliable. On the other hand, each setup.py
is novel, because it's specific to the package. It demands faith in convention "I trust this setup.py takes the same commands as others I have used in the past". That's a regrettable tax on mental willpower.
I'm not saying the setup.py workflow is less secure than a package manager (I understand Pip just runs the setup.py inside), but certainly I feel it's awkard and jarring. There's a harmony to commands all being to the same package manager application. You might even grow fond it.
To convert an integer to a string also involves char
array or memory management.
To handle that part for such short arrays, code could use a compound literal, since C99, to create array space, on the fly. The string is valid until the end of the block.
#define UNS_HEX_STR_SIZE ((sizeof (unsigned)*CHAR_BIT + 3)/4 + 1)
// compound literal v--------------------------v
#define U2HS(x) unsigned_to_hex_string((x), (char[UNS_HEX_STR_SIZE]) {0}, UNS_HEX_STR_SIZE)
char *unsigned_to_hex_string(unsigned x, char *dest, size_t size) {
snprintf(dest, size, "%X", x);
return dest;
}
int main(void) {
// 3 array are formed v v v
printf("%s %s %s\n", U2HS(UINT_MAX), U2HS(0), U2HS(0x12345678));
char *hs = U2HS(rand());
puts(hs);
// `hs` is valid until the end of the block
}
Output
FFFFFFFF 0 12345678
5851F42D
Compiling it with gcc
requires you to pass a number of command line options. Compile it with g++
instead.
I had a similar issue but my schema had a backslash in it. In this case, include the brackets around the schema.
ALTER SCHEMA dbo TRANSFER [DOMAIN\jonathan].MovieData;
Came across this issue in Xcode 11, fix was changing the Minimum Deployment Target from 10.0 to 11.0, hope this helps someone :)
If you're looking to print specific data that you already have access to, whether it's from a Store, AJAX, or available elsewhere, you can leverage my library react-print.
https://github.com/captray/react-print
It makes creating print templates much easier (assuming you already have a dependency on react). You just need to tag your HTML appropriately.
This ID should be added higher up in your actual DOM tree to exclude everything except the "print mount" below.
<div id="react-no-print">
This is where your react-print component will mount and wrap your template that you create:
<div id="print-mount"></div>
An example looks something like this:
var PrintTemplate = require('react-print');
var ReactDOM = require('react-dom');
var React = require('react');
var MyTemplate = React.createClass({
render() {
return (
<PrintTemplate>
<p>Your custom</p>
<span>print stuff goes</span>
<h1>Here</h1>
</PrintTemplate>
);
}
});
ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount'));
It's worth noting that you can create new or utilize existing child components inside of your template, and everything should render fine for printing.
In my opinion, two important scenarios other than stopping thread in which volatile keyword is used are:
If you are looking for something in production winston is probably the best choice.
If you just want to do dev stuff quickly, output directly to a file (I think this works only for *nix systems):
nohup node simple-server.js > output.log &
I know this is somewhat of an old topic, but in case anyone reads this in the future...
I uninstalled xampp, deleted everything under the c:\xampp folder, then reinstalled xampp as administrator and it worked like a charm.
Actually, there appears to now be a simple way. The following code works in TypeScript 1.5:
function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
const name = first + ' ' + last;
console.log(name);
}
sayName({ first: 'Bob' });
The trick is to first put in brackets what keys you want to pick from the argument object, with key=value
for any defaults. Follow that with the :
and a type declaration.
This is a little different than what you were trying to do, because instead of having an intact params
object, you have instead have dereferenced variables.
If you want to make it optional to pass anything to the function, add a ?
for all keys in the type, and add a default of ={}
after the type declaration:
function sayName({first='Bob',last='Smith'}: {first?: string; last?: string}={}){
var name = first + " " + last;
alert(name);
}
sayName();
Math.random()
generates a number between 0 (inclusive) and 1 (exclusive).
So (int)(Math.random() * max)
ranges from 0
to max-1
inclusive.
Then (int)(Math.random() * max) + min
ranges from min
to max + min - 1
, which is not what you want.
Google's formula is correct.
coonstructors are called automatically when you create a new object, thereby "constructing" the object. The reason you can have more than one init is because names are just references in python, and you are allowed to change what each variable references whenever you want (hence dynamic typing)
def func(): #now func refers to an empty funcion
pass
...
func=5 #now func refers to the number 5
def func():
print "something" #now func refers to a different function
in your class definition, it just keeps the later one
I was encountering the same issue. In my App build.gradle I had
apply plugin: 'com.android.application'
apply plugin: 'dexguard'
apply plugin: 'io.fabric'
I just switched Dexguard and Fabric, then it worked!
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'dexguard'
I was gone through same problem & I resolved it by following steps.
If the result is for humans to read and the elements of the array have a proper toString()
defined...
outputString.write(Arrays.toString(array));
I don't know that much about batch files but couldn't you have a pre-made batch file copied from the home directory to the path you have that would return a list of the names of the files then use that name?
Here is a link I think might be helpful in making the pre-made batch file.
To clone a repository and place it in a specified directory use "git clone [url] [directory]". For example
git clone https://github.com/ryanb/railscasts-episodes.git Rails
will create a directory named "Rails" and place it in the new directory. Click here for more information.
There is yet another simpler way to get table names
SHOW TABLES FROM <database_name>
I used the following 4 commands
cd ~/.cocoapods/repos
git clone "https://github.com/CocoaPods/Specs" master --depth 1
cd master
git fetch --unshallow
pod setup
I took time as expected, but at least I didn't have to stair at the screen wondering whats happening in the background.
In C++, Replace:
char *str = "hello";
with:
std::string str ("hello");
And if you want to compare it:
str.compare("HALLO");
To exclude the lines that contain any of the strings in $arrayOfStringsNotInterestedIn, you should use:
(Get-Content $FileName) -notmatch [String]::Join('|',$arrayofStringsNotInterestedIn)
The code proposed by Chris only works if $arrayofStringsNotInterestedIn contains the full lines you want to exclude.
ALTER TABLE `ALLITEMS`
CHANGE COLUMN `itemid` `itemid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;
InOrder
helps you to do that.
ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);
Mockito.doNothing().when(firstMock).methodOne();
Mockito.doNothing().when(secondMock).methodTwo();
//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);
//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();
You can just use String.ToCharArray() and then treat each char as a string in your code.
Here's an example:
foreach (char c in s.ToCharArray())
Debug.Log("one character ... " +c);
I used Calumah's function posted above, but I did run into an issue with his code as poisted.
The rows are joined with a semicolon
csv.push(row.join(';'));
but the link generated has "text/csv" as the content type
Maybe in Windows that isn't a problem, but in Excel for Mac that throws things off. I changed the array join to a comma and it worked perfect.
A complete example using schedule and multiprocessing, with on and off control and parameter to run_job()
the return codes are simplified and interval is set to 10sec, change to every(2).hour.do()
for 2hours. Schedule is quite impressive it does not drift and I've never seen it more than 100ms off when scheduling. Using multiprocessing instead of threading because it has a termination method.
#!/usr/bin/env python3
import schedule
import time
import datetime
import uuid
from flask import Flask, request
from multiprocessing import Process
app = Flask(__name__)
t = None
job_timer = None
def run_job(id):
""" sample job with parameter """
global job_timer
print("timer job id={}".format(id))
print("timer: {:.4f}sec".format(time.time() - job_timer))
job_timer = time.time()
def run_schedule():
""" infinite loop for schedule """
global job_timer
job_timer = time.time()
while 1:
schedule.run_pending()
time.sleep(1)
@app.route('/timer/<string:status>')
def mytimer(status, nsec=10):
global t, job_timer
if status=='on' and not t:
schedule.every(nsec).seconds.do(run_job, str(uuid.uuid4()))
t = Process(target=run_schedule)
t.start()
return "timer on with interval:{}sec\n".format(nsec)
elif status=='off' and t:
if t:
t.terminate()
t = None
schedule.clear()
return "timer off\n"
return "timer status not changed\n"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
You test this by just issuing:
$ curl http://127.0.0.1:5000/timer/on
timer on with interval:10sec
$ curl http://127.0.0.1:5000/timer/on
timer status not changed
$ curl http://127.0.0.1:5000/timer/off
timer off
$ curl http://127.0.0.1:5000/timer/off
timer status not changed
Every 10sec the timer is on it will issue a timer message to console:
127.0.0.1 - - [18/Sep/2018 21:20:14] "GET /timer/on HTTP/1.1" 200 -
timer job id=b64ed165-911f-4b47-beed-0d023ead0a33
timer: 10.0117sec
timer job id=b64ed165-911f-4b47-beed-0d023ead0a33
timer: 10.0102sec
Cmd + Shift + 7 will comment the selected lines.
Here is your code. I'm assuming you're using python 3 based on the your use of print()
and input()
:
import random
def main():
#random.seed() --> don't need random.seed()
#Prompts the user to enter the number of tickets they wish to play.
#python 3 version:
tickets = int(input("How many lottery tickets do you want?\n"))
#Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
winning_numbers = []
winnings = 0
#Generates the winning lotto numbers.
for i in range(tickets * 5):
#del winning_numbers[:] what is this line for?
randNum = random.randint(1,30)
while randNum in winning_numbers:
randNum = random.randint(1,30)
winning_numbers.append(randNum)
print(winning_numbers)
guess = getguess(tickets)
nummatches = checkmatch(winning_numbers, guess)
print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")
winningRanks = [0, 0, 10, 500, 20000, 1000000]
winnings = sum(winningRanks[:nummatches + 1])
print("You won a total of",winnings,"with",tickets,"tickets.\n")
#Gets the guess from the user.
def getguess(tickets):
guess = []
for i in range(tickets):
bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
guess.extend(bubble)
print(bubble)
return guess
#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
match = 0
for i in range(5):
if guess[i] == winning_numbers[i]:
match += 1
return match
main()
On Windows use the Xampp shell (there is a 'Shell' button in your XAMPP control panel)
then
cd php\pear
to go to 'C:\xampp\php\pear'
then type
pear
In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.
The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.
DECLARE
PROD_ROW_ID VARCHAR (10) := NULL;
VIS_ROW_ID NUMBER;
DSC VARCHAR (512);
BEGIN
SELECT ROW_ID
INTO VIS_ROW_ID
FROM SIEBEL.S_PROD_INT
WHERE PART_NUM = 'S0146404';
BEGIN
SELECT RTRIM (VIS.SERIAL_NUM)
|| ','
|| RTRIM (PLANID.DESC_TEXT)
|| ','
|| CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
THEN
'Y'
ELSE
'N'
END
ELSE
'N'
END
|| ','
|| 'GB'
|| ','
|| RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
INTO DSC
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/
Guys the better and clean way is to :
1) Create Schema dump of database (--schema-only) pg_dump mydb -s > schema.sql
2) Drop database drop database mydb;
3) Create Database create database mydb;
4) Import Schema psql mydb < schema.sql
It´s work for me!
Have a nice day. Hiram Walker
One thing that isn't mentioned in other answers is case sensitivity, if it is going to be referenced in multiple places (which it isn't in the original question but is worth taking into consideration as this question appears in a lot of similar searches). Based on other answers I found the following worked for me initially:
Request.Url.AbsoluteUri.ToString()
But in order to be more reliable this then became:
Request.Url.AbsoluteUri.ToString().ToLower()
And then for my requirements (checking what domain name the site is being accessed from and showing the relevant content):
Request.Url.AbsoluteUri.ToString().ToLower().Contains("xxxx")
The answer you're looking for as of June, 2013 can be found here:
https://gist.github.com/dineshcooper/2111366
It's accomplished using jQuery to rewrite the inner HTML of the parent container that holds the facebook widget.
Hope this helps!
Deleted for reasons of redundancy.
vars
are still initialized as the correct variable type - the compiler just infers it from the context. As you alluded to, var enables us to store references to anonymous class instances - but it also makes it easier to change your code. For example:
// If you change ItemLibrary to use int, you need to update this call
byte totalItemCount = ItemLibrary.GetItemCount();
// If GetItemCount changes, I don't have to update this statement.
var totalItemCount = ItemLibrary.GetItemCount();
Yes, if it's hard to determine a variable's type from its name and usage, by all means explicitly declare its type.
Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode
has most of the functions that you would typically associate with array nodes from other API's. As such, you do not need to cast to an ArrayNode
to use. Here's an example:
JSON:
{
"objects" : ["One", "Two", "Three"]
}
Code:
final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
for (final JsonNode objNode : arrNode) {
System.out.println(objNode);
}
}
Output:
"One"
"Two"
"Three"
Note the use of isArray
to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your datas structure, but its available should you need it (and this is no different from most other JSON libraries).
With Java 10, you could now use Set#copyOf
to easily convert a List<E>
to an unmodifiable Set<E>
:
Example:
var set = Set.copyOf(list);
Keep in mind that this is an unordered operation, and null
elements are not permitted, as it will throw a NullPointerException
.
If you wish for it to be modifiable, then simply pass it into the constructor a Set
implementation.
You can create a dict and pass this as the data param to the dataframe constructor:
In [235]:
df = pd.DataFrame({'Gene':s.index, 'count':s.values})
df
Out[235]:
Gene count
0 Ezh2 2
1 Hmgb 7
2 Irf1 1
Alternatively you can create a df from the series, you need to call reset_index
as the index will be used and then rename the columns:
In [237]:
df = pd.DataFrame(s).reset_index()
df.columns = ['Gene', 'count']
df
Out[237]:
Gene count
0 Ezh2 2
1 Hmgb 7
2 Irf1 1
If I remember C++ syntax well, you can add a label to break
statements, just like for goto
. So what you want would be easily written:
while(true) {
switch(msg->state) {
case MSGTYPE: // ...
break;
// ... more stuff ...
case DONE:
break outofloop; // **HERE, I want to break out of the loop itself**
}
}
outofloop:
// rest of your code here
$codeZero = null;
foreach ($xml->code->children() as $child) {
$codeZero = $child;
}
$lat = null;
foreach ($codeZero->children() as $child) {
if (isset($child->lat)) {
$lat = $child->lat;
}
}
Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression A AND B AND C
looks like this:
<And>
A
<And>
B
C
</And>
</And>
Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):
<Where>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>John</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>John</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>John</Value>
</Eq>
</Or>
</Or>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>Doe</Value>
</Eq>
</Or>
</Or>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>123</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>123</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>123</Value>
</Eq>
</Or>
</Or>
</And>
</And>
</Where>
To avoid the limitation of the file size , which can cause the Exception java.lang.OutOfMemoryError
to be thrown when creating an array of the file size byte[] bytes = new byte[(int) length];
, instead we could do
byte[] bytearray = new byte[1024*16];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
OutputStream output= socket.getOututStream();
BufferedInputStream bis = new BufferedInputStream(fis);
int readLength = -1;
while ((readLength = bis.read(bytearray)) > 0) {
output.write(bytearray, 0, readLength);
}
bis.close();
output.close();
}
catch(Exception ex ){
ex.printStackTrace();
} //Excuse the poor exception handling...
I use the NPP_Exec plugin (Found in the plugins manager). Once that is installed, open the console window (ctrl+~) and type:
cmd
This will launch command prompt. Then type:
C:\Program Files\Notepad++> **python "$(FULL_CURRENT_PATH)"**
to execute the current file you are working with.
user1462299's response works great, but if you include fragments, they will use the original activities theme. To apply the theme to all fragments as well you can override the getTheme() method of the Context instead:
@Override
public Resources.Theme getTheme() {
Resources.Theme theme = super.getTheme();
if(useAlternativeTheme){
theme.applyStyle(R.style.AlternativeTheme, true);
}
// you could also use a switch if you have many themes that could apply
return theme;
}
You do not need to call setTheme() in the onCreate() Method anymore. You are overriding every request to get the current theme within this context this way.
This is a variant of UnkwnTech's answer -- it provides a get_local_addr()
function, which returns the primary LAN ip address of the host. I'm posting it because this adds a number of things: ipv6 support, error handling, ignoring localhost/linklocal addrs, and uses a TESTNET addr (rfc5737) to connect to.
# imports
import errno
import socket
import logging
# localhost prefixes
_local_networks = ("127.", "0:0:0:0:0:0:0:1")
# ignore these prefixes -- localhost, unspecified, and link-local
_ignored_networks = _local_networks + ("0.", "0:0:0:0:0:0:0:0", "169.254.", "fe80:")
def detect_family(addr):
if "." in addr:
assert ":" not in addr
return socket.AF_INET
elif ":" in addr:
return socket.AF_INET6
else:
raise ValueError("invalid ipv4/6 address: %r" % addr)
def expand_addr(addr):
"""convert address into canonical expanded form --
no leading zeroes in groups, and for ipv6: lowercase hex, no collapsed groups.
"""
family = detect_family(addr)
addr = socket.inet_ntop(family, socket.inet_pton(family, addr))
if "::" in addr:
count = 8-addr.count(":")
addr = addr.replace("::", (":0" * count) + ":")
if addr.startswith(":"):
addr = "0" + addr
return addr
def _get_local_addr(family, remote):
try:
s = socket.socket(family, socket.SOCK_DGRAM)
try:
s.connect((remote, 9))
return s.getsockname()[0]
finally:
s.close()
except socket.error:
# log.info("trapped error connecting to %r via %r", remote, family, exc_info=True)
return None
def get_local_addr(remote=None, ipv6=True):
"""get LAN address of host
:param remote:
return LAN address that host would use to access that specific remote address.
by default, returns address it would use to access the public internet.
:param ipv6:
by default, attempts to find an ipv6 address first.
if set to False, only checks ipv4.
:returns:
primary LAN address for host, or ``None`` if couldn't be determined.
"""
if remote:
family = detect_family(remote)
local = _get_local_addr(family, remote)
if not local:
return None
if family == socket.AF_INET6:
# expand zero groups so the startswith() test works.
local = expand_addr(local)
if local.startswith(_local_networks):
# border case where remote addr belongs to host
return local
else:
# NOTE: the two addresses used here are TESTNET addresses,
# which should never exist in the real world.
if ipv6:
local = _get_local_addr(socket.AF_INET6, "2001:db8::1234")
# expand zero groups so the startswith() test works.
if local:
local = expand_addr(local)
else:
local = None
if not local:
local = _get_local_addr(socket.AF_INET, "192.0.2.123")
if not local:
return None
if local.startswith(_ignored_networks):
return None
return local
This works for me, the source is here
int MY_PERMISSIONS_REQUEST_CAMERA=0;
// Here, this is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA))
{
}
else
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA );
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
Assuming you want to simply lift the 32bits from one type and dump them as-is into the other type:
uint asUint = unchecked((uint)myInt);
int asInt = unchecked((int)myUint);
The destination type will blindly pick the 32 bits and reinterpret them.
Conversely if you're more interested in keeping the decimal/numerical values within the range of the destination type itself:
uint asUint = checked((uint)myInt);
int asInt = checked((int)myUint);
In this case, you'll get overflow exceptions if:
In our case, we wanted the unchecked
solution to preserve the 32bits as-is, so here are some examples:
int....: 0000000000 (00-00-00-00)
asUint.: 0000000000 (00-00-00-00)
------------------------------
int....: 0000000001 (01-00-00-00)
asUint.: 0000000001 (01-00-00-00)
------------------------------
int....: -0000000001 (FF-FF-FF-FF)
asUint.: 4294967295 (FF-FF-FF-FF)
------------------------------
int....: 2147483647 (FF-FF-FF-7F)
asUint.: 2147483647 (FF-FF-FF-7F)
------------------------------
int....: -2147483648 (00-00-00-80)
asUint.: 2147483648 (00-00-00-80)
uint...: 0000000000 (00-00-00-00)
asInt..: 0000000000 (00-00-00-00)
------------------------------
uint...: 0000000001 (01-00-00-00)
asInt..: 0000000001 (01-00-00-00)
------------------------------
uint...: 2147483647 (FF-FF-FF-7F)
asInt..: 2147483647 (FF-FF-FF-7F)
------------------------------
uint...: 4294967295 (FF-FF-FF-FF)
asInt..: -0000000001 (FF-FF-FF-FF)
------------------------------
int[] testInts = { 0, 1, -1, int.MaxValue, int.MinValue };
uint[] testUints = { uint.MinValue, 1, uint.MaxValue / 2, uint.MaxValue };
foreach (var Int in testInts)
{
uint asUint = unchecked((uint)Int);
Console.WriteLine("int....: {0:D10} ({1})", Int, BitConverter.ToString(BitConverter.GetBytes(Int)));
Console.WriteLine("asUint.: {0:D10} ({1})", asUint, BitConverter.ToString(BitConverter.GetBytes(asUint)));
Console.WriteLine(new string('-',30));
}
Console.WriteLine(new string('=', 30));
foreach (var Uint in testUints)
{
int asInt = unchecked((int)Uint);
Console.WriteLine("uint...: {0:D10} ({1})", Uint, BitConverter.ToString(BitConverter.GetBytes(Uint)));
Console.WriteLine("asInt..: {0:D10} ({1})", asInt, BitConverter.ToString(BitConverter.GetBytes(asInt)));
Console.WriteLine(new string('-', 30));
}
I did the test using java 8 It wont matter the order the builder always takes 0 milliseconds and the concat between 26 and 33 milliseconds under and iteration of a 1000 concatenation
Hope it helps try it with your ide
public void count() {
String result = "";
StringBuilder builder = new StringBuilder();
long millis1 = System.currentTimeMillis(),
millis2;
for (int i = 0; i < 1000; i++) {
builder.append("hello world this is the concat vs builder test enjoy");
}
millis2 = System.currentTimeMillis();
System.out.println("Diff: " + (millis2 - millis1));
millis1 = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
result += "hello world this is the concat vs builder test enjoy";
}
millis2 = System.currentTimeMillis();
System.out.println("Diff: " + (millis2 - millis1));
}
In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :
sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...
[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]
Recently I was working on a game compatible with CocoonJS with DOM limited to the canvas element - here is my approach:
Using fillText with a font that has not been loaded yet will execute properly but with no visual feedback - so the canvas plane will stay intact - all you have to do is periodically check the canvas for any changes (for example looping through getImageData searching for any non transparent pixel) that will happen when the font loads properly.
I have explained this technique a little bit more in my recent article http://rezoner.net/preloading-font-face-using-canvas,686
I tried all these answers, even closed Visual Studio and deleted all bin directories.
After starting it up again the MVC reference appeared to have a yellow exclamation mark on it, so I removed it and added it again.
Now it works, without copy local.
If you're using PHP, I recommend using the PHP SDK for Firebase: Firebase Admin SDK. For an easy configuration you can follow these steps:
Get the project credentials json file from Firebase (Initialize the sdk) and include it in your project.
Install the SDK in your project. I use composer:
composer require kreait/firebase-php ^4.35
Try any example from the Cloud Messaging session in the SDK documentation:
use Kreait\Firebase;
use Kreait\Firebase\Messaging\CloudMessage;
$messaging = (new Firebase\Factory())
->withServiceAccount('/path/to/firebase_credentials.json')
->createMessaging();
$message = CloudMessage::withTarget(/* see sections below */)
->withNotification(Notification::create('Title', 'Body'))
->withData(['key' => 'value']);
$messaging->send($message);
private String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
private String getMy10DigitPhoneNumber(){
String s = getMyPhoneNumber();
return s.substring(2);
}
Try this for compatibility;
<script type="text/javascript">
$(function() {
setTimeout(function() {
window.location.href = $('#myAnchor').attr("href");
}, 1500);
});
</script>
Here's what I use and will only take a few seconds to run:
ffmpeg -i input.mp4 -ss 01:19:27 -to 02:18:51 -c:v copy -c:a copy output.mp4
Reference: https://www.arj.no/2018/05/18/trimvideo
Generated mp4
files could also be used in iMovie
. More info related to get the full duration using get_duration(input_video) modele.
If you want to concatenate multiple cut scenes you can use following Python script:
#!/usr/bin/env python3
import subprocess
def get_duration(input_video):
cmd = ["ffprobe", "-i", input_video, "-show_entries", "format=duration",
"-v", "quiet", "-sexagesimal", "-of", "csv=p=0"]
return subprocess.check_output(cmd).decode("utf-8").strip()
if __name__ == "__main__":
name = "input.mkv"
times = []
times.append(["00:00:00", "00:00:10"])
times.append(["00:06:00", "00:07:00"])
# times = [["00:00:00", get_duration(name)]]
if len(times) == 1:
time = times[0]
cmd = ["ffmpeg", "-i", name, "-ss", time[0], "-to", time[1], "-c:v", "copy", "-c:a", "copy", "output.mp4"]
subprocess.check_output(cmd)
else:
open('concatenate.txt', 'w').close()
for idx, time in enumerate(times):
output_filename = f"output{idx}.mp4"
cmd = ["ffmpeg", "-i", name, "-ss", time[0], "-to", time[1], "-c:v", "copy", "-c:a", "copy", output_filename]
subprocess.check_output(cmd)
with open("concatenate.txt", "a") as myfile:
myfile.write(f"file {output_filename}\n")
cmd = ["ffmpeg", "-f", "concat", "-i", "concatenate.txt", "-c", "copy", "output.mp4"]
output = subprocess.check_output(cmd).decode("utf-8").strip()
Example script will cut and merge scenes in between 00:00:00 - 00:00:10
and 00:06:00 - 00:07:00
.
If you want to cut the complete video (in case if you want to convert mkv
format into mp4
) just uncomment the following line:
# times = [["00:00:00", get_duration(name)]]
.Cells(.Rows.Count,"A").End(xlUp).row
I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:
.Cells(Rows.Count,"A").End(xlUp).row
Before the Cells, you can write your worksheet name, for example:
Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row
The worksheet name is not necessary when you operate on the same worksheet.
Use ISNULL(field, 0)
It can also be used with aggregates:
ISNULL(count(field), 0)
However, you might consider changing count(field) to count(*)
Edit:
try:
closedcases = ISNULL(
(select count(closed) from ticket
where assigned_to = c.user_id and closed is not null
group by assigned_to), 0),
opencases = ISNULL(
(select count(closed) from ticket
where assigned_to = c.user_id and closed is null
group by assigned_to), 0),
Homebrew
brew doctor
and address anything homebrew wants you to fixbrew install mysql
brew services restart mysql
mysql.server start
mysql_secure_installation
for .NET Core console apps you can do this 2 ways - from the launchsettings.json or the properties menu.
Launchsettings.json
or right click the project > properties > debug tab on left
see "Application Arguments:"
Sorry to bring up an old thread, but here is a little manual for those who (like me!) don't see how Eli Grey's example works:
var test = new Object();
test.watch("elem", function(prop,oldval,newval){
//Your code
return newval;
});
Hope this can help someone
The code works for me. (after adding missing except
clause / import
statements)
Did you put \
in the original code?
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
+ stock + '/chartdata;type=quote;range=5d/csv'
If you omit it, it could be a cause of the exception:
>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
BTW, string(e)
should be str(e)
.
It was a firewall issue. There was a hardware firewall that was blocking access to almost all ports. (Turning off software firewall / SELinux bla bla had no effect)
Then I scanned the open ports and used the port that was open.
If you are facing the same problem, Run the following command
sudo nmap -T Aggressive -A -v 127.0.0.1 -p 1-65000
It will scan for all the open ports on your system. Any port that is open can be accessed from outside.
Ref.: http://www.go2linux.org/which_service_or_program_is_listening_on_port
In Python 3, print is a function, whereas it used to be a statement in previous versions. As @holdenweb suggested, use 2to3 to translate your code.
Try this:
while read line
do
echo -e |wc -m
done <abc.txt
I believe this variation of the theme gives debug categories without the need to have a separate macro name per category.
I used this variation in an Arduino project where program space is limited to 32K and dynamic memory is limited to 2K. The addition of debug statements and trace debug strings quickly uses up space. So it is essential to be able to limit the debug trace that is included at compile time to the minimum necessary each time the code is built.
#ifndef DEBUG_H
#define DEBUG_H
#define PRINT(DEBUG_CATEGORY, VALUE) do { if (DEBUG_CATEGORY & DEBUG_MASK) Serial.print(VALUE);} while (0);
#endif
#define DEBUG_MASK 0x06
#include "Debug.h"
...
PRINT(4, "Time out error,\t");
...
I think this should work:
#include <time.h>
clock_t start = clock(), diff;
ProcessIntenseFunction();
diff = clock() - start;
int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("Time taken %d seconds %d milliseconds", msec/1000, msec%1000);
I also faced the same issue , and none of these worked. In my case this was fixed by adding these lines in config file.
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="100000" />
</appSettings>
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true"/>
</scripting>
</system.web.extensions>
Tiggers automatically and manually when needed
$(function () {
TriggerAlertClose();
});
function TriggerAlertClose() {
window.setTimeout(function () {
$(".alert").fadeTo(1000, 0).slideUp(1000, function () {
$(this).remove();
});
}, 5000);
}
If the files are on a remote file system or inside an archive, you can use an implementation of the fsspec AbstractFileSystem class. For example, to list all the files in a zipfile:
from fsspec.implementations.zip import ZipFileSystem
fs = ZipFileSystem("/tmp/test.zip")
fs.glob("/**") # equivalent: fs.find("/")
or to list all the files in a publicly available S3 bucket:
from s3fs import S3FileSystem
fs_s3 = S3FileSystem(anon=True)
fs_s3.glob("noaa-goes16/ABI-L1b-RadF/2020/045/**") # or use fs_s3.find
you can also use it for a local filesystem, which may be interesting if your implementation should be filesystem-agnostic:
from fsspec.implementations.local import LocalFileSystem
fs = LocalFileSystem()
fs.glob("/tmp/test/**")
Other implementations include Google Cloud, Github, SFTP/SSH, Dropbox, and Azure. For details, see the fsspec API documentation.
I have the same error. Following changes helped me to fix this.
I had to check Server Manager->Tool->Services and find the user ("Log On As" column) for service: SQL Server (SQLEXPRESS).
I went to the local folder (C:\Users\Me\Desktop\Backup) and added "NT Service\MSSQL$SQLEXPRESS" as the user to give Write permissions.
Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.
My finally working solution:
$(function () {
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
}
});
You have to include before:
@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")
You can install moment.js using:
Install-Package Moment.js
If you're using PostgreSQL 8 or above, you may need to modify the listen_addresses
setting in /etc/postgresql/8.4/main/postgresql.conf
.
Try adding the line:
listen_addresses = *
which will tell PostgreSQL to listen for connections on all network interfaces.
If not explicitly set, this setting defaults to localhost
which means it will only accept connections from the same machine.
Try this:
select * from your_table
where date >= '2020-10-01'
Update
The scipy.stats.mode
function has been significantly optimized since this post, and would be the recommended method
Old answer
This is a tricky problem, since there is not much out there to calculate mode along an axis. The solution is straight forward for 1-D arrays, where numpy.bincount
is handy, along with numpy.unique
with the return_counts
arg as True
. The most common n-dimensional function I see is scipy.stats.mode, although it is prohibitively slow- especially for large arrays with many unique values. As a solution, I've developed this function, and use it heavily:
import numpy
def mode(ndarray, axis=0):
# Check inputs
ndarray = numpy.asarray(ndarray)
ndim = ndarray.ndim
if ndarray.size == 1:
return (ndarray[0], 1)
elif ndarray.size == 0:
raise Exception('Cannot compute mode on empty array')
try:
axis = range(ndarray.ndim)[axis]
except:
raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))
# If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
if all([ndim == 1,
int(numpy.__version__.split('.')[0]) >= 1,
int(numpy.__version__.split('.')[1]) >= 9]):
modals, counts = numpy.unique(ndarray, return_counts=True)
index = numpy.argmax(counts)
return modals[index], counts[index]
# Sort array
sort = numpy.sort(ndarray, axis=axis)
# Create array to transpose along the axis and get padding shape
transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
shape = list(sort.shape)
shape[axis] = 1
# Create a boolean array along strides of unique values
strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
numpy.diff(sort, axis=axis) == 0,
numpy.zeros(shape=shape, dtype='bool')],
axis=axis).transpose(transpose).ravel()
# Count the stride lengths
counts = numpy.cumsum(strides)
counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
counts[strides] = 0
# Get shape of padded counts and slice to return to the original shape
shape = numpy.array(sort.shape)
shape[axis] += 1
shape = shape[transpose]
slices = [slice(None)] * ndim
slices[axis] = slice(1, None)
# Reshape and compute final counts
counts = counts.reshape(shape).transpose(transpose)[slices] + 1
# Find maximum counts and return modals/counts
slices = [slice(None, i) for i in sort.shape]
del slices[axis]
index = numpy.ogrid[slices]
index.insert(axis, numpy.argmax(counts, axis=axis))
return sort[index], counts[index]
Result:
In [2]: a = numpy.array([[1, 3, 4, 2, 2, 7],
[5, 2, 2, 1, 4, 1],
[3, 3, 2, 2, 1, 1]])
In [3]: mode(a)
Out[3]: (array([1, 3, 2, 2, 1, 1]), array([1, 2, 2, 2, 1, 2]))
Some benchmarks:
In [4]: import scipy.stats
In [5]: a = numpy.random.randint(1,10,(1000,1000))
In [6]: %timeit scipy.stats.mode(a)
10 loops, best of 3: 41.6 ms per loop
In [7]: %timeit mode(a)
10 loops, best of 3: 46.7 ms per loop
In [8]: a = numpy.random.randint(1,500,(1000,1000))
In [9]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 1.01 s per loop
In [10]: %timeit mode(a)
10 loops, best of 3: 80 ms per loop
In [11]: a = numpy.random.random((200,200))
In [12]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 3.26 s per loop
In [13]: %timeit mode(a)
1000 loops, best of 3: 1.75 ms per loop
EDIT: Provided more of a background and modified the approach to be more memory-efficient
Try this code. This does what you want.
LOGIC
""
with blanks and write to the new file at the same time.CODE (TRIED AND TESTED)
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Const MAX_PATH As Long = 260
'~~> Change this where and how you want to save the file
Const FlName = "C:\Users\Siddharth Rout\Desktop\MyWorkbook.txt"
Sub Sample()
Dim tmpFile As String
Dim MyData As String, strData() As String
Dim entireline As String
Dim filesize As Integer
'~~> Create a Temp File
tmpFile = TempPath & Format(Now, "ddmmyyyyhhmmss") & ".txt"
ActiveWorkbook.SaveAs Filename:=tmpFile _
, FileFormat:=xlText, CreateBackup:=False
'~~> Read the entire file in 1 Go!
Open tmpFile For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
'~~> Get a free file handle
filesize = FreeFile()
'~~> Open your file
Open FlName For Output As #filesize
For i = LBound(strData) To UBound(strData)
entireline = Replace(strData(i), """", "")
'~~> Export Text
Print #filesize, entireline
Next i
Close #filesize
MsgBox "Done"
End Sub
Function TempPath() As String
TempPath = String$(MAX_PATH, Chr$(0))
GetTempPath MAX_PATH, TempPath
TempPath = Replace(TempPath, Chr$(0), "")
End Function
SNAPSHOTS
Actual Workbook
After Saving
Better solution for different currency formats:
def text_currency_to_float(text):
t = text
dot_pos = t.rfind('.')
comma_pos = t.rfind(',')
if comma_pos > dot_pos:
t = t.replace(".", "")
t = t.replace(",", ".")
else:
t = t.replace(",", "")
return(float(t))
This will print duplicate lines only, with counts:
sort FILE | uniq -cd
or, with GNU long options (on Linux):
sort FILE | uniq --count --repeated
on BSD and OSX you have to use grep to filter out unique lines:
sort FILE | uniq -c | grep -v '^ *1 '
For the given example, the result would be:
3 123
2 234
If you want to print counts for all lines including those that appear only once:
sort FILE | uniq -c
or, with GNU long options (on Linux):
sort FILE | uniq --count
For the given input, the output is:
3 123
2 234
1 345
In order to sort the output with the most frequent lines on top, you can do the following (to get all results):
sort FILE | uniq -c | sort -nr
or, to get only duplicate lines, most frequent first:
sort FILE | uniq -cd | sort -nr
on OSX and BSD the final one becomes:
sort FILE | uniq -c | grep -v '^ *1 ' | sort -nr
One way is (this is with Bash)
grep -P '\t'
-P
turns on Perl regular expressions so \t will work.
As user unwind says, it may be specific to GNU grep. The alternative is to literally insert a tab in there if the shell, editor or terminal will allow it.
import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions)
with open('data.csv', 'r') as f:
for rec in csv.DictReader(f):
for l, col in zip(data, cols):
l.append(float(rec[col]))
print data
# [[3.0, 3.0], [0.01, 0.01]]
Update: Subversion 1.9 will support a new command "svn youngest" that outputs only the latest revision number. The difference to "svnlook youngest" is that "svn youngest" also works remotely.
One option would be
const styleElement = getComputedStyle(document.getElementById("myDiv"));
console.log(styleElement.height);
From your example it seems reasonable to assume that the siteIP
column is determined by the siteName
column (that is, each site has only one siteIP
). If this is indeed the case, then there is a simple solution using group by
:
select
sites.siteName,
sites.siteIP,
max(history.date)
from sites
inner join history on
sites.siteName=history.siteName
group by
sites.siteName,
sites.siteIP
order by
sites.siteName;
However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP
), then it is not clear from you question which siteIP
you want the query to return in the second column. If just any siteIP
, then the following query will do:
select
sites.siteName,
min(sites.siteIP),
max(history.date)
from sites
inner join history on
sites.siteName=history.siteName
group by
sites.siteName
order by
sites.siteName;
class MyParent:
def sayHi():
print('Mamma says hi')
from path.to.MyParent import MyParent
class ChildClass(MyParent):
pass
An instance of ChildClass
will then inherit the sayHi()
method.
I just did the same. If you look in the "Android SDK Manager" in the "Android 4.0 (API 14)" section you'll see a few packages. One of these is named "ARM EABI v7a System Image".
This is what you need to download in order to create an Android 4.0 virtual device:
The following made it work for me on Ubuntu 14.04:
cd (App Dir)
react-native start > /dev/null 2>&1 &
adb reverse tcp:8081 tcp:8081
Update: See
Update 2: @scgough We got this error because React Native (RN) was unable to fetch JavaScript from the dev server running on our workstations. You can see why this happens here:
If your RN app detects that you're using Genymotion or the emulator it tries to fetch the JavaScript from GENYMOTION_LOCALHOST (10.0.3.2) or EMULATOR_LOCALHOST (10.0.2.2). Otherwise it presumes that you're using a device and it tries to fetch the JavaScript from DEVICE_LOCALHOST (localhost). The problem is that the dev server runs on your workstation's localhost, not the device's, so in order to get it to work you need to either:
I ran into the same issue (exact error message) and after digging for a couple of hours, I found that the content header needs to be set to application/javascript
instead of the application/json
that I had. After changing that, it now works.
Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods, including a startsWith
method. From the docs:
startsWith
_.startsWith(string, starts)
This method checks whether
string
starts withstarts
._("image.gif").startsWith("image") => true
Just to add on to the existing answers: hopefully, you'll encounter something more like this in the future:
>>> word = 'abc'
>>> L = list(word)
>>> L
['a', 'b', 'c']
>>> ''.join(L)
'abc'
But what you're dealing with right now, go with @Cameron's answer.
>>> word = 'a,b,c'
>>> L = word.split(',')
>>> L
['a', 'b', 'c']
>>> ','.join(L)
'a,b,c'
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(hrefLink.Replace("/", "\\"));
}
THis assumes, of course, that you've parsed out the file name.
EDIT #2:
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(Uri.UnescapeDataString(hrefLink).Replace("/", "\\"));
}
This should handle spaces and the like in the file name.
The typical usage of shifting a variable and assigning back to the variable can be rewritten with shorthand operators <<=, >>=, or >>>=, also known in the spec as Compound Assignment Operators.
For example,
i >>= 2
produces the same result as
i = i >> 2
There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.
By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler)
method call you are also able to register a signal handler, but probably not for signals like INT
or TERM
as they are used by the JVM.
To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.
What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid
system call.
I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.
#!/bin/bash
# Check do we have tunnel to example.com server
lsof -i tcp@localhost:6000 > /dev/null
# If exit code wasn't 0 then tunnel doesn't exist.
if [ $? -eq 1 ]
then
echo ' > You missing ssh tunnel. Creating one..'
ssh -L 6000:localhost:5432 example.com
fi
echo ' > DO YOUR STUFF < '
This is a great way to make the video fit a banner, you might need to tweak this a little for full screen but should be ok. 100% CSS.
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
z-index: 1;_x000D_
min-width: 100%;_x000D_
min-height: 100%;_x000D_
width: auto;_x000D_
height: auto;_x000D_
transform: translate(-50%, -50%);
_x000D_
Here is another solution using css transform (for performance purposes on mobiles, see answer of @mate64 ) without having to use animations and keyframes.
I created two versions to slide-in from either side.
$('#toggle').click(function() {_x000D_
$('.slide-in').toggleClass('show');_x000D_
});
_x000D_
.slide-in {_x000D_
z-index: 10; /* to position it in front of the other content */_x000D_
position: absolute;_x000D_
overflow: hidden; /* to prevent scrollbar appearing */_x000D_
}_x000D_
_x000D_
.slide-in.from-left {_x000D_
left: 0;_x000D_
}_x000D_
_x000D_
.slide-in.from-right {_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
.slide-in-content {_x000D_
padding: 5px 20px;_x000D_
background: #eee;_x000D_
transition: transform .5s ease; /* our nice transition */_x000D_
}_x000D_
_x000D_
.slide-in.from-left .slide-in-content {_x000D_
transform: translateX(-100%);_x000D_
-webkit-transform: translateX(-100%);_x000D_
}_x000D_
_x000D_
.slide-in.from-right .slide-in-content {_x000D_
transform: translateX(100%);_x000D_
-webkit-transform: translateX(100%);_x000D_
}_x000D_
_x000D_
.slide-in.show .slide-in-content {_x000D_
transform: translateX(0);_x000D_
-webkit-transform: translateX(0);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="slide-in from-left">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>Lorem</li>_x000D_
<li>Ipsum</li>_x000D_
<li>Dolor</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="slide-in from-right">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>One</li>_x000D_
<li>Two</li>_x000D_
<li>Three</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
You have install nodeJs on your system in order to execute npm
commands. Once npm
is properly working you can visit bower.io
. There you will find complete documentation on this topic. You will find a command $ npm install bower
. this will install bower on your machine. After installing bower you can install Bootstrap easily.
The solution is so simple:
Replace type "Submit" with button
<input type="button" value="Submit" onclick="this.form.submit()" />
You can simply set xhr.responseType = 'json';
const xhr = new XMLHttpRequest();_x000D_
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');_x000D_
xhr.responseType = 'json';_x000D_
xhr.onload = function(e) {_x000D_
if (this.status == 200) {_x000D_
console.log('response', this.response); // JSON response _x000D_
}_x000D_
};_x000D_
xhr.send();_x000D_
_x000D_
I'd go with the default arguments, especially since C++ doesn't let you chain constructors (so you end up having to duplicate the initialiser list, and possibly more, for each overload).
That said, there are some gotchas with default arguments, including the fact that constants may be inlined (and thereby become part of your class' binary interface). Another to watch out for is that adding default arguments can turn an explicit multi-argument constructor into an implicit one-argument constructor:
class Vehicle {
public:
Vehicle(int wheels, std::string name = "Mini");
};
Vehicle x = 5; // this compiles just fine... did you really want it to?
From the builtin module this.py
(import this
):
s = "foobar"
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+13) % 26 + c)
print("".join([d.get(c, c) for c in s])) # sbbone
There is a DateTime constructor that takes a long.
DateTime today = new DateTime(t); // where t represents long format of dateTime
You could use
String newValue = Integer.toString((int)percentageValue);
Or
String newValue = Double.toString(Math.floor(percentageValue));
In my case, I have various layer groups so that users can show/hide clusters of like type markers. But, in any case you delete an individual marker by looping over your layer groups to find and delete it. While looping, search for a marker with a custom attribute, in my case a 'key', added when the marker was added to the layer group. Add your 'key' just like adding a title attribute. Later this is gotten an a layer option. When you find that match, you .removeLayer() and it gets rid of that particular marker. Hope that helps you out!
eventsLayerGroup.addLayer(L.marker([tag.latitude, tag.longitude],{title:tag.title, layer:tag.layer, timestamp:tag.timestamp, key:tag.key, bounceOnAdd: true, icon: L.AwesomeMarkers.icon({icon: 'vignette', markerColor: 'blue', prefix: '', iconColor: 'white'}) }).bindPopup(customPopup(tag),customOptions).on('click', markerClick));
function removeMarker(id){
var layerGroupsArray = [eventsLayerGroup,landmarksLayerGroup,travelerLayerGroup,marketplaceLayerGroup,myLayerGroup];
$.each(layerGroupsArray, function (key, value) {
value.eachLayer(function (layer) {
if(typeof value !== "undefined"){
if (layer.options.layer){
console.log(layer.options.key);
console.log(id);
if (id === layer.options.key){
value.removeLayer(layer);
}
}
}
});
});
}
Depends on how you installed it:
brew: brew uninstall yarn
tarball: rm -rf "$HOME/.yarn"
npm: npm uninstall -g yarn
ubuntu: sudo apt-get remove yarn && sudo apt-get purge yarn
centos: yum remove yarn
windows: choco uninstall yarn
As soon as I saw the problem statement, I thought "Trie". But seeing as several other posters made use of that approach, I looked for another approach just to be different. Alas, the Trie approach performs better. I ran Kent's Perl solution on my machine and it took 0.31 seconds to run, after adapting it to use my dictionary file. My own perl implementation required 0.54 seconds to run.
This was my approach:
Create a transition hash to model the legal transitions.
Iterate through all 16^3 possible three letter combinations.
Then loop through all words in the dictionary.
Print out the words I found.
I tried 3-letter and 4-letter sequences, but 4-letter sequences slowed the program down.
In my code, I use /usr/share/dict/words for my dictionary. It comes standard on MAC OS X and many Unix systems. You can use another file if you want. To crack a different puzzle, just change the variable @puzzle. This would be easy to adapt for larger matrices. You would just need to change the %transitions hash and %legalTransitions hash.
The strength of this solution is that the code is short, and the data structures simple.
Here is the Perl code (which uses too many global variables, I know):
#!/usr/bin/perl
use Time::HiRes qw{ time };
sub readFile($);
sub findAllPrefixes($);
sub isWordTraceable($);
sub findWordsInPuzzle(@);
my $startTime = time;
# Puzzle to solve
my @puzzle = (
F, X, I, E,
A, M, L, O,
E, W, B, X,
A, S, T, U
);
my $minimumWordLength = 3;
my $maximumPrefixLength = 3; # I tried four and it slowed down.
# Slurp the word list.
my $wordlistFile = "/usr/share/dict/words";
my @words = split(/\n/, uc(readFile($wordlistFile)));
print "Words loaded from word list: " . scalar @words . "\n";
print "Word file load time: " . (time - $startTime) . "\n";
my $postLoad = time;
# Define the legal transitions from one letter position to another.
# Positions are numbered 0-15.
# 0 1 2 3
# 4 5 6 7
# 8 9 10 11
# 12 13 14 15
my %transitions = (
-1 => [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
0 => [1,4,5],
1 => [0,2,4,5,6],
2 => [1,3,5,6,7],
3 => [2,6,7],
4 => [0,1,5,8,9],
5 => [0,1,2,4,6,8,9,10],
6 => [1,2,3,5,7,9,10,11],
7 => [2,3,6,10,11],
8 => [4,5,9,12,13],
9 => [4,5,6,8,10,12,13,14],
10 => [5,6,7,9,11,13,14,15],
11 => [6,7,10,14,15],
12 => [8,9,13],
13 => [8,9,10,12,14],
14 => [9,10,11,13,15],
15 => [10,11,14]
);
# Convert the transition matrix into a hash for easy access.
my %legalTransitions = ();
foreach my $start (keys %transitions) {
my $legalRef = $transitions{$start};
foreach my $stop (@$legalRef) {
my $index = ($start + 1) * (scalar @puzzle) + ($stop + 1);
$legalTransitions{$index} = 1;
}
}
my %prefixesInPuzzle = findAllPrefixes($maximumPrefixLength);
print "Find prefixes time: " . (time - $postLoad) . "\n";
my $postPrefix = time;
my @wordsFoundInPuzzle = findWordsInPuzzle(@words);
print "Find words in puzzle time: " . (time - $postPrefix) . "\n";
print "Unique prefixes found: " . (scalar keys %prefixesInPuzzle) . "\n";
print "Words found (" . (scalar @wordsFoundInPuzzle) . ") :\n " . join("\n ", @wordsFoundInPuzzle) . "\n";
print "Total Elapsed time: " . (time - $startTime) . "\n";
###########################################
sub readFile($) {
my ($filename) = @_;
my $contents;
if (-e $filename) {
# This is magic: it opens and reads a file into a scalar in one line of code.
# See http://www.perl.com/pub/a/2003/11/21/slurp.html
$contents = do { local( @ARGV, $/ ) = $filename ; <> } ;
}
else {
$contents = '';
}
return $contents;
}
# Is it legal to move from the first position to the second? They must be adjacent.
sub isLegalTransition($$) {
my ($pos1,$pos2) = @_;
my $index = ($pos1 + 1) * (scalar @puzzle) + ($pos2 + 1);
return $legalTransitions{$index};
}
# Find all prefixes where $minimumWordLength <= length <= $maxPrefixLength
#
# $maxPrefixLength ... Maximum length of prefix we will store. Three gives best performance.
sub findAllPrefixes($) {
my ($maxPrefixLength) = @_;
my %prefixes = ();
my $puzzleSize = scalar @puzzle;
# Every possible N-letter combination of the letters in the puzzle
# can be represented as an integer, though many of those combinations
# involve illegal transitions, duplicated letters, etc.
# Iterate through all those possibilities and eliminate the illegal ones.
my $maxIndex = $puzzleSize ** $maxPrefixLength;
for (my $i = 0; $i < $maxIndex; $i++) {
my @path;
my $remainder = $i;
my $prevPosition = -1;
my $prefix = '';
my %usedPositions = ();
for (my $prefixLength = 1; $prefixLength <= $maxPrefixLength; $prefixLength++) {
my $position = $remainder % $puzzleSize;
# Is this a valid step?
# a. Is the transition legal (to an adjacent square)?
if (! isLegalTransition($prevPosition, $position)) {
last;
}
# b. Have we repeated a square?
if ($usedPositions{$position}) {
last;
}
else {
$usedPositions{$position} = 1;
}
# Record this prefix if length >= $minimumWordLength.
$prefix .= $puzzle[$position];
if ($prefixLength >= $minimumWordLength) {
$prefixes{$prefix} = 1;
}
push @path, $position;
$remainder -= $position;
$remainder /= $puzzleSize;
$prevPosition = $position;
} # end inner for
} # end outer for
return %prefixes;
}
# Loop through all words in dictionary, looking for ones that are in the puzzle.
sub findWordsInPuzzle(@) {
my @allWords = @_;
my @wordsFound = ();
my $puzzleSize = scalar @puzzle;
WORD: foreach my $word (@allWords) {
my $wordLength = length($word);
if ($wordLength > $puzzleSize || $wordLength < $minimumWordLength) {
# Reject word as too short or too long.
}
elsif ($wordLength <= $maximumPrefixLength ) {
# Word should be in the prefix hash.
if ($prefixesInPuzzle{$word}) {
push @wordsFound, $word;
}
}
else {
# Scan through the word using a window of length $maximumPrefixLength, looking for any strings not in our prefix list.
# If any are found that are not in the list, this word is not possible.
# If no non-matches are found, we have more work to do.
my $limit = $wordLength - $maximumPrefixLength + 1;
for (my $startIndex = 0; $startIndex < $limit; $startIndex ++) {
if (! $prefixesInPuzzle{substr($word, $startIndex, $maximumPrefixLength)}) {
next WORD;
}
}
if (isWordTraceable($word)) {
# Additional test necessary: see if we can form this word by following legal transitions
push @wordsFound, $word;
}
}
}
return @wordsFound;
}
# Is it possible to trace out the word using only legal transitions?
sub isWordTraceable($) {
my $word = shift;
return traverse([split(//, $word)], [-1]); # Start at special square -1, which may transition to any square in the puzzle.
}
# Recursively look for a path through the puzzle that matches the word.
sub traverse($$) {
my ($lettersRef, $pathRef) = @_;
my $index = scalar @$pathRef - 1;
my $position = $pathRef->[$index];
my $letter = $lettersRef->[$index];
my $branchesRef = $transitions{$position};
BRANCH: foreach my $branch (@$branchesRef) {
if ($puzzle[$branch] eq $letter) {
# Have we used this position yet?
foreach my $usedBranch (@$pathRef) {
if ($usedBranch == $branch) {
next BRANCH;
}
}
if (scalar @$lettersRef == $index + 1) {
return 1; # End of word and success.
}
push @$pathRef, $branch;
if (traverse($lettersRef, $pathRef)) {
return 1; # Recursive success.
}
else {
pop @$pathRef;
}
}
}
return 0; # No path found. Failed.
}
I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
It works fine for me using a CSS grid. Initially fix the container and then give overflow-y: auto;
for the centre content which has to get scrolled i.e other than header and footer.
.container{
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
display: grid;
grid-template-rows: 5em auto 3em;
}
header{
grid-row: 1;
background-color: rgb(148, 142, 142);
justify-self: center;
align-self: center;
width: 100%;
}
.body{
grid-row: 2;
overflow-y: auto;
}
footer{
grid-row: 3;
background: rgb(110, 112, 112);
}
_x000D_
<div class="container">
<header><h1>Header</h1></header>
<div class="body">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<footer><h3>Footer</h3></footer>
</div>
_x000D_
***LOGIN script that doesnt link to a database or external file. Good for a global password -
Place on Login form page - place this at the top of the login page - above everything else***
<?php
if(isset($_POST['Login'])){
if(strtolower($_POST["username"])=="ChangeThis" && $_POST["password"]=="ChangeThis"){
session_start();
$_SESSION['logged_in'] = TRUE;
header("Location: ./YourPageAfterLogin.php");
}else {
$error= "Login failed !";
}
}
//print"version3<br>";
//print"username=".$_POST["username"]."<br>";
//print"password=".$_POST["username"];
?>
*Login on following pages - Place this at the top of every page that needs to be protected by login. this checks the session and if a user name and password has *
<?php
session_start();
if(!isset($_SESSION['logged_in']) OR $_SESSION['logged_in'] != TRUE){
header("Location: ./YourLoginPage.php");
}
?>
The static calls to withdraw and deposit are your problem. account.withdraw(balance, 2500); This line can't work , since "balance" is an instance variable of Account. The code doesn't make much sense anyway, wouldn't withdraw/deposit be encapsulated inside the Account object itself? so the withdraw should be more like
public void withdraw(double withdrawAmount)
{
balance -= withdrawAmount;
}
Of course depending on your problem you could do additional validation here to prevent negative balance etc.
Using Post call, worked for me.
RestClient restClient = new RestClient();
RestRequest request = new RestRequest();
request.AddQueryParameter("client_id", "value");
request.AddQueryParameter("client_secret", "value");
request.AddQueryParameter("grant_type", "refresh_token");
request.AddQueryParameter("refresh_token", "value");
restClient.BaseUrl = new System.Uri("https://oauth2.googleapis.com/token");
restClient.Post(request);
A .o object file file (also .obj on Windows) contains compiled object code (that is, machine code produced by your C or C++ compiler), together with the names of the functions and other objects the file contains. Object files are processed by the linker to produce the final executable. If your build process has not produced these files, there is probably something wrong with your makefile/project files.
I went through a similar issue. If you consider your "YeagerTechResources.Resources", it means that your Resources.resx is at the root folder of your project.
Be careful to include the full path eg : "project\subfolder(s)\file[.resx]" to the ResourceManager constructor.
Remember that when you write:
MyArray = Range("A1:A5000")
you are really writing
MyArray = Range("A1:A5000").Value
You can also use names:
MyArray = Names("MyWSTable").RefersToRange.Value
But Value is not the only property of Range. I have used:
MyArray = Range("A1:A5000").NumberFormat
I doubt
MyArray = Range("A1:A5000").Font
would work but I would expect
MyArray = Range("A1:A5000").Font.Bold
to work.
I do not know what formats you want to copy so you will have to try.
However, I must add that when you copy and paste a large range, it is not as much slower than doing it via an array as we all thought.
Post Edit information
Having posted the above I tried by own advice. My experiments with copying Font.Color and Font.Bold to an array have failed.
Of the following statements, the second would fail with a type mismatch:
ValueArray = .Range("A1:T5000").Value
ColourArray = .Range("A1:T5000").Font.Color
ValueArray must be of type variant. I tried both variant and long for ColourArray without success.
I filled ColourArray with values and tried the following statement:
.Range("A1:T5000").Font.Color = ColourArray
The entire range would be coloured according to the first element of ColourArray and then Excel looped consuming about 45% of the processor time until I terminated it with the Task Manager.
There is a time penalty associated with switching between worksheets but recent questions about macro duration have caused everyone to review our belief that working via arrays was substantially quicker.
I constructed an experiment that broadly reflects your requirement. I filled worksheet Time1 with 5000 rows of 20 cells which were selectively formatted as: bold, italic, underline, subscript, bordered, red, green, blue, brown, yellow and gray-80%.
With version 1, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" using copy.
With version 2, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the value and the colour via an array.
With version 3, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the formula and the colour via an array.
Version 1 took an average of 12.43 seconds, version 2 took an average of 1.47 seconds while version 3 took an average of 1.83 seconds. Version 1 copied formulae and all formatting, version 2 copied values and colour while version 3 copied formulae and colour. With versions 1 and 2 you could add bold and italic, say, and still have some time in hand. However, I am not sure it would be worth the bother given that copying 21,300 values only takes 12 seconds.
** Code for Version 1**
I do not think this code includes anything that needs an explanation. Respond with a comment if I am wrong and I will fix.
Sub SelectionCopyAndPaste()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
Sheets("Time1").Cells(RowSrcCrnt, ColSrcCrnt).Copy _
Destination:=Sheets("Time2").Cells(RowDestCrnt, ColDestCrnt)
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
NumSelect = NumSelect + 7
Loop
Debug.Print Timer - StartTime
' Average 12.43 secs
Application.Calculation = xlCalculationAutomatic
End Sub
** Code for Versions 2 and 3**
The User type definition must be placed before any subroutine in the module. The code works through the source worksheet copying values or formulae and colours to the next element of the array. Once selection has been completed, it copies the collected information to the destination worksheet. This avoids switching between worksheets more than is essential.
Type ValueDtl
Value As String
Colour As Long
End Type
Sub SelectionViaArray()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim InxVLCrnt As Integer
Dim InxVLCrntMax As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Dim ValueList() As ValueDtl
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' I have sized the array to more than I expect to require because ReDim
' Preserve is expensive. However, I will resize if I fill the array.
' For my experiment I know exactly how many elements I need but that
' might not be true for you.
ReDim ValueList(1 To 25000)
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
InxVLCrntMax = 0 ' Last used element in ValueList.
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
With Sheets("Time1")
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
InxVLCrntMax = InxVLCrntMax + 1
If InxVLCrntMax > UBound(ValueList) Then
' Resize array if it has been filled
ReDim Preserve ValueList(1 To UBound(ValueList) + 1000)
End If
With .Cells(RowSrcCrnt, ColSrcCrnt)
ValueList(InxVLCrntMax).Value = .Value ' Version 2
ValueList(InxVLCrntMax).Value = .Formula ' Version 3
ValueList(InxVLCrntMax).Colour = .Font.Color
End With
NumSelect = NumSelect + 7
Loop
End With
With Sheets("Time2")
For InxVLCrnt = 1 To InxVLCrntMax
With .Cells(RowDestCrnt, ColDestCrnt)
.Value = ValueList(InxVLCrnt).Value ' Version 2
.Formula = ValueList(InxVLCrnt).Value ' Version 3
.Font.Color = ValueList(InxVLCrnt).Colour
End With
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
Next
End With
Debug.Print Timer - StartTime
' Version 2 average 1.47 secs
' Version 3 average 1.83 secs
Application.Calculation = xlCalculationAutomatic
End Sub
Note: The title of this question used to be something like "How to printf in python?"
Since people may come here looking for it based on the title, Python also supports printf-style substitution:
>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
... print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three
And, you can handily multiply string values:
>>> print "." * 10
..........
You can catch it like any other exception:
try {
foo();
}
catch (const std::bad_alloc&) {
return -1;
}
Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.
In general you cannot, and should not try, to respond to this error. bad_alloc
indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.
Worse, modern operating systems often over-allocate: on such systems, malloc
and new
can return a valid pointer even if there is not enough free memory left – std::bad_alloc
will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).
The only thing you could do when catching std::bad_alloc
is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).
In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:
It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1
OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:
lru_cache<widget> widget_cache;
double perform_operation(int widget_id) {
std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
if (not maybe_widget) {
maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
}
return maybe_widget->frobnicate();
}
…
for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
try {
return perform_operation(widget_id);
} catch (std::bad_alloc const&) {
if (widget_cache.empty()) throw; // memory error elsewhere.
widget_cache.remove_oldest();
}
}
// Handle too many failed attempts here.
But even here, using std::set_new_handler
instead of handling std::bad_alloc
provides the same benefit and would be much simpler.
1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.
new
in c++?The usual notion is that if new
operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc
.
However, something more happens even before a bad_alloc
exception is thrown:
C++03 Section 3.7.4.1.3: says
An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.
Consider the following code sample:
#include <iostream>
#include <cstdlib>
// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
std::cerr << "Unable to satisfy request for memory\n";
std::abort();
}
int main()
{
//set the new_handler
std::set_new_handler(outOfMemHandler);
//Request huge memory size, that will cause ::operator new to fail
int *pBigDataArray = new int[100000000L];
return 0;
}
In the above example, operator new
(most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler()
will be called, and the program will abort after issuing an error message.
As seen here the default behavior of new
operator when unable to fulfill a memory request, is to call the new-handler
function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort()
, outOfMemHandler()
would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.
new_handler
and set_new_handler
?new_handler
is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler
is a function that takes and returns a new_handler
.
Something like:
typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();
set_new_handler's parameter is a pointer to the function operator new
should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.
Given the behavior of new
a well designed user program should handle out of memory conditions by providing a proper new_handler
which does one of the following:
Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.
Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler
). The next time operator new calls the new-handler function, it will get the one most recently installed.
(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)
Uninstall the new-handler: This is done by passing a null pointer to set_new_handler
. With no new-handler installed, operator new
will throw an exception ((convertible to) std::bad_alloc
) when memory allocation is unsuccessful.
Throw an exception convertible to std::bad_alloc
. Such exceptions are not be caught by operator new
, but will propagate to the site originating the request for memory.
Not return: By calling abort
or exit
.
For those looking for an SCSS mixin instead, including woff2:
@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
@font-face {
font-family: $family;
@if $svg == '' {
// with OTF without SVG and EOT
src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
} @else {
// traditional src inclusions
src: url('#{$path}#{$type}.eot');
src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
}
font-weight: $weight;
font-style: $style;
}
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);
$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
font-family: Inter;
font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
font-family: AmaticSC;
font-weight: 700; // default font is loaded
}
The $type
parameter is useful for stacking related families with different weights.
The @if
is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.
If you get a can't resolve error, remember to double check your fonts directory ($dir
).
I had this similar issue. I wanted to set a class after looking at multiple expressions. ngClass can evaluate a method inside the component code and tell you what to do.
So inside an *ngFor:
<div [ngClass]="{'shrink': shouldShrink(a.category1, a.category2), 'showAll': section == 'allwork' }">{{a.listing}}</div>
And inside the component:
section = 'allwork';
shouldShrink(cat1, cat2) {
return this.section === cat1 || this.section === cat2 ? false : true;
}
Here I need to calculate if i should shrink a div based on if a 2 different categories have matched what the selected category is. And it works. So from there you can computer a true/false for the [ngClass] based on what your method returns given the inputs.
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.
If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:
Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()
You have to add the android:screenOrientation="portrait"
directive in your AndroidManifest.xml
. This is to be done in your <activity>
tag.
In addition, the Android Developers guide states that :
[...] you should also explicitly declare that your application requires either portrait or landscape orientation with the element. For example,
<uses-feature android:name="android.hardware.screen.portrait" />
.
foo
is used as a place-holder name, usually in example code to signify that the object being named, or the choice of name, is not part of the crux of the example. foo
is often followed by bar
, baz
, and even bundy
, if more than one such name is needed. Wikipedia calls these names Metasyntactic Variables. Python programmers supposedly use spam
, eggs
, ham
, instead of foo
, etc.
There are good uses of foo in SA.
I have also seen foo
used when the programmer can't think of a meaningful name (as a substitute for tmp
, say), but I consider that to be a misuse of foo
.
This is a DependencyObject for attaching to a ComboBox.
It records the currently selected item when the dropdown is opened, and then fires SelectionChanged event if the same index is still selected when the dropdown is closed. It may need to be modified for it to work with Keyboard selection.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Web.UI.WebControls;
namespace MyNamespace
{
public class ComboAlwaysFireSelection : DependencyObject
{
public static readonly DependencyProperty ActiveProperty = DependencyProperty.RegisterAttached(
"Active",
typeof(bool),
typeof(ComboAlwaysFireSelection),
new PropertyMetadata(false, ActivePropertyChanged));
private static void ActivePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var element = d as ComboBox;
if (element == null)
return;
if ((e.NewValue as bool?).GetValueOrDefault(false))
{
element.DropDownClosed += ElementOnDropDownClosed;
element.DropDownOpened += ElementOnDropDownOpened;
}
else
{
element.DropDownClosed -= ElementOnDropDownClosed;
element.DropDownOpened -= ElementOnDropDownOpened;
}
}
private static void ElementOnDropDownOpened(object sender, EventArgs eventArgs)
{
_selectedIndex = ((ComboBox) sender).SelectedIndex;
}
private static int _selectedIndex;
private static void ElementOnDropDownClosed(object sender, EventArgs eventArgs)
{
var comboBox = ((ComboBox) sender);
if (comboBox.SelectedIndex == _selectedIndex)
{
comboBox.RaiseEvent(new SelectionChangedEventArgs(Selector.SelectionChangedEvent, new ListItemCollection(), new ListItemCollection()));
}
}
[AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)]
[AttachedPropertyBrowsableForType(typeof(ComboBox))]
public static bool GetActive(DependencyObject @object)
{
return (bool)@object.GetValue(ActiveProperty);
}
public static void SetActive(DependencyObject @object, bool value)
{
@object.SetValue(ActiveProperty, value);
}
}
}
and add your namespace prefix to make it accessible.
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ut="clr-namespace:MyNamespace" ></UserControl>
and then you need to attach it like so
<ComboBox ut:ComboAlwaysFireSelection.Active="True" />
Since you mention Underscore:
Assuming f
is the function you want to call:
_.each([1,2,3], function (n) { _.times(n, f) });
will do the trick. For example, with f = function (x) { console.log(x); }
, you will get on your console:
0 0 1 0 1 2
If you are going to be changing a String many times, then it is usually more efficient to use a StringBuilder (but measure your performance to find out):
String str = "The rain in Spain falls mainly on the plain";
StringBuilder sb = new StringBuilder(str);
// do your replacing in sb - although you'll find this trickier than simply using String
String newStr = sb.toString();
Every time you do a replace on a String, a new String object is created, because Strings are immutable. StringBuilder is mutable, that is, it can be changed as much as you want.
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
You could use PhoneGap.
This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView
as detailed in @Enigma's answer.
Feel free to use this how ever you like.
/*
* The extendStrArray() method will takes a number "n" and
* a String Array "strArray" and will return a new array
* containing 'n' new positions. This new returned array
* can then be assigned to a new array, or the existing
* one to "extend" it, it contain the old value in the
* new array with the addition n empty positions.
*/
private String[] extendStrArray(int n, String[] strArray){
String[] old_str_array = strArray;
String[] new_str_array = new String[(old_str_array.length + n)];
for(int i = 0; i < old_str_array.length; i++ ){
new_str_array[i] = old_str_array[i];
}//end for loop
return new_str_array;
}//end extendStrArray()
Basically I would use it like this:
String[] students = {"Tom", "Jeff", "Ashley", "Mary"};
// 4 new students enter the class so we need to extend the string array
students = extendStrArray(4, students); //this will effectively add 4 new empty positions to the "students" array.
The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}
Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport
struct over time.
I tried the below and it worked well,
Install Dimensions Data Model and OLE DB Access
and follow the below steps in excel
Data->Get External Data ->From Other sources -> From Data Connection Wizard -> Other/Advanced-> SPSS MR DM-2 OLE DB Provider-> Metadata type as SPSS File(SAV)-> SPSS data file in Metadata Location->Finish
Look at your message
So first thing it relate to permission
open(/var/lib/php/session/sess_isu2r2bqudeosqvpoo8a67oj02, O_RDWR) failed: Permission denied (13) in Unknown on line 0
you have to check file permission
change mode this /var/lib/php/session/
Second thing it relate to session.save_path
Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0
in php.ini
[Session]
; Handler used to store/retrieve data.
session.save_handler = files
; Argument passed to save_handler. In the case of files, this is the path
; where data files are stored. Note: Windows users have to change this
; variable in order to use PHP's session functions.
;
; As of PHP 4.0.1, you can define the path as:
;
; session.save_path = "N;/path"
;
; where N is an integer. Instead of storing all the session files in
; /path, what this will do is use subdirectories N-levels deep, and
; store the session data in those directories. This is useful if you
; or your OS have problems with lots of files in one directory, and is
; a more efficient layout for servers that handle lots of sessions.
;
; NOTE 1: PHP will not create this directory structure automatically.
; You can use the script in the ext/session dir for that purpose.
; NOTE 2: See the section on garbage collection below if you choose to
; use subdirectories for session storage
;
session.save_path = /tmp/ <= HERE YOU HAVE TO MAKE SURE
; Whether to use cookies.
session.use_cookies = 1
Java is not finding where your compiled class file (HelloWorld.class) is. It uses the directories and JAR-files in the CLASSPATH
environment variable for searching if no -cp
or -classpath
option is given when running java.exe.
You don't need the rt.jar in the CLASSPATH
, these was only needed for older versions of Java. You can leave it undefined and the current working directory will be used, or just add .
(a single point), separated by ';', to the CLASSPATH
variable to indicate the current directory:
CLASSPATH: .;C:\...\some.jar
Alternatively you can use the -cp
or -classpath
option:
java -cp . HelloWorld
And, as Andreas wrote, JAVA_HOME
is not needed by Java, just for some third-party tools like ant (but should point to the correct location).
we can use \b as a word boundary and then; \b\d+\b
You can get the "computed" styles of any element.
IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".
You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).
That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.
The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value)
Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:
<div style="width:50%">....</div>
Your variable energies
probably has the wrong shape:
>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'
And that's what happens if you read columnar data using your approach:
>>> data
array([[ 1., 2., 3.],
[ 3., 4., 5.],
[ 5., 6., 7.],
[ 8., 9., 10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
[ 3.],
[ 5.],
[ 8.]])
Probably you can simply use
>>> data[:,0]
array([ 1., 3., 5., 8.])
instead.
(P.S. Your code looks like it's undecided about whether it's data
or elementdata
. I've assumed it's simply a typo.)
There is no any problem to write multiple lines of execution withing a single try catch block like below
try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}
The moment any execption occure either in install_engine
or install_break
function the control will be passed to catch function.
One more recommendation is to eat your exception properly. Which means instead of writing die('Message')
it is always advisable to have exception process properly. You may think of using die()
function in error handling but not in exception handling.
When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:
try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}
try{
install_body();
paint_body();
install_interiour();
}
catch(Exception $e){
throw new exception('Body Makeover faield')
}
You have to open database connection, not workbench file with schema. It looks a bit wierd, but it makes sense when you realize what you are editing.
So, go to home tab, double click database connection (create it if you don't have it yet) and have fun.
with the intl extension in PHP 5.3+, you can use the NumberFormatter class:
$amount = '12345.67';
$formatter = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
echo 'UK: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo 'DE: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
which prints :
UK: €12,345.67
DE: 12.345,67 €