There's no need for a parent POM.
You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.
To do it on the build server, just pass to the mvn
command:
-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases
See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.
It's also possible to set this in your settings.xml
.
Just create a profile there which is enabled and contains the property.
Example settings.xml:
<settings>
[...]
<profiles>
<profile>
<id>nexus</id>
<properties>
<altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
<altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>
Make sure that credentials for "snapshots" and "releases" are in the <servers>
section of your settings.xml
The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message
Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter
To fix this, you can enforce a newer version of the plug-in:
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8</version>
</plugin>
</plugins>
</pluginManagement>
</build>
Just to create a separate answer. The answer is actually found in a comment for the accepted answer.
Try changing the version of your artefact to end with -SNAPSHOT
.
Sonatype Nexus and Apache Maven are two pieces of software that often work together but they do very different parts of the job. Nexus provides a repository while Maven uses a repository to build software.
Here's a quote from "What is Nexus?":
Nexus manages software "artifacts" required for development. If you develop software, your builds can download dependencies from Nexus and can publish artifacts to Nexus creating a new way to share artifacts within an organization. While Central repository has always served as a great convenience for developers you shouldn't be hitting it directly. You should be proxying Central with Nexus and maintaining your own repositories to ensure stability within your organization. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.
And here is a quote from "Maven and Nexus Pro, Made for Each Other" explaining how Maven uses repositories:
Maven leverages the concept of a repository by retrieving the artifacts necessary to build an application and deploying the result of the build process into a repository. Maven uses the concept of structured repositories so components can be retrieved to support the build. These components or dependencies include libraries, frameworks, containers, etc. Maven can identify components in repositories, understand their dependencies, retrieve all that are needed for a successful build, and deploy its output back to repositories when the build is complete.
So, when you want to use both you will have a repository managed by Nexus and Maven will access this repository.
for those who need it in Java, using apache httpcomponents 4.0:
public class PostFile {
protected HttpPost httppost ;
protected MultipartEntity mpEntity;
protected File filePath;
public PostFile(final String fullUrl, final String filePath){
this.httppost = new HttpPost(fullUrl);
this.filePath = new File(filePath);
this.mpEntity = new MultipartEntity();
}
public void authenticate(String user, String password){
String encoding = new String(Base64.encodeBase64((user+":"+password).getBytes()));
httppost.setHeader("Authorization", "Basic " + encoding);
}
private void addParts() throws UnsupportedEncodingException{
mpEntity.addPart("r", new StringBody("repository id"));
mpEntity.addPart("g", new StringBody("group id"));
mpEntity.addPart("a", new StringBody("artifact id"));
mpEntity.addPart("v", new StringBody("version"));
mpEntity.addPart("p", new StringBody("packaging"));
mpEntity.addPart("e", new StringBody("extension"));
mpEntity.addPart("file", new FileBody(this.filePath));
}
public String post() throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
addParts();
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println(httppost.getEntity().getContentLength());
HttpEntity resEntity = response.getEntity();
String statusLine = response.getStatusLine().toString();
System.out.println(statusLine);
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
return statusLine;
}
}
You can upload artifacts via their native publishing capabilities (e.g. maven deploy, npm publish).
You can also upload artifacts to "raw" repositories via a simple curl request, e.g.
curl --fail -u admin:admin123 --upload-file foo.jar 'http://my-nexus-server.com:8081/repository/my-raw-repo/'
The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.
There is a Win32 (C++) function in shlwapi.dll that does exactly what you want: PathRelativePathTo()
I'm not aware of any way to access this from .NET other than to P/Invoke it, though.
I made some changes to Dan's answer so that I could add borders to multiple edges with one command:
infoView.addBorder(toEdges: [.left, .bottom, .right], color: borderColor, thickness: 1)
Here's the full code:
extension UIView {
func addBorder(toEdges edges: UIRectEdge, color: UIColor, thickness: CGFloat) {
func addBorder(toEdge edges: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
switch edges {
case .top:
border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
case .bottom:
border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
case .left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
case .right:
border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
default:
break
}
layer.addSublayer(border)
}
if edges.contains(.top) || edges.contains(.all) {
addBorder(toEdge: .top, color: color, thickness: thickness)
}
if edges.contains(.bottom) || edges.contains(.all) {
addBorder(toEdge: .bottom, color: color, thickness: thickness)
}
if edges.contains(.left) || edges.contains(.all) {
addBorder(toEdge: .left, color: color, thickness: thickness)
}
if edges.contains(.right) || edges.contains(.all) {
addBorder(toEdge: .right, color: color, thickness: thickness)
}
}
}
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
Key codes can differ between browsers, so you may need to check for more than just 115.
$('.testimonal').each(function(i,v){
if (condition) {
doSomething();
}
});
I got this error when I tried to call a webservice using "localhost". I fixed it by using the actual IP instead (192.168...)
set a WebViewClient
to your WebView, start your progress dialog on you onCreate()
method an dismiss it when the page has finished loading in onPageFinished(WebView view, String url)
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Main extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.webview = (WebView)findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(Main.this, "WebView Example", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl("http://www.google.com");
}
}
your main.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView android:id="@string/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
This will direct everything from the old host to the root of the new host:
RewriteEngine on
RewriteCond %{http_host} ^www.old.com [NC,OR]
RewriteCond %{http_host} ^old.com [NC]
RewriteRule ^(.*)$ http://www.thenewdomain.org/ [R=301,NC,L]
If you are worrying about Case sensitive change the case and compare the string.
if (stringvalue.toLocaleLowerCase().indexOf("mytexttocompare")!=-1)
{
alert("found");
}
I had an issue with github missing out on some case sensitive changes to folders. I needed to keep migration history so an example of how I changed "basicApp" folder in github to "basicapp"
$ git ls-files
$ git mv basicApp basicapp_temp
$ git add .
$ git commit -am "temporary change"
$ git push origin master
$ git mv basicapp_temp basicapp
$ git add .
$ git commit -am "change to desired name"
$ git push origin master
PS: git ls-files
will show you how github sees your folder name
Here's a a couple of useful link that I found when I started with JNI
http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html
concerning your problem you can use this
JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)
{
const char *nativeString = env->GetStringUTFChars(javaString, 0);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
}
I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.
Solution:
First of all find the application which is causing heavy memory usage.
You can find this in the Details section of the Task Manager.
Next.
If this solution works for you please add a comment so that I can know.
Use this gem: https://rubygems.org/gems/active_record_importer
class Moulding < ActiveRecord::Base
acts_as_importable
end
Then you may now use:
Moulding.import!(file: File.open(PATH_TO_FILE))
Just be sure to that your headers match the column names of your table
It's working fine try this.Link
UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
[top presentViewController:secondView animated:YES completion: nil];
https://github.com/rackt/react-router/blob/e7c6f3d848e55dda11595447928e843d39bed0eb/examples/query-params/app.js#L4
Router
is also one of the properties of react-router
.
So change your modules require code like that:
var reactRouter = require('react-router')
var Router = reactRouter.Router
var Route = reactRouter.Route
var Link = reactRouter.Link
If you want to use ES6 syntax the link use(import
), use babel as helper.
BTW, to make your code works, we can add {this.props.children}
in the App
,
like
render() {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/about">About</Link></li>
</ul>
{this.props.children}
</div>
)
}
Doing the same in declarative pipeline syntax, below are few examples:
stage('master-branch-stuff') {
when {
branch 'master'
}
steps {
echo 'run this stage - ony if the branch = master branch'
}
}
stage('feature-branch-stuff') {
when {
branch 'feature/*'
}
steps {
echo 'run this stage - only if the branch name started with feature/'
}
}
stage('expression-branch') {
when {
expression {
return env.BRANCH_NAME != 'master';
}
}
steps {
echo 'run this stage - when branch is not equal to master'
}
}
stage('env-specific-stuff') {
when {
environment name: 'NAME', value: 'this'
}
steps {
echo 'run this stage - only if the env name and value matches'
}
}
More effective ways coming up -
https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at -
https://jenkins.io/doc/book/pipeline/syntax/#when
The directive beforeAgent true
can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:
when { beforeAgent true; expression { return isStageConfigured(config) } }
Release post and docs
UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative
equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.
changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.
buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.
tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.
If the new branch contains edits that are different from the current branch for that particular changed file, then it will not allow you to switch branches until the change is committed or stashed. If the changed file is the same on both branches (that is, the committed version of that file), then you can switch freely.
Example:
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "adding file.txt"
$ git checkout -b experiment
$ echo 'goodbye world' >> file.txt
$ git add file.txt
$ git commit -m "added text"
# experiment now contains changes that master doesn't have
# any future changes to this file will keep you from changing branches
# until the changes are stashed or committed
$ echo "and we're back" >> file.txt # making additional changes
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
file.txt
Please, commit your changes or stash them before you can switch branches.
Aborting
This goes for untracked files as well as tracked files. Here's an example for an untracked file.
Example:
$ git checkout -b experimental # creates new branch 'experimental'
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "added file.txt"
$ git checkout master # master does not have file.txt
$ echo 'goodbye world' > file.txt
$ git checkout experimental
error: The following untracked working tree files would be overwritten by checkout:
file.txt
Please move or remove them before you can switch branches.
Aborting
A good example of why you WOULD want to move between branches while making changes would be if you were performing some experiments on master, wanted to commit them, but not to master just yet...
$ echo 'experimental change' >> file.txt # change to existing tracked file
# I want to save these, but not on master
$ git checkout -b experiment
M file.txt
Switched to branch 'experiment'
$ git add file.txt
$ git commit -m "possible modification for file.txt"
I use outline a css 2 property that simply works. Check this out, is simple and even easy to animate:
.double-border {_x000D_
display: block;_x000D_
clear: both;_x000D_
background: red;_x000D_
border: 5px solid yellow;_x000D_
outline: 5px solid blue;_x000D_
transition: 0.7s all ease-in;_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
}_x000D_
.double-border:hover {_x000D_
background: yellow;_x000D_
outline-color: red;_x000D_
border-color: blue;_x000D_
}
_x000D_
<div class="double-border"></div>
_x000D_
This help
target will only print targets which have ##
followed by a description. This allows for documenting both public and private targets. Using the .DEFAULT_GOAL
makes the help more discoverable.
Only sed
, xargs
and printf
used which are pretty common.
Using the < $(MAKEFILE_LIST)
allows for the makefile to be called something other than Makefile
for instance Makefile.github
You can customize the output to suit your preference in the printf
. This example is set up to match the OP's request for rake
style output
When cutting and pasting the below make file, don't forget to change the 4 spaces indentation to tabs.
# vim:ft=make
# Makefile
.DEFAULT_GOAL := help
.PHONY: test help
help: ## these help instructions
@sed -rn 's/^([a-zA-Z_-]+):.*?## (.*)$$/"\1" "\2"/p' < $(MAKEFILE_LIST) | xargs printf "make %-20s# %s\n"
lint: ## style, bug and quality checker
pylint src test
private: # for internal usage only
@true
test: private ## run pytest with coverage
pytest --cov test
Here is the output from the Makefile
above. Notice the private
target doesn't get output because it only has a single #
for it's comment.
$ make
make help # these help instructions
make lint # style, bug and quality checker
make test # run pytest with coverage
<span class="btn-pTool">
<a class="btn-pToolName" href="#"></a>
</span>
Try to add display:block
to .btn-pTool
, and give it a width and height.
Also in your code both tbn-pTool and btn-pToolName have no text content, so that may result in them not being displayed at all.
You can try to force come content in them this way
.btn-pTool, .btn-pToolName {
content: " ";
}
I do not believe there is a way to do this strictly with CSS. The reason is your "important" qualifier to the question: forcing the parent element to expand with the contents of its child.
My guess is that you will have to use some bits of JavaScript to find the height of the child, and make adjustments.
So, with this HTML:
<div class="parentElement">
<div class="childElement">
...Some Contents...
</div>
</div>
This CSS:
.parentElement { position:relative; width:960px; } .childElement { position:absolute; top:50%; left:50%; }
This jQuery might be useful:
$('.childElement').each(function(){
// determine the real dimensions of the element: http://api.jquery.com/outerWidth/
var x = $(this).outerWidth();
var y = $(this).outerHeight();
// adjust parent dimensions to fit child
if($(this).parent().height() < y) {
$(this).parent().css({height: y + 'px'});
}
// offset the child element using negative margins to "center" in both axes
$(this).css({marginTop: 0-(y/2)+'px', marginLeft: 0-(x/2)+'px'});
});
Remember to load the jQ properly, either in the body below the affected elements, or in the head inside of $(document).ready(...)
.
I had the very same error message. Finally I figured out I misspelled the name of the table in the command:
ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES country (id);
versus
ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES countries (id);
I wonder why on earth MySQL cannot tell such a table does not exist...
You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)
$content = simplexml_load_string(
'<content><![CDATA[Hello, world!]]></content>'
);
echo (string) $content;
// or with parent element:
$foo = simplexml_load_string(
'<foo><content><![CDATA[Hello, world!]]></content></foo>'
);
echo (string) $foo->content;
You might have better luck with LIBXML_NOCDATA
:
$content = simplexml_load_string(
'<content><![CDATA[Hello, world!]]></content>'
, null
, LIBXML_NOCDATA
);
if you are using httpd/apache, you can add a file something like ws.conf and add this code to it. Also, this solution can proxy something like this "http://localhost:6001/socket.io" to just this "http://localhost/socket.io"
<VirtualHost *:80>
RewriteEngine on
#redirect WebSocket
RewriteCond %{REQUEST_URI} ^/socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /(.*) ws://localhost:6001/$1 [P,L]
ProxyPass /socket.io http://localhost:6001/socket.io
ProxyPassReverse /socket.io http://localhost:6001/socket.io
</VirtualHost>
Yes you can pass variable no. of arguments to a function. You can use apply
to achieve this.
E.g.:
var arr = ["Hi","How","are","you"];
function applyTest(){
var arg = arguments.length;
console.log(arg);
}
applyTest.apply(null,arr);
Here is a minor improvement to CMS's solution:
if(!String.prototype.startsWith){
String.prototype.startsWith = function (str) {
return !this.indexOf(str);
}
}
"Hello World!".startsWith("He"); // true
var data = "Hello world";
var input = 'He';
data.startsWith(input); // true
Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library. For example, the Prototype Library implements this function already.
Using !
is slightly faster and more concise than === 0
though not as readable.
Change the position
attribute to fixed
instead of absolute
.
I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.
declare @myVal int;
set @myVal = isnull((select a from table1), 0);
Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.
if you find this error when you are installing angular-cli,
-bash: ng: command not found
try this it works,
After removing Node from your system
install NVM from here https://github.com/creationix/nvm
Install Node via NVM: nvm install stable
run npm install -g angular-cli
Can use CSS to show error message only on error.
.form-group.has-error .help-block {
display: block;
}
.form-group .help-block {
display: none;
}
<div class="form-group has-error">
<label class="control-label" for="inputError">Input with error</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Please correct the error</span>
</div>
The HTML Tidy library is able to fix some malformed XML files. Running your feeds through that before passing them on to the parser may help.
StringUtils.isEmpty(str)
or StringUtils.isNotEmpty(str)
StringUtils.isBlank(str)
or StringUtils.isNotBlank(str)
from Apache commons-lang.
The difference between empty
and blank
is : a string consisted of whitespaces only is blank
but isn't empty
.
I generally prefer using apache-commons if possible, instead of writing my own utility methods, although that is also plausible for simple ones like these.
Shortest way: Click lock icon in address bar. Then click Site settings, then click Reset permissions
Making @sulai suggestion more generic :
@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
asyncTask.execute(params);
}
I would just raise ValueError, unless you need a more specific exception..
def import_to_orm(name, save=False, recurse=False):
if recurse and not save:
raise ValueError("save must be True if recurse is True")
There's really no point in doing class BadValueError(ValueError):pass
- your custom class is identical in use to ValueError, so why not use that?
math.sqrt
is the C implementation of square root and is therefore different from using the **
operator which implements Python's built-in pow
function. Thus, using math.sqrt
actually gives a different answer than using the **
operator and there is indeed a computational reason to prefer numpy
or math
module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas **
operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow
function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".
See this Stack Overflow question for more information on the difference between **
and math.sqrt
.
In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like **
e.g. C++. So **
is probably more Pythonic, but whether or not it's objectively better depends on the use case.
You would need to use a reinterpret_cast<>
as the two types you are casting between are unrelated to each other.
just tested doing this and it seems to work in firefox & IE
<html>
<head>
<script type="text/javascript">
function alertFilename()
{
var thefile = document.getElementById('thefile');
alert(thefile.value);
}
</script>
</head>
<body>
<form>
<input type="file" id="thefile" onchange="alertFilename()" />
<input type="button" onclick="alertFilename()" value="alert" />
</form>
</body>
</html>
conda
will only keep track of the packages it installed. And pip
will give you the packages that were either installed using the pip
installer itself or they used setuptools
in their setup.py
so conda build generated the egg information. So you have basically three options.
You can take the union of the conda list
and pip freeze
and manage packages that were installed using conda
(that show in the conda list
) with the conda
package manager and the ones that are installed with pip
(that show in pip freeze
but not in conda list
) with pip
.
Install in your environment only the python
, pip
and distribute
packages and manage everything with pip
. (This is not that trivial if you're on Windows...)
Build your own conda
packages, and manage everything with conda
.
I would personally recommend the third option since it's very easy to build conda
packages. There is a git repository of example recipes on the continuum's github account. But it usually boils down to:
conda skeleton pypi PACKAGE
conda build PACKAGE
or just:
conda pipbuild PACKAGE
Also when you have built them once, you can upload them to https://binstar.org/ and just install from there.
Then you'll have everything managed using conda
.
Something happened in Java 8 Update 91 that broke existing JSP code. That seems pretty clear. Here is a sample of similar questions and bug reports:
java.io.ObjectInputStream
in Update 91 that "made it incompatible with RHEL6's current ECJ version")All these are about problems with Java 8 Update 91 (or later) that are not present when using earlier JRE/JDK versions.
The following OpenJDK changeset from 22 January 2016 appears to be related: http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/rev/32f64c19b5fb (commit message "8144430: Improve JMX connections"). The changeset seems to be related to this vulnerability, https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-3427, which is mentioned in a comment to this Red Hat bug report, https://bugzilla.redhat.com/show_bug.cgi?id=1336481.
The Update 91 release notes document mentions JDK-8144430 (non-public ticket): http://www.oracle.com/technetwork/java/javase/8u91-relnotes-2949462.html.
In "Oracle Critical Patch Update Advisory - April 2016", the CVE-2016-3427 vulnerability is mentioned: http://www.oracle.com/technetwork/security-advisory/cpuapr2016v3-2985753.html.
To avoid unnecessary duplication, I added the following to my ~/.bash_profile
case ":$PATH:" in
*:/usr/local/bin:*) ;; # do nothing if $PATH already contains /usr/local/bin
*) PATH=/usr/local/bin:$PATH ;; # in every other case, add it to the front
esac
Credit: https://superuser.com/a/580611
The last argument of CONVERT
seems to determine the format used for parsing. Consult MSDN docs for CONVERT.
111
- the one you are using is Japan yy/mm/dd
.
I guess the one you are looking for is 103
, that is dd/mm/yyyy
.
So you should try:
SELECT convert(datetime, '23/07/2009', 103)
Try this, For the example, I used a fixed height. I think it is doesn't affect the responsive scenario.
<html lang="en">_x000D_
<head>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
</head>_x000D_
<body>_x000D_
<div class="d-flex justify-content-center align-items-center bg-secondary w-100" style="height: 300px;">_x000D_
<div class="bg-primary" style="width: 200px; height: 50px;"></div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Why not doing it in two lines?
var a, b, c, d; // All in the same scope
a = b = c = d = 1; // Set value to all.
The reason why, is to preserve the local scope on variable declarations, as this:
var a = b = c = d = 1;
will lead to the implicit declarations of b
, c
and d
on the window scope.
I know this is a question regarding the CSS.Tooltips library. However, for anyone else came here resulting from google search "tooltip for input box" like I did, here is the simplest way:
<input title="This is the text of the tooltip" value="44"/>
Main classes should be under src/main/java
and
test classes should be under src/test/java
If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue
I think that this is an old error that you tried to fix by importing random things in your module and now the code does not compile anymore. while you don't pay attention to the shell output, the browser reload, and you still get the same error.
Your module should be :
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
declarations: [
ContactComponent
]
})
export class ContactModule {}
Update: Webm with an alpha channel is now supported in Chrome and Firefox.
For other browers, there are workarounds, but they involve re-rendering the video using Canvas and it is kind of a hack. seeThru is one example. It works pretty well on HTML5 desktop browsers (even IE9) but it doesn't seem to work very well on mobile. I couldn't get it to work at all on Chrome for Android. It did work on Firefox for Android but with a pretty lousy framerate. I think you might be out of luck for mobile, although I'd love to be proven wrong.
To add text on an image file, just copy/paste the code below
<?php
$source = "images/cer.jpg";
$image = imagecreatefromjpeg($source);
$output = "images/certificate".rand(1,200).".jpg";
$white = imagecolorallocate($image,255,255,255);
$black = imagecolorallocate($image,7,94,94);
$font_size = 30;
$rotation = 0;
$origin_x = 250;
$origin_y = 450;
$font = __DIR__ ."/font/Roboto-Italic.ttf";
$text = "Dummy";
$text1 = imagettftext($image,$font_size,$rotation,$origin_x,$origin_y,$black,$font,$text);
imagejpeg($image,$output,99);
?> <img src="<?php echo $output; ?>"> <a href="<?php echo $output; ?>" download="<?php echo $output; ?>">Download Certificate</a>
You can also do this in phpMyAdmin without writing SQL.
Note: You'll see that phpMyAdmin is issuing the same SQL that is mentioned in the other answers.
This looks to be the fastest way by far...
var el;
while (el = arr.shift()) {
el *= 2;
}
Take into account that this will consume the array, eating it, and leaving nothing left...
Just use a onchnage Event
for select box.
<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
<option value="https://www.yahoo.com/" selected>Option1</option>
<option value="https://www.google.co.in/">Option2</option>
<option value="https://www.gmail.com/">Option3</option>
</select>
And if selected option to be loaded at the page load then add some javascript code
<script type="text/javascript">
window.onload = function(){
location.href=document.getElementById("selectbox").value;
}
</script>
for jQuery: Remove the onchange event from <select>
tag
jQuery(function () {
// remove the below comment in case you need chnage on document ready
// location.href=jQuery("#selectbox").val();
jQuery("#selectbox").change(function () {
location.href = jQuery(this).val();
})
})
Try that out bud
sudo wget http://cdn.mysql.com//Downloads/Connector-Python/mysql-connector-python-2.1.3.tar.gz
gunzip mysql-connector-python-2.1.3.tar.gz
tar xf mysql-connector-python-2.1.3.tar
cd mysql-connector-python-2.1.3
sudo python3 setup.py install
The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS
Use:
<?php
header('Location: redirectpage.php');
header('Location: redirectpage.php');
exit();
echo "<script>location.href='redirectpage.php';</script>";
?>
This is a regular and normal PHP redirect, but you can make a redirecting page with a few seconds wait by the below code:
<?php
header('refresh:5;url=redirectpage.php '); // Note: here 5 means 5 seconds wait for redirect.
?>
If you know the pid of the thing you want to kill, you can usually go from the session id, and everything in the same session. I'd double check, but I used this for scripts starting rsyncs in loops that I want to die, and not start another (because of the loop) as it would if I'd just killall'd rsync.
kill $(ps -o pid= -s $(ps -o sess --no-heading --pid 21709))
If you don't know the pid you can still nest more
kill $(ps -o pid= -s $(ps -o sess --no-heading --pid $(pgrep rsync )))
The only way I've found to work with files on SharePoint while having to server rights is to map the WebDAV folder to a drive letter. Here's an example for the implementation.
Add references to the following ActiveX libraries in VBA:
wshom.ocx
) - for WshNetworkscrrun.dll
) - for FileSystemObjectCreate a new class module, call it DriveMapper
and add the following code:
Option Explicit
Private oMappedDrive As Scripting.Drive
Private oFSO As New Scripting.FileSystemObject
Private oNetwork As New WshNetwork
Private Sub Class_Terminate()
UnmapDrive
End Sub
Public Function MapDrive(NetworkPath As String) As Scripting.Folder
Dim DriveLetter As String, i As Integer
UnmapDrive
For i = Asc("Z") To Asc("A") Step -1
DriveLetter = Chr(i)
If Not oFSO.DriveExists(DriveLetter) Then
oNetwork.MapNetworkDrive DriveLetter & ":", NetworkPath
Set oMappedDrive = oFSO.GetDrive(DriveLetter)
Set MapDrive = oMappedDrive.RootFolder
Exit For
End If
Next i
End Function
Private Sub UnmapDrive()
If Not oMappedDrive Is Nothing Then
If oMappedDrive.IsReady Then
oNetwork.RemoveNetworkDrive oMappedDrive.DriveLetter & ":"
End If
Set oMappedDrive = Nothing
End If
End Sub
Then you can implement it in your code:
Sub test()
Dim dm As New DriveMapper
Dim sharepointFolder As Scripting.Folder
Set sharepointFolder = dm.MapDrive("http://your/sharepoint/path")
Debug.Print sharepointFolder.Path
End Sub
socket.send
is implemented for compatibility with vanilla WebSocket interface. socket.emit
is feature of Socket.IO only. They both do the same, but socket.emit
is a bit more convenient in handling messages.
To answer your direct question, it is:
Range("A1").NumberFormat = "@"
Or
Cells(1,1).NumberFormat = "@"
However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.
The only one way on Android to get properly formatted stanalone month name for such languages as ukrainian, russian, czech
private String getMonthName(Calendar calendar, boolean short) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR;
if (short) {
flags |= DateUtils.FORMAT_ABBREV_MONTH;
}
return DateUtils.formatDateTime(getContext(), calendar.getTimeInMillis(), flags);
}
Tested on API 15-25
Output for May is ??? but not ???
Here's a complete example of how it can be done. However you need flashback query privileges on the child table.
Here's the setup.
create table parent_tab
(parent_id number primary key,
val varchar2(20));
create table child_tab
(child_id number primary key,
parent_id number,
child_val number,
constraint child_par_fk foreign key (parent_id) references parent_tab);
insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');
insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);
commit;
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).
delete from child_tab where child_val = 100;
Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab
delete from parent_tab
where parent_id in
(select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
minus
select parent_id from child_tab);
'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
select * from parent_tab;
It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.
In Windows, you can also use ctypes with GetSystemMetrics()
:
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
so that you don't need to install the pywin32 package; it doesn't need anything that doesn't come with Python itself.
For multi-monitor setups, you can retrieve the combined width and height of the virtual monitor:
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79)
Change your default controller which is in config file.
i.e : config/routes.php
$route['default_controller'] = "Your controller name";
Hope this will help.
win32gui.GetCursorPos(point)
This retrieves the cursor's position, in screen coordinates - point = (x,y)
flags, hcursor, (x,y) = win32gui.GetCursorInfo()
Retrieves information about the global cursor.
Links:
I am assuming that you would be using python win32 API bindings or pywin32.
take a look here... this was very helpfull to me https://datatables.net/examples/ajax/null_data_source.html
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "data/arrays.txt",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
$('#example tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( data[0] +"'s salary is: "+ data[ 5 ] );
} );
} );
Correct solution is to copy or install to /usr/local/bin
not /usr/bin
.This is due to System Integrity Protection (SIP). SIP makes /usr/bin
read-only but leaves /usr/local
as read-write.
SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.
As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."
Faced the same error. In my case , what i did wrong was that i injected the service(named DataService in my case) inside the constructor within the Component but I simply forgot to import it within the component.
constructor(private dataService:DataService ) {
console.log("constructor called");
}
I missed the below import code.
import { DataService } from '../../services/data.service';
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
If space is going to be an issue, have a 3rd table Tags(Tag_Id, Title) to store the text for the tag and then change your Tags table to be (Tag_Id, Item_Id). Those two values should provide a unique composite primary key as well.
Short answer: H.264 MPEG (MP4)
Long answer from Apple.com:
Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,
Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
In Swift 2, you would do:
let rightButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = rightButton
(Not a major change) In Swift 4/5, it will be:
let rightButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = rightButton
This is a general error message, you may have encountered during the react native application development. So In this tutorial we are going to provide solution to this issue.
Issue Description : Unable to load script from assets index.android.bundle on windows Unable to load script from assets index.android.bundle on windows
Follow the below steps to solve above issue :
Step-1 : Create "assets" folder inside your project directory Now create assets folder inside the project directory that is "MobileApp\android\app\src\main". You can manually create assets folder :
< OR >
you can create folder by using command as well. Command : mkdir android/app/src/main/assets
Step-2 : Running your React Native application Lets run the below command to run the react native application in emulator or physical device.
Switch to project directory. cd MobileApp
Run the below command that helps to bundle you android application project.
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
Run the Final step to run react native application in emulator or physical device. react-native run-android
< OR >
Also you can combine last two command in one, In this case case you have to execute command only once.
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android
< OR >
You can automate the above steps by placing them in scripts part of package.json like this:
"android-android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android"
If everything is set up correctly, you should see your new app running in your Android emulator shortly.
Simple solution to resolve this problem is to set an empty value by default :
<input name='myInput' value={this.state.myInput || ''} onChange={this.handleChange} />
A more powerful and flexible example can be found here: C# File Upload with form fields, cookies and headers
Being new to grunt and setting it up, I am running (perhaps foolishly) my grunt project/folder from a Google Drive so I can access the same code/builds from either my laptop or workstation.
There is a fair bit of synchronisation of the nodes_modules folders back to Google Drive and there seemed to be a conflict at some point, and the /nodes_modules/grunt folder was renamed to /nodes_modules/grunt (1)
Renaming it back by removing the (1) seemed to fix it for me.
An other way of CASE:
SELECT *
FROM MyTable
WHERE 1 = CASE WHEN @myParm = value1 AND MyColumn IS NULL THEN 1
WHEN @myParm = value2 AND MyColumn IS NOT NULL THEN 1
WHEN @myParm = value3 THEN 1
END
I had this same problem.
Did:
f1 = plt.figure(1)
# code for figure 1
# don't write 'plt.show()' here
f2 = plt.figure(2)
# code for figure 2
plt.show()
Write 'plt.show()' only once, after the last figure.
Worked for me.
Louis' answer is great, but I thought I would try to sum it up succinctly:
The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".
Here is a simple function which does exactly this :
#include <windows.h>
#include <string>
bool dirExists(const std::string& dirName_in)
{
DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
header("Location: route_to_main_page");
I've encountered this problem while having a custom 404 error handling file. Instead of throwing some html content it was suppose to redirect to the main page url. It worked well.
Then I used this as a skeleton for a next project, therefore not changing the "route_to_main_page" actually on the new project (different URL) became a "route_to_external_url" so any 404 errors within your code (missing css stylesheets, js libraries) would return the "Uncaught SyntaxError: Unexpected token <".
Here's what I use. Note you have to use the @autoreleasepool
feature or the program might crash or lockup the IDE. I had to restart my IDE three times until I realized the fix. It appears that this code is ARC compliant.
This question has been asked many times, and many answers given, but sadly all of the ones selected (and a few others suggested) are wrong.
Here's the test string that I used: This is my 123+ test & test2. Got it?!
These are my Objective C++ class methods:
static NSString * urlDecode(NSString *stringToDecode) {
NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:@"+" withString:@" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
static NSString * urlEncode(NSString *stringToEncode) {
@autoreleasepool {
NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)stringToEncode,
NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
kCFStringEncodingUTF8
));
result = [result stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
return result;
}
}
return array as string
>>> list(str(12345))
['1', '2', '3', '4', '5']
return array as integer
>>> map(int,str(12345))
[1, 2, 3, 4, 5]
Using jQuery you can use contents()
. For example:
var inside = $('#one').contents();
You're looking for delete
:
delete myhash['key2']
See the Core Javascript Guide
Make sure your routing.yml
file has 'id'
specified in it. In other words, it should look like:
_category:
path: /category/{id}
I found this the most simple when toggling boolean values. Simply put if the value is already true then it sets it to false and vice versa. Beware of undefined errors, make sure your property was defined before executing
this.setState({
propertyName: this.propertyName = !this.propertyName
});
jut add allowfullscreen="true"
to iframe
<iframe src="URL here" allowfullscreen="true"> </iframe>
results.show(false)
will show you the full column content.
Show method by default limit to 20, and adding a number before false
will show more rows.
display
is not one of the properties that transition works upon.
See Animatable CSS properties for the list of CSS properties that can have transitions applied to them. See CSS Values and Units Module Level 4, Combining Values: Interpolation, Addition, and Accumulation for how they are interpolated.
Up to CSS 3 was listed in 9.1. Properties from CSS (just close the warning popup)
I've also tried using height, but that just failed miserably.
Last time I had to do this, I used max-height
instead, which is an animatable property (although it was a bit of a hack, it did work), but beware that it may be very janky for complex pages or users with low-end mobile devices.
Occasionally when a disk runs out of space, the message "transaction log for database XXXXXXXXXX is full due to 'LOG_BACKUP'" will be returned when an update SQL statement fails. Check your diskspace :)
I had this problem when I started using Entity Framework, it happened when I did not change the old SQL server connection to EntityFrameWork connection.
Solution: in the file where connection is made through web.config file "add name="Entities" connectionString=XYZ", make sure you are referring to the correct connection, in my case I had to do this
public static string MyEntityFrameworkConnection
{
get
{
return ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
}
}
call MyEntityFrameworkConnection whenever connection need to be established.
private string strConnection= Library.DataAccessLayer.DBfile.AdoSomething.MyEntityFrameworkConnection;
note: the connection in web.config file will be generated automatically when adding Entity model to the solution.
It's mentioned as SSL_ERROR_SYSCALL, errno 10054.
To resolve this SSL issue I went to .gitconfig file (which is located in c drive in my desktop) I changed sslverify
to false and added my username and email id.
sslVerify = `false` //make sslVerify as false
[user]
name = `***<Enter your name>**`
email = `**<Email Id>**`
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
Feb 3rd 2020:
---
did produce the line, but I could not get new lines to work with suggestions above.[space][space]
suggestion, since my editor removes trailing spaces on save, and I like this feature on.I ended up doing this:
TEXT...
<br><hr><br>
TEXT...
Resulting in:
TEXT...
<AN EMPTY LINE>
----------------- AN HORIZONTAL LINE ----------------
<AN EMPTY LINE>
TEXT...
=SUMPRODUCT((A1:A5="FRANCE")*B1:D5)
Sometimes it's because laravel 5.1 require PHP >= 5.5.9. Update php will solve the problem.
December 2020 :
To answer the question :
<video>
element.I think this question should be closed.
Use below code.
NSString* myString;
myString = [[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];
I had this problem, and turns out the problem was that I had used
new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("foo")
instead of
new SimpleJdbcCall(jdbcTemplate)
.withFunctionName("foo")
from msvcrt import getch
pos = [0, 0]
def fright():
global pos
pos[0] += 1
def fleft():
global pos
pos[0] -= 1
def fup():
global pos
pos[1] += 1
def fdown():
global pos
pos[1] -= 1
while True:
print'Distance from zero: ', pos
key = ord(getch())
if key == 27: #ESC
break
elif key == 13: #Enter
print('selected')
elif key == 32: #Space
print('jump')
elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
key = ord(getch())
if key == 80: #Down arrow
print('down')
fdown
elif key == 72: #Up arrow
print('up')
fup()
elif key == 75: #Left arrow
print('left')
fleft()
elif key == 77: #Right arrow
print('right')
fright()
Assuming that obj
is a pre-constructed object (and not a JSON string), you can achieve this with the following:
Object.keys(obj).forEach(function(key){
console.log(key + '=' + obj[key]);
});
Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")
' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close
' Write file
outFile.write (strRetVal)
outFile.Close
I was able to get all errors via the below code:
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post.
You can also use something like Bugsnag to track your uncaught exceptions and be notified via email, chatroom or have a ticket created for an uncaught exception (I am the co-founder of Bugsnag).
They are functionally equivalent, but INNER JOIN
can be a bit clearer to read, especially if the query has other join types (i.e. LEFT
or RIGHT
or CROSS
) included in it.
Updated March 31st, 2016:
We have announced that Visual Studio now includes Xamarin at no extra cost, including Community Edition, which is free for individual developers, open source projects, academic research, education, and small professional teams. There is no size restriction on the Community Edition and offers the same features as the Pro & Enterprise editions. Read more about the update here: https://blog.xamarin.com/xamarin-for-all/
Be sure to browse the store on how to download and get started: https://visualstudio.microsoft.com/vs/pricing/ and there is a nice FAQ section: https://visualstudio.microsoft.com/vs/support/
For Swift 3.0
String(describing: <Class-Name>.self)
For Swift 2.0 - 2.3
String(<Class-Name>)
You can also use split
and join
:
"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games
Using PyParsing
import pyparsing as pp
word = pp.Word(pp.alphanums)
s = 'gfgfdAAA1234ZZZuijjk'
rule = pp.nestedExpr('AAA', 'ZZZ')
for match in rule.searchString(s):
print(match)
which yields:
[['1234']]
%Started Program or Command% | taskkill /F /IM cmd.exe
Example:
notepad.exe | taskkill /F /IM cmd.exe
try this, will work.
Thread[] threads = new Thread[10];
List<Thread> allThreads = new ArrayList<Thread>();
for(Thread thread : threads){
if(null != thread){
if(thread.isAlive()){
allThreads.add(thread);
}
}
}
while(!allThreads.isEmpty()){
Iterator<Thread> ite = allThreads.iterator();
while(ite.hasNext()){
Thread thread = ite.next();
if(!thread.isAlive()){
ite.remove();
}
}
}
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("C:\\");
}
}
If your application needs cmd arguments, use something like this:
using System.Diagnostics;
class Program
{
static void Main()
{
LaunchCommandLineApp();
}
/// <summary>
/// Launch the application with some options set.
/// </summary>
static void LaunchCommandLineApp()
{
// For the example
const string ex1 = "C:\\";
const string ex2 = "C:\\Dir";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch
{
// Log error.
}
}
}
If I understand you need following code. (passing expression lambda by parameter) The Method
public static void Method(Expression<Func<int, bool>> predicate) {
int[] number={1,2,3,4,5,6,7,8,9,10};
var newList = from x in number
.Where(predicate.Compile()) //here compile your clausuly
select x;
newList.ToList();//return a new list
}
Calling method
Method(v => v.Equals(1));
You can do the same in their class, see this is example.
public string Name {get;set;}
public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
{
List<Class> c = new List<Class>();
c.Add(new Class("name1"));
c.Add(new Class("name2"));
var f = from g in c.
Where (predicate.Compile())
select g;
f.ToList();
return f;
}
Calling method
Class.GetList(c=>c.Name=="yourname");
I hope this is useful
You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:
SELECT TO_CHAR(
TO_DATE('15/August/2009,4:30 PM'
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM DUAL;
15-08-2009
For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:
SELECT TO_CHAR(
TO_DATE(MYDATESTRING
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM MYTABLE;
Have you seen this question and its answer?
You can set a globally valid value for you app like this:
app.value('key', 'value');
and then use it in your services. You could move this code to a config.js file and execute it on page load or another convenient moment.
You can use the "extract" or "date_part" functions on intervals as well as timestamps, but I don't think that does what you want. For example, it gives 3 for an interval of '2 days, 3 hours'. However, you can convert an interval to a number of seconds by specifying 'epoch' as the time element you want: extract(epoch from '2 days, 3 hours'::interval)
returns 183600 (which you then divide by 3600 to convert seconds to hours).
So, putting this all together, you get basically Michael's answer: extract(epoch from timestamp1 - timestamp2)/3600
. Since you don't seem to care about which timestamp precedes which, you probably want to wrap that in abs
:
SELECT abs(extract(epoch from timestamp1 - timestamp2)/3600)
If you want to apply an extra small class in Bootstrap 4,you need to use col-. important thing to know is that col-xs- is dropped in Bootstrap4
Although, @Tomasz is absolutely right there is another way:
@RequestMapping(value="/controller", method=GET)
public void foo(HttpServletResponse res) {
try {
PrintWriter out = res.getWriter();
out.println("Hello, world!");
out.close();
} catch (IOException ex) {
...
}
}
but the first method is preferable. You can use this method if you want to return response with custom content type or return binary type (file, etc...);
Source: http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html
Intrinsic Content Size of Multi-Line Text
The intrinsic content size of UILabel and NSTextField is ambiguous for multi-line text. The height of the text depends on the width of the lines, which is yet to be determined when solving the constraints. In order to solve this problem, both classes have a new property called preferredMaxLayoutWidth, which specifies the maximum line width for calculating the intrinsic content size.
Since we usually don’t know this value in advance, we need to take a two-step approach to get this right. First we let Auto Layout do its work, and then we use the resulting frame in the layout pass to update the preferred maximum width and trigger layout again.
- (void)layoutSubviews
{
[super layoutSubviews];
myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
[super layoutSubviews];
}
The first call to [super layoutSubviews] is necessary for the label to get its frame set, while the second call is necessary to update the layout after the change. If we omit the second call we get a NSInternalInconsistencyException error, because we’ve made changes in the layout pass which require updating the constraints, but we didn’t trigger layout again.
We can also do this in a label subclass itself:
@implementation MyLabel
- (void)layoutSubviews
{
self.preferredMaxLayoutWidth = self.frame.size.width;
[super layoutSubviews];
}
@end
In this case, we don’t need to call [super layoutSubviews] first, because when layoutSubviews gets called, we already have a frame on the label itself.
To make this adjustment from the view controller level, we hook into viewDidLayoutSubviews. At this point the frames of the first Auto Layout pass are already set and we can use them to set the preferred maximum width.
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
[self.view layoutIfNeeded];
}
Lastly, make sure that you don’t have an explicit height constraint on the label that has a higher priority than the label’s content compression resistance priority. Otherwise it will trump the calculated height of the content. Make sure to check all the constraints that can affect label's height.
getattr(object, 'x')
is completely equivalent to object.x
.
There are only two cases where getattr
can be useful.
object.x
, because you don't know in advance which attribute you want (it comes from a string). Very useful for meta-programming.object.y
will raise an AttributeError
if there's no y
. But getattr(object, 'y', 5)
will return 5
.On the "Scripts" tab, go to where your code is. At the left of the line number, click. This will set a breakpoint.
Screenshot:
You will then be able to track your breakpoints within the right tab (as shown in the screenshot).
You could apply position: relative;
to the div and then position: absolute; top: 0;
to a paragraph or span inside of it containing the text.
This will uninstall a gem installed by bundler:
bundle exec gem uninstall GEM_NAME
Note that this throws
ERROR: While executing gem ... (NoMethodError) undefined method `delete' for #<Bundler::SpecSet:0x00000101142268>
but the gem is actually removed. Next time you run bundle install
the gem will be reinstalled.
Simplyfing for the begginers:
If you want to select an element immediatly after another element you use the +
selector.
For example:
div + p
The "+" element selects all <p>
elements that are placed immediately after <div>
elements
If you want to learn more about selectors use this table
Best way to replace linebreaks safely is
yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n") //handling mac linebreaks
that should produce a string with only \n (eg linefeed) as linebreaks. this code is usefull to fix mixed linebreaks too.
To replace only factors:
i <- sapply(bob, is.factor)
bob[i] <- lapply(bob[i], as.character)
In package dplyr in version 0.5.0 new function mutate_if
was introduced:
library(dplyr)
bob %>% mutate_if(is.factor, as.character) -> bob
...and in version 1.0.0 was replaced by across
:
library(dplyr)
bob %>% mutate(across(where(is.factor), as.character)) -> bob
Package purrr from RStudio gives another alternative:
library(purrr)
bob %>% modify_if(is.factor, as.character) -> bob
The documentation for focusout says (emphasis mine):
The
focusout
event is sent to an element when it, or any element inside of it, loses focus. This is distinct from theblur
event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
The same distinction exists between the focusin and focus events.
string result = System.Text.Encoding.UTF8.GetString(fs.ToArray());
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.
BEST
DECLARE @yourSpecialMark = '/';
select len(@yourString) - len(replace(@yourString,@yourSpecialMark,''))
It will count, how many times occours the special mark '/'
I've created this query:
SELECT
db.name AS [Database Name],
mf.name AS [Logical Name],
mf.type_desc AS [File Type],
mf.physical_name AS [Path],
CAST(
(mf.Size * 8
) / 1024.0 AS DECIMAL(18, 1)) AS [Initial Size (MB)],
'By '+IIF(
mf.is_percent_growth = 1, CAST(mf.growth AS VARCHAR(10))+'%', CONVERT(VARCHAR(30), CAST(
(mf.growth * 8
) / 1024.0 AS DECIMAL(18, 1)))+' MB') AS [Autogrowth],
IIF(mf.max_size = 0, 'No growth is allowed', IIF(mf.max_size = -1, 'Unlimited', CAST(
(
CAST(mf.max_size AS BIGINT) * 8
) / 1024 AS VARCHAR(30))+' MB')) AS [MaximumSize]
FROM
sys.master_files AS mf
INNER JOIN sys.databases AS db ON
db.database_id = mf.database_id
In sublime text, you simply write the two word you are interested in keeping for example in your case it is
"This is" and "sentence"
and you write .* in between
i.e. This is .* sentence
and this should do you well
hello you can try this bellow :
char arr[nb_of_string][max_string_length];
strcpy(arr[0], "word");
a nice example of using, array of strings in c if you want it
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
int i, j, k;
// to set you array
//const arr[nb_of_string][max_string_length]
char array[3][100];
char temp[100];
char word[100];
for (i = 0; i < 3; i++){
printf("type word %d : ",i+1);
scanf("%s", word);
strcpy(array[i], word);
}
for (k=0; k<3-1; k++){
for (i=0; i<3-1; i++)
{
for (j=0; j<strlen(array[i]); j++)
{
// if a letter ascii code is bigger we swap values
if (array[i][j] > array[i+1][j])
{
strcpy(temp, array[i+1]);
strcpy(array[i+1], array[i]);
strcpy(array[i], temp);
j = 999;
}
// if a letter ascii code is smaller we stop
if (array[i][j] < array[i+1][j])
{
j = 999;
}
}
}
}
for (i=0; i<3; i++)
{
printf("%s\n",array[i]);
}
return 0;
}
The answer is yes, as long as you don't set left: 0
or right: 0
after you set the div position to fixed.
Checkout the sidebar div. It is fixed, but related to the parent, not to the window view point.
body {
background: #ccc;
}
.wrapper {
margin: 0 auto;
height: 1400px;
width: 650px;
background: green;
}
.sidebar {
background-color: #ddd;
float: left;
width: 300px;
height: 100px;
position: fixed;
}
.main {
float: right;
background-color: yellow;
width: 300px;
height: 1400px;
}
_x000D_
<div class="wrapper">wrapper
<div class="sidebar">sidebar</div>
<div class="main">main</div>
</div>
_x000D_
I don't think it's necessary to use semi-quotes around the variables, try:
curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"
%2f
is the escape code for a /
.
http://www.december.com/html/spec/esccodes.html
Also, do you need to specify a port? ( just checking :) )
A cleaner way of iterating the lists is:
// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
for (String string : innerList) {
// do stuff with string
}
}
AGE
is defined as "42"
so the line:
str += "Do you feel " + AGE + " years old?";
is converted to:
str += "Do you feel " + "42" + " years old?";
Which isn't valid since "Do you feel "
and "42"
are both const char[]
. To solve this, you can make one a std::string
, or just remove the +
:
// 1.
str += std::string("Do you feel ") + AGE + " years old?";
// 2.
str += "Do you feel " AGE " years old?";
I encountered the same error. My linker command did have the rt library included -lrt
which is correct and it was working for a while. After re-installing Kubuntu it stopped working.
A separate forum thread suggested the -lrt
needed to come after the project object files.
Moving the -lrt
to the end of the command fixed this problem for me although I don't know the details of why.
A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine. Static class members are declared using the static keyword before the return type of the membe
Laravel 5 uses bcrypt
. So, you can do this as well.
$hashedpassword = bcrypt('plaintextpassword');
output of which you can save to your database table's password field.
Fn Ref: bcrypt
If you run your legacy program with ProcessBuilder, you will be able to specify its working directory.
I know this is an old question, but browsers have been changing over time. Although some of the answers to this question mentioned here like: creating a temporary text box above the password field and hiding it may have worked in the past, currently the easiest way to prevent the browser from popping up the password manager is to have at least three separate additional hidden password inputs, each with different dummy values, like so:
<form method="post" autocomplete="off" action="">
<ul class="field-set">
<li>
<label>Username:</label>
<input type="text" name="acct" id="username" maxlength="100" size="20">
</li>
<li>
<label>Password:</label>
<input type="password" name="pswd" id="password" maxlength="16" size="20" >
<input type="password" style="display: none;" value="dummyinput1"/>
<input type="password" style="display: none;" value="dummyinput2"/>
<input type="password" style="display: none;" value="dummyinput3"/>
</li>
<li>
<input type="submit" class="button" value="Login" id="Login" name="Login">
</li>
</ul>
</form>
I suposse this is the output you need:
title,intro,tagline
2.9,Gardena,CA
It can be done with this changes to your code:
import csv
import itertools
with open('log.txt', 'r') as in_file:
lines = in_file.read().splitlines()
stripped = [line.replace(","," ").split() for line in lines]
grouped = itertools.izip(*[stripped]*1)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro', 'tagline'))
for group in grouped:
writer.writerows(group)
Quoting the Scheduling Repeating Alarms - Understand the Trade-offs docs:
A common scenario for triggering an operation outside the lifetime of your app is syncing data with a server. This is a case where you might be tempted to use a repeating alarm. But if you own the server that is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with sync adapter is a better solution than AlarmManager. A sync adapter gives you all the same scheduling options as AlarmManager, but it offers you significantly more flexibility.
So, based on this, the best way to schedule a server call is using Google Cloud Messaging (GCM) in conjunction with sync adapter.
My solution is little tricky and simpler.
<div>
<mat-select
[placeholder]="selected2">
<mat-option
*ngFor="let option of options2"
value="{{ option.id }}">
{{ option.name }}
</mat-option>
</mat-select>
</div>
I just made use of the placeholder. The default color of material placeholder is light gray
. To make it look like the option is selected, I just manipulated the CSS as follows:
::ng-deep .mat-select-placeholder {
color: black;
}
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
The date format for mysql insert query is YYYY-MM-DD
example:
INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');
Robust C89 strtol
-based solution
With:
atoi
family)strtol
(e.g. no leading whitespace nor trailing trash chars)#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
typedef enum {
STR2INT_SUCCESS,
STR2INT_OVERFLOW,
STR2INT_UNDERFLOW,
STR2INT_INCONVERTIBLE
} str2int_errno;
/* Convert string s to int out.
*
* @param[out] out The converted int. Cannot be NULL.
*
* @param[in] s Input string to be converted.
*
* The format is the same as strtol,
* except that the following are inconvertible:
*
* - empty string
* - leading whitespace
* - any trailing characters that are not part of the number
*
* Cannot be NULL.
*
* @param[in] base Base to interpret string in. Same range as strtol (2 to 36).
*
* @return Indicates if the operation succeeded, or why it failed.
*/
str2int_errno str2int(int *out, char *s, int base) {
char *end;
if (s[0] == '\0' || isspace(s[0]))
return STR2INT_INCONVERTIBLE;
errno = 0;
long l = strtol(s, &end, base);
/* Both checks are needed because INT_MAX == LONG_MAX is possible. */
if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
return STR2INT_OVERFLOW;
if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
return STR2INT_UNDERFLOW;
if (*end != '\0')
return STR2INT_INCONVERTIBLE;
*out = l;
return STR2INT_SUCCESS;
}
int main(void) {
int i;
/* Lazy to calculate this size properly. */
char s[256];
/* Simple case. */
assert(str2int(&i, "11", 10) == STR2INT_SUCCESS);
assert(i == 11);
/* Negative number . */
assert(str2int(&i, "-11", 10) == STR2INT_SUCCESS);
assert(i == -11);
/* Different base. */
assert(str2int(&i, "11", 16) == STR2INT_SUCCESS);
assert(i == 17);
/* 0 */
assert(str2int(&i, "0", 10) == STR2INT_SUCCESS);
assert(i == 0);
/* INT_MAX. */
sprintf(s, "%d", INT_MAX);
assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
assert(i == INT_MAX);
/* INT_MIN. */
sprintf(s, "%d", INT_MIN);
assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
assert(i == INT_MIN);
/* Leading and trailing space. */
assert(str2int(&i, " 1", 10) == STR2INT_INCONVERTIBLE);
assert(str2int(&i, "1 ", 10) == STR2INT_INCONVERTIBLE);
/* Trash characters. */
assert(str2int(&i, "a10", 10) == STR2INT_INCONVERTIBLE);
assert(str2int(&i, "10a", 10) == STR2INT_INCONVERTIBLE);
/* int overflow.
*
* `if` needed to avoid undefined behaviour
* on `INT_MAX + 1` if INT_MAX == LONG_MAX.
*/
if (INT_MAX < LONG_MAX) {
sprintf(s, "%ld", (long int)INT_MAX + 1L);
assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
}
/* int underflow */
if (LONG_MIN < INT_MIN) {
sprintf(s, "%ld", (long int)INT_MIN - 1L);
assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
}
/* long overflow */
sprintf(s, "%ld0", LONG_MAX);
assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
/* long underflow */
sprintf(s, "%ld0", LONG_MIN);
assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
return EXIT_SUCCESS;
}
title = u"Klüft skräms inför på fédéral électoral große"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
'Kluft skrams infor pa federal electoral groe'
If you want to monitor the execution of task, you could spin 1 or 2 threads (maybe more depending on the load) and use them to take tasks from an ExecutionCompletionService wrapper.
if you read a bit further - "Of course, on the backend, there are threads and processes for DB access and process execution. However, these are not explicitly exposed to your code, so you can’t worry about them other than by knowing that I/O interactions e.g. with the database, or with other processes will be asynchronous from the perspective of each request since the results from those threads are returned via the event loop to your code."
about - "everything runs in parallel except your code" - your code is executed synchronously, whenever you invoke an asynchronous operation such as waiting for IO, the event loop handles everything and invokes the callback. it just not something you have to think about.
in your example: there are two requests A (comes first) and B. you execute request A, your code continue to run synchronously and execute request B. the event loop handles request A, when it finishes it invokes the callback of request A with the result, same goes to request B.
This one maybe work for you, it can read/write Excel 2007 xlsx file. SmartXLS
const promise = new Promise(resolve => {
setTimeout(() => {
resolve("Hello from a Promise!");
}, 2000);
});
promise.then(value => console.log(value));
Observable example now. Here also we pass a function to observable, an observer to handle the async task. Unlike resolve in the promise it has the following method and subscribes in place of then.
So both handles async tasks. Now let's see the difference.
const observable = new Observable(observer => {
setTimeout(() => {
observer.next('Hello from a Observable!');
}, 2000);
});
observable.subscribe(value => console.log(value));
Promise
Observable
I try to make the code a little bit understandable by naming the variables, I hope this can help
function getDistanceFromLatLonInKm(point1, point2) {
const [lat1, lon1] = point1;
const [lat2, lon2] = point2;
const earthRadius = 6371;
const dLat = convertDegToRad(lat2 - lat1);
const dLon = convertDegToRad(lon2 - lon1);
const squarehalfChordLength =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(convertDegToRad(lat1)) * Math.cos(convertDegToRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const angularDistance = 2 * Math.atan2(Math.sqrt(squarehalfChordLength), Math.sqrt(1 - squarehalfChordLength));
const distance = earthRadius * angularDistance;
return distance;
}
You just have to change to a Custom format - right click and select format and at the bottom of the list is custom.
0.00##\%;[Red](0.00##\%)
The first part of custom format is your defined format you posted. Everything after the semicolon is for negative numbers. [RED] tells Excel to make the negative numbers red and the () make sure that negative number is in parentheses.
/^$|\s+/
This matches when empty or white spaces
/(?!^$)([^\s])/
This matches when its not empty or white spaces
label.font = UIFont.systemFontOfSize(20)
if you downloaded redis yourself (not apt-get install redis-server) and then edited the redis.conf with
the above suggestions, make sure your start redis with the config
like so: ./src/redis-server redis.conf
It works for me..
public class ShapeTypes
{
private ShapeTypes() { }
public static string OVAL
{
get
{
return "ov";
}
private set { }
}
public static string SQUARE
{
get
{
return "sq";
}
private set { }
}
public static string RECTANGLE
{
get
{
return "rec";
}
private set { }
}
}
I think this is also a solution of this problem.
Change your document type from 'Encode in UTF-8' To 'Encode in UTF-8 without BOM'
I got resolved my problem by doing same changes.
Besides put all your assets in the public folder, you can use the HTML::image()
Method, and only needs an argument which is the path to the image, relative on the public folder, as well:
{{ HTML::image('imgs/picture.jpg') }}
Which generates the follow HTML code:
<img src="http://localhost:8000/imgs/picture.jpg">
The link to other elements of HTML::image()
Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element
The top answer (if e.errno == errno.EPIPE:
) here didn't really work for me. I got:
AttributeError: 'BrokenPipeError' object has no attribute 'EPIPE'
However, this ought to work if all you care about is ignoring broken pipes on specific writes. I think it's safer than trapping SIGPIPE:
try:
# writing, flushing, whatever goes here
except BrokenPipeError:
exit( 0 )
You obviously have to make a decision as to whether your code is really, truly done if you hit the broken pipe, but for most purposes I think that's usually going to be true. (Don't forget to close file handles, etc.)
I wanted my XAML to remain as elegant as possible so I created a class to wrap the bool which resides in one of my shared libraries, the implicit operators allow the class to be used as a bool in code-behind seamlessly
public class InvertableBool
{
private bool value = false;
public bool Value { get { return value; } }
public bool Invert { get { return !value; } }
public InvertableBool(bool b)
{
value = b;
}
public static implicit operator InvertableBool(bool b)
{
return new InvertableBool(b);
}
public static implicit operator bool(InvertableBool b)
{
return b.value;
}
}
The only changes needed to your project are to make the property you want to invert return this instead of bool
public InvertableBool IsActive
{
get
{
return true;
}
}
And in the XAML postfix the binding with either Value or Invert
IsEnabled="{Binding IsActive.Value}"
IsEnabled="{Binding IsActive.Invert}"
In case that you need to add the http redirect in many sites, you could use it as a c# console program:
class Program
{
static int Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
return 1;
}
if (args.Length == 3)
{
if (args[0].ToLower() == "-insert-redirect")
{
var path = args[1];
var value = args[2];
if (InsertRedirect(path, value))
Console.WriteLine("Redirect added.");
return 0;
}
}
Console.WriteLine("Wrong parameters.");
return 1;
}
static bool InsertRedirect(string path, string value)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
// This should find the appSettings node (should be only one):
XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");
var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
if (existNode != null)
return false;
// Create new <add> node
XmlNode nodeNewKey = doc.CreateElement("httpRedirect");
XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
XmlAttribute attributeDestination = doc.CreateAttribute("destination");
//XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");
// Assign values to both - the key and the value attributes:
attributeEnable.Value = "true";
attributeDestination.Value = value;
//attributeResponseStatus.Value = "Permanent";
// Add both attributes to the newly created node:
nodeNewKey.Attributes.Append(attributeEnable);
nodeNewKey.Attributes.Append(attributeDestination);
//nodeNewKey.Attributes.Append(attributeResponseStatus);
// Add the node under the
nodeAppSettings.AppendChild(nodeNewKey);
doc.Save(path);
return true;
}
catch (Exception e)
{
Console.WriteLine($"Exception adding redirect: {e.Message}");
return false;
}
}
}
If you want to due this in component.ts
HTML:
<button class="class1 class2" (click)="clicked($event)">Click me</button>
Component:
clicked(event) {
event.target.classList.add('class3'); // To ADD
event.target.classList.remove('class1'); // To Remove
event.target.classList.contains('class2'); // To check
event.target.classList.toggle('class4'); // To toggle
}
For more options, examples and browser compatibility visit this link.
This is a known issue. The problem is that a div tag has the style "overflow: auto" which apparently is not implemented well with WebKit which is used by Safari and Chrome (see Emanuele Greco's answer). I did not know how to take advantage of Emanuele's suggestion to use the RS:ReportViewerHost element, but I solved it using JavaScript.
Problem
Solution
Since "overflow: auto" is specified in the style attribute of the div element with id "ctl31_ctl10", we can't override it in a stylesheet file so I resorted to JavaScript. I appended the following code to "C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js"
function FixSafari()
{
var element = document.getElementById("ctl31_ctl10");
if (element)
{
element.style.overflow = "visible"; //default overflow value
}
}
// Code from http://stackoverflow.com/questions/9434/how-do-i-add-an-additional-window-onload-event-in-javascript
if (window.addEventListener) // W3C standard
{
window.addEventListener('load', FixSafari, false); // NB **not** 'onload'
}
else if (window.attachEvent) // Microsoft
{
window.attachEvent('onload', FixSafari);
}
Note
There appears to be a solution for SSRS 2005 that I have not tried but I don't think it is applicable to SSRS 2008 because I can't find the "DocMapAndReportFrame" class.
I'm using jQuery and JavaScript and it works fine for me:
var rege = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(rege.test($('#uemail').val())){ //do something }
The downfall of ArrayList and LinkedList is that when iterating through them, depending on the search algorithm, the time it takes to find an item grows with the size of the list.
The beauty of hashing is that although you sacrifice some extra time searching for the element, the time taken does not grow with the size of the map. This is because the HashMap finds information by converting the element you are searching for, directly into the index, so it can make the jump.
Long story short... LinkedList: Consumes a little more memory than ArrayList, low cost for insertions(add & remove) ArrayList: Consumes low memory, but similar to LinkedList, and takes extra time to search when large. HashMap: Can perform a jump to the value, making the search time constant for large maps. Consumes more memory and takes longer to find the value than small lists.
In C#, they are interchangeable (although method is the proper term) because you cannot write a method without incorporating it into a class. If it were independent of a class, then it would be a function. Methods are functions that operate through a designated class.
Do you just mean spaces or all whitespace?
For just spaces, use str_replace:
$string = str_replace(' ', '', $string);
For all whitespace (including tabs and line ends), use preg_replace:
$string = preg_replace('/\s+/', '', $string);
(From here).
Run installer in command line (Admin) with argument:
vs_community_ENU.exe /uninstall /force
Then:
vs_community_ENU /CustomInstallPath E:\VisualStudio2015
I would add the following code to the accepted answer
public static class Retry<TException> where TException : Exception //ability to pass the exception type
{
//same code as the accepted answer ....
public static T Do<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3)
{
var exceptions = new List<Exception>();
for (int retry = 0; retry < retryCount; retry++)
{
try
{
return action();
}
catch (TException ex) //Usage of the exception type
{
exceptions.Add(ex);
Thread.Sleep(retryInterval);
}
}
throw new AggregateException(String.Format("Failed to excecute after {0} attempt(s)", retryCount), exceptions);
}
}
Basically the above code is making the Retry
class generic so you can pass the type of the exception you want to catch for retry.
Now use it almost in the same way but specifying the exception type
Retry<EndpointNotFoundException>.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));
Minor update in @Joran's code.
Using the code below, you can avoid the ambiguity and only get the unique of two columns:
dat <- data.frame(id=c(1,1,3), id2=c(1,1,4) ,somevalue=c("x","y","z"))
dat[row.names(unique(dat[,c("id", "id2")])), c("id", "id2")]
You can use a special designated object as the null object in case of references as follows:
class SomeClass
{
public:
int operator==(SomeClass &object)
{
if(this == &object)
{
return true;
}
return false;
}
static SomeClass NullObject;
};
SomeClass SomeClass::NullObject;
void print(SomeClass &val)
{
if(val == SomeClass::NullObject)
{
printf("\nNULL");
}
else
{
printf("\nNOT NULL");
}
}
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
If you use the Angular CLI to create your components, let's say CarComponent
, it attaches app
to the selector name (i.e app-car
) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car>
or change the selector in the CarComponent
to selector: 'car'
Unlike Java where you would declare boolean flag = True
, in Python you can just declare myFlag = True
Python would interpret this as a boolean variable
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
First of all
<div id="demo" align="center" value="1"></div>
that is not valid HTML. Read up on custom data attributes or use the following instead:
<div id="demo" align="center" data-value="1"></div>
Since "data-value" is an attribute, you have to use the getAttribute function to retrieve its value.
var cookieValue = document.getElementById("demo").getAttribute("data-value");
^\+[1-9]{1}[0-9]{7,11}$
The Regular Expression ^\+[1-9]{1}[0-9]{7,11}$
fails for "+290 8000" and similar valid numbers that are shorter than 8 digits.
The longest numbers could be something like 3 digit country code, 3 digit area code, 8 digit subscriber number, making 14 digits.
I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....
So here's my answer and can be run out of the box.
<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {
$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})
$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end = $('#enddate').datepicker('getDate');
if (start<end) {
var days = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>
a Fiddle can be seen here DEMO
[nodemon] Internal watch failed: watch /home/Document/nmmExpressServer/bin ENOSPC
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `nodemon ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
This is the error I got when running nodemon ./bin/www
.
The solution was closing an Atom window that had a entire directory of folders open in the project window.
I don't know why, but I'm assuming Atom and nodemon use similar processes to watch files/folders.
Instruction is base on the "icemelon" post. Link to the post:
how-do-i-compile-and-run-a-c-program-in-sublime-text-2
Use the link below to find out how to setup enviroment variable on your OS:
The instruction below was tested on the Windows 8.1 system and Sublime Text 3 - build 3065.
1) Install MinGW. 2) Add path to the "MinGW\bin" in the "PATH environment variable".
"System Properties -> Advanced -> Environment" variables and there update "PATH' variable.
3) Then check your PATH environment variable by the command below in the "Command Prompt":
echo %path%
4) Add new Build System to the Sublime Text.
My version of the code below ("C.sublime-build").
link to the code:
// Put this file here:
// "C:\Users\[User Name]\AppData\Roaming\Sublime Text 3\Packages\User"
// Use "Ctrl+B" to Build and "Crtl+Shift+B" to Run the project.
// OR use "Tools -> Build System -> New Build System..." and put the code there.
{
"cmd" : ["gcc", "$file_name", "-o", "${file_base_name}.exe"],
// Doesn't work, sublime text 3, Windows 8.1
// "cmd" : ["gcc $file_name -o ${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path",
// You could add path to your gcc compiler this and don't add path to your "PATH environment variable"
// "path" : "C:\\MinGW\\bin"
"variants" : [
{ "name": "Run",
"cmd" : ["${file_base_name}.exe"]
}
]
}
If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:
sqlite3 database.sqlite
Replace database.sqlite
with your database file. Then, if the database is small enough, you can view the entire contents with:
sqlite> .dump
Or you can list the tables:
sqlite> .tables
Regular SQL works here as well:
sqlite> select * from some_table;
Replace some_table
as appropriate.
If you want it to be a jquery method, you can do it like this :
$.sum = function(arr) {
var r = 0;
$.each(arr, function(i, v) {
r += +v;
});
return r;
}
and call it like this :
var sum = $.sum(["20", "40", "80", "400"]);
SELECT column_name from table_name
WHERE RTRIM(ISNULL(column_name, '')) LIKE ''
ISNULL(column_name, '')
will return '' if column_name is NULL, otherwise it will return column_name.
UPDATE
In Oracle, you can use NVL
to achieve the same results.
SELECT column_name from table_name
WHERE RTRIM(NVL(column_name, '')) LIKE ''
If you like HTML tags more than markdown + center alignment:
<div align="center">_x000D_
<a href="https://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE"><img src="https://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg" alt="IMAGE ALT TEXT"></a>_x000D_
</div>
_x000D_
To convert the byte[] to string[], simply use the below line.
byte[] fileData; // Some byte array
//Convert byte[] to string[]
var table = (Encoding.Default.GetString(
fileData,
0,
fileData.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" },
StringSplitOptions.None);
$scope.popoverPostion = function(event){
$scope.pos = '';
if(event.x <= 207 && event.x >= 140){
$scope.pos = 'top';
event.x = '';
}
else if(event.x < 140){
$scope.pos = 'top-left';
event.x = '';
}
else if(event.x > 207){
$scope.pos = 'top-right';
event.x = '';
}
};
a = if true then 5 else 10
a = if false then 5 else 10
See documentation.
Killing off the binding when it does not exist yet is not the best solution but seems effective enough! The second time you ‘click’ you can know with certainty that it will not create a duplicate binding.
I therefore use die() or unbind() like this:
$("#someid").die("click").live("click",function(){...
or
$("#someid").unbind("click").bind("click",function(){...
or in recent jQuery versions:
$("#someid").off("click").on("click",function(){...
//in html file
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Country</label>
<select class="form-control" formControlName="country" (change)="onCountryChange($event.target.value)">
<option disabled selected value [ngValue]="null"> -- Select Country -- </option>
<option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
<div *ngIf="isEdit">
<option></option>
</div>
</select>
</div>
</div>
</div>
<div class="help-block" *ngIf="studentForm.get('country').invalid && studentForm.get('country').touched">
<div *ngIf="studentForm.get('country').errors.required">*country is required</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">State</label>
<select class="form-control" formControlName="state" (change)="onStateChange($event.target.value)">
<option disabled selected value [ngValue]="null"> -- Select State -- </option>
<option *ngFor="let state of states" [value]="state.id">{{state.state_name}}</option>
</select>
</div>
</div>
</div>
<div class="help-block" *ngIf="studentForm.get('state').invalid && studentForm.get('state').touched">
<div *ngIf="studentForm.get('state').errors.required">*state is enter code hererequired</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">City</label>
<select class="form-control" formControlName="city">
<option disabled selected value [ngValue]="null"> -- Select City -- </option>
<option *ngFor="let city of cities" [value]="city.id" >{{city.city_name}}</option>
</select>
</div>
</div>
</div>
<div class="help-block" *ngIf="studentForm.get('city').invalid && studentForm.get('city').touched">
<div *ngIf="studentForm.get('city').errors.required">*city is required</div>
</div>
//then in component
onCountryChange(countryId:number){
this.studentServive.getSelectedState(countryId).subscribe(resData=>{
this.states = resData;
});
}
onStateChange(stateId:number){
this.studentServive.getSelectedCity(stateId).subscribe(resData=>{
this.cities = resData;
});
}`enter code here`
Using D3:
If you want to add the element in the reverse order to the data use:
.insert('g', ":first-child")
Instead of .append
It's !=
without type coercion. See the MDN documentation for comparison operators.
Also see this StackOverflow answer, which includes a quote from "JavaScript: The Good Parts" about the problems with ==
and !=
. (null == undefined
, false == "0"
, etc.)
Short answer: always use ===
and !==
unless you have a compelling reason to do otherwise. (Tools like JSLint, JSHint, ESLint, etc. will give you this same advice.)
Here's how I've worked it out:
tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log
FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end
start notepad.exe
:end
del search.log
The above will open Notepad if it is not already running.
Edit: Note that this won't find applications hidden from the tasklist. This will include any scheduled tasks running as a different user, as these are automatically hidden.
Given that Windows has no sys/socket.h, you might consider just doing something like this:
#ifdef __WIN32__
# include <winsock2.h>
#else
# include <sys/socket.h>
#endif
I know you indicated that you won't use WinSock, but since WinSock is how TCP networking is done under Windows, I don't see that you have any alternative. Even if you use a cross-platform networking library, that library will be calling WinSock internally. Most of the standard BSD sockets API calls are implemented in WinSock, so with a bit of futzing around, you can make the same sockets-based program compile under both Windows and other OS's. Just don't forget to do a
#ifdef __WIN32__
WORD versionWanted = MAKEWORD(1, 1);
WSADATA wsaData;
WSAStartup(versionWanted, &wsaData);
#endif
at the top of main()... otherwise all of your socket calls will fail under Windows, because the WSA subsystem wasn't initialized for your process.
If you code is intended for a different OS (like Mac OS X, Linux) you may use following:
#ifdef _WIN32
#define _CRT_SECURE_NO_DEPRECATE
#endif