This will be more efficient, plus you have control over the ordering it uses to pick a value:
SELECT DISTINCT
FIRST_VALUE(person)
OVER(PARTITION BY language
ORDER BY person)
,language
FROM tableA;
If you really don't care which person is picked for each language, you can omit the ORDER BY clause:
SELECT DISTINCT
FIRST_VALUE(person)
OVER(PARTITION BY language)
,language
FROM tableA;
For Wamp x86+Phalcon users (with same error):
Take care of download the right version of Phalcon:
Phalcon 1.3.2 - Windows x86 for PHP 5.5.0 (VC11)
.row {
letter-spacing: -.31em;
word-spacing: -.43em;
}
.col-md-4 {
float: none;
display: inline-block;
vertical-align: middle;
}
Note: .col-md-4 could be any grid column, its just an example here.
One of the subtleties in this question involves the "leading delimiter" question: if you are going to have a combined array of tokens and delimiters you have to know whether it starts with a token or a delimiter. You could of course just assume that a leading delim should be discarded but this seems an unjustified assumption. You might also want to know whether you have a trailing delim or not. This sets two boolean flags accordingly.
Written in Groovy but a Java version should be fairly obvious:
String tokenRegex = /[\p{L}\p{N}]+/ // a String in Groovy, Unicode alphanumeric
def finder = phraseForTokenising =~ tokenRegex
// NB in Groovy the variable 'finder' is then of class java.util.regex.Matcher
def finderIt = finder.iterator() // extra method added to Matcher by Groovy magic
int start = 0
boolean leadingDelim, trailingDelim
def combinedTokensAndDelims = [] // create an array in Groovy
while( finderIt.hasNext() )
{
def token = finderIt.next()
int finderStart = finder.start()
String delim = phraseForTokenising[ start .. finderStart - 1 ]
// Groovy: above gets slice of String/array
if( start == 0 ) leadingDelim = finderStart != 0
if( start > 0 || leadingDelim ) combinedTokensAndDelims << delim
combinedTokensAndDelims << token // add element to end of array
start = finder.end()
}
// start == 0 indicates no tokens found
if( start > 0 ) {
// finish by seeing whether there is a trailing delim
trailingDelim = start < phraseForTokenising.length()
if( trailingDelim ) combinedTokensAndDelims << phraseForTokenising[ start .. -1 ]
println( "leading delim? $leadingDelim, trailing delim? $trailingDelim, combined array:\n $combinedTokensAndDelims" )
}
You can specify git log
options to show only the last commit, -1
, and a format that includes only the commit ID, like this:
git log -1 --format=%H
If you prefer the shortened commit ID:
git log -1 --format=%h
Use the Process class. The MSDN documentation has an example how to use it.
The right way to iterate over objects is
Object.keys(someObject).map(function(item)...
Object.keys(someObject).forEach(function(item)...;
// ES way
Object.keys(data).map(item => {...});
Object.keys(data).forEach(item => {...});
We overflowed an integer primary key once (which is ~2.4 billion rows) on a table. If there's a row limit, you're not likely to ever hit it at a mere 36 million rows per year.
I was getting the exact same error, however I solved it by running $false
first and then $true
.
The answer to the question specifically asked is no. But have you been looking at mocking frameworks? I use MOQ but there's millions of them out there and they allow you to implement/stub (partially or fully) interfaces in-line. Eg.
public void ThisWillWork()
{
var source = new DummySource[0];
var mock = new Mock<DummyInterface>();
mock.SetupProperty(m => m.A, source.Select(s => s.A));
mock.SetupProperty(m => m.B, source.Select(s => s.C + "_" + s.D));
DoSomethingWithDummyInterface(mock.Object);
}
CSS only
line-height: 1.5;
white-space: normal;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
Compiler It converts the source code into the object code.
Linker It combines the multiple object files into a single executable program file.
Loader It loads the executable file into main memory.
(?<![\d.])(\d{1,2}|\d{0,2}\.\d{1,2})?(?![\d.])
Matches:
Does not match:
If you are fetching the URL from a database you can manually assign it to the web service proxy class URL property. This should be done before calling the web method.
If you would like to use the config file, you can set the proxy classes URL behavior to dynamic.
Think of void as the "empty structure". Let me explain.
Every function takes a sequence of parameters, where each parameter has a type. In fact, we could package up the parameters into a structure, with the structure slots corresponding to the parameters. This makes every function have exactly one argument. Similarly, functions produce a result, which has a type. It could be a boolean, or it could be float, or it could be a structure, containing an arbitrary set of other typed values. If we want a languge that has multiple return values, it is easy to just insist they be packaged into a structure. In fact, we could always insist that a function returned a structure. Now every function takes exactly one argument, and produces exactly one value.
Now, what happens when I need a function that produces "no" value? Well, consider what I get when I form a struct with 3 slots: it holds 3 values. When I have 2 slots, it holds two values. When it has one slot, one value. And when it has zero slots, it holds... uh, zero values, or "no" value". So, I can think of a function returning void as returning a struct containing no values. You can even decide that "void" is just a synonym for the type represented by the empty structure, rather than a keyword in the language (maybe its just a predefined type :)
Similarly, I can think of a function requiring no values as accepting an empty structure, e.g., "void".
I can even implement my programming language this way. Passing a void value takes up zero bytes, so passing void values is just a special case of passing other values of arbitrary size. This makes it easy for the compiler to treat the "void" result or argument. You probably want a langauge feature that can throw a function result away; in C, if you call the non-void result function foo in the following statement: foo(...); the compiler knows that foo produces a result and simply ignores it. If void is a value, this works perfectly and now "procedures" (which are just an adjective for a function with void result) are just trivial special cases of general functions.
Void* is a bit funnier. I don't think the C designers thought of void in the above way; they just created a keyword. That keyword was available when somebody needed a point to an arbitrary type, thus void* as the idiom in C. It actually works pretty well if you interpret void as an empty structure. A void* pointer is the address of a place where that empty structure has been put.
Casts from void* to T* for other types T, also work out with this perspective. Pointer casts are a complete cheat that work on most common architectures to take advantage of the fact that if a compound type T has an element with subtype S placed physically at the beginning of T in its storage layout, then casting S* to T* and vice versa using the same physical machine address tends to work out, since most machine pointers have a single representation. Replacing the type S by the type void gives exactly the same effect, and thus casting to/from void* works out.
The PARLANSE programming language implements the above ideas pretty closely. We goofed in its design, and didn't pay close attention to "void" as a return type and thus have langauge keywords for procedure. Its mostly just a simple syntax change but its one of things you don't get around to once you get a large body working code in a language.
Updated 2018
IMO, the best way to approach this in Bootstrap 3 would be using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens. This way you keep the responsiveness...
@media (min-width:768px) {
#sidebar {
width: inherit;
min-width: 240px;
max-width: 240px;
min-height: 100%;
position:relative;
}
#sidebar2 {
min-width: 160px;
max-width: 160px;
min-height: 100%;
position:relative;
}
#main {
width:calc(100% - 400px);
}
}
Working Bootstrap Fixed-Fluid Demo
Bootstrap 4 will has flexbox so layouts like this will be much easier: http://www.codeply.com/go/eAYKvDkiGw
Example
So, if we had a child element with an id of "child-element" and we wanted to get it's left/top position relative to a parent element, say a div that had a class of "item-parent", we'd use this code.
var position = $("#child-element").offsetRelative("div.item-parent");
alert('left: '+position.left+', top: '+position.top);
Plugin Finally, for the actual plugin (with a few notes expalaining what's going on):
// offsetRelative (or, if you prefer, positionRelative)
(function($){
$.fn.offsetRelative = function(top){
var $this = $(this);
var $parent = $this.offsetParent();
var offset = $this.position();
if(!top) return offset; // Didn't pass a 'top' element
else if($parent.get(0).tagName == "BODY") return offset; // Reached top of document
else if($(top,$parent).length) return offset; // Parent element contains the 'top' element we want the offset to be relative to
else if($parent[0] == $(top)[0]) return offset; // Reached the 'top' element we want the offset to be relative to
else { // Get parent's relative offset
var parent_offset = $parent.offsetRelative(top);
offset.top += parent_offset.top;
offset.left += parent_offset.left;
return offset;
}
};
$.fn.positionRelative = function(top){
return $(this).offsetRelative(top);
};
}(jQuery));
Note : You can Use this on mouseClick or mouseover Event
$(this).offsetRelative("div.item-parent");
I got this in a WCF service due to having an x86 build type selected, causing the bins to live under bin\x86 instead of bin. Selecting Any CPU caused the recompiled DLLs to go to the correct locations (I wont go into detail as to how this happened in the first place).
Best way to find out is to record the macro and perform the exact steps and see what VBA code it generates. you can then go and replace the bits you want to make generic (i.e. file names and stuff)
Edited on 2014/8/25: Here was where I forked it.
Thanks @anvarik.
Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @
<div ng-controller="MyCtrl">
<h2>Parent Scope</h2>
<input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>
<br><br>
<!-- attribute-foo binds to a DOM attribute which is always
a string. That is why we are wrapping it in curly braces so
that it can be interpolated. -->
<my-component attribute-foo="{{foo}}" binding-foo="foo"
isolated-expression-foo="updateFoo(newFoo)" >
<h2>Attribute</h2>
<div>
<strong>get:</strong> {{isolatedAttributeFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedAttributeFoo">
<i>// This does not update the parent scope.</i>
</div>
<h2>Binding</h2>
<div>
<strong>get:</strong> {{isolatedBindingFoo}}
</div>
<div>
<strong>set:</strong> <input ng-model="isolatedBindingFoo">
<i>// This does update the parent scope.</i>
</div>
<h2>Expression</h2>
<div>
<input ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
<i>// And this calls a function on the parent scope.</i>
</div>
</my-component>
</div>
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'@attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.foo = 'Hello!';
$scope.updateFoo = function (newFoo) {
$scope.foo = newFoo;
}
}]);
Use >
and <
for 'greater-than' and 'less-than' respectively
The data-role="none" is the key to make them work together. You can apply to the elements you want bootstrap to touch but jquery mobile to ignore. like this input type="text" class="form-control" placeholder="Search" data-role="none"
Waking up all does not make much significance here. wait notify and notifyall, all these are put after owning the object's monitor. If a thread is in the waiting stage and notify is called, this thread will take up the lock and no other thread at that point can take up that lock. So concurrent access can not take place at all. As far as i know any call to wait notify and notifyall can be made only after taking the lock on the object. Correct me if i am wrong.
Regarding parameters:
See this answer first. To get a list of all the builds for a project (obtained as per that answer):
project.builds
When you find your particular build, you need to get all actions of type ParametersAction with build.getActions(hudson.model.ParametersAction)
. You then query the returned object for your specific parameters.
Regarding p4.change: I suspect that it is also stored as an action. In Jenkins Groovy console get all actions for a build that contains p4.change and examine them - it will give you an idea what to look for in your code.
The problem with formulating an answer to this question is that you do not specify the desired output when the nullable datetime has no value. The following code will output DateTime.MinValue
in such a case, and unlike the currently accepted answer, will not throw an exception.
dt2.GetValueOrDefault().ToString(format);
Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.
I show you here the easiest way using Vs2017 and Vs2019 Open your xsd with Visual Studio and generate a sample xml file as in the url suggested.
2. Within “XML Schema Explorer” scroll all the way down to find the root/data node. Right click on root/data node and it will show “Generate Sample XML”. If it does not show, it means you are not on the data element node but you are on any of the data definition node.
First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:
I would use an anonymous type filled with your results
type:
string json = JsonConvert.SerializeObject(new
{
results = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" }
}
});
Also, note that the generated JSON has result items with id
s of type Number
instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id
to string
in the C#.
I'd also tweak your results
type and get rid of the backing fields:
public class Result
{
public int id { get ;set; }
public string value { get; set; }
public string info { get; set; }
}
Furthermore, classes conventionally are PascalCased
and not camelCased
.
Here's the generated JSON from the code above:
{
"results": [
{
"id": 1,
"value": "ABC",
"info": "ABC"
},
{
"id": 2,
"value": "JKL",
"info": "JKL"
}
]
}
Because when the script executes the browser has not yet parsed the <body>
, so it does not know that there is an element with the specified id.
Try this instead:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = (function () {
var refButton = document.getElementById("btnButton");
refButton.onclick = function() {
alert('Dhoor shala!');
};
});
</script>
</head>
<body>
<form id="form1">
<div>
<input id="btnButton" type="button" value="Click me"/>
</div>
</form>
</body>
</html>
Note that you may as well use addEventListener
instead of window.onload = ...
to make that function only execute after the whole document has been parsed.
You cannot do it for File, which is primarily an intelligent file path. Can you refactor your code so that it declares the variables, and passes around arguments, with type OutputStream instead of FileOutputStream? If so, see classes java.io.ByteArrayOutputStream and java.io.ByteArrayInputStream
OutputStream outStream = new ByteArrayOutputStream();
outStream.write(whatever);
outStream.close();
byte[] data = outStream.toByteArray();
InputStream inStream = new ByteArrayInputStream(data);
...
strconv.Itoa(int(time.Now().Unix()))
In Python, a method is a function that is available for a given object because of the object's type.
For example, if you create my_list = [1, 2, 3]
, the append
method can be applied to my_list
because it's a Python list: my_list.append(4)
. All lists have an append
method simply because they are lists.
As another example, if you create my_string = 'some lowercase text'
, the upper
method can be applied to my_string
simply because it's a Python string: my_string.upper()
.
Lists don't have an upper
method, and strings don't have an append
method. Why? Because methods only exist for a particular object if they have been explicitly defined for that type of object, and Python's developers have (so far) decided that those particular methods are not needed for those particular objects.
To call a method, the format is object_name.method_name()
, and any arguments to the method are listed within the parentheses. The method implicitly acts on the object being named, and thus some methods don't have any stated arguments since the object itself is the only necessary argument. For example, my_string.upper()
doesn't have any listed arguments because the only required argument is the object itself, my_string
.
One common point of confusion regards the following:
import math
math.sqrt(81)
Is sqrt
a method of the math
object? No. This is how you call the sqrt
function from the math
module. The format being used is module_name.function_name()
, instead of object_name.method_name()
. In general, the only way to distinguish between the two formats (visually) is to look in the rest of the code and see if the part before the period (math
, my_list
, my_string
) is defined as an object or a module.
Use Css Selector for this, or learn more about Css Selector just go here
https://www.w3schools.com/cssref/css_selectors.asp
#main_text > .title {
/* Style goes here */
}
#main_text .title {
/* Style goes here */
}
As far as I can tell, there is no way to write a setter for a class property without creating a new metaclass.
I have found that the following method works. Define a metaclass with all of the class properties and setters you want. IE, I wanted a class with a title
property with a setter. Here's what I wrote:
class TitleMeta(type):
@property
def title(self):
return getattr(self, '_title', 'Default Title')
@title.setter
def title(self, title):
self._title = title
# Do whatever else you want when the title is set...
Now make the actual class you want as normal, except have it use the metaclass you created above.
# Python 2 style:
class ClassWithTitle(object):
__metaclass__ = TitleMeta
# The rest of your class definition...
# Python 3 style:
class ClassWithTitle(object, metaclass = TitleMeta):
# Your class definition...
It's a bit weird to define this metaclass as we did above if we'll only ever use it on the single class. In that case, if you're using the Python 2 style, you can actually define the metaclass inside the class body. That way it's not defined in the module scope.
jQuery has the inArray
function:
Logic: A hash can have only unique keys, so iterate over array, assign any value to each element of array, keeping element as key of that hash. Return keys of the hash, its your unique array.
my @unique = keys {map {$_ => 1} @array};
Better to make a subroutine if we are supposed to use this functionality multiple times in our code.
sub get_unique {
my %seen;
grep !$seen{$_}++, @_;
}
my @unique = get_unique(@array);
List::MoreUtils
use List::MoreUtils qw(uniq);
my @unique = uniq(@array);
We don't have to reinvent the wheel. Just use a library to save the time and headache.
https://github.com/dankogai/js-base64 is good and I confirm it supports unicode very well.
Base64.encode('dankogai'); // ZGFua29nYWk=
Base64.encode('???'); // 5bCP6aO85by+
Base64.encodeURI('???'); // 5bCP6aO85by-
Base64.decode('ZGFua29nYWk='); // dankogai
Base64.decode('5bCP6aO85by+'); // ???
// note .decodeURI() is unnecessary since it accepts both flavors
Base64.decode('5bCP6aO85by-'); // ???
SELECT TOP 75 * FROM MyTable
EXCEPT
SELECT TOP 50 * FROM MyTable
One more subtle difference is the treatment of falsy values in {{#property}}...{{/property}}
blocks. Most mustache implementations will just obey JS falsiness here, not rendering the block if property
is ''
or '0'.
Handlebars will render the block for ''
and 0
, but not other falsy values. This can cause some trouble when migrating templates.
@choz answer is the correct way. If you have many usages and want to make sure it works everywhere without changes you can add these small migration-snippet:
/* Migration jQuery from 1.8 to 3.x */
jQuery.fn.load = function (callback) {
var el = $(this);
el.on('load', callback);
return el;
};
In this case you got no erros on other nodes e.g. on $image
like in @Korsmakolnikov answer!
const $image = $('img.image').load(function() {
$(this).doSomething();
});
$image.doSomethingElseWithTheImage();
The following
find * -maxdepth 0 -type d
basically filters the expansion of '*', i.e. all entries in the current dir, by the -type d
condition.
Advantage is that, output is same as ls -1 *
, but only with directories
and entries do not start with a dot
In modern versions of IE (IE10 and above), scrollbars can be hidden using the -ms-overflow-style
property.
html {
-ms-overflow-style: none;
}
In Chrome, scrollbars can be styled:
::-webkit-scrollbar {
display: none;
}
This is very useful if you want to use the 'default' body scrolling in a web application, which is considerably faster than overflow-y: scroll
.
Using hamishmcn's answer as a template I was able to search for a line in a file that match my regex and replacing it with empty string.
import re
fin = open("in.txt", 'r') # in file
fout = open("out.txt", 'w') # out file
for line in fin:
p = re.compile('[-][0-9]*[.][0-9]*[,]|[-][0-9]*[,]') # pattern
newline = p.sub('',line) # replace matching strings with empty string
print newline
fout.write(newline)
fin.close()
fout.close()
abs()
is for integers only. For floating point, use fabs()
(or one of the fabs()
line with the correct precision for whatever a actually is)
I don't have access to a Linux box right now, but [
is actually a program (and a Bash builtin), so I think you have to put a space between [
and the first parameter.
Also note that the string equality operator seems to be a single =
.
Use pivot tables, it will definitely save you time. If you are using excel 2007+ use tables (structured references) to keep your table dynamic. However if you insist on using functions, go with Smandoli's suggestion. Again, if you are on 2007+ use SUMIFS, it's faster compared to SUMIF.
In your case here is a implementation using directions service.
function displayRoute() {
var start = new google.maps.LatLng(28.694004, 77.110291);
var end = new google.maps.LatLng(28.72082, 77.107241);
var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get "DirectionsRendererOptions" object
directionsDisplay.setMap(map); // map should be already initialized.
var request = {
origin : start,
destination : end,
travelMode : google.maps.TravelMode.DRIVING
};
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
And what about using this.getClass().getProtectionDomain().getCodeSource().getLocation()
?
I had a similar problem with wget to my own live web site returning errors after installing a new SSL certificate. I'd already checked several browsers and they didn't report any errors:
wget --no-cache -O - "https://example.com/..." ERROR: The certificate of ‘example.com’ is not trusted. ERROR: The certificate of ‘example.com’ hasn't got a known issuer.
The problem was I had installed the wrong certificate authority .pem/.crt file from the issuer. Usually they bundle the SSL certificate and CA file as a zip file, but DigiCert email you the certificate and you have to figure out the matching CA on your own. https://www.digicert.com/help/ has an SSL certificate checker which lists the SSL authority and the hopefully matching CA with a nice blue link graphic if they agree:
`SSL Cert: Issuer GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1
CA: Subject GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1 Valid from 16/Jul/2020 to 31/May/2023 Issuer DigiCert Global Root CA`
You can also try this, after injecting $window service.
$window.location.reload();
Please follow below steps :
1.Open Your project.
2.Go to the Left side of the Gradle button.
3.Look at below image.
4.Click button above image show.
5.if this type of view you are not in offline mode.
6.Go to Build and rebuild the project.
All above point is work for me.
You should be able to accomplish this by adding a refspec for tags to your local config. Concretely:
[remote "upstream"]
url = <redacted>
fetch = +refs/heads/*:refs/remotes/upstream/*
fetch = +refs/tags/*:refs/tags/*
You can edit the ~/.gitconfig
file in your home folder. This is where all --global
settings are saved.
Here's a dictionary that will take any type of key as long as the toString() property returns unique values. The dictionary uses anything as the value for the key value pair.
See Would JavaScript Benefit from a Dictionary Object.
To use the dictionary as is:
var dictFact = new Dict();
var myDict = dictFact.New();
myDict.addOrUpdate("key1", "Value1");
myDict.addOrUpdate("key2", "Value2");
myDict.addOrUpdate("keyN", "ValueN");
The dictionary code is below:
/*
* Dictionary Factory Object
* Holds common object functions. similar to V-Table
* this.New() used to create new dictionary objects
* Uses Object.defineProperties so won't work on older browsers.
* Browser Compatibility (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties)
* Firefox (Gecko) 4.0 (2), Chrome 5, Internet Explorer 9, Opera 11.60, Safari 5
*/
function Dict() {
/*
* Create a new Dictionary
*/
this.New = function () {
return new dict();
};
/*
* Return argument f if it is a function otherwise return undefined
*/
function ensureF(f) {
if (isFunct(f)) {
return f;
}
}
function isFunct(f) {
return (typeof f == "function");
}
/*
* Add a "_" as first character just to be sure valid property name
*/
function makeKey(k) {
return "_" + k;
};
/*
* Key Value Pair object - held in array
*/
function newkvp(key, value) {
return {
key: key,
value: value,
toString: function () { return this.key; },
valueOf: function () { return this.key; }
};
};
/*
* Return the current set of keys.
*/
function keys(a) {
// remove the leading "-" character from the keys
return a.map(function (e) { return e.key.substr(1); });
// Alternative: Requires Opera 12 vs. 11.60
// -- Must pass the internal object instead of the array
// -- Still need to remove the leading "-" to return user key values
// Object.keys(o).map(function (e) { return e.key.substr(1); });
};
/*
* Return the current set of values.
*/
function values(a) {
return a.map(function(e) { return e.value; } );
};
/*
* Return the current set of key value pairs.
*/
function kvPs(a) {
// Remove the leading "-" character from the keys
return a.map(function (e) { return newkvp(e.key.substr(1), e.value); });
}
/*
* Returns true if key exists in the dictionary.
* k - Key to check (with the leading "_" character)
*/
function exists(k, o) {
return o.hasOwnProperty(k);
}
/*
* Array Map implementation
*/
function map(a, f) {
if (!isFunct(f)) { return; }
return a.map(function (e, i) { return f(e.value, i); });
}
/*
* Array Every implementation
*/
function every(a, f) {
if (!isFunct(f)) { return; }
return a.every(function (e, i) { return f(e.value, i) });
}
/*
* Returns subset of "values" where function "f" returns true for the "value"
*/
function filter(a, f) {
if (!isFunct(f)) {return; }
var ret = a.filter(function (e, i) { return f(e.value, i); });
// if anything returned by array.filter, then get the "values" from the key value pairs
if (ret && ret.length > 0) {
ret = values(ret);
}
return ret;
}
/*
* Array Reverse implementation
*/
function reverse(a, o) {
a.reverse();
reindex(a, o, 0);
}
/**
* Randomize array element order in-place.
* Using Fisher-Yates shuffle algorithm.
*/
function shuffle(a, o) {
var j, t;
for (var i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
t = a[i];
a[i] = a[j];
a[j] = t;
}
reindex(a, o, 0);
return a;
}
/*
* Array Some implementation
*/
function some(a, f) {
if (!isFunct(f)) { return; }
return a.some(function (e, i) { return f(e.value, i) });
}
/*
* Sort the dictionary. Sorts the array and reindexes the object.
* a - dictionary array
* o - dictionary object
* sf - dictionary default sort function (can be undefined)
* f - sort method sort function argument (can be undefined)
*/
function sort(a, o, sf, f) {
var sf1 = f || sf; // sort function method used if not undefined
// if there is a customer sort function, use it
if (isFunct(sf1)) {
a.sort(function (e1, e2) { return sf1(e1.value, e2.value); });
}
else {
// sort by key values
a.sort();
}
// reindex - adds O(n) to perf
reindex(a, o, 0);
// return sorted values (not entire array)
// adds O(n) to perf
return values(a);
};
/*
* forEach iteration of "values"
* uses "for" loop to allow exiting iteration when function returns true
*/
function forEach(a, f) {
if (!isFunct(f)) { return; }
// use for loop to allow exiting early and not iterating all items
for(var i = 0; i < a.length; i++) {
if (f(a[i].value, i)) { break; }
}
};
/*
* forEachR iteration of "values" in reverse order
* uses "for" loop to allow exiting iteration when function returns true
*/
function forEachR(a, f) {
if (!isFunct(f)) { return; }
// use for loop to allow exiting early and not iterating all items
for (var i = a.length - 1; i > -1; i--) {
if (f(a[i].value, i)) { break; }
}
}
/*
* Add a new Key Value Pair, or update the value of an existing key value pair
*/
function add(key, value, a, o, resort, sf) {
var k = makeKey(key);
// Update value if key exists
if (exists(k, o)) {
a[o[k]].value = value;
}
else {
// Add a new Key value Pair
var kvp = newkvp(k, value);
o[kvp.key] = a.length;
a.push(kvp);
}
// resort if requested
if (resort) { sort(a, o, sf); }
};
/*
* Removes an existing key value pair and returns the "value" If the key does not exists, returns undefined
*/
function remove(key, a, o) {
var k = makeKey(key);
// return undefined if the key does not exist
if (!exists(k, o)) { return; }
// get the array index
var i = o[k];
// get the key value pair
var ret = a[i];
// remove the array element
a.splice(i, 1);
// remove the object property
delete o[k];
// reindex the object properties from the remove element to end of the array
reindex(a, o, i);
// return the removed value
return ret.value;
};
/*
* Returns true if key exists in the dictionary.
* k - Key to check (without the leading "_" character)
*/
function keyExists(k, o) {
return exists(makeKey(k), o);
};
/*
* Returns value assocated with "key". Returns undefined if key not found
*/
function item(key, a, o) {
var k = makeKey(key);
if (exists(k, o)) {
return a[o[k]].value;
}
}
/*
* changes index values held by object properties to match the array index location
* Called after sorting or removing
*/
function reindex(a, o, i){
for (var j = i; j < a.length; j++) {
o[a[j].key] = j;
}
}
/*
* The "real dictionary"
*/
function dict() {
var _a = [];
var _o = {};
var _sortF;
Object.defineProperties(this, {
"length": { get: function () { return _a.length; }, enumerable: true },
"keys": { get: function() { return keys(_a); }, enumerable: true },
"values": { get: function() { return values(_a); }, enumerable: true },
"keyValuePairs": { get: function() { return kvPs(_a); }, enumerable: true},
"sortFunction": { get: function() { return _sortF; }, set: function(funct) { _sortF = ensureF(funct); }, enumerable: true }
});
// Array Methods - Only modification to not pass the actual array to the callback function
this.map = function(funct) { return map(_a, funct); };
this.every = function(funct) { return every(_a, funct); };
this.filter = function(funct) { return filter(_a, funct); };
this.reverse = function() { reverse(_a, _o); };
this.shuffle = function () { return shuffle(_a, _o); };
this.some = function(funct) { return some(_a, funct); };
this.sort = function(funct) { return sort(_a, _o, _sortF, funct); };
// Array Methods - Modified aborts when funct returns true.
this.forEach = function (funct) { forEach(_a, funct) };
// forEach in reverse order
this.forEachRev = function (funct) { forEachR(_a, funct) };
// Dictionary Methods
this.addOrUpdate = function(key, value, resort) { return add(key, value, _a, _o, resort, _sortF); };
this.remove = function(key) { return remove(key, _a, _o); };
this.exists = function(key) { return keyExists(key, _o); };
this.item = function(key) { return item(key, _a, _o); };
this.get = function (index) { if (index > -1 && index < _a.length) { return _a[index].value; } } ,
this.clear = function() { _a = []; _o = {}; };
return this;
}
return this;
}
Stream version, filters spaces and tabs.
Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
You don't say what module you want to install - hence npm looks for a file package.json
which describes your dependencies, and obviously this file is missing.
So either you have to explicitly tell npm which module to install, e.g.
npm install express
or
npm install -g express-generator
or you have to add a package.json
file and register your modules here. The easiest way to get such a file is to let npm create one by running
npm init
and then add what you need. Please note that this does only work for locally installed modules, not for global ones.
A simple example might look like this:
{
"name": "myapp",
"version": "0.0.1",
"dependencies": {
"express": "4.0.0"
}
}
or something like that. For more info on the package.json
file see its official documentation and this interactive guide.
<div id="elem" class="className"></div>
With Javascript
document.getElementById('elem').className;
With jQuery
$('#elem').attr('class');
OR
$('#elem').get(0).className;
Maps from JDK are not meant for storing data under duplicated keys.
At best new value will override the previous ones.
Worse scenario is exception (e.g when you try to collect it as a stream):
No duplicates:
Stream.of("one").collect(Collectors.toMap(x -> x, x -> x))
Ok. You will get: $2 ==> {one=one}
Duplicated stream:
Stream.of("one", "not one", "surely not one").collect(Collectors.toMap(x -> 1, x -> x))
Exception java.lang.IllegalStateException: Duplicate key 1 (attempted merging values one and not one) | at Collectors.duplicateKeyException (Collectors.java:133) | at Collectors.lambda$uniqKeysMapAccumulator$1 (Collectors.java:180) | at ReduceOps$3ReducingSink.accept (ReduceOps.java:169) | at Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948) | at AbstractPipeline.copyInto (AbstractPipeline.java:484) | at AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:474) | at ReduceOps$ReduceOp.evaluateSequential (ReduceOps.java:913) | at AbstractPipeline.evaluate (AbstractPipeline.java:234) | at ReferencePipeline.collect (ReferencePipeline.java:578) | at (#4:1)
To deal with duplicated keys - use other package, e.g: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html
There is a lot of other implementations dealing with duplicated keys. Those are needed for web (e.g. duplicated cookie keys, Http headers can have same fields, ...)
Good luck! :)
The infix operator %>%
is not part of base R, but is in fact defined by the package magrittr
(CRAN) and is heavily used by dplyr
(CRAN).
It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.
What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris
gets passed to head()
:
library(magrittr)
iris %>% head()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
Thus, iris %>% head()
is equivalent to head(iris)
.
Often, %>%
is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris
is passed to head()
, then the result of that is passed to summary()
.
iris %>% head() %>% summary()
Thus iris %>% head() %>% summary()
is equivalent to summary(head(iris))
. Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.
It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"
), it is possible to modify/read the content of an app even on a non-rooted device.
Solution - use android:allowBackup="false"
in the manifest file.
You can read this post to have more information: Hacking Android Apps Using Backup Techniques
You could do this:
find ./ -type f -ls |grep '10 Sep'
Example:
[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235 4 -rw-r--r-- 1 root root 29 Dec 24 03:24 /var/lib/prelink/full
798227 288 -rw-r--r-- 1 root root 292323 Dec 24 23:53 /var/log/sa/sar24
797244 320 -rw-r--r-- 1 root root 321300 Dec 24 23:50 /var/log/sa/sa24
another possibility is that the server does not handle the OPTIONS request.
Lets try to answer this question, with a good and simple scenario, with 3 MySQL
tables i.e. datetable, colortable and jointable.
first see values of table
datetable with primary key
assigned to column
dateid:
mysql> select * from datetable;
+--------+------------+
| dateid | datevalue |
+--------+------------+
| 101 | 2015-01-01 |
| 102 | 2015-05-01 |
| 103 | 2016-01-01 |
+--------+------------+
3 rows in set (0.00 sec)
now move to our second table
values colortable with primary key
assigned to column
colorid:
mysql> select * from colortable;
+---------+------------+
| colorid | colorvalue |
+---------+------------+
| 11 | blue |
| 12 | yellow |
+---------+------------+
2 rows in set (0.00 sec)
and our final third table
jointable have no primary keys
and values are:
mysql> select * from jointable;
+--------+---------+
| dateid | colorid |
+--------+---------+
| 101 | 11 |
| 102 | 12 |
| 101 | 12 |
+--------+---------+
3 rows in set (0.00 sec)
Now our condition is to find the dateid's, which have both color values blue and yellow.
So, our query is:
mysql> SELECT t1.dateid FROM jointable AS t1 INNER JOIN jointable t2
-> ON t1.dateid = t2.dateid
-> WHERE
-> (t1.colorid IN (SELECT colorid FROM colortable WHERE colorvalue = 'blue'))
-> AND
-> (t2.colorid IN (SELECT colorid FROM colortable WHERE colorvalue = 'yellow'));
+--------+
| dateid |
+--------+
| 101 |
+--------+
1 row in set (0.00 sec)
Hope, this would help many one.
Below solution work for 2.3(Gingerbread)-4.4(Kitkat), 5.0(Lollipop) and 6.0(Marshmallow) also:-
Step 1 Code for opening the gallery to select pics:
public static final int PICK_IMAGE = 1;
private void takePictureFromGalleryOrAnyOtherFolder()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
Step 2 Code for getting data in onActivityResult
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE) {
Uri selectedImageUri = data.getData();
String imagePath = getRealPathFromURI(selectedImageUri);
//Now you have imagePath do whatever you want to do now
}//end of inner if
}//end of outer if
}
public String getRealPathFromURI(Uri contentUri) {
//Uri contentUri = Uri.parse(contentURI);
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[] { id }, null);
} else {
cursor = context.getContentResolver().query(contentUri,
projection, null, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
String path = null;
try {
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return path;
}
It's usually \t
in command-line interfaces, which will convert the char \t
into the whitespace tab character.
For example, hello\talex
-> hello--->alex
.
After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout
. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".
This is an old question but I think it needs a more up to date answer because now there is a way to have more control of website caching.
In Offline Web Applications (which is really any HTML5 website) applicationCache.swapCache()
can be used to update the cached version of your website without the need for manually reloading the page.
This is a code example from the Beginner's Guide to Using the Application Cache on HTML5 Rocks explaining how to update users to the newest version of your site:
// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false);
See also Using the application cache on Mozilla Developer Network for more info.
Things change quickly on the Web. This question was asked in 2009 and in 2012 I posted an update about a new way to handle the problem described in the question. Another 4 years passed and now it seems that it is already deprecated. Thanks to cgaldiolo for pointing it out in the comments.
Currently, as of July 2016, the HTML Standard, Section 7.9, Offline Web applications includes a deprecation warning:
This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using any of the offline Web application features at this time is highly discouraged. Use service workers instead.
So does Using the application cache on Mozilla Developer Network that I referenced in 2012:
Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
See also Bug 1204581 - Add a deprecation notice for AppCache if service worker fetch interception is enabled.
Here are the steps to fix the problem: (instant fast SWAP file allocation method used)
Server SWAP Setup (Ubuntu 16.04 SWAP to Fix Out of Memory Errors)
Check if you have swap already, memory and disk size:
sudo swapon -s
free -m
df -h
Make swap file: (change 1G to 4G if you want 4GB SWAP memory)
sudo fallocate -l 1G /swapfile
Check swap file:
ls -lh /swapfile
Assign Swap File:
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Check if swap OK, memory and disk size:
sudo swapon -s
free -m
df -h
Attach Swap File on System Restart:
sudo nano /etc/fstab
/swapfile none swap sw 0 0
Adjust Swap File Settings:
cat /proc/sys/vm/swappiness
cat /proc/sys/vm/vfs_cache_pressure
sudo sysctl vm.swappiness=10
sudo sysctl vm.vfs_cache_pressure=50
sudo nano /etc/sysctl.conf
SWAP File Priority: (0-100% => 0: Don't put to swap, 100: Put on SWAP and free the RAM)
vm.swappiness=10
Remove inode from cache: (100: system removes inode information from the cache too quickly)
vm.vfs_cache_pressure = 50
If you are using macOS {mine 'High Sierra'} and Installed XAMPP
You can find mysql data files;
Go to : /Applications/XAMPP/xamppfiles/var/mysql/
perlfaq5: How do I select a random line from a file? Here's a reservoir-sampling algorithm from the Camel Book:
perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line;' file
This has a significant advantage in space over reading the whole file in. You can find a proof of this method in The Art of Computer Programming, Volume 2, Section 3.4.2, by Donald E. Knuth.
Here is a complete answer that will hopefully help others...
I want to setup mysql replication using master and slave, and since the only thing I knew was that it uses log file(s) to synchronize, if the slave goes offline and gets out of sync, in theory it should only need to connect back to its master and keep reading the log file from where it left off, as user malonso mentioned.
So here are the test result after configuring the master and slave as mentioned by: http://dev.mysql.com/doc/refman/5.0/en/replication-howto.html ...
Provided you use the recommended master/slave configuration and don't write to the slave, he and I where right (as far as mysql-server 5.x is concerned). I didn't even need to use "START SLAVE;", it just caught up to its master. But there is a default 88000 something retries every 60 second so I guess if you exhaust that you might have to start or restart the slave. Anyways, for those like me who wanted to know if having a slave going offline and back up again requires manual intervention.. no, it doesn't.
Maybe the original poster had corruption in the log-file(s)? But most probably not just a server going off-line for a day.
pulled from /usr/share/doc/mysql-server-5.1/README.Debian.gz which probably makes sense to non debian servers as well:
* FURTHER NOTES ON REPLICATION =============================== If the MySQL server is acting as a replication slave, you should not set --tmpdir to point to a directory on a memory-based filesystem or to a directory that is cleared when the server host restarts. A replication slave needs some of its temporary files to survive a machine restart so that it can replicate temporary tables or LOAD DATA INFILE operations. If files in the temporary file directory are lost when the server restarts, replication fails.
you can use something sql like: show variables like 'tmpdir'; to find out.
To get only the name of the directory where script executed:
//Path to script: /data/html/cars/index.php
echo basename(dirname(__FILE__)); //"cars"
What the other answers suggest will work for the program in question, but it has the potential to cause breakage in other programs and unknown dependence elsewhere. It's better to make a tiny wrapper script:
#!/bin/sh
export LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH
program_needing_different_run_time_library_path
This mostly avoids the problem described in Why LD_LIBRARY_PATH is bad by confining the effects to the program which needs them.
Note that despite the names LD_RUN_PATH works at link-time and is non-evil, while LD_LIBRARY_PATH works at both link and run time (and is evil :).
In your ajax success callback do this:
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}
As you want to reload the page after 5 seconds, then you need to have a timeout as suggested in the answer.
<div style="display: inline">
<div style="width:80%; display: inline-block; float:left; margin-right: 10px;"></div>
<div style="width: 19%; display: inline-block; border: 1px solid red"></div>
</div>
I spent a lot of time looking for a solution to this problem too. Here's what i've found thus far:
If you want your users to be able to click on a button and copy some text, you may have to use Flash.
If you want your users to press Ctrl+C anywhere on the page, but always copy xyz to the clipboard, I wrote an all-JS solution in YUI3 (although it could easily be ported to other frameworks, or raw JS if you're feeling particularly self-loathing).
It involves creating a textbox off the screen which gets highlighted as soon as the user hits Ctrl/CMD. When they hit 'C' shortly after, they copy the hidden text. If they hit 'V', they get redirected to a container (of your choice) before the paste event fires.
This method can work well, because while you listen for the Ctrl/CMD keydown anywhere in the body, the 'A', 'C' or 'V' keydown listeners only attach to the hidden text box (and not the whole body). It also doesn't have to break the users expectations - you only get redirected to the hidden box if you had nothing selected to copy anyway!
Here's what i've got working on my site, but check http://at.cg/js/clipboard.js for updates if there are any:
YUI.add('clipboard', function(Y) {
// Change this to the id of the text area you would like to always paste in to:
pasteBox = Y.one('#pasteDIV');
// Make a hidden textbox somewhere off the page.
Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');
// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:
// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
copyData();
// Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
// alert(e.keyCode);
// }, 'body', 'down:', Y);
}, 'body', 'down:91,224,17', Y);
// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
// Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
// Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
pasteBox.select();
}, '#copyBox', 'down:86', Y);
// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
pasteBox.select();
}, '#copyBox', 'down:65', Y);
// What to do when keybindings are fired:
// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
var txt = '';
// props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
if (window.getSelection) { txt = window.getSelection(); }
else if (document.getSelection) { txt = document.getSelection(); }
else if (document.selection) { txt = document.selection.createRange().text; }
else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');
// If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy.
if(txt=='') {
copyBox.select();
}
// They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
else if (txt == copyBox.get('value')) {
alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
copyBox.select();
} else {
// They also might have selected something completely different! If so, let them. It's only fair.
}
}
});
Hope someone else finds this useful :]
I tried this code and it's working for me .
$html = file_get_contents('www.google.com');
$myVar = htmlspecialchars($html, ENT_QUOTES);
echo($myVar);
If you just want the last date for each account, you'd use this:
var q = from n in table
group n by n.AccountId into g
select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};
If you want the whole record:
var q = from n in table
group n by n.AccountId into g
select g.OrderByDescending(t=>t.Date).FirstOrDefault();
See help(Sys.sleep)
.
For example, from ?Sys.sleep
testit <- function(x)
{
p1 <- proc.time()
Sys.sleep(x)
proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)
Yielding
> testit(3.7)
user system elapsed
0.000 0.000 3.704
Specific type of array in typescript
export class RegisterFormComponent
{
genders = new Array<GenderType>(); // Use any array supports different kind objects
loadGenders()
{
this.genders.push({name: "Male",isoCode: 1});
this.genders.push({name: "FeMale",isoCode: 2});
}
}
type GenderType = { name: string, isoCode: number }; // Specified format
I had installed CUDA 10.1 and CUDNN 7.6 by mistake. You can use following configurations (This worked for me - as of 9/10). :
But I had to create symlinks for it to work as tensorflow originally works with CUDA 10.
sudo ln -s /opt/cuda/targets/x86_64-linux/lib/libcublas.so /opt/cuda/targets/x86_64-linux/lib/libcublas.so.10.0
sudo cp /usr/lib/x86_64-linux-gnu/libcublas.so.10 /usr/local/cuda-10.1/lib64/
sudo ln -s /usr/local/cuda-10.1/lib64/libcublas.so.10 /usr/local/cuda-10.1/lib64/libcublas.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcusolver.so.10 /usr/local/cuda/lib64/libcusolver.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcurand.so.10 /usr/local/cuda/lib64/libcurand.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcufft.so.10 /usr/local/cuda/lib64/libcufft.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcudart.so /usr/local/cuda/lib64/libcudart.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcusparse.so.10 /usr/local/cuda/lib64/libcusparse.so.10.0
And add the following to my ~/.bashrc -
export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
export PATH=/usr/local/cuda-10.1/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.1/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/cuda/targets/x86_64-linux/lib/
Try this if your service is not returning the right application/json content type header:
$('.typeahead').typeahead({
source: function (query, process) {
return $.get('/typeahead', { query: query }, function (data) {
var json = JSON.parse(data); // string to json
return process(json.options);
});
}
});
I noticed that there is another CSS selector that does the same thing . The syntax is as follows :
[id|="name_id"]
This will select all elements ID which begins with the word enclosed in double quotes.
check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
main
System.out.println("date : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));
method
public String getMyDate(String myDate, String returnFormat, String myFormat)
{
DateFormat dateFormat = new SimpleDateFormat(returnFormat);
Date date=null;
String returnValue="";
try {
date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
returnValue = dateFormat.format(date);
} catch (ParseException e) {
returnValue= myDate;
System.out.println("failed");
e.printStackTrace();
}
return returnValue;
}
i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:
your jQuery script needs to be after the elements you are referring to !
so your script needs to be after the html-code you want to access!
seems like jQuery can't access it otherwise.
You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application
I just want to add to all great answers above,
that if you write a library it's a good practice to use ConfigureAwait(false)
and get better performance, as said here.
So this snippet seems to be better:
public static async Task DoWork()
{
int[] ids = new[] { 1, 2, 3, 4, 5 };
await Task.WhenAll(ids.Select(i => DoSomething(1, i))).ConfigureAwait(false);
}
A full fiddle link here.
Try this
$('document').ready(function(){
window.setTimeout('test()',time in milliseconds);
});
function test(){
$('#divid').hide();
}
why not both to be sure?
if(opener.document){
$("#testdiv",opener.document).doStuff();
}else{
$("#testdiv",window.opener).doStuff();
}
If you use OmniFaces you can also use it's EL functions like of:formatDate()
to format Date
objects. You would use it like this:
<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />
This way you can not only use it for output but also to pass it on to other JSF components.
I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:
query.exec(function (err, results){
if (err) res.writeHead(500, err.message)
else if (!results.length) res.writeHead(404);
else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
}
res.end();
});
Here's an alternative regular expression:
^(?=(.{4})*$)[A-Za-z0-9+/]*={0,2}$
It satisfies the following conditions:
(?=^(.{4})*$)
[A-Za-z0-9+/]*
={0,2}
Old Thread, But in VS 2015 Console.WriteLine does not Write to Output Window If "Enable the Visual Studio Hosting Process" does not Checked or its Disabled in Project Properties -> Debug tab
Adding manifest.file=manifest.mf into project.properties and creating manifest.mf file in the project directory works fine in NB 6.9 and should work also in NB 6.8.
Use below code.
NSString* myString;
myString = [[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];
For me for this issue worked to:
After eclipse restart everything worked well.
After you run MySQL Shell and you have seen following:
mysql-js>
Firstly, you should:
mysql-js>\sql
Secondly:
mysql-sql>\connect username@servername (root@localhost)
And finally:
Enter password:*********
Check that you have the correct rights set on CA certificates bundle. Usually, that means read access for everyone to CA files in the /etc/ssl/certs directory, for instance /etc/ssl/certs/ca-certificates.crt.
You can see what files have been configured for you curl version with the
curl-config --configurecommand :
$ curl-config --configure
'--prefix=/usr'
'--mandir=/usr/share/man'
'--disable-dependency-tracking'
'--disable-ldap'
'--disable-ldaps'
'--enable-ipv6'
'--enable-manual'
'--enable-versioned-symbols'
'--enable-threaded-resolver'
'--without-libidn'
'--with-random=/dev/urandom'
'--with-ca-bundle=/etc/ssl/certs/ca-certificates.crt'
'CFLAGS=-march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4' 'LDFLAGS=-Wl,-O1,--sort-common,--as-needed,-z,relro'
'CPPFLAGS=-D_FORTIFY_SOURCE=2'
Here you need read access to /etc/ssl/certs/ca-certificates.crt
$ curl-config --configure
'--build' 'i486-linux-gnu'
'--prefix=/usr'
'--mandir=/usr/share/man'
'--disable-dependency-tracking'
'--enable-ipv6'
'--with-lber-lib=lber'
'--enable-manual'
'--enable-versioned-symbols'
'--with-gssapi=/usr'
'--with-ca-path=/etc/ssl/certs'
'build_alias=i486-linux-gnu'
'CFLAGS=-g -O2'
'LDFLAGS='
'CPPFLAGS='
And the same here.
Edit: This implementation obsoleted with ARC. Please have a look at How do I implement an Objective-C singleton that is compatible with ARC? for correct implementation.
All the implementations of initialize I've read in other answers share a common error.
+ (void) initialize {
_instance = [[MySingletonClass alloc] init] // <----- Wrong!
}
+ (void) initialize {
if (self == [MySingletonClass class]){ // <----- Correct!
_instance = [[MySingletonClass alloc] init]
}
}
The Apple documentation recommend you check the class type in your initialize block. Because subclasses call the initialize by default. There exists a non-obvious case where subclasses may be created indirectly through KVO. For if you add the following line in another class:
[[MySingletonClass getInstance] addObserver:self forKeyPath:@"foo" options:0 context:nil]
Objective-C will implicitly create a subclass of MySingletonClass resulting in a second triggering of +initialize
.
You may think that you should implicitly check for duplicate initialization in your init block as such:
- (id) init { <----- Wrong!
if (_instance != nil) {
// Some hack
}
else {
// Do stuff
}
return self;
}
But you will shoot yourself in the foot; or worse give another developer the opportunity to shoot themselves in the foot.
- (id) init { <----- Correct!
NSAssert(_instance == nil, @"Duplication initialization of singleton");
self = [super init];
if (self){
// Do stuff
}
return self;
}
TL;DR, here's my implementation
@implementation MySingletonClass
static MySingletonClass * _instance;
+ (void) initialize {
if (self == [MySingletonClass class]){
_instance = [[MySingletonClass alloc] init];
}
}
- (id) init {
ZAssert (_instance == nil, @"Duplication initialization of singleton");
self = [super init];
if (self) {
// Initialization
}
return self;
}
+ (id) getInstance {
return _instance;
}
@end
(Replace ZAssert with our own assertion macro; or just NSAssert.)
Here's my utility method for getting the local IP address, assuming you are looking for an IPv4 address and the machine only has one real network interface. It could easily be refactored to return an array of IP addresses for multi-interface machines.
function getIPAddress() {
var interfaces = require('os').networkInterfaces();
for (var devName in interfaces) {
var iface = interfaces[devName];
for (var i = 0; i < iface.length; i++) {
var alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
return alias.address;
}
}
return '0.0.0.0';
}
Use NSLog()
like this:
NSLog(@"The code runs through here!");
Or like this - with placeholders:
float aFloat = 5.34245;
NSLog(@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat);
In NSLog()
you can use it like + (id)stringWithFormat:(NSString *)format, ...
float aFloat = 5.34245;
NSString *aString = [NSString stringWithFormat:@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat];
You can add other placeholders, too:
float aFloat = 5.34245;
int aInteger = 3;
NSString *aString = @"A string";
NSLog(@"This is my float: %f \n\nAnd here is my integer: %i \n\nAnd finally my string: %@", aFloat, aInteger, aString);
Global $myArr;
$myArr = array();
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
Be forewarned, generally people stick away from globals as it has some downsides.
You could try this
function someFuntion($myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
return $myArr;
}
$myArr = someFunction($myArr);
That would make it so you aren't relying on Globals.
See How to Make Dialogs.
You can use:
JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.
I ran into this same issue trying to install the dbf package in Python 2.7. The problem is that the enum package wasn't added to Python until version 3.4.
It has been backported to versions 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4, you just need the package from here: https://pypi.python.org/pypi/enum34#downloads
What the heck, I'll throw in a quickly-cobbled-together answer as well...it looks a bit like some other implementations here, but I'll add it anywho:
(barely tested, hopefully I'm not embarassing myself)
Let's state some goals first (my assumptions):
1) Must sort ObservableCollection<T>
in place, to maintain notifications, etc.
2) Must not be horribly inefficient (i.e., something close to standard "good" sorting efficiency)
public static class Ext
{
public static void Sort<T>(this ObservableCollection<T> src)
where T : IComparable<T>
{
// Some preliminary safety checks
if(src == null) throw new ArgumentNullException("src");
if(!src.Any()) return;
// N for the select,
// + ~ N log N, assuming "smart" sort implementation on the OrderBy
// Total: N log N + N (est)
var indexedPairs = src
.Select((item,i) => Tuple.Create(i, item))
.OrderBy(tup => tup.Item2);
// N for another select
var postIndexedPairs = indexedPairs
.Select((item,i) => Tuple.Create(i, item.Item1, item.Item2));
// N for a loop over every element
var pairEnum = postIndexedPairs.GetEnumerator();
pairEnum.MoveNext();
for(int idx = 0; idx < src.Count; idx++, pairEnum.MoveNext())
{
src.RemoveAt(pairEnum.Current.Item1);
src.Insert(idx, pairEnum.Current.Item3);
}
// (very roughly) Estimated Complexity:
// N log N + N + N + N
// == N log N + 3N
}
}
You can also use gdb instead of addr2line to examine memory address. Load executable file in gdb and print the name of a symbol which is stored at the address. 16 Examining the Symbol Table.
(gdb) info symbol 0x4005BDC
You can use like below -
this.setState(() => ({ subChartType1: value }), () => this.props.dispatch(setChartData(null)));
DECLARE @chr nvarchar(50) = (SELECT CONVERT(nvarchar(50), GETDATE(), 103))
SELECT @chr chars, CONVERT(date, @chr, 103) date_again
A concrete example of overhead is the difference between a "local" procedure call and a "remote" procedure call.
For example, with classic RPC (and many other remote frameworks, like EJB), a function or method call looks the same to a coder whether its a local, in memory call, or a distributed, network call.
For example:
service.function(param1, param2);
Is that a normal method, or a remote method? From what you see here you can't tell.
But you can imagine that the difference in execution times between the two calls are dramatic.
So, while the core implementation will "cost the same", the "overhead" involved is quite different.
I think the simplest will be
let minutes = Date(timeIntervalSinceNow:(minutes * 60.0))
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
This simple jquery API extention (from: https://benjamin-schweizer.de/jquerypostjson.html) for $.postJSON() does the trick. You can use postJSON() like every other native jquery Ajax call. You can attach event handlers and so on.
$.postJSON = function(url, data, callback) {
return jQuery.ajax({
'type': 'POST',
'url': url,
'contentType': 'application/json; charset=utf-8',
'data': JSON.stringify(data),
'dataType': 'json',
'success': callback
});
};
Like other Ajax APIs (like $http from AngularJS) it sets the correct contentType to application/json. You can pass your json data (javascript objects) directly, since it gets stringified here. The expected returned dataType is set to JSON. You can attach jquery's default event handlers for promises, for example:
$.postJSON(apiURL, jsonData)
.fail(function(res) {
console.error(res.responseText);
})
.always(function() {
console.log("FINISHED ajax post, hide the loading throbber");
});
Past : from sklearn.cross_validation
(This package is deprecated in 0.18 version from 0.20 onwards it is changed to from sklearn import model_selection
).
Present: from sklearn import model_selection
Example 2:
Past : from sklearn.cross_validation import cross_val_score
(Version 0.18 which is deprecated)
Present : from sklearn.model_selection import cross_val_score
I used once this method: This may be totally unoptimized (ie it uses an array of point so its unusable for big circles) but gives random distribution enough. You could skip the creation of the matrix and draw directly if you wish to. The method is to randomize all points in a rectangle that fall inside the circle.
bool[,] getMatrix(System.Drawing.Rectangle r) {
bool[,] matrix = new bool[r.Width, r.Height];
return matrix;
}
void fillMatrix(ref bool[,] matrix, Vector center) {
double radius = center.X;
Random r = new Random();
for (int y = 0; y < matrix.GetLength(0); y++) {
for (int x = 0; x < matrix.GetLength(1); x++)
{
double distance = (center - new Vector(x, y)).Length;
if (distance < radius) {
matrix[x, y] = r.NextDouble() > 0.5;
}
}
}
}
private void drawMatrix(Vector centerPoint, double radius, bool[,] matrix) {
var g = this.CreateGraphics();
Bitmap pixel = new Bitmap(1,1);
pixel.SetPixel(0, 0, Color.Black);
for (int y = 0; y < matrix.GetLength(0); y++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
if (matrix[x, y]) {
g.DrawImage(pixel, new PointF((float)(centerPoint.X - radius + x), (float)(centerPoint.Y - radius + y)));
}
}
}
g.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
System.Drawing.Rectangle r = new System.Drawing.Rectangle(100,100,200,200);
double radius = r.Width / 2;
Vector center = new Vector(r.Left + radius, r.Top + radius);
Vector normalizedCenter = new Vector(radius, radius);
bool[,] matrix = getMatrix(r);
fillMatrix(ref matrix, normalizedCenter);
drawMatrix(center, radius, matrix);
}
If you don't want to go the SMO route you can search and replace "GO" for ";" and the query as you would. Note that soly the the last result set will be returned.
HtmlAgilityPack uses XPath syntax, and though many argues that it is poorly documented, I had no trouble using it with help from this XPath documentation: https://www.w3schools.com/xml/xpath_syntax.asp
To parse
<h2>
<a href="">Jack</a>
</h2>
<ul>
<li class="tel">
<a href="">81 75 53 60</a>
</li>
</ul>
<h2>
<a href="">Roy</a>
</h2>
<ul>
<li class="tel">
<a href="">44 52 16 87</a>
</li>
</ul>
I did this:
string url = "http://website.com";
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//h2//a"))
{
names.Add(node.ChildNodes[0].InnerHtml);
}
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//li[@class='tel']//a"))
{
phones.Add(node.ChildNodes[0].InnerHtml);
}
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
Another way to define a 2-d vector is to declare a vector of pair's.
vector < pair<int,int> > v;
**To insert values**
cin >> x >>y;
v.push_back(make_pair(x,y));
**Retrieve Values**
i=0 to size(v)
x=v[i].first;
y=v[i].second;
For 3-d vectors take a look at tuple and make_tuple.
For anyone still struggling with this, this simple extension in swift should fix the problem for you.
extension UINavigationController {
override open var childForStatusBarStyle: UIViewController? {
return self.topViewController
}
}
If you don't have bs-config.json
, you can change the port inside the lite-server module. Go to node_modules/lite-server/lib/config-defaults.js
in your project, then add the port in "modules.export" like this.
module.export {
port :8000, // to any available port
...
}
Then you can restart the server.
private void txtuser_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
https://firebase.google.com/docs/auth/web/manage-users
You have to add an auth state change observer.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
--get tables that contains selected columnName
SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%batchno%'
its worked...
In case you do not have the fragment tag, the following code works well for me.
Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (currentFragment instanceof "NAME OF YOUR FRAGMENT CLASS") {
FragmentTransaction fragTransaction = (getActivity()).getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();}
}
Ajax call error handler will be triggered if the call itself fails.
You are probably trying to get the error from server in case login credentials do not go through. In that case, you need to inspect the server response json object and display appropriate message.
e.preventDefault();
$.ajax(
{
type: 'POST',
url: requestURI,
data: $(formLogin).serialize(),
dataType: 'json',
success: function(result){
if(result.hasError == true)
{
if(result.error_code == 'AUTH_FAILURE')
{
//wrong password
console.log('Recieved authentication error');
$('#login_errors_auth').fadeIn();
}
else
{
//generic error here
$('#login_errors_unknown').fadeIn();
}
}
}
});
Here, "result" is the json object returned form the server which could have a structure like:
$return = array(
'hasError' => !$validPassword,
'error_code' => 'AUTH_FAILURE'
);
die(jsonEncode($return));
You can pass an array and let php/curl do the dirty work of encoding etc.
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
i have successfully done by below line
//data == html data which you want to load
String data = "Your data which you want to load";
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadData(data, "text/html; charset=utf-8", "UTF-8");
Or You can try
webview.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
I realize this is an old question, but here is an approach which might be slightly more elegant (and may or may not have been available before)...
using System;
using System.Windows;
using System.Windows.Forms;
// ...
/// <summary>
/// Utilities for easier integration with WinForms.
/// </summary>
public static class WinFormsCompatibility {
/// <summary>
/// Gets a handle of the given <paramref name="window"/> and wraps it into <see cref="IWin32Window"/>,
/// so it can be consumed by WinForms code, such as <see cref="FolderBrowserDialog"/>.
/// </summary>
/// <param name="window">
/// The WPF window whose handle to get.
/// </param>
/// <returns>
/// The handle of <paramref name="window"/> is returned as <see cref="IWin32Window.Handle"/>.
/// </returns>
public static IWin32Window GetIWin32Window(this Window window) {
return new Win32Window(new System.Windows.Interop.WindowInteropHelper(window).Handle);
}
/// <summary>
/// Implementation detail of <see cref="GetIWin32Window"/>.
/// </summary>
class Win32Window : IWin32Window { // NOTE: This is System.Windows.Forms.IWin32Window, not System.Windows.Interop.IWin32Window!
public Win32Window(IntPtr handle) {
Handle = handle; // C# 6 "read-only" automatic property.
}
public IntPtr Handle { get; }
}
}
Then, from your WPF window, you can simply...
public partial class MainWindow : Window {
void Button_Click(object sender, RoutedEventArgs e) {
using (var dialog = new FolderBrowserDialog()) {
if (dialog.ShowDialog(this.GetIWin32Window()) == System.Windows.Forms.DialogResult.OK) {
// Use dialog.SelectedPath.
}
}
}
}
Actually, does it matter?
I'm not sure if it matters in this case, but generally, you should tell Windows what is your window hierarchy, so if a parent window is clicked while child window is modal, Windows can provide a visual (and possibly audible) clue to the user.
Also, it ensures the "right" window is on top when there are multiple modal windows (not that I'm advocating such UI design). I've seen UIs designed by a certain multi-billion dollar corporation (which shell remain unnamed), that hanged simply because one modal dialog got "stuck" underneath another, and user had no clue it was even there, let alone how to close it.
this
refers to a reference of the current class.
super
refers to the parent of the current class (which called the super
keyword).
By doing this
, it allows you to access methods/attributes of the current class (including its own private methods/attributes).
super
allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.
select * from tableName where columnName is null
DB::statement("your query")
I used it for add index to column in migration
I'll recommend reading this link https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html from SpringBoot docs about injecting external configs. They didn't only talk about retrieving from a properties file but also YAML and even JSON files. I found it helpful. I hope you do too.
By default Windows defines the following prefix that is available to everyone: http://+:80/Temporary_Listen_Addresses/
So you can register your HttpListener
via:
Prefixes.Add("http://+:80/Temporary_Listen_Addresses/" + Guid.NewGuid().ToString("D") + "/";
This sometimes causes problems with software such as Skype which will try to utilise port 80 by default.
According to the documentation on random.uniform
:
Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.
while random.random
:
Return the next random floating point number in the range [0.0, 1.0).
I.e. with random.uniform
you specify a range you draw pseudo-random numbers from, e.g. between 3 and 10. With random.random
you get a number between 0 and 1.
If you are in the context of a Faraday request, you can also just pass the params hash as the second argument and faraday takes care of making proper param URL part out of it:
faraday_instance.get(url, params_hsh)
In angular 8:
//for catch:
import { catchError } from 'rxjs/operators';
//for throw:
import { Observable, throwError } from 'rxjs';
//and code should be written like this.
getEmployees(): Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
}
erroHandler(error: HttpErrorResponse) {
return throwError(error.message || 'server Error');
}
I resolved that problem just moving my project from E: to C:. I think it happened becouse nodejs and npm was installed in my C: and the project was in my E:
app.config
app.name=Properties Sample Code
app.version=1.09
Source code:
Properties prop = new Properties();
String fileName = "app.config";
InputStream is = null;
try {
is = new FileInputStream(fileName);
} catch (FileNotFoundException ex) {
...
}
try {
prop.load(is);
} catch (IOException ex) {
...
}
System.out.println(prop.getProperty("app.name"));
System.out.println(prop.getProperty("app.version"));
Output:
Properties Sample Code
1.09
To know the format string used by Excel without having to guess it: create an excel file, write a date in cell A1 and format it as you want. Then run the following lines:
FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);
Then copy-paste the resulting string, remove the backslashes (for example d/m/yy\ h\.mm;@
becomes d/m/yy h.mm;@
) and use it in the http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells code:
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
Note: You may also want to run
git clean -fd
as
git reset --hard
will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under git tracking. WARNING - BE CAREFUL WITH THIS! It is helpful to run a dry-run with git-clean first, to see what it will delete.
This is also especially useful when you get the error message
~"performing this command will cause an un-tracked file to be overwritten"
Which can occur when doing several things, one being updating a working copy when you and your friend have both added a new file of the same name, but he's committed it into source control first, and you don't care about deleting your untracked copy.
In this situation, doing a dry run will also help show you a list of files that would be overwritten.
Solved it by setting the naughty EditText:
etSearch = (EditText) view.findViewById(R.id.etSearch);
etSearch.setInputType(InputType.TYPE_NULL);
etSearch.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
etSearch.setInputType(InputType.TYPE_CLASS_TEXT);
return false;
}
});
Not a single answer does what was asked in vanilla JS, and I want a vanilla answer so I made it myself.
clientWidth includes padding and offsetWidth includes everything else (jsfiddle link). What you want is to get the computed style (jsfiddle link).
function getInnerWidth(elem) {
return parseFloat(window.getComputedStyle(elem).width);
}
EDIT: getComputedStyle
is non-standard, and can return values in units other than pixels. Some browsers also return a value which takes the scrollbar into account if the element has one (which in turn gives a different value than the width set in CSS). If the element has a scrollbar, you would have to manually calculate the width by removing the margins and paddings from the offsetWidth
.
function getInnerWidth(elem) {
var style = window.getComputedStyle(elem);
return elem.offsetWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight) - parseFloat(style.borderLeft) - parseFloat(style.borderRight) - parseFloat(style.marginLeft) - parseFloat(style.marginRight);
}
With all that said, this is probably not an answer I would recommend following with my current experience, and I would resort to using methods that don't rely on JavaScript as much.
Do you mean these hex values?
.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
...
You can find these in glyphicons.css
here:
http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css
(If you only want to know the Glyphicons classes: http://getbootstrap.com/components/#glyphicons)
Eventually, you might not have anything in your /Library/StartupItems
.
Using the following command helps :
sudo /Library/Application\ Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh restart
It worked for me on two different Mavericks installs.
I wanted summerize some of the answers into one post.
First, don't think of the MD5 hash as a character string but as a hex number. Therefore, each digit is a hex digit (0-15 or 0-F) and represents four bits, not eight.
Taking that further, one byte or eight bits are represented by two hex digits, e.g. b'1111 1111
' = 0xFF
= 255
.
MD5 hashes are 128 bits in length and generally represented by 32 hex digits.
SHA-1 hashes are 160 bits in length and generally represented by 40 hex digits.
For the SHA-2 family, I think the hash length can be one of a pre-determined set. So SHA-512 can be represented by 128 hex digits.
Again, this post is just based on previous answers.
I'd actually suggest using a solid open-source library as an http client. If you take a look at http client by ASF you'll find life a lot easier. It is an easy-to-use,scalable and robust client for http.
You can use File.Move
to do it.
Below answer worked for angular 4/5.
In app.component.css
.image{
height:40em; background-size:cover; width:auto;
background-image:url('copied image address');
background-position:50% 50%;
}
Also in app.component.html simply add as below
<div class="image">
Your content
</div>
This way I was able to set background image in Angular 4/5.
I'm on Linux Mint 19 (Ubuntu 18 based). I wanted to have coredump
files in current folder. I had to do two things:
/proc/sys/kernel/core_pattern
(by # echo "core.%p.%s.%c.%d.%P > /proc/sys/kernel/core_pattern
or by # sysctl -w kernel.core_pattern=core.%p.%s.%c.%d.%P)
$ ulimit -c unlimited
That was written already in the answers, but I wrote to summarize succinctly. Interestingly changing limit did not require root privileges (as per https://askubuntu.com/questions/162229/how-do-i-increase-the-open-files-limit-for-a-non-root-user non-root can only lower the limit, so that was unexpected - comments about it are welcome).
See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS
filter when you do.
Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.
This won't work. You first have to initialize the array. So far, you only have a String[] reference, pointing to null
.
When you try to read the length member, what you actually do is null.length
, which results in a NullPointerException.
Good to also check the other combinators in the family and to get back to what is this specific one.
ul li
ul > li
ul + ul
ul ~ ul
Example checklist:
ul li
- Looking inside - Selects all the li
elements placed (anywhere) inside the ul
; Descendant selectorul > li
- Looking inside - Selects only the direct li
elements of ul
; i.e. it will only select direct children li
of ul
; Child Selector or Child combinator selectorul + ul
- Looking outside - Selects the ul
immediately following the ul
; It is not looking inside, but looking outside for the immediately following element; Adjacent Sibling Selectorul ~ ul
- Looking outside - Selects all the ul
which follows the ul
doesn't matter where it is, but both ul
should be having the same parent; General Sibling SelectorThe one we are looking at here is General Sibling Selector
Please try below code for it :
$('#msform').fadeOut(50);
$('#msform').fadeIn(50);
new Date(moment('23:04:33', "HH:mm")).getTime()
Output: 1499755980000 (in millisecond) ( 1499755980000/1000) (in second)
Note : this output calculate diff from 1970-01-01 12:0:0 to now and we need to implement the moment.js
KD.py
class A:
a=10;
KD2.py
from com.jbk.KD import A;
class B:
b=120;
aa=A();
print(aa.a)
THIS works perfectly file for me
Another example is
main.py
=======
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff
_init();
stuff();
settings.py
==========
def _init():
print("kiran")
subfile.py
==========
def stuff():
print("asasas")
If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):
DECLARE
last_used NUMBER;
curr_seq NUMBER;
BEGIN
SELECT MAX(pk_val) INTO last_used FROM your_table;
LOOP
SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
IF curr_seq >= last_used THEN EXIT;
END IF;
END LOOP;
END;
This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...
There is a third option - using stream().toArray()
- see comments under why didn't stream have a toList method. It turns out to be slower than forEach() or collect(), and less expressive. It might be optimised in later JDK builds, so adding it here just in case.
assuming List<String>
myFinalList = Arrays.asList(
myListToParse.stream()
.filter(Objects::nonNull)
.map(this::doSomething)
.toArray(String[]::new)
);
with a micro-micro benchmark, 1M entries, 20% nulls and simple transform in doSomething()
private LongSummaryStatistics benchmark(final String testName, final Runnable methodToTest, int samples) {
long[] timing = new long[samples];
for (int i = 0; i < samples; i++) {
long start = System.currentTimeMillis();
methodToTest.run();
timing[i] = System.currentTimeMillis() - start;
}
final LongSummaryStatistics stats = Arrays.stream(timing).summaryStatistics();
System.out.println(testName + ": " + stats);
return stats;
}
the results are
parallel:
toArray: LongSummaryStatistics{count=10, sum=3721, min=321, average=372,100000, max=535}
forEach: LongSummaryStatistics{count=10, sum=3502, min=249, average=350,200000, max=389}
collect: LongSummaryStatistics{count=10, sum=3325, min=265, average=332,500000, max=368}
sequential:
toArray: LongSummaryStatistics{count=10, sum=5493, min=517, average=549,300000, max=569}
forEach: LongSummaryStatistics{count=10, sum=5316, min=427, average=531,600000, max=571}
collect: LongSummaryStatistics{count=10, sum=5380, min=444, average=538,000000, max=557}
parallel without nulls and filter (so the stream is SIZED
):
toArrays has the best performance in such case, and .forEach()
fails with "indexOutOfBounds" on the recepient ArrayList, had to replace with .forEachOrdered()
toArray: LongSummaryStatistics{count=100, sum=75566, min=707, average=755,660000, max=1107}
forEach: LongSummaryStatistics{count=100, sum=115802, min=992, average=1158,020000, max=1254}
collect: LongSummaryStatistics{count=100, sum=88415, min=732, average=884,150000, max=1014}
For me the Anonymous User access was fine at the server level, but varied at just one of my "virtual" folders.
Took me quite a bit of foundering about and then some help from a colleague to learn that IIS has "authentication" settings at the virtual folder level too - hopefully this helps someone else with my predicament.
All are different.
typeof
takes a type name (which you specify at compile time).GetType
gets the runtime type of an instance.is
returns true if an instance is in the inheritance tree.class Animal { }
class Dog : Animal { }
void PrintTypes(Animal a) {
Console.WriteLine(a.GetType() == typeof(Animal)); // false
Console.WriteLine(a is Animal); // true
Console.WriteLine(a.GetType() == typeof(Dog)); // true
Console.WriteLine(a is Dog); // true
}
Dog spot = new Dog();
PrintTypes(spot);
What about
typeof(T)
? Is it also resolved at compile time?
Yes. T is always what the type of the expression is. Remember, a generic method is basically a whole bunch of methods with the appropriate type. Example:
string Foo<T>(T parameter) { return typeof(T).Name; }
Animal probably_a_dog = new Dog();
Dog definitely_a_dog = new Dog();
Foo(probably_a_dog); // this calls Foo<Animal> and returns "Animal"
Foo<Animal>(probably_a_dog); // this is exactly the same as above
Foo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal.
Foo(definitely_a_dog); // this calls Foo<Dog> and returns "Dog"
Foo<Dog>(definitely_a_dog); // this is exactly the same as above.
Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal".
Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"
I got the same issue, and here is how I fixed it after doing some research:
Git Shell
from task menu. This will open a power shell including Git commands.cd C:\path\to\old\repository
Show status of the old repository
Type git remote -v
to get the remote path for fetch and push remote. If your local repository is connected to a remote, it will show something like this:
origin https://[email protected]/team-or-user-name/myproject.git (fetch) origin https://[email protected]/team-or-user-name/myproject.git (push)
If it's not connected, it might show origin
only.
Now remove the remote repository from local repository by using
git remote rm origin
Check again with step 4. It should show origin
only, instead of the fetch and push path.
Now that your old remote repository is disconnected, you can add the new remote repository. Use the following to connect to your new repository.
Note: In case you are using Bitbucket, you would create a project on Bitbucket first. After creation, Bitbucket will display all required Git commands to push your repository to remote, which look similar to the next code snippet. However, this works for other repositories, too.
cd /path/to/my/repo # If haven't done yet
git remote add mynewrepo https://[email protected]/team-or-user-name/myproject.git
git push -u mynewrepo master # To push changes for the first time
That's it.
Most probably you might have parameterized constructor in your controller and whatever dependency resolver you are using is not able to resolve the dependency properly. You need to put break-point where the dependency resolver method is written and you will get the exact error in inner exception.
Either two different IP addresses (like recommended) or one web server is reverse-proxying the other (which is listening on a port <>80).
For instance: Apache listens on port 80, IIS on port 8080. Every http request goes to Apache first (of course). You can then decide to forward every request to a particular (named virtual) domain or every request that contains a particular directory (e.g. http://www.example.com/winapp/) to the IIS.
Advantage of this concept is that you have only one server listening to the public instead of two, you are more flexible as with two distinct servers.
Drawbacks: some webapps are crappily designed and a real pain in the ass to integrate into a reverse-proxy infrastructure. A working IIS webapp is dependent on a working Apache, so we have some inter-dependencies.
Use Visual Studio Setup project. Setup project can automatically include .NET framework setup in your installation package:
Here is my step-by-step for windows forms application:
Create setup project. You can use Setup Wizard.
Select project type.
Select output.
Hit Finish.
Open setup project properties.
Chose to include .NET framework.
Build setup project
Check output
Note: The Visual Studio Installer projects are no longer pre-packed with Visual Studio. However, in Visual Studio 2013 you can download them by using:
Tools > Extensions and Updates > Online (search) > Visual Studio Installer Projects
Below is answering the original first question:
Should I use
dict
orOrderedDict
in Python 3.6?
I think this sentence from the documentation is actually enough to answer your question
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon
dict
is not explicitly meant to be an ordered collection, so if you want to stay consistent and not rely on a side effect of the new implementation you should stick with OrderedDict
.
Make your code future proof :)
There's a debate about that here.
EDIT: Python 3.7 will keep this as a feature see
You can use the by_row
function from the package purrrlyr
for this:
myfn <- function(row) {
#row is a tibble with one row, and the same
#number of columns as the original df
#If you'd rather it be a list, you can use as.list(row)
}
purrrlyr::by_row(df, myfn)
By default, the returned value from myfn
is put into a new list column in the df called .out
.
If this is the only output you desire, you could write purrrlyr::by_row(df, myfn)$.out
We print the value using mainList.get(index) where index starts with '0'. For Example: mainList.get(2) prints the 3rd element in the list.
tl;dr
All maven POMs inherit from a base Super POM.
The snippet below is part of the Super POM for Maven 3.5.4.
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
Check date is monday or sunday before get last monday or last sunday
public function getWeek($date){
$date_stamp = strtotime(date('Y-m-d', strtotime($date)));
//check date is sunday or monday
$stamp = date('l', $date_stamp);
$timestamp = strtotime($date);
//start week
if(date('D', $timestamp) == 'Mon'){
$week_start = $date;
}else{
$week_start = date('Y-m-d', strtotime('Last Monday', $date_stamp));
}
//end week
if($stamp == 'Sunday'){
$week_end = $date;
}else{
$week_end = date('Y-m-d', strtotime('Next Sunday', $date_stamp));
}
return array($week_start, $week_end);
}
If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:
from collections import OrderedDict
order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)
Use asp:image
<asp:Image id="Image1" runat="server"
AlternateText="Image text"
ImageAlign="left"
ImageUrl="images/image1.jpg"/>
and codebehind to change image url
Image1.ImageUrl = "/MyProject;component/Images/down.png";
You need to go to Settings and set under the Java compiler the following:
also check the Project Settings
This can be done just using Copy-Item. No need to use Get-Childitem. I think you are just overthinking it.
Copy-Item -Path C:\MyFolder -Destination \\Server\MyFolder -recurse -Force
I just tested it and it worked for me.
edit: included suggestion from the comments
# Add wildcard to source folder to ensure consistent behavior
Copy-Item -Path $sourceFolder\* -Destination $targetFolder -Recurse
With the Underscore.js
var arr=['a','a1','b']
_.filter(arr, function(a){ return a.indexOf('a') > -1; })
Much easier solution:
Use the poppler-utils package. To install it use homebrew (homebrew is MacOS specific, but you can find the poppler-utils package for Widows or Linux here: https://poppler.freedesktop.org/). First line of code below installs poppler-utils using homebrew. After installation the second line (run from the command line) then extracts images from a PDF file and names them "image*". To run this program from within Python use the os or subprocess module. Third line is code using os module, beneath that is an example with subprocess (python 3.5 or later for run() function). More info here: https://www.cyberciti.biz/faq/easily-extract-images-from-pdf-file/
brew install poppler
pdfimages file.pdf image
import os
os.system('pdfimages file.pdf image')
or
import subprocess
subprocess.run('pdfimages file.pdf image', shell=True)
Like "VB's On Error Resume Next?" That sounds kind of scary. First recommendation is don't do it. Second recommendation is don't do it and don't think about it. You need to isolate your faults better. As to how to approach this problem, it depends on how you're code is structured. If you are using a pattern like MVC or the like then this shouldn't be too difficult and would definitely not require a global exception swallower. Secondly, look for a good logging library like log4net or use tracing. We'd need to know more details like what kinds of exceptions you're talking about and what parts of your application may result in exceptions being thrown.
You should use the bisect module. Also, the list needs to be sorted before using bisect.insort_left
It's a pretty big difference.
>>> l = [0, 2, 4, 5, 9]
>>> bisect.insort_left(l,8)
>>> l
[0, 2, 4, 5, 8, 9]
timeit.timeit("l.append(8); l = sorted(l)",setup="l = [4,2,0,9,5]; import bisect; l = sorted(l)",number=10000)
1.2235019207000732
timeit.timeit("bisect.insort_left(l,8)",setup="l = [4,2,0,9,5]; import bisect; l=sorted(l)",number=10000)
0.041441917419433594
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic('../angularjs'), {default: 'angular.min.js'}); app.listen(3000);
Use regular expression:
String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""));
output: i=1234;
If you need first number combination then you should try below code:
String s="abc123xyz456";
int i=NumberFormat.getInstance().parse(s).intValue();
output: i=123;
For current page - window.location.href = "Your url here";
For Parent page - window.top.location.href = "Your url here";
From HTML
<a href="http://someurl" target="_top">link</a>
I just had that problem (Java 1.8 vs. Java 9 on Windows 7) and my findings are:
short version
default seems to be (because of Path entry)
c:\ProgramData\Oracle\Java\javapath\java -version
select the version you want (test, use tab completing in cmd, not sure what those numbers represent), I had 2 options, see longer version for details
c:\ProgramData\Oracle\Java\javapath_target_[tab]
remove junction/link and link to your version (the one ending with 181743567 in my case for Java 8)
rmdir javapath
mklink /D javapath javapath_target_181743567
longer version:
Reinstall Java 1.8 after Java 9 didn't work. The sequence of installations was jdk1.8.0_74, jdk-9.0.4 and attempt to make Java 8 default with jdk1.8.0_162...
After jdk1.8.0_162 installation I still have
java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)
What I see in path is
Path=...;C:\ProgramData\Oracle\Java\javapath;...
So I checked what is that and I found it is a junction (link)
c:\ProgramData\Oracle\Java>dir
Volume in drive C is OSDisk
Volume Serial Number is DA2F-C2CC
Directory of c:\ProgramData\Oracle\Java
2018-02-07 17:06 <DIR> .
2018-02-07 17:06 <DIR> ..
2018-02-08 17:08 <DIR> .oracle_jre_usage
2017-08-22 11:04 <DIR> installcache
2018-02-08 17:08 <DIR> installcache_x64
2018-02-07 17:06 <JUNCTION> javapath [C:\ProgramData\Oracle\Java\javapath_target_185258831]
2018-02-07 17:06 <DIR> javapath_target_181743567
2018-02-07 17:06 <DIR> javapath_target_185258831
Those hashes doesn't ring a bell, but when I checked
c:\ProgramData\Oracle\Java\javapath_target_181743567>.\java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
c:\ProgramData\Oracle\Java\javapath_target_185258831>.\java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)
so to make Java 8 default again I had to delete the link as described here
rmdir javapath
and recreate with Java I wanted
mklink /D javapath javapath_target_181743567
tested:
c:\ProgramData\Oracle\Java>java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
** update (Java 10) **
With Java 10 it is similar, only javapath is in c:\Program Files (x86)\Common Files\Oracle\Java\ which is strange as I installed 64-bit IMHO
.\java -version
java version "10.0.2" 2018-07-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)
This solution is using javascript to open a new window when a user clicks on your custom share button.
HTML:
<a href="#" onclick="share_fb('http://urlhere.com/test/55d7258b61707022e3050000');return false;" rel="nofollow" share_url="http://urlhere.com/test/55d7258b61707022e3050000" target="_blank">
//using fontawesome
<i class="uk-icon-facebook uk-float-left"></i>
Share
</a>
and in your javascript file. note window.open params are (url, dialogue title, width, height)
function share_fb(url) {
window.open('https://www.facebook.com/sharer/sharer.php?u='+url,'facebook-share-dialog',"width=626, height=436")
}
General answer is:
method
has object context (this, or class instance reference),
function
has none context (null, or global, or static).
But answer to question is dependent on terminology of language you use.
In JavaScript (ES 6) you are free to customising function context (this) for any you desire, which is normally must be link to the (this) object instance context.
In Java world you always hear that "only OOP classes/objects, no functions", but if you watch in detailes to static methods
in Java, they are really in global/null context (or context of classes, whithout instancing), so just functions whithout object. Java teachers could told you, that functions were rudiment of C in C++ and dropped in Java
, but they told you it for simplification of history and avoiding unnecessary questions of newbies. If you see at Java after 7 version, you can find many elements of pure function programming (even not from C, but from older 1988 Lisp) for simplifying parallel computing, and it is not OOP classes style.
In C++ and D world things are stronger, and you have separated functions and objects with methods and fields. But in practice, you again see functions without this
and methods whith this
(with object context).
In FreePascal/Lazarus and Borland Pascal/Delphi things about separation terms of functions and objects (variables and fields) are usually similar to C++.
Objective-C comes from C world, so you must separate C functions and Objective-C objects with methods addon.
C# is very similar to Java, but has many C++ advantages.
In fileA.c:
int myGlobal = 0;
In fileA.h
extern int myGlobal;
In fileB.c:
#include "fileA.h"
myGlobal = 1;
So this is how it works:
int
)You need to download log4j and add in your classpath.
It some what depends on your definition of whitespace. I would generally call whitespace to be spaces, tabs, line breaks and carriage returns. If this is your definition you want to use a regex with \s to replace all whitespace charactors:
import re
def myCleaner(foo):
print 'dirty: ', foo
foo = re.sub(r'\s', '', foo)
foo = foo[:-3]
foo = foo.upper()
print 'clean:', foo
print
myCleaner("BS1 1AB")
myCleaner("bs11ab")
myCleaner("BS111ab")
you should you use following code
$configValue = Mage::getStoreConfig(
'sectionName/groupName/fieldName',
Mage::app()->getStore()
);
Mage::app()->getStore()
this will add store code in fetch values so that you can get correct configuration values for current store this will avoid incorrect store's values because magento is also use for multiple store/views so must add store code to fetch anything in magento.
if we have more then one store or multiple views configured then this will insure that we are getting values for current store
To be highly positive you work with the actual email body (yet, still with the possibility you're not parsing the right part), you have to skip attachments, and focus on the plain or html part (depending on your needs) for further processing.
As the before-mentioned attachments can and very often are of text/plain or text/html part, this non-bullet-proof sample skips those by checking the content-disposition header:
b = email.message_from_string(a)
body = ""
if b.is_multipart():
for part in b.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
# skip any text/plain (txt) attachments
if ctype == 'text/plain' and 'attachment' not in cdispo:
body = part.get_payload(decode=True) # decode
break
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
else:
body = b.get_payload(decode=True)
BTW, walk()
iterates marvelously on mime parts, and get_payload(decode=True)
does the dirty work on decoding base64 etc. for you.
Some background - as I implied, the wonderful world of MIME emails presents a lot of pitfalls of "wrongly" finding the message body. In the simplest case it's in the sole "text/plain" part and get_payload() is very tempting, but we don't live in a simple world - it's often surrounded in multipart/alternative, related, mixed etc. content. Wikipedia describes it tightly - MIME, but considering all these cases below are valid - and common - one has to consider safety nets all around:
Very common - pretty much what you get in normal editor (Gmail,Outlook) sending formatted text with an attachment:
multipart/mixed
|
+- multipart/related
| |
| +- multipart/alternative
| | |
| | +- text/plain
| | +- text/html
| |
| +- image/png
|
+-- application/msexcel
Relatively simple - just alternative representation:
multipart/alternative
|
+- text/plain
+- text/html
For good or bad, this structure is also valid:
multipart/alternative
|
+- text/plain
+- multipart/related
|
+- text/html
+- image/jpeg
Hope this helps a bit.
P.S. My point is don't approach email lightly - it bites when you least expect it :)
For greater results, you can use listdir()
method of the os
module along with a generator (a generator is a powerful iterator that keeps its state, remember?). The following code works fine with both versions: Python 2 and Python 3.
Here's a code:
import os
def files(path):
for file in os.listdir(path):
if os.path.isfile(os.path.join(path, file)):
yield file
for file in files("."):
print (file)
The listdir()
method returns the list of entries for the given directory. The method os.path.isfile()
returns True
if the given entry is a file. And the yield
operator quits the func but keeps its current state, and it returns only the name of the entry detected as a file. All the above allows us to loop over the generator function.
In simple way, Its not possible. Because DropdownList
contain ListItem
and it will be selected by default
But, you can use ValidationControl
for that:
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic"
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>
You can use simple trick which is import flask app variable from main inside another file, like:
test-routes.py
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
and in your main files, where you declared flask app, import test-routes, like:
app.py
from flask import Flask, request, abort
app = Flask(__name__)
# import declared routes
import test-routes
It works from my side.
In python, when you have an iterable, usually you iterate without an index:
letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
print(l)
If you need to traverse the iterable in reverse order, you would do:
for l in letters[::-1]:
print(l)
When for any reason you need the index, you can use enumerate
:
for i, l in enumerate(letters, start=1): #start is 0 by default
print(i,l)
You can enumerate in reverse order too...
for i, l in enumerate(letters[::-1])
print(i,l)
ON ANOTHER NOTE...
Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map
:
If we need to capitilize each letter:
map(str.upper, letters)
Or get the Unicode code of each letter:
map(ord, letters)
If you are using at least Java 8 you can use method runAsync
from class CompletableFuture
CompletableFuture.runAsync(() -> {...});
If you need to return a result use supplyAsync
instead
CompletableFuture.supplyAsync(() -> 1);
If the display of the div is block by default, you can just use .show()
and .hide()
, or even simpler, .toggle()
to toggle between visibility.
Visible gallery changes visibility which is how you get the gallery over other view overlap. the Home sample app has some good examples of this technique.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
Apparently \r
is the key!
$ sed 's/, /\r/g' file3.txt > file4.txt
Transformed this:
ABFS, AIRM, AMED, BOSC, CALI, ECPG, FRGI, GERN, GTIV, HSON, IQNT, JRCC, LTRE,
MACK, MIDD, NKTR, NPSP, PME, PTIX, REFR, RSOL, UBNT, UPI, YONG, ZEUS
To this:
ABFS
AIRM
AMED
BOSC
CALI
ECPG
FRGI
GERN
GTIV
HSON
IQNT
JRCC
LTRE
MACK
MIDD
NKTR
NPSP
PME
PTIX
REFR
RSOL
UBNT
UPI
YONG
ZEUS