For a quick and cheap way to host an angular app, I have been using the Firbase hosting. It's free on the first tier and very easy to deploy new versions using the Firebase CLI. This article here explains the necessary steps to deploy your production angular 2 app to Firebase: https://medium.com/codingthesmartway-com-blog/hosting-angular-2-applications-on-firebase-f194688c978d
In short, you run ng build --prod
which creates a dist folder in the package and that's the folder that gets deployed to Firebase Hosting.
Click Product
> Archive
from the menu, once this is complete open up the Organiser
and click the latest version > Distribute
> Save for Enterprise or Ad-Hoc Deployment
> Choose correct signing > Save to destination
What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!
As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you set — Official Documentation
Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!
How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.
Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.
Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…
First Approach: Are your files gzipped?
Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.
How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.
const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())
Second Approach:: Analyze your Angular bundle
If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.
It’s super easy to get this graph.
npm install -g webpack-bundle-analyzer
ng build --stats-json
(don’t use flag --prod
). By enabling --stats-json
you will get an additional file stats.jsonwebpack-bundle-analyzer ./dist/stats.json
and your browser will pop up the page at localhost:8888. Have fun with it.ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours
your line raising the error is here:
comment = Comment.objects.get(pk=comment_id)
you try to access a non-existing comment.
from django.shortcuts import get_object_or_404
comment = get_object_or_404(Comment, pk=comment_id)
Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.
Ok up to here I suppose you are aware of this.
Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.
Other users go to addresses from their history, (same if data have been deleted since it may happens).
First of all thanks for those who have upvoted this answer over the years.
Please be aware that this question was asked in August 2013, when Docker was still a very new technology. Since then: Kubernetes was launched on June 2014, Docker swarm was integrated into the Docker engine in Feb 2015, Amazon launched it's container solution, ECS, in April 2015 and Google launched GKE in August 2015. It's fair to say the production container landscape has changed substantially.
The short answer is that you'd have to write your own logic to do this.
I would expect this kind of feature to emerge from the following projects, built on top of docker, and designed to support applications in production:
Another related project I recently discovered:
The latest release Openstack contains support for managing Docker containers:
System for managing Docker instances
And a presentation on how to use tools like Packer, Docker and Serf to deliver an immutable server infrastructure pattern
A neat article on how to wire together docker containers using serf:
Run Docker on Mesos using the Marathon framework
Mesosphere Docker Developer Tutorial
Run Docker on Tsuru as it supports docker-cluster and segregated scheduler deploy
Docker-based environments orchestration
Google kubernetes
Redhat have refactored their openshift PAAS to integrate Docker
A Docker NodeJS lib wrapping the Docker command line and managing it from a json file.
Amazon's new container service enables scaling in the cluster.
Strictly speaking Flocker does not "scale" applications, but it is designed to fufil a related function of making stateful containers (running databases services?) portable across multiple docker hosts:
A project to create portable templates that describe Docker applications:
The Docker project is now addressing orchestration natively (See announcement)
See also:
The Openstack project now has a new "container as a service" project called Magnum:
Shows a lot of promise, enables the easy setup of Docker orchestration frameworks like Kubernetes and Docker swarm.
Rancher is a project that is maturing rapidly
Nice UI and strong focus on hyrbrid Docker infrastructures
The Lattice project is an offshoot of Cloud Foundry for managing container clusters.
Docker recently bought Tutum:
Package manager for applications deployed on Kubernetes.
Vamp is an open source and self-hosted platform for managing (micro)service oriented architectures that rely on container technology.
A Distributed, Highly Available, Datacenter-Aware Scheduler
From the guys that gave us Vagrant and other powerful tools.
Container hosting solution for AWS, open source and based on Kubernetes
Apache Mesos based container hosted located in Germany
https://sloppy.io/features/#features
And Docker Inc. also provide a container hosting service called Docker cloud
Jelastic is a hosted PAAS service that scales containers automatically.
Kotlin version of @Swapnil Kotwal's answer.
Android Studio 4.0.1, Kotlin 1.3.72
val greenText = SpannableString("This is green,")
greenText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someGreenColor), null), 0, greenText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.text = greenText
val yellowText = SpannableString("this is yellow, ")
yellowText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someYellowColor), null), 0, yellowText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(yellowText)
val redText = SpannableString("and this is red.")
redText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someRedColor), null), 0, redText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(redText)
I had the same problem. I think the best solution is to use log.exception, which will automatically print out stack trace and error message, such as:
try:
pass
log.info('Success')
except:
log.exception('Failed')
A different method - using setTag() and getTag() methods of the View class.
use setTag() in the onBindViewHolder method of your adapter
@Override
public void onBindViewHolder(myViewHolder viewHolder, int position) {
viewHolder.mCardView.setTag(position);
}
where mCardView is defined in the myViewHolder class
private class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public View mCardView;
public myViewHolder(View view) {
super(view);
mCardView = (CardView) view.findViewById(R.id.card_view);
mCardView.setOnClickListener(this);
}
}
use getTag() in your OnClickListener implementation
@Override
public void onClick(View view) {
int position = (int) view.getTag();
//display toast with position of cardview in recyclerview list upon click
Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
}
see https://stackoverflow.com/a/33027953/4658957 for more details
Just use a simple button
instead of a submit button. And call a JavaScript function to handle form submit:
<input type="button" name="submit" value="submit" onclick="submit_form();"/>
Function within a script
tag:
function submit_form() {
if (conditions) {
document.forms['myform'].submit();
}
else {
returnToPreviousPage();
}
}
You can also try window.history.forward(-1);
Specifying a max-width
or fixed width doesn't work for all situations, and the table should be fluid and auto-space its cells. That's what tables are for. Works on IE9 and other browsers.
Use this: http://jsfiddle.net/maruxa1j/
table {
width: 100%;
}
.first {
width: 50%;
}
.ellipsis {
position: relative;
}
.ellipsis:before {
content: ' ';
visibility: hidden;
}
.ellipsis span {
position: absolute;
left: 0;
right: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
_x000D_
<table border="1">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ellipsis first"><span>This Text Overflows and is too large for its cell.</span></td>
<td class="ellipsis"><span>This Text Overflows and is too large for its cell.</span></td>
<td class="ellipsis"><span>This Text Overflows and is too large for its cell.</span></td>
<td class="ellipsis"><span>This Text Overflows and is too large for its cell.</span></td>
</tr>
</tbody>
</table>
_x000D_
http://msdn.microsoft.com/en-us/library/wkze6zky.aspx
menu: Project-->Add Reference
click: assemblies, framework
Put a checkmark on Microsoft.VisualBasic.
Hit OK.
That link is for Visual Studio 2013, you can use the "Other versions" dropdown for different versions of visual studio.
In all cases you need to add a reference to the .NET assembly "Microsoft.VisualBasic".
At the top of your c# file you neeed:
using Microsoft.VisualBasic;
Then you can look at writing the code.
The code would be something like:
private void btnOK_Click(object sender, EventArgs e)
{
if ( Information.IsNumeric(startingbudget) )
{
MessageBox.Show("This is a number.");
}
}
This Blog article explains the internals of ODEX files:
WHAT IS AN ODEX FILE?
In Android file system, applications come in packages with the extension .apk. These application packages, or APKs contain certain .odex files whose supposed function is to save space. These ‘odex’ files are actually collections of parts of an application that are optimized before booting. Doing so speeds up the boot process, as it preloads part of an application. On the other hand, it also makes hacking those applications difficult because a part of the coding has already been extracted to another location before execution.
If you have already staged files, simply unstage them:
git reset HEAD [file-name-A.ext] [file-name-B.ext]
Then add them bit by bit back in.
Windows 8 64bit runs both 32bit and 64bit applications. You want chromedriver 32bit for the 32bit version of chrome you're using.
The current release of chromedriver (v2.16) has been mentioned as running much smoother since it's older versions (there were a lot of issues before). This post mentions this and some of the slight differences between chromedriver and running the normal firefox driver:
http://seleniumsimplified.com/2015/07/recent-course-source-code-changes-for-webdriver-2-46-0/
What you mentioned about "doesn't call main method" is an odd remark. You may want to elaborate.
function add(){
var first=parseFloat($("#first").val());
var second=parseFloat($("#second").val());
$("#result").val(+(first+second).toFixed(2));
}
There is a great explanation in the given url below.
http://www.codeproject.com/Articles/330447/Understanding-Association-Aggregation-and-Composit
Please check!!!
You are using incorrect overload. You should use this overload
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
Object routeValues,
Object htmlAttributes
)
And the correct code would be
<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>
Note that extra parameter at the end.
For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object
overload that you are trying to use.
Use the BFG Repo-Cleaner, a simpler, faster alternative to git-filter-branch
specifically designed for removing unwanted files from Git history.
Carefully follow the usage instructions, the core part is just this:
$ java -jar bfg.jar --strip-blobs-bigger-than 100M my-repo.git
Any files over 100MB in size (that aren't in your latest commit) will be removed from your Git repository's history. You can then use git gc
to clean away the dead data:
$ git gc --prune=now --aggressive
The BFG is typically at least 10-50x faster than running git-filter-branch
, and generally easier to use.
Full disclosure: I'm the author of the BFG Repo-Cleaner.
str.replace()
v2|v3 does not recognize regular expressions.
To perform a substitution using a regular expression, use re.sub()
v2|v3.
For example:
import re
line = re.sub(
r"(?i)^.*interfaceOpDataFile.*$",
"interfaceOpDataFile %s" % fileIn,
line
)
In a loop, it would be better to compile the regular expression first:
import re
regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
# do something with the updated line
I had same problem in my xiaomi note 4a device. I solved it by turning off MIUI optimization.
You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.
You could give the span a set width, then add the margin:0 auto
again. This would center-align it.
.left
{
background-color: #999999;
height: 50px;
width: 24.5%;
}
span.panelTitleTxt
{
display:block;
width:100px;
height: 100%;
margin: 0 auto;
}
The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.
The semantics of the recursive execution is as follows:
-- Table: "user"
-- DROP TABLE "user";
CREATE TABLE "user"
(
id bigserial NOT NULL,
name text NOT NULL,
email character varying(20) NOT NULL,
password text NOT NULL,
CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "user"
OWNER TO postgres;
Actually, casting doesn't always work. If the object is not an instanceof
the class you're casting it to you will get a ClassCastException
at runtime.
Does it support
<!DOCTYPE html>
Yes it does.
Perhaps a better question is what modern web features IE8 supports. Some of the best places to answer that are caniuse.com, html5test.com, and browserscope.org.
HTML5 means a lot of different things to different people. These days, it means HTML, CSS, and JavaScript functionality. The term is becoming a bit "Web 2.0"-like.
You can have class something like below from which you can add 'n' number of functions or console_scripts you want to execute in parallel passion and start the execution and wait for all jobs to complete..
from multiprocessing import Process
class ProcessParallel(object):
"""
To Process the functions parallely
"""
def __init__(self, *jobs):
"""
"""
self.jobs = jobs
self.processes = []
def fork_processes(self):
"""
Creates the process objects for given function deligates
"""
for job in self.jobs:
proc = Process(target=job)
self.processes.append(proc)
def start_all(self):
"""
Starts the functions process all together.
"""
for proc in self.processes:
proc.start()
def join_all(self):
"""
Waits untill all the functions executed.
"""
for proc in self.processes:
proc.join()
def two_sum(a=2, b=2):
return a + b
def multiply(a=2, b=2):
return a * b
#How to run:
if __name__ == '__main__':
#note: two_sum, multiply can be replace with any python console scripts which
#you wanted to run parallel..
procs = ProcessParallel(two_sum, multiply)
#Add all the process in list
procs.fork_processes()
#starts process execution
procs.start_all()
#wait until all the process got executed
procs.join_all()
your markup was a bit messed up. Here's the styles you need and proper html
CSS:
.navbar-brand,
.navbar-nav li a {
line-height: 150px;
height: 150px;
padding-top: 0;
}
HTML:
<nav class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="img/logo.png" /></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="">Portfolio</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</nav>
Or check out the fiddle at: http://jsfiddle.net/TP5V8/1/
Maybe you could add a static class with your custom namespace and the same class name:
using CLRConsole = System.Console;
namespace ExtensionMethodsDemo
{
public static class Console
{
public static void WriteLine(string value)
{
CLRConsole.WriteLine(value);
}
public static void WriteBlueLine(string value)
{
System.ConsoleColor currentColor = CLRConsole.ForegroundColor;
CLRConsole.ForegroundColor = System.ConsoleColor.Blue;
CLRConsole.WriteLine(value);
CLRConsole.ForegroundColor = currentColor;
}
public static System.ConsoleKeyInfo ReadKey(bool intercept)
{
return CLRConsole.ReadKey(intercept);
}
}
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteBlueLine("This text is blue");
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
}
On an Arm7 (armhf) device running Debian Stretch, I had to issue either of the following:
$ nodejs -v
$ nodejs -h
The following did not work:
$ node -v
$ node -h
$ apm -v
Hope this helps someone else.
If you don't want to touch your current table too much you can make a fake pinned column in front of the table.
The example shows one way of doing it without JS
table {_x000D_
border-collapse: collapse;_x000D_
border-spacing: 0;_x000D_
border: 1px solid #ddd;_x000D_
min-width: 600px;_x000D_
}_x000D_
_x000D_
.labels {_x000D_
display:flex;_x000D_
flex-direction: column_x000D_
}_x000D_
_x000D_
.overflow {_x000D_
overflow-x: scroll;_x000D_
min width: 400px;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
.label {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
white-space:nowrap;_x000D_
padding: 10px;_x000D_
flex: 1;_x000D_
border-bottom: 1px solid #ddd;_x000D_
border-right: 2px solid #ddd;_x000D_
}_x000D_
_x000D_
.label:last-of-type {_x000D_
overflow-x: scroll;_x000D_
border-bottom: 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
border: 1px solid #ddd;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
display:flex;_x000D_
max-width: 600px;_x000D_
padding: 0;_x000D_
border: 5px solid #ddd;_x000D_
}
_x000D_
<div class="flex">_x000D_
<div class="labels">_x000D_
<span class="label">Label 1</span>_x000D_
<span class="label">Lorem ipsum dolor sit amet.</span>_x000D_
<span class="label">Lorem ipsum dolor.</span>_x000D_
</div>_x000D_
<div class="overflow">_x000D_
<table>_x000D_
<tr>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
What are iml files in Android Studio project?
A Google search on iml file
turns up:
IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.
(from this page)
why not to use gradle scripts to integrate with external modules that you add to your project.
You do "use gradle scripts to integrate with external modules", or your own modules.
However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml
files and the metadata in .idea/
directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle
. This is also why you don't bother putting .iml
files or .idea/
in version control, as their contents will be regenerated.
If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?
To a large extent, you can't.
You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle
, how to find files in that structure. However, other metadata (compileSdkVersion
, dependencies, etc.) will not be nearly as easily replicated.
Other alternatives include:
Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio
Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts
Have everyone use one IDE
This Code detects whenever a textbox's content has changed by the user and modified by Javascript code.
var $myText = jQuery("#textbox");
$myText.data("value", $myText.val());
setInterval(function() {
var data = $myText.data("value"),
val = $myText.val();
if (data !== val) {
console.log("changed");
$myText.data("value", val);
}
}, 100);
Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery
As a result of a deep code analysis, I've created a function: function callPlayer
requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.
On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.
/**
* @author Rob W <[email protected]>
* @website https://stackoverflow.com/a/7513356/938089
* @version 20190409
* @description Executes function on a framed YouTube video (see website link)
* For a full list of possible functions, see:
* https://developers.google.com/youtube/js_api_reference
* @param String frame_id The id of (the div containing) the frame
* @param String func Desired function to call, eg. "playVideo"
* (Function) Function to call when the player is ready.
* @param Array args (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
var iframe = document.getElementById(frame_id);
if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
}
// When the player is not ready yet, add the event to a queue
// Each frame_id is associated with an own queue.
// Each queue has three possible states:
// undefined = uninitialised / array = queue / .ready=true = ready
if (!callPlayer.queue) callPlayer.queue = {};
var queue = callPlayer.queue[frame_id],
domReady = document.readyState == 'complete';
if (domReady && !iframe) {
// DOM is ready and iframe does not exist. Log a message
window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
if (queue) clearInterval(queue.poller);
} else if (func === 'listening') {
// Sending the "listener" message to the frame, to request status updates
if (iframe && iframe.contentWindow) {
func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
iframe.contentWindow.postMessage(func, '*');
}
} else if ((!queue || !queue.ready) && (
!domReady ||
iframe && !iframe.contentWindow ||
typeof func === 'function')) {
if (!queue) queue = callPlayer.queue[frame_id] = [];
queue.push([func, args]);
if (!('poller' in queue)) {
// keep polling until the document and frame is ready
queue.poller = setInterval(function() {
callPlayer(frame_id, 'listening');
}, 250);
// Add a global "message" event listener, to catch status updates:
messageEvent(1, function runOnceReady(e) {
if (!iframe) {
iframe = document.getElementById(frame_id);
if (!iframe) return;
if (iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
if (!iframe) return;
}
}
if (e.source === iframe.contentWindow) {
// Assume that the player is ready if we receive a
// message from the iframe
clearInterval(queue.poller);
queue.ready = true;
messageEvent(0, runOnceReady);
// .. and release the queue:
while (tmp = queue.shift()) {
callPlayer(frame_id, tmp[0], tmp[1]);
}
}
}, false);
}
} else if (iframe && iframe.contentWindow) {
// When a function is supplied, just call it (like "onYouTubePlayerReady")
if (func.call) return func();
// Frame exists, send message
iframe.contentWindow.postMessage(JSON.stringify({
"event": "command",
"func": func,
"args": args || [],
"id": frame_id
}), "*");
}
/* IE8 does not support addEventListener... */
function messageEvent(add, listener) {
var w3 = add ? window.addEventListener : window.removeEventListener;
w3 ?
w3('message', listener, !1)
:
(add ? window.attachEvent : window.detachEvent)('onmessage', listener);
}
}
Usage:
callPlayer("whateverID", function() {
// This function runs once the player is ready ("onYouTubePlayerReady")
callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");
Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.
Q: playVideo
does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay"
on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />
but the function doesn't execute any function!
A: You have to add ?enablejsapi=1
at the end of your URL: /embed/vid_id?enablejsapi=1
.
Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://
). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.
Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage
method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.
Q: What browsers are supported?
A: Every browser which supports JSON and postMessage
.
document.readyState
was implemented in 3.6)Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference
onYouTubePlayerReady
: callPlayer('frame_id', function() { ... })
.callPlayer
forces a check of readiness. This is needed, because when callPlayer
is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage
, which was ignored.&origin=*
in the URL.&origin=*
to the URL.Right click on eclipse icon and click on open file location then delete the eclipse folder from drive(Save backup of your eclipse workspace if you want). Also delete eclipse icon. Thats it..
To just download a commit using the 7-digit SHA1 short form do:
Working Example:
https://github.com/python/cpython/archive/31af650.zip
Description:
`https://github.com/username/projectname/archive/commitshakey.zip`
If you have the long hash key
31af650ee25f65794b75d4dfefed6fe4758781c1
, just get the first 7 chars31af650
. It's the default for GitHub.
I think this may help you...programme is very simple and works fine
import java.util.*;
public class NumberToWord
{
public void pw(int n, String ch)
{
String one[] = {
" ", " one", " two", " three", " four", " five", " six", " seven",
" eight", " Nine", " ten", " eleven", " twelve", " thirteen",
" fourteen", "fifteen", " sixteen", " seventeen", " eighteen",
" nineteen" };
String ten[] = { " ", " ", " twenty", " thirty", " forty", " fifty",
" sixty", "seventy", " eighty", " ninety" };
if (n > 19) {
System.out.print(ten[n / 10] + " " + one[n % 10]);
} else {
System.out.print(one[n]);
}
if (n > 0)
System.out.print(ch);
}
public static void main(String[] args)
{
int n = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer number: ");
n = s.nextInt();
if (n <= 0)
System.out.print("Enter numbers greater than 0");
else
{
NumberToWord a = new NumberToWord();
System.out.print("After conversion number in words is :");
a.pw((n / 1000000000), " Hundred");
a.pw((n / 10000000) % 100, " crore");
a.pw(((n / 100000) % 100), " lakh");
a.pw(((n / 1000) % 100), " thousand");
a.pw(((n / 100) % 10), " hundred");
a.pw((n % 100), " ");
}
}
}
The rename
function does this
rename('image1.jpg', 'del/image1.jpg');
If you want to keep the existing file on the same place you should use copy
copy('image1.jpg', 'del/image1.jpg');
If you want to move an uploaded file use the move_uploaded_file
, although this is almost the same as rename
this function also checks that the given file is a file that was uploaded via the POST
, this prevents for example that a local file is moved
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
code snipet from docs
The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.
Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.
It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.
Here is another way to do it. I have used it in some cases and it's working.
Function IsArrayEmpty(arr As Variant) As Boolean
Dim index As Integer
index = -1
On Error Resume Next
index = UBound(arr)
On Error GoTo 0
If (index = -1) Then IsArrayEmpty = True Else IsArrayEmpty = False
End Function
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
If you're desperate (like i was) for tooltips on checkboxes, textboxes and the like, then here is my hackey workaround:
$('input:disabled, button:disabled').after(function (e) {
d = $("<div>");
i = $(this);
d.css({
height: i.outerHeight(),
width: i.outerWidth(),
position: "absolute",
})
d.css(i.offset());
d.attr("title", i.attr("title"));
d.tooltip();
return d;
});
Working examples: http://jsfiddle.net/WB6bM/11/
For what its worth, I believe tooltips on disabled form elements is very important to the UX. If you're preventing somebody from doing something, you should tell them why.
You could use reflection and loop through all the object properties, then get their values and save them to the log. The formatting is really trivial (you could use \t to indent an objects properties and its values):
MyObject
Property1 = value
Property2 = value2
OtherObject
OtherProperty = value ...
You can write this in a more compact way:
var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";
And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:
For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.
You don't have to have a method for that. You could create a property like this instead:
class SalesPerson
{
string firstName, lastName;
public string FirstName { get { return firstName; } set { firstName = value; } }
public string LastName { get { return lastName; } set { lastName = value; } }
public string FullName { get { return this.FirstName + " " + this.LastName; } }
}
The class could even be shortened to:
class SalesPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName {
get { return this.FirstName + " " + this.LastName; }
}
}
The property could then be accessed like any other property:
class Program
{
static void Main(string[] args)
{
SalesPerson x = new SalesPerson("John", "Doe");
Console.WriteLine(x.FullName); // Will print John Doe
}
}
list( map( lambda x: x[4][0], socket.getaddrinfo( \
'www.example.com.',22,type=socket.SOCK_STREAM)))
gives you a list of the addresses for www.example.com. (ipv4 and ipv6)
Building on my normal Android .gitignore, and after reading through documentation on the Intellij IDEA website and reading posts on StackOverflow, I have constructed the following file:
# built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# built native files (uncomment if you build your own)
# *.o
# *.so
# generated files
bin/
gen/
# Ignore gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Eclipse Metadata
.metadata/
# Mac OS X clutter
*.DS_Store
# Windows clutter
Thumbs.db
# Intellij IDEA (see https://intellij-support.jetbrains.com/entries/23393067)
.idea/workspace.xml
.idea/tasks.xml
.idea/datasources.xml
.idea/dataSources.ids
Also note that as pointed out, the built native files section is primarily useful when you are building your own native code with the Android NDK. If, on the other hand, you are using a third party library that includes these files, you may wish to remove these lines (*.o and *.so) from your .gitignore.
It's an encoding error - so if it's a unicode string, this ought to fix it:
text.encode("windows-1252").decode("utf-8")
If it's a plain string, you'll need an extra step:
text.decode("utf-8").encode("windows-1252").decode("utf-8")
Both of these will give you a unicode string.
By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:
>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}
Maybe this answer will help:
nginx error connect to php5-fpm.sock failed (13: Permission denied)
The solution was to replace www-data with nginx in /var/www/php/fpm/pool.d/www.conf
And respectively modify the socket credentials:
$ sudo chmod nginx:nginx /var/run/php/php7.2-fpm.sock
Ive found another: http://swipejs.com/
seems to work nicely however I encounter an issue with it when paired with bootstrap on the OS X version of Chrome. If total cross-browser compatibility isn't an issue, then you're golden.
A no throw specification on an inlined function that only returns a member variable and could not possibly throw exceptions may be used by some compilers to do pessimizations (a made-up word for the opposite of optimizations) that can have a detrimental effect on performance. This is described in the Boost literature: Exception-specification
With some compilers a no-throw specification on non-inline functions may be beneficial if the correct optimizations are made and the use of that function impacts performance in a way that it justifies it.
To me it sounds like whether to use it or not is a call made by a very critical eye as part of a performance optimization effort, perhaps using profiling tools.
A quote from the above link for those in a hurry (contains an example of bad unintended effects of specifying throw on an inline function from a naive compiler):
Exception-specification rationale
Exception specifications [ISO 15.4] are sometimes coded to indicate what exceptions may be thrown, or because the programmer hopes they will improve performance. But consider the following member from a smart pointer:
T& operator*() const throw() { return *ptr; }
This function calls no other functions; it only manipulates fundamental data types like pointers Therefore, no runtime behavior of the exception-specification can ever be invoked. The function is completely exposed to the compiler; indeed it is declared inline Therefore, a smart compiler can easily deduce that the functions are incapable of throwing exceptions, and make the same optimizations it would have made based on the empty exception-specification. A "dumb" compiler, however, may make all kinds of pessimizations.
For example, some compilers turn off inlining if there is an exception-specification. Some compilers add try/catch blocks. Such pessimizations can be a performance disaster which makes the code unusable in practical applications.
Although initially appealing, an exception-specification tends to have consequences that require very careful thought to understand. The biggest problem with exception-specifications is that programmers use them as though they have the effect the programmer would like, instead of the effect they actually have.
A non-inline function is the one place a "throws nothing" exception-specification may have some benefit with some compilers.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, csv, sqlite3
def main():
con = sqlite3.connect(sys.argv[1]) # database file input
cur = con.cursor()
cur.executescript("""
DROP TABLE IF EXISTS t;
CREATE TABLE t (COL1 TEXT, COL2 TEXT);
""") # checks to see if table exists and makes a fresh table.
with open(sys.argv[2], "rb") as f: # CSV file input
reader = csv.reader(f, delimiter=',') # no header information with delimiter
for row in reader:
to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8")] # Appends data from CSV file representing and handling of text
cur.execute("INSERT INTO neto (COL1, COL2) VALUES(?, ?);", to_db)
con.commit()
con.close() # closes connection to database
if __name__=='__main__':
main()
Update (2019, latest)
Since Jan 2019, GitHub allows private repositories for up to three collaborators.
Previous answer:
Here is the comparison for free plans listed by tree main Git Cloud based solutions:
Here is the comparison for paid plans listed by tree main Git Cloud based solutions:
I'm not seeing people mentioning GitLab here, but it seems like the best free private plan for me. I myself am using it with no problems.
GitHub: If you have a student account or want to pay for $7 monthly, GitHub has the biggest community and you can take advantage of it's public repositories, forks, etc.
Bitbucket: If you use other products from Atlassian like Jira or Confluence, Bitbucket works great with them.
GitLab: Everything that I care about (free private repository, number of private repositories, number of collaborators, etc.) are offered for free. This seems like the best choice for me.
This command,
numpy.append(a, a[0])
does not alter a
array. However, it returns a new modified array.
So, if a
modification is required, then the following must be used.
a = numpy.append(a, a[0])
Use intersection of two arrays.
Ex:
var sortArray = ['a', 'b', 'c', 'd', 'e'];
var arrayToBeSort = ['z', 's', 'b', 'e', 'a'];
_.intersection(sortArray, arrayToBeSort)
=> ['a', 'b', 'e']
if 'z and 's' are out of range of first array, append it at the end of result
The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:
http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.
CODE
<?php
# setup test array.
$cats = array();
$cats[] = (object) array('id' => 15);
$cats[] = (object) array('id' => 18);
$cats[] = (object) array('id' => 23);
function extract_ids($array = array())
{
$ids = array();
foreach ($array as $object) {
$ids[] = $object->id;
}
return $ids;
}
$cat_ids = extract_ids($cats);
var_dump($cats);
var_dump($cat_ids);
?>
OUTPUT
# var_dump($cats);
array(3) {
[0]=>
object(stdClass)#1 (1) {
["id"]=>
int(15)
}
[1]=>
object(stdClass)#2 (1) {
["id"]=>
int(18)
}
[2]=>
object(stdClass)#3 (1) {
["id"]=>
int(23)
}
}
# var_dump($cat_ids);
array(3) {
[0]=>
int(15)
[1]=>
int(18)
[2]=>
int(23)
}
I know its using a loop, but it's the simplest way to do it! And using a function it still ends up on a single line.
Using java.time…
LocalDate.parse( // Generate `LocalDate` object from String input.
"23/2/2010" ,
DateTimeFormatter.ofPattern( "d/M/uuuu" )
)
.getDayOfWeek() // Get `DayOfWeek` enum object.
.getDisplayName( // Localize. Generate a String to represent this day-of-week.
TextStyle.SHORT_STANDALONE , // How long or abbreviated. Some languages have an alternate spelling for "standalone" use (not so in English).
Locale.US // Or Locale.CANADA_FRENCH and such. Specify a `Locale` to determine (1) human language for translation, and (2) cultural norms for abbreviation, punctuation, etc.
)
Tue
See this code run live at IdeOne.com (but only Locale.US
works there).
See my example code above, and see the correct Answer for java.time by Przemek.
if just the day ordinal is desired, how can that be retrieved?
For ordinal number, consider passing around the DayOfWeek
enum object instead such as DayOfWeek.TUESDAY
. Keep in mind that a DayOfWeek
is a smart object, not just a string or mere integer number. Using those enum objects makes your code more self-documenting, ensures valid values, and provides type-safety.
But if you insist, ask DayOfWeek
for a number. You get 1-7 for Monday-Sunday per the ISO 8601 standard.
int ordinal = myLocalDate.getDayOfWeek().getValue() ;
UPDATE: The Joda-Time project is now in maintenance mode. The team advises migrating to the java.time classes. The java.time framework is built into Java 8 (as well as back-ported to Java 6 & 7 and further adapted to Android).
Here is example code using the Joda-Time library version 2.4, as mentioned in the accepted answer by Bozho. Joda-Time is far superior to the java.util.Date/.Calendar classes bundled with Java.
LocalDate
Joda-Time offers the LocalDate
class to represent a date-only without any time-of-day or time zone. Just what this Question calls for. The old java.util.Date/.Calendar classes bundled with Java lack this concept.
Parse the string into a date value.
String input = "23/2/2010";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( input );
Extract from the date value the day of week number and name.
int dayOfWeek = localDate.getDayOfWeek(); // Follows ISO 8601 standard, where Monday = 1, Sunday = 7.
Locale locale = Locale.US; // Locale specifies the human language to use in determining day-of-week name (Tuesday in English versus Mardi in French).
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "E" ).withLocale( locale );
String output = formatterOutput.print( localDate ); // 'E' is code for abbreviation of day-of-week name. See Joda-Time doc.
String outputQuébécois = formatterOutput.withLocale( Locale.CANADA_FRENCH ).print( localDate );
Dump to console.
System.out.println( "input: " + input );
System.out.println( "localDate: " + localDate ); // Defaults to ISO 8601 formatted strings.
System.out.println( "dayOfWeek: " + dayOfWeek );
System.out.println( "output: " + output );
System.out.println( "outputQuébécois: " + outputQuébécois );
When run.
input: 23/2/2010
localDate: 2010-02-23
dayOfWeek: 2
output: Tue
outputQuébécois: mar.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Directive for autoFocus first field
import {_x000D_
Directive,_x000D_
ElementRef,_x000D_
AfterViewInit_x000D_
} from "@angular/core";_x000D_
_x000D_
@Directive({_x000D_
selector: "[appFocusFirstEmptyInput]"_x000D_
})_x000D_
export class FocusFirstEmptyInputDirective implements AfterViewInit {_x000D_
constructor(private el: ElementRef) {}_x000D_
ngAfterViewInit(): void {_x000D_
const invalidControl = this.el.nativeElement.querySelector(".ng-untouched");_x000D_
if (invalidControl) {_x000D_
invalidControl.focus();_x000D_
}_x000D_
}_x000D_
}
_x000D_
Have you tried not setting the responseType and just type casting the response?
This is what worked for me:
/**
* Client for consuming recordings HTTP API endpoint.
*/
@Injectable({
providedIn: 'root'
})
export class DownloadUrlClientService {
private _log = Log.create('DownloadUrlClientService');
constructor(
private _http: HttpClient,
) {}
private async _getUrl(url: string): Promise<string> {
const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
// const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
// const res = await (this._http.get(url, httpOptions)).toPromise();
return res;
}
}
an array does not contain index when elements are associative. An array in php can contain mixed values like this:
$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");
print_r($var);
Gives you:
Array
(
[0] => apple
[1] => banana
[foo] => grape
[2] => carrot
[bar] => donkey
)
What are you trying to achieve since you need the index value in an associative array?
Assuming the parent has a fixed width, e.g #page { width: 1000px; }
and is centered #page { margin: auto; }
, you want the child to fit the width of browser viewport you could simply do:
#page {
margin: auto;
width: 1000px;
}
.fullwidth {
margin-left: calc(500px - 50vw); /* 500px is half of the parent's 1000px */
width: 100vw;
}
Make it simpler
<input type="text" maxlength="3" />
and use an alert to show that max chars have been used.
I had the same problem a month ago on Windows 10. Whenever I tried to access http://localhost/ it led me to the IIS page. I tried removing the IIS feature from windows features. Once I was sure it was gone, I tried running XAMPP, but it still did not work. I did not want to mess with the configuration files. But from this, I was quite sure it had something to do with my web browser. So, deleted the cache from the web browser I was using (Google Chrome).
To do so, I went to:
Chrome > Settings > Show Advanced Settings > Privacy > Clear browsing data > Clear Cached images and files.
Its almost the same process for any web browsers. Right after that, I was able to run XAMPP without any problem!
Hope it helps!
You don't fetch a branch, you fetch an entire remote:
git fetch origin
git merge origin/an-other-branch
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
I only needed to uncheck 'Automatically manage signing', check it again, and rebuild.
Try the following:
document.getElementById("successAndErrorMessages").innerHTML="someContent";
msdn link for detail : innerHTML Property
This is for the total beginner... like me:
HTML:
<ul>
<li>
<a href="#"> Home </a>
</li>
<li>
<a href="#Info"> Info </a>
</li>
</ul>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-view>
</div>
</div>
Angular:
//Create App
var app = angular.module("myApp", ["ngRoute"]);
//Configure routes
app.config(function ($routeProvider) {
$routeProvider
.otherwise({ template: "<p>Coming soon</p>" })
.when("/", {
template: "<p>Home information</p>"
})
.when("/Info", {
template: "<p>Basic information</p>"
//templateUrl: "/content/views/Info.html"
});
});
//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
$scope.location = $location.path();
$rootScope.$on('$routeChangeStart', function () {
console.log("routeChangeStart");
//Place code here:....
});
});
Hope this helps a total beginner like me. Here is the full working sample:
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#"> Home </a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#Info"> Info </a>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="MainCtrl">_x000D_
<div ng-view>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
<script>_x000D_
//Create App_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
_x000D_
//Configure routes_x000D_
app.config(function ($routeProvider) {_x000D_
$routeProvider_x000D_
.otherwise({ template: "<p>Coming soon</p>" })_x000D_
.when("/", {_x000D_
template: "<p>Home information</p>"_x000D_
})_x000D_
.when("/Info", {_x000D_
template: "<p>Basic information</p>"_x000D_
//templateUrl: "/content/views/Info.html"_x000D_
});_x000D_
});_x000D_
_x000D_
//Controller_x000D_
app.controller('MainCtrl', function ($scope, $rootScope, $location) {_x000D_
$scope.location = $location.path();_x000D_
$rootScope.$on('$routeChangeStart', function () {_x000D_
console.log("routeChangeStart");_x000D_
//Place code here:...._x000D_
});_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Its also possible to just create a matplotlib figure
object and then use plt.savefig(...)
:
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure
For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.
This is what i did for rendering html files. And it solved the errors. Install consolidate and mustache by executing the below command in your project folder.
$ sudo npm install consolidate mustache --save
And make the following changes to your app.js file
var engine = require('consolidate');
app.set('views', __dirname + '/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html');
And now html pages will be rendered properly.
Here a reusable and more generic approach for Java 8+ that does not require external libraries:
public interface IUnreliable<T extends Exception>
{
void tryRun ( ) throws T;
}
public static <T extends Exception> void retry (int retryCount, IUnreliable<T> runnable) throws T {
for (int retries = 0;; retries++) {
try {
runnable.tryRun();
return;
} catch (Exception e) {
if (retries < retryCount) {
continue;
} else {
throw e;
}
}
}
}
Usage:
@Test
public void demo() throws IOException {
retry(3, () -> {
new File("/tmp/test.txt").createNewFile();
});
}
Click on the WAMP server icon and from the menu under Config Files select httpd.conf. A long text file will open up in notepad. In this file scroll down to the line that reads Port 80 and change this to read Port 8080, Save the file and close notepad. Once again click on the wamp server icon and select restart all services. One more change needs to be made before we are done. In Windows Explorer find the location where WAMP server was installed which is by Default C:\Wamp.
double doubleVal = 1.745;
double doubleVal1 = 0.745;
System.out.println(new BigDecimal(doubleVal));
System.out.println(new BigDecimal(doubleVal1));
outputs:
1.74500000000000010658141036401502788066864013671875
0.74499999999999999555910790149937383830547332763671875
Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).
More about double precision:
Typically a .sh file is a shell script which you can execute in a terminal. Specifically, the script you mentioned is a bash script, which you can see if you open the file and look in the first line of the file, which is called the shebang or magic line.
Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?
A common mistake is also not to leave a space after and before the square brackets.
on the last line, don't use $(this).remove()
use $(this).hide()
instead.
EDIT: To clarify,on the close click event you're removing the #terms
div from the DOM which is why its not coming back. You just need to hide it instead.
If you get below state and rebase does not work anymore,
$ git status
rebase in progress; onto (null)
You are currently rebasing.
(all conflicts fixed: run "git rebase --continue")
Then first run,
$ git rebase -quit
And then restore previous state from reflog,
$ git reflog
97f7c6f (HEAD, origin/master, origin/HEAD) HEAD@{0}: pull --rebase: checkout 97f7c6f292d995b2925c2ea036bb4823a856e1aa
4035795 (master) HEAD@{1}: commit (amend): Adding 2nd commit
d16be84 HEAD@{2}: commit (amend): Adding 2nd commit
8577ca8 HEAD@{3}: commit: Adding 2nd commit
3d2088d HEAD@{4}: reset: moving to head~
52eec4a HEAD@{5}: commit: Adding initial commit
Using,
$ git checkout HEAD@{1} #or
$ git checkout master #or
$ git checkout 4035795 #or
I had a very difficult time getting this working one under VS2015 one day. After the initial install everything was working, but I come in this morning and my keyboard shortcuts don't work. Going through Resharper's Environment > Keyboard & Menus didn't work; reinstalling Resharper didn't work. Even deleting every configuration from Resharper's AppData folder didn't work.
So what did work? Going to Visual Studio's Tools > Options > Environment > Keyboard and clicking Reset. After I did that, then Resharper's schemes would take.
Something like this works fine for me:
public partial class Form1 : Form
{
Form mainFormHandler;
...
}
private void Form1_Load(object sender, EventArgs e){
mainFormHandler = Application.OpenForms[0];
//or instead use this one:
//mainFormHandler = Application.OpenForms["Form1"];
}
Then you can change the size as below:
mainFormHandler.Width = 600;
mainFormHandler.Height= 400;
or
mainFormHandler.Size = new Size(600, 400);
Another useful point is that if you want to change the size of mainForm
from another Form
, you can simply use Property to set the size.
It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied
.
One thing you can try is doing a user install of the package with pip install lxml --user
. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)
You can also run pip install
as a superuser with sudo pip install lxml
but it is not generally a good idea because it can cause issues with your system-level packages.
The getChars
string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.
Try this link for a more verbose description of the getChars
method.
I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.
For visual learners, when defining the function without .prototype
ExampleClass = function(){};
ExampleClass.method = function(customString){
console.log((customString !== undefined)?
customString :
"called from func def.");}
ExampleClass.method(); // >> output: `called from func def.`
var someInstance = new ExampleClass();
someInstance.method('Called from instance');
// >> error! `someInstance.method is not a function`
With same code, if .prototype
is added,
ExampleClass.prototype.method = function(customString){
console.log((customString !== undefined)?
customString :
"called from func def.");}
ExampleClass.method();
// > error! `ExampleClass.method is not a function.`
var someInstance = new ExampleClass();
someInstance.method('Called from instance');
// > output: `Called from instance`
To make it clearer,
ExampleClass = function(){};
ExampleClass.directM = function(){} //M for method
ExampleClass.prototype.protoM = function(){}
var instanceOfExample = new ExampleClass();
ExampleClass.directM(); ? works
instanceOfExample.directM(); x Error!
ExampleClass.protoM(); x Error!
instanceOfExample.protoM(); ? works
****Note for the example above, someInstance.method() won't be executed as,
ExampleClass.method() causes error & execution cannot continue.
But for the sake of illustration & easy understanding, I've kept this sequence.****
Results generated from chrome developer console
& JS Bin
Click on the jsbin link above to step through the code.
Toggle commented section with ctrl+/
Solution it's quite simple
Just enable Builds for iOS 8 and Later
Add this to your web.config
. You need to tell IIS what PUT
PATCH
DELETE
and OPTIONS
means. And which IHttpHandler
to invoke.
<configuation>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</configuration>
Also check you don't have WebDAV enabled.
The atob
function will decode a Base64-encoded string into a new string with a character for each byte of the binary data.
const byteCharacters = atob(b64Data);
Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt
method for each character in the string.
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array
constructor.
const byteArray = new Uint8Array(byteNumbers);
This in turn can be converted to a BLOB by wrapping it in an array and passing it to the Blob
constructor.
const blob = new Blob([byteArray], {type: contentType});
The code above works. However the performance can be improved a little by processing the byteCharacters
in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);
window.location = blobUrl;
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {_x000D_
const byteCharacters = atob(b64Data);_x000D_
const byteArrays = [];_x000D_
_x000D_
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
const slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
const byteNumbers = new Array(slice.length);_x000D_
for (let i = 0; i < slice.length; i++) {_x000D_
byteNumbers[i] = slice.charCodeAt(i);_x000D_
}_x000D_
_x000D_
const byteArray = new Uint8Array(byteNumbers);_x000D_
byteArrays.push(byteArray);_x000D_
}_x000D_
_x000D_
const blob = new Blob(byteArrays, {type: contentType});_x000D_
return blob;_x000D_
}_x000D_
_x000D_
const contentType = 'image/png';_x000D_
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
const blob = b64toBlob(b64Data, contentType);_x000D_
const blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
const img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
Docker sets the hostname to the container ID by default, but users can override this with --hostname
. Instead, inspect /proc
:
$ more /proc/self/cgroup
14:name=systemd:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
13:pids:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
12:hugetlb:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
11:net_prio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
10:perf_event:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
9:net_cls:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
8:freezer:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
7:devices:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
6:memory:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
5:blkio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
4:cpuacct:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
3:cpu:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
2:cpuset:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
1:name=openrc:/docker
Here's a handy one-liner to extract the container ID:
$ grep "memory:/" < /proc/self/cgroup | sed 's|.*/||'
7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
If your compiler supports (at least part of) C++11 you could do something like:
for (auto& t : myMap)
std::cout << t.first << " "
<< t.second.first << " "
<< t.second.second << "\n";
For C++03 I'd use std::copy
with an insertion operator instead:
typedef std::pair<string, std::pair<string, string> > T;
std::ostream &operator<<(std::ostream &os, T const &t) {
return os << t.first << " " << t.second.first << " " << t.second.second;
}
// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));
Answer seems to be a little old, What I did was to use this mapper to convert a MAP
ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);
a simple Map
:
Map<String, Object> user = new HashMap<String,Object>(); user.put( "id", teklif.getAccount().getId() ); user.put( "fname", teklif.getAccount().getFname()); user.put( "lname", teklif.getAccount().getLname()); user.put( "email", teklif.getAccount().getEmail()); user.put( "test", null);
Use it like this for example:
String json = mapper.writeValueAsString(user);
If you want a real timer you need to use the date object.
Calculate the difference.
Format your string.
window.onload=function(){
var start=Date.now(),r=document.getElementById('r');
(function f(){
var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
if(diff>3e5){
start=Date.now()
}
setTimeout(f,1e3);
})();
}
Example
not so precise timer
var time=5*60,r=document.getElementById('r'),tmp=time;
setInterval(function(){
var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
tmp!=0||(tmp=time);
},1000);
myDiv.textContent = arbitraryHtmlString
as @Dan pointed out, do not use innerHTML, even in nodes you don't append to the document because deffered callbacks and scripts are always executed. You can check this https://gomakethings.com/preventing-cross-site-scripting-attacks-when-using-innerhtml-in-vanilla-javascript/ for more info.
1 - remove the margin from your BODY CSS.
2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>
3 - Define the CSS for the wrapper:
This will hold everything together, centered on the page.
#wrapper {
margin-left:auto;
margin-right:auto;
width:960px;
}
In my case runat="server"
was missing in the asp:content tag. I know it's stupid, but someone might have removed from the code in the build I got.
It worked for me. Someone may face the same thing. Hence shared.
Use window.open
instead of window.location
to open a new window or tab (depending on browser settings).
Your fiddle does not work because there is no button
element to select. Try input[type=button]
or give the button an id
and use #buttonId
.
To check on elasticsearch cluster health you need to use
curl localhost:9200/_cat/health
More on the cat APIs here.
I usually use elasticsearch-head plugin to visualize that.
You can find it's github project here.
It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head
and then you can open localhost:9200/_plugin/head/
in your web brower.
You should have something that looks like this :
Other than all the amazing answers here, there is a way to use getattr
to save copious lines of code and keeping it snug. This thought came following the dreadful representation of code that sometimes might be a necessity.
Scenario
Suppose your directory structure is as follows:
- superheroes.py
- properties.py
And, you have functions for getting information about Thor
, Iron Man
, Doctor Strange
in superheroes.py
. You very smartly write down the properties of all of them in properties.py
in a compact dict
and then access them.
properties.py
thor = {
'about': 'Asgardian god of thunder',
'weapon': 'Mjolnir',
'powers': ['invulnerability', 'keen senses', 'vortex breath'], # and many more
}
iron_man = {
'about': 'A wealthy American business magnate, playboy, and ingenious scientist',
'weapon': 'Armor',
'powers': ['intellect', 'armor suit', 'interface with wireless connections', 'money'],
}
doctor_strange = {
'about': ' primary protector of Earth against magical and mystical threats',
'weapon': 'Magic',
'powers': ['magic', 'intellect', 'martial arts'],
}
Now, let's say you want to return capabilities of each of them on demand in superheroes.py
. So, there are functions like
from .properties import thor, iron_man, doctor_strange
def get_thor_weapon():
return thor['weapon']
def get_iron_man_bio():
return iron_man['about']
def get_thor_powers():
return thor['powers']
...and more functions returning different values based on the keys and superhero.
With the help of getattr
, you could do something like:
from . import properties
def get_superhero_weapon(hero):
superhero = getattr(properties, hero)
return superhero['weapon']
def get_superhero_powers(hero):
superhero = getattr(properties, hero)
return superhero['powers']
You considerably reduced the number of lines of code, functions and repetition!
Oh and of course, if you have bad names like properties_of_thor
for variables , they can be made and accessed by simply doing
def get_superhero_weapon(hero):
superhero = 'properties_of_{}'.format(hero)
all_properties = getattr(properties, superhero)
return all_properties['weapon']
NOTE: For this particular problem, there can be smarter ways to deal with the situation, but the idea is to give an insight about using getattr
in right places to write cleaner code.
SELECT * FROM sys.objects WHERE type='p' ORDER BY modify_date DESC
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
SELECT name, crdate, refdate
FROM sysobjects
WHERE type = 'P'
ORDER BY refdate desc
SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';
Since pg_stat_activity
contains connection statistics of all databases having any state, either idle
or active
, database name and connection state should be included in the query to get the desired output.
fs = require('fs');
fs.readFile('FILENAME WITH PATH','utf8', function(err,content){
if(err){
console.log('error occured ' +JSON.stringify(err));
}
console.log('Fileconetent are ' + JSON.stringify(content));
})
Another way would be to use attributes of a suitable object, e.g. like so:
function plus(a,b) { return a+b; };
Plus = { a: function(x) { return { b: function(y) { return plus(x,y) }}},
b: function(y) { return { a: function(x) { return plus(x,y) }}}};
sum = Plus.a(3).b(5);
Of course for this made up example it is somewhat meaningless. But in cases where the function looks like
do_something(some_connection_handle, some_context_parameter, some_value)
it might be more useful. It also could be combined with "parameterfy" idea to create such an object out of an existing function in a generic way. That is for each parameter it would create a member that can evaluate to a partial evaluated version of the function.
This idea is of course related to Schönfinkeling aka Currying.
If is a package then you can get the source for that with:
select text from all_source where name = 'PADCAMPAIGN'
and type = 'PACKAGE BODY'
order by line;
Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.
Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use
select text from all_source where name = 'pAdCampaign'
and type = 'PACKAGE BODY'
order by line;
You must change the location of MySQL's temporary folder which is '/tmp' in most cases to a location with a bigger disk space. Change it in MySQL's config file.
Basically your server is running out of disk space where /tmp is located.
you can do it like this
$.when(funtion1()).then(function(){
funtion2();
})
You can use white-space: nowrap;
to define this behaviour:
// HTML:
.nowrap {_x000D_
white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
<span class="nowrap">How do I wrap this line of text</span>_x000D_
<span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
</p>
_x000D_
// CSS:
.nowrap {
white-space: nowrap ;
}
Depending on your browser support, you could use a css animation. Browser support is IE10 and up for CSS animation. This is nice so you don't have to add jquery UI dependency if its only a small easter egg. If it is integral to your site (aka needed for IE9 and below) go with the jquery UI solution.
.your-animation {
background-color: #fff !important;
-webkit-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
//You have to add the vendor prefix versions for it to work in Firefox, Safari, and Opera.
@-webkit-keyframes your-animation-name {
from { background-color: #5EB4FE;}
to {background-color: #fff;}
}
-moz-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@-moz-keyframes your-animation-name {
from { background-color: #5EB4FE;}
to {background-color: #fff;}
}
-ms-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@-ms-keyframes your-animation-name {
from { background-color: #5EB4FE;}
to {background-color: #fff;}
}
-o-animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@-o-keyframes your-animation-name {
from { background-color: #5EB4FE;}
to {background-color: #fff;}
}
animation: your-animation-name 1s ease 0s 1 alternate !important;
}
@keyframes your-animation-name {
from { background-color: #5EB4FE;}
to {background-color: #fff;}
}
Next create a jQuery click event that adds the your-animation
class to the element you wish to animate, triggering the background fading from one color to another:
$(".some-button").click(function(e){
$(".place-to-add-class").addClass("your-animation");
});
here is a working version :
function countbackgrounds() {
var book = SpreadsheetApp.getActiveSpreadsheet();
var range_input = book.getRange("B3:B4");
var range_output = book.getRange("B6");
var cell_colors = range_input.getBackgroundColors();
var color = "#58FA58";
var count = 0;
for( var i in cell_colors ){
Logger.log(cell_colors[i][0])
if( cell_colors[i][0] == color ){ ++count }
}
range_output.setValue(count);
}
Use:
var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"
and for time:
var s = new Date(1504095567183).toLocaleTimeString("en-US")
console.log(s)
// expected output "3:19:27 PM"
_x000D_
Maven is a Framework, Ant is a Toolbox
Maven is a pre-built road car, whereas Ant is a set of car parts. With Ant you have to build your own car, but at least if you need to do any off-road driving you can build the right type of car.
To put it another way, Maven is a framework whereas Ant is a toolbox. If you're content with working within the bounds of the framework then Maven will do just fine. The problem for me was that I kept bumping into the bounds of the framework and it wouldn't let me out.
XML Verbosity
tobrien is a guy who knows a lot about Maven and I think he provided a very good, honest comparison of the two products. He compared a simple Maven pom.xml with a simple Ant build file and he made mention of how Maven projects can become more complex. I think that its worth taking a look at a comparison of a couple of files that you are more likely to see in a simple real-world project. The files below represent a single module in a multi-module build.
First, the Maven file:
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-4_0_0.xsd">
<parent>
<groupId>com.mycompany</groupId>
<artifactId>app-parent</artifactId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>persist</artifactId>
<name>Persistence Layer</name>
<dependencies>
<dependency>
<groupId>com.mycompany</groupId>
<artifactId>common</artifactId>
<scope>compile</scope>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.mycompany</groupId>
<artifactId>domain</artifactId>
<scope>provided</scope>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.2.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons-dbcp.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc</artifactId>
<version>${oracle-jdbc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
And the equivalent Ant file:
<project name="persist" >
<import file="../build/common-build.xml" />
<path id="compile.classpath.main">
<pathelement location="${common.jar}" />
<pathelement location="${domain.jar}" />
<pathelement location="${hibernate.jar}" />
<pathelement location="${commons-lang.jar}" />
<pathelement location="${spring.jar}" />
</path>
<path id="compile.classpath.test">
<pathelement location="${classes.dir.main}" />
<pathelement location="${testng.jar}" />
<pathelement location="${dbunit.jar}" />
<pathelement location="${easymock.jar}" />
<pathelement location="${commons-dbcp.jar}" />
<pathelement location="${oracle-jdbc.jar}" />
<path refid="compile.classpath.main" />
</path>
<path id="runtime.classpath.test">
<pathelement location="${classes.dir.test}" />
<path refid="compile.classpath.test" />
</path>
</project>
tobrien used his example to show that Maven has built-in conventions but that doesn't necessarily mean that you end up writing less XML. I have found the opposite to be true. The pom.xml is 3 times longer than the build.xml and that is without straying from the conventions. In fact, my Maven example is shown without an extra 54 lines that were required to configure plugins. That pom.xml is for a simple project. The XML really starts to grow significantly when you start adding in extra requirements, which is not out of the ordinary for many projects.
But you have to tell Ant what to do
My Ant example above is not complete of course. We still have to define the targets used to clean, compile, test etc. These are defined in a common build file that is imported by all modules in the multi-module project. Which leads me to the point about how all this stuff has to be explicitly written in Ant whereas it is declarative in Maven.
Its true, it would save me time if I didn't have to explicitly write these Ant targets. But how much time? The common build file I use now is one that I wrote 5 years ago with only slight refinements since then. After my 2 year experiment with Maven, I pulled the old Ant build file out of the closet, dusted it off and put it back to work. For me, the cost of having to explicitly tell Ant what to do has added up to less than a week over a period of 5 years.
Complexity
The next major difference I'd like to mention is that of complexity and the real-world effect it has. Maven was built with the intention of reducing the workload of developers tasked with creating and managing build processes. In order to do this it has to be complex. Unfortunately that complexity tends to negate their intended goal.
When compared with Ant, the build guy on a Maven project will spend more time:
In contrast:
Familiarity
Another difference is that of familiarity. New developers always require time to get up to speed. Familiarity with existing products helps in that regard and Maven supporters rightly claim that this is a benefit of Maven. Of course, the flexibility of Ant means that you can create whatever conventions you like. So the convention I use is to put my source files in a directory name src/main/java. My compiled classes go into a directory named target/classes. Sounds familiar doesn't it.
I like the directory structure used by Maven. I think it makes sense. Also their build lifecycle. So I use the same conventions in my Ant builds. Not just because it makes sense but because it will be familiar to anyone who has used Maven before.
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
Java dynamically loads classes, so your universe of classes would be only those that have already been loaded (and not yet unloaded). Perhaps you can do something with a custom class loader that could check the supertypes of each loaded class. I don't think there's an API to query the set of loaded classes.
it's my understanding that target = whatever
will look for a frame/window with that name. If not found, it will open up a new window with that name. If whatever == "_new"
, it will appear just as if you used _blank
except.....
Using one of the reserved target names will bypass the "looking" phase. So, target = "_blank"
on a dozen links will open up a dozen blank windows, but target = whatever
on a dozen links will only open up one window. target = "_new"
on a dozen links may give inconstant behavior. I haven't tried it on several browsers, but should only open up one window.
At least this is how I interpret the rules.
I've made something quite easy. First I put the TextArea into a DIV. Second, I've called on the ready
function to this script.
<div id="divTable">
<textarea ID="txt" Rows="1" TextMode="MultiLine" />
</div>
$(document).ready(function () {
var heightTextArea = $('#txt').height();
var divTable = document.getElementById('divTable');
$('#txt').attr('rows', parseInt(parseInt(divTable .style.height) / parseInt(altoFila)));
});
Simple. It is the maximum height of the div once it is rendered, divided by the height of one TextArea of one row.
When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php
. That is how PHP works with includes.
So, in your example, since you've set a variable called $name
in your front.inc
file, and then included both front.inc
and end.inc
in your index.php
, you will be able to echo
the variable $name
anywhere after the include
of front.inc
within your index.php
. Again, PHP processes your index.php
as if the code from the two files you are including are part of the file.
When you place an echo
within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.
In other words, to do the behavior you're expecting, you will need to define it as a global.
class stack
{ private int top;
private int[] element;
stack()
{element=new int[10];
top=-1;
}
void push(int item)
{top++;
if(top==9)
System.out.println("Overflow");
else
{
top++;
element[top]=item;
}
void pop()
{if(top==-1)
System.out.println("Underflow");
else
top--;
}
void display()
{
System.out.println("\nTop="+top+"\nElement="+element[top]);
}
public static void main(String args[])
{
stack s1=new stack();
s1.push(10);
s1.display();
s1.push(20);
s1.display();
s1.push(30);
s1.display();
s1.pop();
s1.display();
}
}
Output
Top=0
Element=10
Top=1
Element=20
Top=2
Element=30
Top=1
Element=20
This works!
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<http.Response> postRequest () async {
var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
Map data = {
'apikey': '12345678901234567890'
}
//encode Map to JSON
var body = json.encode(data);
var response = await http.post(url,
headers: {"Content-Type": "application/json"},
body: body
);
print("${response.statusCode}");
print("${response.body}");
return response;
}
As I found the default Bootstrap <hr/>
size unsightly, here's some simple HTML and CSS to balance out the element visually:
HTML:
<hr class="half-rule"/>
CSS:
.half-rule {
margin-left: 0;
text-align: left;
width: 50%;
}
Here is solution:
<?php
$students['e1003']['birthplace'] = ("Mandaluyong <br>");
$students['ter1003']['birthplace'] = ("San Juan <br>");
$students['fgg1003']['birthplace'] = ("Quezon City <br>");
$students['bdf1003']['birthplace'] = ("Manila <br>");
$key = array_search('Delata Jona', array_column($students, 'name'));
echo $key;
?>
I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.
Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.
Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.
Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.
I found the below stuff in ffmpeg Docs. Hope this helps! :)
Reference: http://ffmpeg.org/ffmpeg.html#toc-Generic-options
‘-report’ Dump full command line and console output to a file named program-YYYYMMDD-HHMMSS.log in the current directory. This file can be useful for bug reports. It also implies -loglevel verbose.
Note: setting the environment variable FFREPORT to any value has the same effect.
I use a simple jQuery plugin to return the numeric value of any single CSS property.
It applies parseFloat
to the value returned by jQuery's default css
method.
Plugin Definition:
$.fn.cssNum = function(){
return parseFloat($.fn.css.apply(this,arguments));
}
Usage:
var element = $('.selector-class');
var numericWidth = element.cssNum('width') * 10 + 'px';
element.css('width', numericWidth);
I faced the problem of gettng entire text from Text widget and following solution worked for me :
txt.get(1.0,END)
Where 1.0 means first line, zeroth character (ie before the first!) is the starting position and END is the ending position.
Thanks to Alan Gauld in this link
Change the img-class responsive to:
.img-responsive, x:-moz-any-link {
display: block;
max-width: 100%;
width: auto;
height: auto;
Your script is using too much memory. This can often happen in PHP if you have a loop that has run out of control and you are creating objects or adding to arrays on each pass of the loop.
Check for infinite loops.
If that isn't the problem, try and help out PHP by destroying objects that you are finished with by setting them to null. eg. $OldVar = null;
Check the code where the error actually happens as well. Would you expect that line to be allocating a massive amount of memory? If not, try and figure out what has gone wrong...
do_something 2>&1 | tee -a some_file
This is going to redirect stderr to stdout and stdout to some_file
and print it to stdout.
Try not to go
MAMP > conf > [your PHP version] > php.ini
but
MAMP > bin > php > [your PHP version] > conf > php.ini
and change it there, it worked for me...
According to Daniel Simmons:
Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.
This is from his comprehensive article here:
http://msdn.microsoft.com/en-us/magazine/ee335715.aspx
I believe this advice extends to HTTP requests, so would be valid for ASP.NET. A stateful, fat-client application such as a WPF application might be the only case for a "shared" context.
JavaScript does require semicolons, it's just that the interpreter will insert them for you on line breaks where possible*.
Unfortunately, the code
var a = new B(args)(stuff)()
does not result in a syntax error, so no ;
will be inserted. (An example which can run is
var answer = new Function("x", "return x")(function(){return 42;})();
To avoid surprises like this, train yourself to always end a statement with ;
.
In general the less number of calls to the database the better (meaning faster, more efficient), so try to code the inserts in such a way that it minimizes database accesses. Remember, unless your using a connection pool, each databse access has to create a connection, execute the sql, and then tear down the connection. Quite a bit of overhead!
In a multi-select option box, you can use $('#input1 :selected').length;
to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.
function refreshButtons () {
if ($('#input :selected').length == 0)
{
$('#submit').attr ('disabled', 'disabled');
}
else
{
$('#submit').removeAttr ('disabled');
}
}
There are two ways to approach this.
Option 1: Update the Android Manifest If the settings Activity is always called from the same activity, you can make the relationship in the Android Manifest. Android will automagically show the 'back' button in the ActionBar
<activity
android:name=".SettingsActivity"
android:label="Setting Activity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.example.MainActivity" />
</activity>
Option 2: Change a setting for the ActionBar If you don't know which Activity will call the Settings Activity, you can create it like this. First in your activity that extends ActionBarActivity (Make sure your @imports match the level of compatibility you are looking for).
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_test);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
Then, detect the 'back button' press and tell Android to close the currently open Activity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
That should do it!
As opposed to what's written on the chosen answer, you don't need root and it is possible to get the APKs of the installed apps, which is how I've done it on my app (here). Example:
List<PackageInfo> packages=getPackageManager().getInstalledPackages(0);
Then, for each of the items of the list, you can access packageInfo.applicationInfo.sourceDir, which is the full path of the APK of the installed app.
No fancy tricks needed:
for i in *.java; do
[ -f "$i" ] || break
...
done
The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java
. In bash
(or shells supporting something similar), you can use the nullglob
option
to simply ignore a failed match and not enter the body of the loop.
shopt -s nullglob
for i in *.java; do
...
done
Swift 2.0
let dateNow = NSDate()
let calendar = NSCalendar.currentCalendar()
let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow)
let minute = calendar.component(NSCalendarUnit.Minute, fromDate: dateNow)
print(String(hour))
print(String(minute))
Please do take note of the cast to String in the print statement, you can easily assign that value to variables, like this:
var hoursString = String(hour)
var minutesString = String(minute)
Then you can concatenate values like this:
var compoundString = "\(hour):\(minute)"
print(compoundString)
Consider 2 dataFrames:
>>> aDF.show()
+---+----+
| id|datA|
+---+----+
| 1| a1|
| 2| a2|
| 3| a3|
+---+----+
and
>>> bDF.show()
+---+----+
| id|datB|
+---+----+
| 2| b2|
| 3| b3|
| 4| b4|
+---+----+
To accomplish what you are looking for, there are 2 ways:
1. Different joining condition. Instead of saying aDF.id == bDF.id
aDF.join(bDF, aDF.id == bDF.id, "outer")
Write this:
aDF.join(bDF, "id", "outer").show()
+---+----+----+
| id|datA|datB|
+---+----+----+
| 1| a1|null|
| 3| a3| b3|
| 2| a2| b2|
| 4|null| b4|
+---+----+----+
This will automatically get rid of the extra the dropping process.
2. Use Aliasing: You will lose data related to B Specific Id's in this.
>>> from pyspark.sql.functions import col
>>> aDF.alias("a").join(bDF.alias("b"), aDF.id == bDF.id, "outer").drop(col("b.id")).show()
+----+----+----+
| id|datA|datB|
+----+----+----+
| 1| a1|null|
| 3| a3| b3|
| 2| a2| b2|
|null|null| b4|
+----+----+----+
That's a good question! You may get into troubles if you invoke API that uses generics and want to assign or return that result with a different subtype of the generic type. Java 8 helps to transform:
List<String> input = new LinkedList<>(Arrays.asList("a", "b", "c"));
List<CharSequence> result;
// result = input; // <-- Type mismatch: cannot convert from List<String> to List<CharSequence>
result = input.stream().collect(Collectors.toList());
System.out.println(result);
As of today, there is an official Android-hosted copy of Volley available on JCenter:
compile 'com.android.volley:volley:1.0.0'
This was compiled from the AOSP volley source code.
You can try this
str = "Wow its so COOL"_x000D_
searchStr = "CoOl"_x000D_
_x000D_
console.log(str.toLowerCase().includes(searchStr.toLowerCase()))
_x000D_
I think the largely correct way, is to set css to this:
html
{
overflow: hidden;
}
body
{
margin: 0;
box-sizing: border-box;
}
html, body
{
height: 100%;
}
Using Query parameter
<a href="edit.jsp?userId=${user.id}" />
Using Hidden variable .
<form method="post" action="update.jsp">
...
<input type="hidden" name="userId" value="${user.id}">
you can send Using Session object.
session.setAttribute("userId", userid);
These values will now be available from any jsp as long as your session is still active.
int userid = session.getAttribute("userId");
If it helps you can embed a tab character in a double quoted string:
PS> "`t hello"
I have a function next()
which will maybe inspire you.
function queue(target) {
var array = Array.prototype;
var queueing = [];
target.queue = queue;
target.queued = queued;
return target;
function queued(action) {
return function () {
var self = this;
var args = arguments;
queue(function (next) {
action.apply(self, array.concat.apply(next, args));
});
};
}
function queue(action) {
if (!action) {
return;
}
queueing.push(action);
if (queueing.length === 1) {
next();
}
}
function next() {
queueing[0](function (err) {
if (err) {
throw err;
}
queueing = queueing.slice(1);
if (queueing.length) {
next();
}
});
}
}
// Common ajax caller
function AjaxCall(url,successfunction){
var targetUrl=url;
$.ajax({
'url': targetUrl,
'type': 'GET',
'dataType': 'json',
'success': successfunction,
'error': function() {
alert("error");
}
});
}
// Calling Ajax
$(document).ready(function() {
AjaxCall("productData.txt",ajaxSuccessFunction);
});
// Function details of success function
function ajaxSuccessFunction(d){
alert(d.Pioneer.Product[0].category);
}
it may help, create a common ajax call function and attach a function which invoke when success the ajax call, see the example
If you want to simply access a global variable you just use its name. However to change its value you need to use the global
keyword.
E.g.
global someVar
someVar = 55
This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.
The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.
You should check the $GOPATH
directory. If there is an empty directory of the package name, go get
doesn't download the package from the repository.
For example, If I want to get the github.com/googollee/go-socket.io
package from it's github repository, and there is already an empty directory github.com/googollee/go-socket.io
in the $GOPATH
, go get
doesn't download the package and then complains that there is no buildable Go source file in the directory. Delete any empty directory first of all.
On svg, the right way to write the title
<svg>
<title id="unique-id">Checkout</title>
</svg>
check here for more details https://css-tricks.com/svg-title-vs-html-title-attribute/
As @huttelihut pointed out, this is now possible as of SQL Server 2008 R2 - Read More Here
Prior to 2008 R2 it does't appear possible but MSDN Social has some suggested workarounds.
I'm currently using Bootstrap 4.3 in Angular 8 and want to open modal window programmatically (without actually clicking on some button as the official demo shows).
Following method works for me:
The general idea is to create a button associated to a modal window.
First make sure after you click this button, it can open the modal.
Then give this button tag an id using hashtag, for example #hiddenBtn
.
In component ts file, import ViewChild from @angular/core
and write below code:
@ViewChild('hiddenBtn', {static: false}) myHiddenBtn;
After that, whenever you want to open this modal window in your component ts code, write following code to simulate click operation
this.myHiddenBtn.nativeElement.click();
CppUTest - very nice, light weight framework with mock libraries. Worthwhile taking a closer look.
Please run below script in your terminal
curl -X POST \
-H "Authorization: key= write here api_key" \
-H "Content-Type: application/json" \
-d '{
"registration_ids": [
"write here reg_id generated by gcm"
],
"data": {
"message": "Manual push notification from Rajkumar"
},
"priority": "high"
}' \
https://android.googleapis.com/gcm/send
it will give the message if it is succeeded or failed
SELECT CASE CHARINDEX(' ', @Foo, 1)
WHEN 0 THEN @Foo -- empty or single word
ELSE SUBSTRING(@Foo, 1, CHARINDEX(' ', @Foo, 1) - 1) -- multi-word
END
You could perhaps use this in a UDF:
CREATE FUNCTION [dbo].[FirstWord] (@value varchar(max))
RETURNS varchar(max)
AS
BEGIN
RETURN CASE CHARINDEX(' ', @value, 1)
WHEN 0 THEN @value
ELSE SUBSTRING(@value, 1, CHARINDEX(' ', @value, 1) - 1) END
END
GO -- test:
SELECT dbo.FirstWord(NULL)
SELECT dbo.FirstWord('')
SELECT dbo.FirstWord('abc')
SELECT dbo.FirstWord('abc def')
SELECT dbo.FirstWord('abc def ghi')
::
is called Method Reference. It is basically a reference to a single method. I.e. it refers to an existing method by name.
Short Explanation:
Below is an example of a reference to a static method:
class Hey {
public static double square(double num){
return Math.pow(num, 2);
}
}
Function<Double, Double> square = Hey::square;
double ans = square.apply(23d);
square
can be passed around just like object references and triggered when needed. In fact, it can be just as easily used as a reference to "normal" methods of objects as static
ones. For example:
class Hey {
public double square(double num) {
return Math.pow(num, 2);
}
}
Hey hey = new Hey();
Function<Double, Double> square = hey::square;
double ans = square.apply(23d);
Function
above is a functional interface. To fully understand ::
, it is important to understand functional interfaces as well. Plainly, a functional interface is an interface with just one abstract method.
Examples of functional interfaces include Runnable
, Callable
, and ActionListener
.
Function
above is a functional interface with just one method: apply
. It takes one argument and produces a result.
The reason why ::
s are awesome is that:
Method references are expressions which have the same treatment as lambda expressions (...), but instead of providing a method body, they refer an existing method by name.
E.g. instead of writing the lambda body
Function<Double, Double> square = (Double x) -> x * x;
You can simply do
Function<Double, Double> square = Hey::square;
At runtime, these two square
methods behave exactly the same as each other. The bytecode may or may not be the same (though, for the above case, the same bytecode is generated; compile the above and check with javap -c
).
The only major criterion to satisfy is: the method you provide should have a similar signature to the method of the functional interface you use as object reference.
The below is illegal:
Supplier<Boolean> p = Hey::square; // illegal
square
expects an argument and returns a double
. The get
method in Supplier returns a value but does not take an argument. Thus, this results in an error.
A method reference refers to the method of a functional interface. (As mentioned, functional interfaces can have only one method each).
Some more examples: the accept
method in Consumer takes an input but doesn't return anything.
Consumer<Integer> b1 = System::exit; // void exit(int status)
Consumer<String[]> b2 = Arrays::sort; // void sort(Object[] a)
Consumer<String> b3 = MyProgram::main; // void main(String... args)
class Hey {
public double getRandom() {
return Math.random();
}
}
Callable<Double> call = hey::getRandom;
Supplier<Double> call2 = hey::getRandom;
DoubleSupplier sup = hey::getRandom;
// Supplier is functional interface that takes no argument and gives a result
Above, getRandom
takes no argument and returns a double
. So any functional interface that satisfies the criteria of: take no argument and return double
can be used.
Another example:
Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("leo","bale","hanks"));
Predicate<String> pred = set::contains;
boolean exists = pred.test("leo");
In case of parameterized types:
class Param<T> {
T elem;
public T get() {
return elem;
}
public void set(T elem) {
this.elem = elem;
}
public static <E> E returnSame(E elem) {
return elem;
}
}
Supplier<Param<Integer>> obj = Param<Integer>::new;
Param<Integer> param = obj.get();
Consumer<Integer> c = param::set;
Supplier<Integer> s = param::get;
Function<String, String> func = Param::<String>returnSame;
Method references can have different styles, but fundamentally they all mean the same thing and can simply be visualized as lambdas:
ClassName::methName
)instanceRef::methName
)super::methName
)ClassName::methName
)ClassName::new
)TypeName[]::new
)For further reference, see http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html.
Legacy. List was originally defined to be functional-languages-looking:
1 :: 2 :: Nil // a list
list1 ::: list2 // concatenation of two lists
list match {
case head :: tail => "non-empty"
case Nil => "empty"
}
Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++
to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.
At first you have to understand what does join do? We connect multiple table and get specific result from the joined tables. The simplest way to do this is cross join.
Lets say tableA has two column A and B. And tableB has three column C and D. If we apply cross join it will produce lot of meaningless row. Then we have to match using primary key to get actual data.
Left: it will return all records from left table and matched record from right table.
Right: it will return opposite to Left join. It will return all records from right table and matched records from left table.
Inner: This is like intersection. It will return only matched records from both table.
Outer: And this is like union. It will return all available record from both table.
Some times we don't need all of the data, and also we should need only common data or records. we can easily get it using these join methods. Remember left and right join also are outer join.
You can get all records just using cross join. But it could be expensive when it comes to millions of records. So make it simple by using left, right, inner or outer join.
thanks
var input = {"document":
{"people":[
{"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
{"name":["hermione granger"],"age":["18"],"gender":["Female"]},
]}
}
var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
Object.keys(input.document.people[i]).forEach(function(key){
if(keys.indexOf(key) == -1)
{
keys.push(key);
}
});
}
console.log(keys);
The code I'll give you works and retrieves not only keys, but a lot of data from a table in SQL Server. Is tested in SQL Server 2k5/2k8, dunno about 2k. Enjoy!
SELECT DISTINCT
sys.tables.object_id AS TableId,
sys.columns.column_id AS ColumnId,
sys.columns.name AS ColumnName,
sys.types.name AS TypeName,
sys.columns.precision AS NumericPrecision,
sys.columns.scale AS NumericScale,
sys.columns.is_nullable AS IsNullable,
( SELECT
COUNT(column_name)
FROM
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
WHERE
TABLE_NAME = sys.tables.name AND
CONSTRAINT_NAME =
( SELECT
constraint_name
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
TABLE_NAME = sys.tables.name AND
constraint_type = 'PRIMARY KEY' AND
COLUMN_NAME = sys.columns.name
)
) AS IsPrimaryKey,
sys.columns.max_length / 2 AS CharMaxLength /*BUG*/
FROM
sys.columns, sys.types, sys.tables
WHERE
sys.tables.object_id = sys.columns.object_id AND
sys.types.system_type_id = sys.columns.system_type_id AND
sys.types.user_type_id = sys.columns.user_type_id AND
sys.tables.name = 'TABLE'
ORDER BY
IsPrimaryKey
You can use only the primary key part, but I think that the rest might become handy. Best regards, David
from sklearn import svm, datasets
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
import matplotlib.pyplot as plt
breast_cancer = load_breast_cancer()
X = breast_cancer.data
y = breast_cancer.target
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33, random_state=44)
clf = LogisticRegression(penalty='l2', C=0.1)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy", metrics.accuracy_score(y_test, y_pred))
y_pred_proba = clf.predict_proba(X_test)[::,1]
fpr, tpr, _ = metrics.roc_curve(y_test, y_pred_proba)
auc = metrics.roc_auc_score(y_test, y_pred_proba)
plt.plot(fpr,tpr,label="data 1, auc="+str(auc))
plt.legend(loc=4)
plt.show()
from: Outline effect to text
.strokeme
{
color: white;
text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
}
You may use simplehtmldom. Most of the jQuery selectors are supported in simplehtmldom. An example is given below
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
You can use .add() and .subtract() method to get yesterday and tomorrow date. Then use format method to get only date .format("D/M/Y"), D stand for Day, M for Month, Y for Year. Check in Moment Docs
let currentMilli = Date.now()
let today = Moment(currentMilli).format("D/M/Y");
let tomorrow = Moment(currentMilli).add(1, 'days').format("D/M/Y");
let yesterday = Moment(currentMilli).subtract(1, 'days').format("D/M/Y");
Result will be:
Current Milli - 1576693800000
today - 19/12/2019
tomorrow - 18/12/2019
yesterday - 18/12/2019
if you are handling the config changes in your fragment activity specified in android manifest like this
<activity
android:name=".courses.posts.EditPostActivity"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="unspecified" />
then the onSaveInstanceState
of the fragment will not be invoked and the savedInstanceState
object will always be null.
binding name="BindingName"
maxReceivedMessageSize="2097152"
maxBufferSize="2097152"
maxBufferPoolSize="2097152"
on client side and server side
The same way as you'd set the type (number format mask) after writing a value to it:
$objPHPExcel->getActiveSheet()
->getStyle('A1')
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_GENERAL
);
or
$objPHPExcel->getActiveSheet()
->getStyle('A1')
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
Though "Number" isn't a valid format mask.
You can find a list of pre-defined format masks in Classes/PHPExcel/Style/NumberFormat.php or set the value to any valid Excel number format masking string.
var files = Directory.GetFiles(@"E:\ftproot\sales");
Option A:
git clone [email protected]:whatever folder-name
Ergo, for right here
use:
git clone [email protected]:whatever .
Option B:
Move the .git
folder, too. Note that the .git
folder is hidden in most graphical file explorers, so be sure to show hidden files.
mv /where/it/is/right/now/* /where/I/want/it/
mv /where/it/is/right/now/.* /where/I/want/it/
The first line grabs all normal files, the second line grabs dot-files. It is also possibe to do it in one line by enabling dotglob (i.e. shopt -s dotglob
) but that is probably a bad solution if you are asking the question this answer answers.
Better yet:
Keep your working copy somewhere else, and create a symbolic link. Like this:
ln -s /where/it/is/right/now /the/path/I/want/to/use
For your case this would be something like:
ln -sfn /opt/projectA/prod/public /httpdocs/public
Which easily could be changed to test if you wanted it, i.e.:
ln -sfn /opt/projectA/test/public /httpdocs/public
without moving files around. Added -fn
in case someone is copying these lines (-f
is force, -n
avoid some often unwanted interactions with already and non-existing links).
If you just want it to work, use Option A, if someone else is going to look at what you have done, use Option C.
Lazy notes in comments.
#include <stdio.h>
// for malloc
#include <stdlib.h>
// you need the prototype
char *substring(int i,int j,char *ch);
int main(void /* std compliance */)
{
int i=0,j=2;
char s[]="String";
char *test;
// s points to the first char, S
// *s "is" the first char, S
test=substring(i,j,s); // so s only is ok
// if test == NULL, failed, give up
printf("%s",test);
free(test); // you should free it
return 0;
}
char *substring(int i,int j,char *ch)
{
int k=0;
// avoid calc same things several time
int n = j-i+1;
char *ch1;
// you can omit casting - and sizeof(char) := 1
ch1=malloc(n*sizeof(char));
// if (!ch1) error...; return NULL;
// any kind of check missing:
// are i, j ok?
// is n > 0... ch[i] is "inside" the string?...
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return ch1;
}
This is one I like
update: I didnt like the previous one because it didn't show files in the current directory, it only listed directories.
Example output for /var
on ubuntu:
sudo du -hDaxd1 /var | sort -h | tail -n10
4.0K /var/lock
4.0K /var/run
4.0K /var/www
12K /var/spool
3.7M /var/backups
33M /var/log
45M /var/webmin
231M /var/cache
1.4G /var/lib
1.7G /var
The operators delete
and delete []
are used respectively to destroy the objects created with new
and new[]
, returning to the allocated memory left available to the compiler's memory manager.
Objects created with new
must necessarily be destroyed with delete
, and that the arrays created with new[]
should be deleted with delete[]
.
Check out pyinotify.
inotify replaces dnotify (from an earlier answer) in newer linuxes and allows file-level rather than directory-level monitoring.
I believe this would work. It takes const char*'s as a parameter.
//params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
//ASSERT(find != NULL);
//ASSERT(replace != NULL);
size_t findLen = strlen(find);
size_t replaceLen = strlen(replace);
size_t pos = 0;
//search for the next occurrence of find within source
while ((pos = source.find(find, pos)) != std::string::npos)
{
//replace the found string with the replacement
source.replace( pos, findLen, replace );
//the next line keeps you from searching your replace string,
//so your could replace "hello" with "hello world"
//and not have it blow chunks.
pos += replaceLen;
}
}
You can simply write
try
{
//Your Logic and code
}
catch (Exception ex)
{
//Error message in alert box
Response.Write("<script>alert('Error :" +ex.Message+"');</script>");
}
it will work fine
I think your asking to select only <span class = "my_class">hello</span>
this element, You have do like this, If I am understand your question correctly this is the answer,
$("#my_id [class='my_class']").addClass('test');
Stack is a LIFO (last in first out) data structure. The associated link to wikipedia contains detailed description and examples.
Queue is a FIFO (first in first out) data structure. The associated link to wikipedia contains detailed description and examples.
PowerShell is pretty common these days so I use it often as a quick way to invoke C# since that has functions for pretty much everything:
@echo off
set pathToResolve=%~dp0\..\SomeFile.txt
for /f "delims=" %%a in ('powershell -Command "[System.IO.Path]::GetFullPath( '%projectDirMc%' )"') do @set resolvedPath=%%a
echo Resolved path: %resolvedPath%
It's a bit slow, but the functionality gained is hard to beat unless without resorting to an actual scripting language.
try white-space:normal;
This will override inheriting white-space:nowrap;
just don't validate:
flyway.setValidateOnMigrate(false);
for all views (you need dba privileges for this query)
select view_name from dba_views
for all accessible views (accessible by logged user)
select view_name from all_views
for views owned by logged user
select view_name from user_views
We have just rolled our own due to limited functionality requirements on our grids. We use some JQuery here and there for some niceties like pagination and that is all we really need.
If you need something a little more fully featured you could check out ExtJs grids here.
Also MvcContrib has a grid implementation that you could check out - try here. Or more specifically here.
As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:
Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}
From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.
This along with @BlackHawkDesign comment should help you find what you need.
I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00
Factory methods (alternative constructors) are indeed a classic example of class methods.
Basically, class methods are suitable anytime you would like to have a method which naturally fits into the namespace of the class, but is not associated with a particular instance of the class.
As an example, in the excellent unipath module:
Path.cwd()
Path("/tmp/my_temp_dir")
. This is a class method..chdir()
As the current directory is process wide, the cwd
method has no particular instance with which it should be associated. However, changing the cwd
to the directory of a given Path
instance should indeed be an instance method.
Hmmm... as Path.cwd()
does indeed return a Path
instance, I guess it could be considered to be a factory method...
WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.
The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).
Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.
To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).
A valid entry looks like:
public static class ConsoleProgram
{
[STAThread]
static void Main()
{
Console.WriteLine("Got here");
Console.ReadLine();
}
}
I had issues as I'm writing a web application, but for the dreadly loading time, I wanted to quickly convert the same project to a console application and perform quick method tests without loading the entire solution.
My entry point was placed in /App_Code/Main.cs, and I had to do the following:
After this, I can set the output (as mentioned in Step 1) to Class Library to start the web site, or Console Application to enter the console mode.
Why I did this instead of 2 separate projects?
Simply because I had references to Entity Framework and other specific references that created problems running 2 separate projects.
For easier solutions, I would still recommend 2 separate projects as the console output is mainly test code and you probably don't want to risk that going out in production code.
This is what I have done. (Adapt from all of your answers)
<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />
It works. Thanks to all of you. :)
Uses $.extend()
of jquery, like this:
token = {_token:window.Laravel.csrfToken};
data = {v1:'asdass',v2:'sdfsdf'}
dat = $.extend(token,data);
I hope you serve them.
Step 1: You have to add the line: default-storage-engine = InnoDB under the [mysqld] section of your mysql config file (my.cnf or my.ini depending on your OS) and restart the mysqld service.
Step 2: Now when you create the table you will see the type of table is: InnoDB
Step 3: Create both Parent and Child table. Now open the Child table and select the column U like to have the Foreign Key: Select the Index Key from Action Label as shown below.
Step 4: Now open the Relation View in the same child table from bottom near the Print View as shown below.
Step 5: Select the column U like to have the Foreign key as Select the Parent column from the drop down. dbName.TableName.ColumnName
Another css that can make the margin problem is that you have direction:someValue
in your css, so just remove it by setting it to initial.
For example:
body {
direction:rtl;
}
@media (max-width: 480px) {
body {
direction:initial;
}
}
Another approach to do it..
May it help someone...
if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
//starts with http
}
you can save the xlsx file as a tab-delimited text file and do
BULK INSERT TableName
FROM 'C:\SomeDirectory\my table.txt'
WITH
(
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
GO
There are two different ways to change a background image CSS with jQuery.
$('selector').css('backgroundImage','url(images/example.jpg)');
$('selector').css({'background-image':'url(images/example.jpg)'});
Look carefully to note the differences. In the second, you can use conventional CSS and string multiple CSS properties together.
You can use this command:
document.getElementById('iframeid').contentWindow.print();
This command basically is the same as window.print(), but as the window we would like to print is in the iframe, we first need to obtain an instance of that window as a javascript object.
So, in reference to that iframe, we first obtain the iframe by using it's id, and then it's contentWindow returns a window(DOM) object. So, we are able to directly use the window.print() function on this object.
In my case the issue was caused due to mismatch in .Xauthority file. Which initially showed up with "Invalid MIT-MAGIC-COOKIE-1" error and then "Error: cannot open display: :0.0" afterwards
Regenerating the .Xauthorityfile from the user under which I am running the vncserver and resetting the password with a restart of the vnc service and dbus service fixed the issue for me.
UPDATE
only changes the values you specify:
UPDATE table SET cell='new_value' WHERE whatever='somevalue'
You need to use a hashbang. Add it to the first line of your python script.
#! <full path of python interpreter>
Then change the file permissions, and add the executing permission.
chmod +x <filename>
And finally execute it using
./<filename>
If its in the current directory,
Alternate solution of the values check
//Duplicate Title Entry
$.each(ar , function (i, val) {
if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
});
I suggest you to draw a circle with CustomPainter. It's very easy and way more efficient than creating a bunch of widgets/masks:
/// Draws a circle if placed into a square widget.
class CirclePainter extends CustomPainter {
final _paint = Paint()
..color = Colors.red
..strokeWidth = 2
// Use [PaintingStyle.fill] if you want the circle to be filled.
..style = PaintingStyle.stroke;
@override
void paint(Canvas canvas, Size size) {
canvas.drawOval(
Rect.fromLTWH(0, 0, size.width, size.height),
_paint,
);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => false;
}
Usage:
Widget _buildCircle(BuildContext context) {
return SizedBox(
width: 20,
height: 20,
child: CustomPaint(
painter: CirclePainter(),
),
);
}
Try this:
String numberStr = "3.5";
Float number = null;
try {
number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
System.out.println("numberStr is not a number");
}
You are dividing by rr
which may be 0.0. Check if rr
is zero and do something reasonable other than using it in the denominator.
In package json
:
"scripts": {
"start": "node index",
"dev": "nodemon index"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
And in the terminal for developing:
npm run dev
And for starting the server regular:
npm start
Shift and integer multiply instructions have similar performance on most modern CPUs - integer multiply instructions were relatively slow back in the 1980s but in general this is no longer true. Integer multiply instructions may have higher latency, so there may still be cases where a shift is preferable. Ditto for cases where you can keep more execution units busy (although this can cut both ways).
Integer division is still relatively slow though, so using a shift instead of division by a power of 2 is still a win, and most compilers will implement this as an optimisation. Note however that for this optimisation to be valid the dividend needs to be either unsigned or must be known to be positive. For a negative dividend the shift and divide are not equivalent!
#include <stdio.h>
int main(void)
{
int i;
for (i = 5; i >= -5; --i)
{
printf("%d / 2 = %d, %d >> 1 = %d\n", i, i / 2, i, i >> 1);
}
return 0;
}
Output:
5 / 2 = 2, 5 >> 1 = 2
4 / 2 = 2, 4 >> 1 = 2
3 / 2 = 1, 3 >> 1 = 1
2 / 2 = 1, 2 >> 1 = 1
1 / 2 = 0, 1 >> 1 = 0
0 / 2 = 0, 0 >> 1 = 0
-1 / 2 = 0, -1 >> 1 = -1
-2 / 2 = -1, -2 >> 1 = -1
-3 / 2 = -1, -3 >> 1 = -2
-4 / 2 = -2, -4 >> 1 = -2
-5 / 2 = -2, -5 >> 1 = -3
So if you want to help the compiler then make sure the variable or expression in the dividend is explicitly unsigned.
TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.
Try this code:
<form id="myform">
<!-- form elements -->
<a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>
But users with disabled JavaScript won't be able to submit the form, so you could add the following code:
<noscript>
<input type="submit" value="Submit form!" />
</noscript>
DesiredCapabilities
are options that you can use to customize and configure a browser session.
You can read more about them here!
In Python 2, open outfile
with mode 'wb'
instead of 'w'
. The csv.writer
writes \r\n
into the file directly. If you don't open the file in binary mode, it will write \r\r\n
because on Windows text mode will translate each \n
into \r\n
.
In Python 3 the required syntax changed (see documentation links below), so open outfile
with the additional parameter newline=''
(empty string) instead.
# Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
writer = csv.writer(outfile)
# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)