The CGRectZero
constant is equal to a rectangle at position (0,0)
with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.
But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)
Note that you also need to use addSubview
otherwise your view is not added to the view hierarchy.
There was another question that was closed as being a duplicate of this one, but if you read it closely, it's subtly different. So in case someone (like me) actually wants to split a list into a given number of almost equally sized sublists, then read on.
I simply ported the algorithm described here to Java.
@Test
public void shouldPartitionListIntoAlmostEquallySizedSublists() {
List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f", "g");
int numberOfPartitions = 3;
List<List<String>> split = IntStream.range(0, numberOfPartitions).boxed()
.map(i -> list.subList(
partitionOffset(list.size(), numberOfPartitions, i),
partitionOffset(list.size(), numberOfPartitions, i + 1)))
.collect(toList());
assertThat(split, hasSize(numberOfPartitions));
assertEquals(list.size(), split.stream().flatMap(Collection::stream).count());
assertThat(split, hasItems(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e"), Arrays.asList("f", "g")));
}
private static int partitionOffset(int length, int numberOfPartitions, int partitionIndex) {
return partitionIndex * (length / numberOfPartitions) + Math.min(partitionIndex, length % numberOfPartitions);
}
There are a number of ways this can be done.
How to find max. and min. in array using minimum comparisons?
If you are really paranoid about speed, runtime & number of comparisons, also refer to http://www.geeksforgeeks.org/maximum-and-minimum-in-an-array/
After using hg update -r REV
it wasn't clear in the answer about how to commit that change so that you can then push.
If you just try to commit after the update, Mercurial doesn't think there are any changes.
I had to first make a change to any file (say in a README) so Mercurial recognized that I made a new change, then I could commit that.
This then created two heads as mentioned.
To get rid of the other head before pushing, I then followed the No-Op Merges step to remedy that situation.
I was then able to push.
It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.
var text = "sossjj ssskkk";
var regex = new Regex(@"\s");
regex.IsMatch(text); // true
You can see if the file is locked by trying to read or lock it yourself first.
Since :last-child
is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child
is supported, as it's defined in the CSS2.1 specification.
One possible solution is to simply give the last child a class name and style that class.
Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child
pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.
I have created a general multi replace string Oracle function by a table of varchar2 as parameter. The varchar will be replaced for the position rownum value of table.
For example:
Text: Hello {0}, this is a {2} for {1}
Parameters: TABLE('world','all','message')
Returns:
Hello world, this is a message for all.
You must create a type:
CREATE OR REPLACE TYPE "TBL_VARCHAR2" IS TABLE OF VARCHAR2(250);
The funcion is:
CREATE OR REPLACE FUNCTION FN_REPLACETEXT(
pText IN VARCHAR2,
pPar IN TBL_VARCHAR2
) RETURN VARCHAR2
IS
vText VARCHAR2(32767);
vPos INT;
vValue VARCHAR2(250);
CURSOR cuParameter(POS INT) IS
SELECT VAL
FROM
(
SELECT VAL, ROWNUM AS RN
FROM (
SELECT COLUMN_VALUE VAL
FROM TABLE(pPar)
)
)
WHERE RN=POS+1;
BEGIN
vText := pText;
FOR i IN 1..REGEXP_COUNT(pText, '[{][0-9]+[}]') LOOP
vPos := TO_NUMBER(SUBSTR(REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i),2, LENGTH(REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i)) - 2));
OPEN cuParameter(vPos);
FETCH cuParameter INTO vValue;
IF cuParameter%FOUND THEN
vText := REPLACE(vText, REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i), vValue);
END IF;
CLOSE cuParameter;
END LOOP;
RETURN vText;
EXCEPTION
WHEN OTHERS
THEN
RETURN pText;
END FN_REPLACETEXT;
/
Usage:
TEXT_RETURNED := FN_REPLACETEXT('Hello {0}, this is a {2} for {1}', TBL_VARCHAR2('world','all','message'));
The main gotcha I see is that you're not handling any errors: .login() and .sendmail() both have documented exceptions that they can throw, and it seems like .connect() must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.
If it's a single byte, just cast the byte
to a char
and it should work out to be fine i.e. give a char
entity corresponding to the codepoint value of the given byte. If not, use the String
constructor as mentioned elsewhere.
char ch = (char)0x63;
System.out.println(ch);
This blog post may be a good start: http://benno.id.au/blog/2007/11/13/android-native-apps Unfortunately, lots of the important stuff is "left as an exercise to the reader".
function naturalCompare(a, b) {_x000D_
var ax = [], bx = [];_x000D_
_x000D_
a.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });_x000D_
b.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });_x000D_
_x000D_
while (ax.length && bx.length) {_x000D_
var an = ax.shift();_x000D_
var bn = bx.shift();_x000D_
var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);_x000D_
if (nn) return nn;_x000D_
}_x000D_
_x000D_
return ax.length - bx.length;_x000D_
}_x000D_
_x000D_
let builds = [ _x000D_
{ id: 1, name: 'Build 91'}, _x000D_
{ id: 2, name: 'Build 32' }, _x000D_
{ id: 3, name: 'Build 13' }, _x000D_
{ id: 4, name: 'Build 24' },_x000D_
{ id: 5, name: 'Build 5' },_x000D_
{ id: 6, name: 'Build 56' }_x000D_
]_x000D_
_x000D_
let sortedBuilds = builds.sort((n1, n2) => {_x000D_
return naturalCompare(n1.name, n2.name)_x000D_
})_x000D_
_x000D_
console.log('Sorted by name property')_x000D_
console.log(sortedBuilds)
_x000D_
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
CONVERT(date, GETDATE())
and CONVERT(time, GETDATE())
works in SQL Server 2008. I'm uncertain about 2005.
ifstream inFile;
string name, temp;
int age;
inFile.open("file.txt");
getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age;
cout << name << endl;
cout << age << endl;
inFile.close();
coffee-script
can accomplish this with aplomb..
for x in [ 'a', 'b', 'c' ] then "#{x}" : true
[ { a: true }, { b: true }, { c: true } ]
Constructor acts very similarly to a method returning the constructed type. And async
method can't return just any type, it has to be either “fire and forget” void
, or Task
.
If the constructor of type T
actually returned Task<T>
, that would be very confusing, I think.
If the async constructor behaved the same way as an async void
method, that kind of breaks what constructor is meant to be. After constructor returns, you should get a fully initialized object. Not an object that will be actually properly initialized at some undefined point in the future. That is, if you're lucky and the async initialization doesn't fail.
All this is just a guess. But it seems to me that having the possibility of an async constructor brings more trouble than it's worth.
If you actually want the “fire and forget” semantics of async void
methods (which should be avoided, if possible), you can easily encapsulate all the code in an async void
method and call that from your constructor, as you mentioned in the question.
Here are two methods:
<script type="text/javascript">
var s="http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu
=true&pcode=1235";
var st=s.substring(0, s.indexOf("?"));
alert(st);
alert(s.replace(/\?.*/,''));
</script>
This comes up a lot when your gemfile.lock has different versions of the gems installed on your machine. You may get a warning after running rake (or rspec or others) such as:
You have already activated rake 10.3.1, but your Gemfile requires rake 10.1.0. Prepending "bundle exec" to your command may solve this.
Prepending bundle exec
tells the bundler to execute this command regardless of the version differential. There isn't always an issue, however, you might run into problems.
Fortunately, there is a gem that solves this: rubygems-bundler.
$ gem install rubygems-bundler
$ $ gem regenerate_binstubs
Then try your rake, rspec, or whatever again.
For googlers:
This jquery-workaround makes #containment get a height automatically (by, height: auto), then gets the actual height assigned as a pixel value.
<script type="text/javascript">
<!--
$(function () {
// workaround for webkit-bug http://stackoverflow.com/a/8468131/348841
var rz = function () {
$('#containment')
.css('height', 'auto')
.css('height', $('#containment').height() + 'px');
};
$(window).resize(function () {
rz();
});
rz();
})
-->
</script>
Use setDataAndType on the Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);
Use "video/mp4" as MIME or use "video/*" if you don't know the type.
Sharing files between a docker container and the host system, or between separate containers is best accomplished using volumes.
Having your app running in another container is probably your best solution since it will ensure that your whole application can be well isolated and easily deployed. What you're trying to do sounds very close to the setup described in this excellent blog post, take a look!
You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.
Check the John Resig's post describing how helpful this method is.
For Mac OS X, I replaced the utilities that come with the operating system and replaced them with a newer version of coreutils. This allows you to access tools like readlink -f
(for absolute path to files) and realpath
(absolute path to directories) on your Mac.
The Homebrew version appends a 'G' (for GNU Tools) in front of the command name -- so the equivalents become greadlink -f FILE
and grealpath DIRECTORY
.
Instructions for how to install the coreutils/GNU Tools on Mac OS X through Homebrew can be found in this StackExchange arcticle.
NB: The readlink -f
and realpath
commands should work out of the box for non-Mac Unix users.
Other answers are probably simpler for this case, but for completeness I thought I would add the use of cellfun with an anonymous function
indices = find(cellfun(@(x) strcmp(x,'KU'), strs))
which has the advantage that you can easily make it case insensitive or use it in cases where you have cell array of structures:
indices = find(cellfun(@(x) strcmpi(x.stringfield,'KU'), strs))
Use this code
Environment.Exit(0);
use 0 as the int if you don't want to return anything.
You can get it one line like this:
String monthName = new DataFormatSymbols.getMonths()[cal.get(Calendar.MONTH)]
I use a package.json
for my packages and a config.js
for my configuration, which looks like:
var config = {};
config.twitter = {};
config.redis = {};
config.web = {};
config.default_stuff = ['red','green','blue','apple','yellow','orange','politics'];
config.twitter.user_name = process.env.TWITTER_USER || 'username';
config.twitter.password= process.env.TWITTER_PASSWORD || 'password';
config.redis.uri = process.env.DUOSTACK_DB_REDIS;
config.redis.host = 'hostname';
config.redis.port = 6379;
config.web.port = process.env.WEB_PORT || 9980;
module.exports = config;
I load the config from my project:
var config = require('./config');
and then I can access my things from config.db_host
, config.db_port
, etc... This lets me either use hardcoded parameters, or parameters stored in environmental variables if I don't want to store passwords in source control.
I also generate a package.json
and insert a dependencies section:
"dependencies": {
"cradle": "0.5.5",
"jade": "0.10.4",
"redis": "0.5.11",
"socket.io": "0.6.16",
"twitter-node": "0.0.2",
"express": "2.2.0"
}
When I clone the project to my local machine, I run npm install
to install the packages. More info on that here.
The project is stored in GitHub, with remotes added for my production server.
So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:
php artisan make:middleware Cors
. This will create app/Http/Middleware/Cors.php
for you.Add the following code inside the handles
function in Cors.php
:
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
In app/Http/kernel.php
, add the following entry in $routeMiddleware
array:
‘cors’ => \App\Http\Middleware\Cors::class
(There would be other entries in the array like auth
, guest
etc. Also make sure you're doing this in app/Http/kernel.php
because there is another kernel.php
too in Laravel)
Add this middleware on route registration for all the routes where you want to allow access, like this:
Route::group(['middleware' => 'cors'], function () {
Route::get('getData', 'v1\MyController@getData');
Route::get('getData2', 'v1\MyController@getData2');
});
mounted()
function and not in data()
. Also make sure you use http://
or https://
with the URL in your fetch()
call.Full credits to Pete Houston's blog article.
You have to select "Refresh Dependencies" in the "Gradle" context menu that appears when you right-click the project in the Package Explorer.
EDIT: Updated broken link as of February, the 7th, 2017.
I think noone mentioned this:
At CERN they use a full reflection system for C++:
CERN Reflex. It seems to work very well.
Easy. text = text.remove(text.length - 3)
. I subtracted 3 because the Remove
function removes all items from that index to the end of the string which is text.length
. So if I subtract 3 then I get the string with 3 characters removed from it.
You can generalize this to removing a
characters from the end of the string, like this:
text = text.remove(text.length - a)
So what I did was the same logic. The remove
function removes all items from its inside to the end of the string which is the length of the text. So if I subtract a
from the length of the string that will give me the string with a
characters removed.
So it doesn't just work for 3, it works for all positive integers, except if the length of the string is less than or equal to a
, in that case it will return a negative number or 0.
On Ubuntu, you'll need to install unixodbc-dev:
sudo apt-get install unixodbc-dev
Install pip by using this command:
sudo apt-get install python-pip
once that is installed, you should be able to install pyodbc successfully:
pip install pyodbc
Synchronized Vs Atomic Vs Volatile:
Please correct me if anything i missed.
I had fix this with adduser *username* dialout
. I never had this error again, even though previously the only way to get it to work was to reboot the PC or unplug and replug the usb to serial adapter.
When you checkout to a commit git checkout <commit-hash>
or to a remote branch your HEAD will get detached and try to create a new commit on it.
Commits that are not reachable by any branch or tag will be garbage collected and removed from the repository after 30 days.
Another way to solve this is by creating a new branch for the newly created commit and checkout to it. git checkout -b <branch-name> <commit-hash>
This article illustrates how you can get to detached HEAD state.
The most upvoted answers will fail if the file list is too long.
A more portable solution would be using fd
fd -e txt -d 1 -X awk 1 > combined.txt
-d 1
limits the search to the current directory. If you omit this option then it will recursively find all .txt
files from the current directory.
-X
(otherwise known as --exec-batch
) executes a command (awk 1
in this case) for all the search results at once.
you have to use collections to return more then one return values
in your case you write your code as
public static List something(){
List<Integer> list = new ArrayList<Integer>();
int number1 = 1;
int number2 = 2;
list.add(number1);
list.add(number2);
return list;
}
// Main class code
public static void main(String[] args) {
something();
List<Integer> numList = something();
}
The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent. Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1).
this is what you want:
<html>
<head>
<style>
li { color: blue }<br>
li:nth-child(even) { color:red }
li:nth-child(odd) { color:green}
</style>
</head>
<body>
<ul>
<li>ho</li>
<li>ho</li>
<li>ho</li>
<li>ho</li>
<li>ho</li>
</ul>
</body>
</html>
you need to use backslash before ". like \"
From the doc here you can see that
A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.
and " (double quote) is a escacpe sequence
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
Components can be extended as same as a typescript class inheritance, just that you have to override the selector with a new name. All Input() and Output() Properties from the Parent Component works as normal
Update
@Component is a decorator,
Decorators are applied during the declaration of class not on objects.
Basically, decorators add some metadata to the class object and that cannot be accessed via inheritance.
If you want to achieve the Decorator Inheritance I would Suggest writing a custom decorator. Something like below example.
export function CustomComponent(annotation: any) {
return function (target: Function) {
var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
var parentParamTypes = Reflect.getMetadata('design:paramtypes', parentTarget);
var parentPropMetadata = Reflect.getMetadata('propMetadata', parentTarget);
var parentParameters = Reflect.getMetadata('parameters', parentTarget);
var parentAnnotation = parentAnnotations[0];
Object.keys(parentAnnotation).forEach(key => {
if (isPresent(parentAnnotation[key])) {
if (!isPresent(annotation[key])) {
annotation[key] = parentAnnotation[key];
}
}
});
// Same for the other metadata
var metadata = new ComponentMetadata(annotation);
Reflect.defineMetadata('annotations', [ metadata ], target);
};
};
Refer: https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7
Microsoft SQL (AFAIK) does not allow you to alter the table and add a column after a specific column. Your best bet is using Sql Server Management Studio, or play around with either dropping and re-adding the table, or creating a new table and moving the data over manually. neither are very graceful.
MySQL does however:
ALTER TABLE mytable
ADD COLUMN new_column <type>
AFTER existing_column
Sometime the problem could be on your windows firewall, make sure your server allow access to all port associated with your mysql database.
It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char*
could indicate an array of char
s, a char**
could indicate that it points to and array of char*
s.
Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.
Anyway, I'd just do this:
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
There is a pandas function that can be applied to DateTime index in pandas data frame.
date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list
the element inside the list:
u'1910-11-02'
You might need to replace the 'u'.
There might be some additional arguments that I should put into the previous functions.
When I installed Android Studio 1.0 it ended up in
/Library/Android/sdk/
ul.nav li a, ul.nav li a:visited {
color: #anycolor !important;
}
ul.nav li a:hover, ul.nav li a:active {
color: #anycolor !important;
}
ul.nav li.active a {
color: #anycolor !important;
}
Change the styles as you wish.
Please see this.
Text inside a CDATA section will be ignored by the parser.
http://www.w3schools.com/xml/dom_cdatasection.asp
This is will help you to understand the basics about XML
You'd want the COUNT
operator.
SELECT NUMBER, COUNT(*)
FROM T_NAME
GROUP BY NUMBER
ORDER BY NUMBER ASC
Check out gcc's Diagnostic Pragma support, and the list of -W warning options (changed: new link to warning options).
For gcc, you can use #pragma warning
directives like explained here.
If you're using Django you can use this. Yes i'm aware OP did not ask for django, but i ran across this question looking for a Django solution, didn't find one, and put it here for the next boy/gal that looks for it.
# It's available for v1.7+
# https://github.com/django/django/blob/stable/1.7.x/django/utils/module_loading.py
from django.utils.module_loading import import_string
Klass = import_string('path.to.module.Klass')
func = import_string('path.to.module.func')
var = import_string('path.to.module.var')
Keep in mind, if you want to import something that doesn't have a .
, like re
or argparse
use:
re = __import__('re')
Another workaround is to get a free domain from no-ip.org and point it to your local ip address.
Then, instead of using http://localhost/yourwebservice
you can try http://yourdomain.no-ip.org/yourwebservice
Add a spinner to the XML layout, and then add this code to the Java file:
Spinner spinner;
spinner = (Spinner) findViewById(R.id.spinner1) ;
java.util.ArrayList<String> strings = new java.util.ArrayList<>();
strings.add("Mobile") ;
strings.add("Home");
strings.add("Work");
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(AddMember.this, R.layout.support_simple_spinner_dropdown_item, strings);
spinner.setAdapter(spinnerAdapter);
If storage class is static or global then during loading, the BSS initialises the variable or memory location(ML) to 0 unless the variable is initially assigned some value. In case of local uninitialized variables the trap representation is assigned to memory location. So if any of your registers containing important info is overwritten by compiler the program may crash.
but some compilers may have mechanism to avoid such a problem.
I was working with nec v850 series when i realised There is trap representation which has bit patterns that represent undefined values for data types except for char. When i took a uninitialized char i got a zero default value due to trap representation. This might be useful for any1 using necv850es
"instance to an application" means nothing.
"object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()
). For example there is the class Car
, and there are instance with different properties like mileage, max speed, horse-power, brand, etc.
Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null;
- s
is a reference, that currently references no instance, but can reference an instance of the String
class.
*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value.
The value of s is a reference. It's very important to distinguish between variables and values, and objects and references.
I came across the same problem and have found a simple solution. Add after calling the append function a document ready.
$("#root").append(child);_x000D_
$(document).ready(function () {_x000D_
// Action after append is completly done_x000D_
});
_x000D_
Use -exec
:
"your-script-name": "nodemon [options] --exec 'npm start -s'"
The code you wrote will always return true
because state
cannot be both 10 and 15 for the statement to be false. if ((state != 10) && (state != 15)....
AND
is what you need not OR
.
Use $.inArray instead. This returns the index of the element in the array.
var statesArray = [10, 15, 19]; // list out all
var index = $.inArray(state, statesArray);
if(index == -1) {
console.log("Not there in array");
return true;
} else {
console.log("Found it");
return false;
}
Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.
So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.
AngularJS / UI-Bootstrap Answer
style="cursor: pointer; pointer-events: all;"
ng-click
to clear the text.JavaScript (app.js)
var app = angular.module('plunker', ['ui.bootstrap']);
app.controller('MainCtrl', function($scope) {
$scope.params = {};
$scope.clearText = function() {
$scope.params.text = null;
}
});
HTML (index.html snippet)
<div class="form-group has-feedback">
<label>text box</label>
<input type="text"
ng-model="params.text"
class="form-control"
placeholder="type something here...">
<span ng-if="params.text"
ng-click="clearText()"
class="glyphicon glyphicon-remove form-control-feedback"
style="cursor: pointer; pointer-events: all;"
uib-tooltip="clear">
</span>
</div>
Here's the plunker: http://plnkr.co/edit/av9VFw?p=preview
You can use the document's import (or adopt) method to add XML fragments:
/**
* @param docBuilder
* the parser
* @param parent
* node to add fragment to
* @param fragment
* a well formed XML fragment
*/
public static void appendXmlFragment(
DocumentBuilder docBuilder, Node parent,
String fragment) throws IOException, SAXException {
Document doc = parent.getOwnerDocument();
Node fragmentNode = docBuilder.parse(
new InputSource(new StringReader(fragment)))
.getDocumentElement();
fragmentNode = doc.importNode(fragmentNode, true);
parent.appendChild(fragmentNode);
}
If you NPM those modules you can serve them using static redirect.
First install the packages:
npm install jquery
npm install bootstrap
Then on the server.js:
var express = require('express');
var app = express();
// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap
Then, finally, at the .html:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.
Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.
@Query("SELECT rd FROM ReleaseDateType rd, CacheMedia cm WHERE ...")
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
My JSON file name: terrifcalculatordata.json
[
{
"id": 1,
"name": "Vigo",
"picture": "./static/images/vigo.png",
"charges": "PKR 100 per excess km"
},
{
"id": 2,
"name": "Mercedes",
"picture": "./static/images/Marcedes.jpg",
"charges": "PKR 200 per excess km"
},
{
"id": 3,
"name": "Lexus",
"picture": "./static/images/Lexus.jpg",
"charges": "PKR 150 per excess km"
}
]
First , import on top:
import calculatorData from "../static/data/terrifcalculatordata.json";
then after return:
<div>
{
calculatorData.map((calculatedata, index) => {
return (
<div key={index}>
<img
src={calculatedata.picture}
class="d-block"
height="170"
/>
<p>
{calculatedata.charges}
</p>
</div>
If you're on Windows:
Go to your php.ini file and remove the ;
mark from the beginning of the following line:
;extension=php_curl.dll
After you have saved the file you must restart your HTTP server software (e.g. Apache) before this can take effect.
For Ubuntu 13.0 and above, simply use the debundled package. In a terminal type the following to install it and do not forgot to restart server.
sudo apt-get install php-curl
Or if you're using the old PHP5
sudo apt-get install php5-curl
or
sudo apt-get install php5.6-curl
Then restart apache to activate the package with
sudo service apache2 restart
If your are using MySQL Latest version following may help to reach your requirement.
select * from products where attribs_json->"$.feature.value[*]" in (1,3)
You must not use StreamReader
for binary files (like gifs or jpgs). StreamReader
is for text data. You will almost certainly lose data if you use it for arbitrary binary data. (If you use Encoding.GetEncoding(28591) you will probably be okay, but what's the point?)
Why do you need to use a StreamReader
at all? Why not just keep the binary data as binary data and write it back to disk (or SQL) as binary data?
EDIT: As this seems to be something people want to see... if you do just want to copy one stream to another (e.g. to a file) use something like this:
/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
To use it to dump a stream to a file, for example:
using (Stream file = File.Create(filename))
{
CopyStream(input, file);
}
Note that Stream.CopyTo
was introduced in .NET 4, serving basically the same purpose.
This error can occur when your connection gets interrupted during your dependencies are being downloaded. Delete the relevant repository folder and run following command again to download a fresh copy of corrupted file.
mvn clean install
Send params from View to an other View, from Sender View to Receiver View use viewParam and includeViewParams=true
In Sender
Sender.xhtml
<f:metadata>
<f:viewParam name="ID" value="#{senderMB._strID}" />
</f:metadata>
“includeViewParams=true”
in return String of click button event
Click button fire senderMB.clickBtnDetail(dto) with dto from senderMB._arrDataSender.xhtml
<p:dataTable rowIndexVar="index" id="dataTale"value="#{senderMB._arrData}" var="dto">
<p:commandButton action="#{senderMB.clickBtnDetail(dto)}" value="??"
ajax="false"/>
</p:dataTable>
In senderMB.clickBtnDetail(dto) we assign _strID with argument we got from button event (dto), here this is Sender_DTO and assign to senderMB._strID
Sender_MB.java
public String clickBtnDetail(sender_DTO sender_dto) {
this._strID = sender_dto.getStrID();
return "Receiver?faces-redirect=true&includeViewParams=true";
}
The link when clicked will become http://localhost:8080/my_project/view/Receiver.xhtml?*ID=12345*
In Recever
Receiver.xhtml
<f:metadata><f:viewParam name="ID" value="#{receiver_MB._strID}"/></f:metadata>
It will get param ID from sender View and assign to receiver_MB._strID
Receiver.xhtml
<f:event listener="#{receiver_MB.preRenderView}" type="preRenderView" />
into f:metadata tag
Receiver.xhtml
<f:metadata>
<f:viewParam name="ID" value="#{receiver_MB._strID}" />
<f:event listener="#{receiver_MB.preRenderView}"
type="preRenderView" />
</f:metadata>
Now we want to use this param in our read database method, it is available to use
Receiver_MB.java
public void preRenderView(ComponentSystemEvent event) throws Exception {
if (FacesContext.getCurrentInstance().isPostback()) {
return;
}
readFromDatabase();
}
private void readFromDatabase() {
//use _strID to read and set property
}
Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300
Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.
Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
BrowserVersion | ConnectionsPerHostname | MaxConnections
----------------------------------------------------------
Chrome34/32 | 6 | 10
IE9 | 6 | 35
IE10 | 8 | 17
IE11 | 13 | 17
Firefox27/26 | 6 | 17
Safari7.0.1 | 6 | 17
Android4 | 6 | 17
ChromeMobile18 | 6 | 16
IE Mobile9 | 6 | 60
The first value is ConnectionsPerHostname and the second value is MaxConnections.
Source: http://www.browserscope.org/?category=network&v=top
Note: ConnectionsPerHostname is the maximum number of concurrent http requests that browsers will make to the same domain. To increase the number of concurrent connections, one can host resources (e.g. images) in different domains. However, you cannot exceed MaxConnections, the maximum number of connections a browser will open in total - across all domains.
2020 Update
Number of parallel connections per browser
| Browser | Connections per Domain | Max Connections |
| -------------------- | ------------------------------ | ------------------------------ |
| Chrome 81 | 6 [^note1] | 256[^note2] |
| Edge 18 | *same as Internet Explorer 11* | *same as Internet Explorer 11* |
| Firefox 68 | 9 [^note1] or 6 [^note3] | 1000+[^note2] |
| Internet Explorer 11 | 12 [^note4] | 1000+[^note2] |
| Safari 13 | 6 [^note1] | 1000+[^note2] |
setTimeout
, + requestAnimationFrame
, then
...Like this
DECLARE @date DATETIME
SET @date = '2011-09-28 18:01:00'
select convert(varchar, @date,105) + ' ' + convert(varchar, @date,108)
Arrays are default passed by pointers. You can try modifying an array inside a function call for better understanding.
import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)
Just another method....
In ASP.NET Core MVC.
public IActionResult Foo()
{
var data = GetData();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return Json(data, settings);
}
Make sure you also start the MySQL service in Xampp control panel. This might resolve this.
public String randomString(String chars, int length) {
Random rand = new Random();
StringBuilder buf = new StringBuilder();
for (int i=0; i<length; i++) {
buf.append(chars.charAt(rand.nextInt(chars.length())));
}
return buf.toString();
}
Don't forget to look at the Javascript as well. My guess is that there is custom Javascript code getting executed when you click on the link and it's that Javascript that is generating the URL and navigating to it.
...and when I got one how to process it (do I need to use Fourier Transform like it was instructed in the above post)?
If you want a "tap" then I think you are interested in amplitude more than frequency. So Fourier transforms probably aren't useful for your particular goal. You probably want to make a running measurement of the short-term (say 10 ms) amplitude of the input, and detect when it suddenly increases by a certain delta. You would need to tune the parameters of:
Although I said you're not interested in frequency, you might want to do some filtering first, to filter out especially low and high frequency components. That might help you avoid some "false positives". You could do that with an FIR or IIR digital filter; Fourier isn't necessary.
<a href="delete.php?id=22" onclick = "if (! confirm('Continue?')) { return false; }">Confirm OK, then goto URL (uses onclick())</a>
If you want a copy-paste bash script:
var=$(mysql -e 'SELECT CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8 COLLATE utf8_czech_ci;") AS execTabs FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="zabbix" AND TABLE_TYPE="BASE TABLE"' -uroot -p )
var+='ALTER DATABASE zabbix CHARACTER SET utf8 COLLATE utf8_general_ci;'
echo $var | cut -d " " -f2- | mysql -uroot -p zabbix
Change zabbix to your database name.
Adding the Local Python Path before the WindowsApps resolved the problem.
TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).
From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.
Since it's an external resource you'd need to go with JSONP because of the Same origin policy.
To do that you need to add the querystring parameter callback
:
$.getJSON("http://myjsonsource?callback=?", function(data) {
// Get the element with id summary and set the inner text to the result.
$('#summary').text(data.result);
});
Here is a minimal design that should work fine. What you have to do is to simply inherit Observer
in a class and afterwards use observe(event_name, callback_fn)
to listen for a specific event. Whenever that specific event is fired anywhere in the code (ie. Event('USB connected')
), the corresponding callback will fire.
class Observer():
_observers = []
def __init__(self):
self._observers.append(self)
self._observed_events = []
def observe(self, event_name, callback_fn):
self._observed_events.append({'event_name' : event_name, 'callback_fn' : callback_fn})
class Event():
def __init__(self, event_name, *callback_args):
for observer in Observer._observers:
for observable in observer._observed_events:
if observable['event_name'] == event_name:
observable['callback_fn'](*callback_args)
Example:
class Room(Observer):
def __init__(self):
print("Room is ready.")
Observer.__init__(self) # DON'T FORGET THIS
def someone_arrived(self, who):
print(who + " has arrived!")
# Observe for specific event
room = Room()
room.observe('someone arrived', room.someone_arrived)
# Fire some events
Event('someone left', 'John')
Event('someone arrived', 'Lenard') # will output "Lenard has arrived!"
Event('someone Farted', 'Lenard')
# file? will only return true for files
File.file?(filename)
and
# Will also return true for directories - watch out!
File.exist?(filename)
Say you have a makefile like this:
action:
echo argument is $(argument)
You would then call it make action argument=something
I confirm some methods proposed here that also worked for me : you have to put your local .json file in your public directory where fetch() is looking for (looking in http://localhost:3000/) for example : I use this fetch() in my src/App.js file:
componentDidMount(){
fetch('./data/json-data.json')
.then ( resp1 => resp1.json() )
.then ( users1 => this.setState( {cards : users1} ) )
}
so I created public/data/json-data.json
and everything was fine then :)
I solved my problem of visual svn server rep-cache.db corruption.
Their are two solutions.
Stop the Visual SVN Server service.
Download sqllite3.exe shell from sqllite website and copy that into repo's db folder.
Type the following commands at command prompt in the repo's db folder.
-- First Solution --
sqlite3 rep-cache.db
.clone rep-cache-new.db
press ctrl+c to exit sqllite.
ren rep-cache.db rep-cache-old.db
ren re-cache-new.db rep-cache.db
-- 2nd Solution --
Delete The rep-cache.db
del rep-cache.db
it will be automatically created.
props.put("mail.smtp.starttls.enable", "true");
solved my problem ;)
My problem was :
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. u186sm7971862pfu.82 - gsmtp
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.example.sendmail.SendEmailExample2.main(SendEmailExample2.java:53)
These articles seem to suggest that checking for 1.5
or 1.6
prefix should work, as it follows proper version naming convention.
java.version
system property"java.version
system property"First you need to understand, that both are different things. Stored Procedures
are best used for INSERT-UPDATE-DELETE
statements. Whereas Views
are used for SELECT
statements. You should use both of them.
In views you cannot alter the data. Some databases have updatable Views where you can use INSERT-UPDATE-DELETE
on Views
.
JMX, The MXBeans (ThreadMXBean, etc) provided will give you Memory and CPU usages.
OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
operatingSystemMXBean.getSystemCpuLoad();
If you want to use familiar NSString, you can declare it explicitly:
var someString: NSString = "abcdefghi"
var someRange: NSRange = someString.rangeOfString("c")
I'm not sure yet how to do this in Swift.
Another way without JavaScript is to use <form autocomplete="off">
to prevent the browser from re-filling the form with the last values.
See also this question
Tested this only with a single <input type="text"
> inside the form, but works fine in current Chrome and Firefox, unfortunately not in IE10.
Define the following function (not mine, not sure where I found it long ago):
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then:
String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
{
success = true;
InputStream response = conn.getInputStream();
jsonReply = convertStreamToString(response);
// Do JSON handling here....
}
Each deployed webapp has a context.xml
file that lives in
$CATALINA_BASE/conf/[enginename]/[hostname]
(conf/Catalina/localhost by default)
and has the same name as the webapp (manager.xml
in this case). If no file is present, default values are used.
So, you need to create a file conf/Catalina/localhost/manager.xml
and specify the rule you want to allow remote access. For example, the following content of manager.xml
will allow access from all machines:
<Context privileged="true" antiResourceLocking="false"
docBase="${catalina.home}/webapps/manager">
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>
Note that the allow attribute of the Valve
element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).
Other Valve
classes cater for other rules (e.g. RemoteHostValve
for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.
Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml
you should have access to the Manager.
According to section 2.2 of the manual, you can use the Escape key pressed twice in place of the CTRL key. This allowed me to use Nano's key combination for GO TO LINE when running Nano on a Jupyter/ JupyterHub and accessing through my browser. The normal key combination was getting 'swallowed' as the manual warns about can more often happen with the ALT key on some systems, and which can be replaced by one press of the ESCAPE key.
So for jump to line it was ESCAPE pressed twice, followed by shift key + dash key.
Taken from above:
from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435
For a two-tailed test:
Import numpy as np
z = 1.96
p_value = 2 * norm.cdf(-np.abs(z))
0.04999579029644087
I wanted to comment, but since my reputation won't qualify for commenting, it had to be an answer. Github will actually let you not only cancel a pull request, but also delete it by simply deleting the fork you are trying to push. Hope this may help some others googling this.
The context referenced by 'this'
keyword in JavasSript is different.
look at the following code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<input id="btnSubmit" type="button" value="Submit" />
<script>
function disable() {
this.disabled = true;
}
var btnSubmit = document.getElementById('btnSubmit');
btnSubmit.onclick = disable();
//btnSubmit.addEventListener('click', disable, false);
</script>
</body>
</html>
What it does is really simple. when you click the button, the button will be disabled automatically.
First when you try to hook up the events in this way button.onclick = function(),
onclick event will be triggered by clicking the button, however, the button will not be disabled because there's no explicit binding between button.onclick and onclick event handler. If you debug see the 'this'
object, you can see it refers to 'window'
object.
Secondly, if you comment btnSubmit.onclick = disable();
and uncomment
//btnSubmit.addEventListener('click', disable, false);
you can see that the button is disabled because with this way there's explicit binding between button.onclick event and onclick event handler. If you debug into disable function, you can see 'this'
refers to the button control
rather than the window
.
This is something I don't like about JavaScript which is inconsistency.
Btw, if you are using jQuery($('#btnSubmit').on('click', disable);
), it uses explicit binding.
As well described in React's official docs, If you use routers that use the HTML5 pushState
history API under the hood, you just need to below content to .htaccess
file in public
directory of your react-app.
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
And if using relative path update the package.json
like this:
"homepage": ".",
Note: If you are using react-router@^4
, you can root <Link>
using the basename
prop on any <Router>
.
import React from 'react';
import BrowserRouter as Router from 'react-router-dom';
...
<Router basename="/calendar"/>
<Link to="/today"/>
DELETE FROM blob
WHERE fileid NOT IN
(SELECT id
FROM files
WHERE id is NOT NULL/*This line is unlikely to be needed
but using NOT IN...*/
)
For SDK 29 :
String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}
public static void createTextFile(String sBody, String FileName, String Where) {
try {
File gpxfile = new File(Where, FileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then you can save your file like this :
createTextFile("This is Content","file.txt",str1);
You can use the document.createElement()
function like this:
function addScript( src ) {
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
document.body.appendChild( s );
}
I rewrote the code provided by Ninja2k because I didn't like that it looped through cells. For future reference here's a version using arrays instead which works noticeably faster over lots of ranges but has the same result:
Function concat2(useThis As Range, Optional delim As String) As String
Dim tempValues
Dim tempString
Dim numValues As Long
Dim i As Long, j As Long
tempValues = useThis
numValues = UBound(tempValues) * UBound(tempValues, 2)
ReDim values(1 To numValues)
For i = UBound(tempValues) To LBound(tempValues) Step -1
For j = UBound(tempValues, 2) To LBound(tempValues, 2) Step -1
values(numValues) = tempValues(i, j)
numValues = numValues - 1
Next j
Next i
concat2 = Join(values, delim)
End Function
I can't help but think there's definitely a better way...
Here are steps to do it manually without VBA which only works with 1d arrays and makes static values instead of retaining the references:
=Sheet2!A1:A15
{ and }
CONCATENATE(
at the front of the formula after the =
sign and )
at the end of the formula.In Clean Code, Robert C. Martin devoted four pages to the subject. Here's the gist:
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification -- and then shouldn't be used anyway.
Answer by Paul is right, I am just putting the visual to easily get there.
Go to Tools->Options->Debugging->Symbols
Set the checkbox marked in red and it will download the pdb files from microsoft. When you set the checkbox, it will also set a default path for the pdb files in the edit box under, you don't need to change that.
Most of the previous answer didn't work for me in Firefox 38.0.5. This did...
<div style='padding: 3px; width: 130px; word-break: break-all; word-wrap: break-word;'>
// Content goes here
</div>
Documentation:
You can use the following code to fit your system screen and task bar is visible.
private void Form1_Load(object sender, EventArgs e)
{
// hide max,min and close button at top right of Window
this.FormBorderStyle = FormBorderStyle.None;
// fill the screen
this.Bounds = Screen.PrimaryScreen.Bounds;
}
No need to use:
this.TopMost = true;
That line interferes with alt+tab
to switch to other application. ("TopMost" means the window stays on top of other windows, unless they are also marked "TopMost".)
You could write your own by looking at the JPEG format.
That said, try a pre-existing library like CImg, or Boost's GIL. Or for strictly JPEG's, libjpeg. There is also the CxImage class on CodeProject.
Here's a big list.
To show a problem is NP complete, you need to:
In other words, given some information C
, you can create a polynomial time algorithm V
that will verify for every possible input X
whether X
is in your domain or not.
Prove that the problem of vertex covers (that is, for some graph G
, does it have a vertex cover set of size k
such that every edge in G
has at least one vertex in the cover set?) is in NP:
our input X
is some graph G
and some number k
(this is from the problem definition)
Take our information C
to be "any possible subset of vertices in graph G
of size k
"
Then we can write an algorithm V
that, given G
, k
and C
, will return whether that set of vertices is a vertex cover for G
or not, in polynomial time.
Then for every graph G
, if there exists some "possible subset of vertices in G
of size k
" which is a vertex cover, then G
is in NP
.
Note that we do not need to find C
in polynomial time. If we could, the problem would be in `P.
Note that algorithm V
should work for every G
, for some C
. For every input there should exist information that could help us verify whether the input is in the problem domain or not. That is, there should not be an input where the information doesn't exist.
This involves getting a known NP-complete problem like SAT, the set of boolean expressions in the form:
(A or B or C) and (D or E or F) and ...
where the expression is satisfiable, that is there exists some setting for these booleans, which makes the expression true.
Then reduce the NP-complete problem to your problem in polynomial time.
That is, given some input X
for SAT
(or whatever NP-complete problem you are using), create some input Y
for your problem, such that X
is in SAT if and only if Y
is in your problem. The function f : X -> Y
must run in polynomial time.
In the example above, the input Y
would be the graph G
and the size of the vertex cover k
.
For a full proof, you'd have to prove both:
that X
is in SAT
=> Y
in your problem
and Y
in your problem => X
in SAT
.
marcog's answer has a link with several other NP-complete problems you could reduce to your problem.
Footnote: In step 2 (Prove it is NP-hard), reducing another NP-hard (not necessarily NP-complete) problem to the current problem will do, since NP-complete problems are a subset of NP-hard problems (that are also in NP).
I've just finished a releaseable version of a clientside JS-lib (defiant.js) that does what you're looking for. With defiant.js, you can query a JSON structure with the XPath expressions you're familiar with (no new syntax expressions as in JSONPath).
Example of how it works (see it in browser here http://defiantjs.com/defiant.js/demo/sum.avg.htm):
var data = [
{ "x": 2, "y": 0 },
{ "x": 3, "y": 1 },
{ "x": 4, "y": 1 },
{ "x": 2, "y": 1 }
],
res = JSON.search( data, '//*[ y > 0 ]' );
console.log( res.sum('x') );
// 9
console.log( res.avg('x') );
// 3
console.log( res.min('x') );
// 2
console.log( res.max('x') );
// 4
As you can see, DefiantJS extends the global object JSON with a search function and the returned array is delivered with aggregate functions. DefiantJS contains a few other functionalities but those are out of the scope for this subject.
Anywho, you can test the lib with a clientside XPath Evaluator. I think people not familiar with XPath will find this evaluator useful.
http://defiantjs.com/#xpath_evaluator
More information about defiant.js
http://defiantjs.com/
https://github.com/hbi99/defiant.js
I hope you find it useful... Regards
I had the same issue on my React Native Project. Was not just that ADV Manager didn't show up on the menu but other tools where missing as well.
Everything was back to normal when I opened the project using Import project option instead of Open an Existing Android Studio project.
You can use np.concatenate()
specifying which axis
to append, using np.newaxis
:
import numpy as np
movie = np.concatenate((img1[:,np.newaxis], img2[:,np.newaxis]), axis=3)
If you are reading from many files:
import glob
movie = np.concatenate([cv2.imread(p)[:,np.newaxis] for p in glob.glob('*.jpg')], axis=3)
I also had this problem today, and deleting files org.eclipse.jst.server.tomcat.core.prefs
and org.eclipse.wst.server.core.prefs
didn't work.
Finally I found it's permission issue:
By default <apache-tomcat-version>/conf/*
can be read only by owner, after I made it readable for all, it works! So run this command:
chmod a+r <apache-tomcat-version>/conf/*
Here is the link where I found the root cause:
http://www.thecodingforums.com/threads/eclipse-cannot-create-tomcat-server.953960/#post-5058434
in my case, I forget to add (or deleted accidentally) firebase core in build gradle
implementation 'com.google.firebase:firebase-core:xx.x.x'
Follow this simple steps; (Works on MAC OS too)
Open terminal and run sudo mongod
Open a new terminal tab(Don't close step 1 tab) and run sudo mongo
That's all
I think the selected answer is not correct, as the original question is "how to add a new validator after create the formControl".
As far as I know, that's not possible. The only thing you can do, is create the array of validators dynamicaly.
But what we miss is to have a function addValidator() to not override the validators already added to the formControl. If anybody has an answer for that requirement, would be nice to be posted here.
import gzip
import shutil
with gzip.open('file.txt.gz', 'rb') as f_in:
with open('file.txt', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'w+') as file:
file.write(str(exDict))
If you bind to a (collection) of concrete objects, you can get the that concrete object via the DataBoundItem property of the row. (To avoid check for magic strings in the cell and using "real" properties of the object)
Skeleton example below:
DTO/POCO
public class Employee
{
public int EmployeeKey {get;set;}
public string LastName {get;set;}
public string FirstName {get;set;}
public bool IsActive {get;set;}
}
Binding to the datagridview
private void BindData(ICollection<Employee> emps)
{
System.ComponentModel.BindingList<Employee> bindList = new System.ComponentModel.BindingList<Employee>(emps.OrderBy(emp => emp.LastName).ThenBy(emp => emp.FirstName).ToList());
this.dgvMyDataGridView.DataSource = bindList;
}
then the event handler and getting the concrete object (instead of a DataGridRow and/or cells)
private void dgvMyDataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
Employee concreteSelectedRowItem = this.dgvMyDataGridView.Rows[e.RowIndex].DataBoundItem as Employee;
if (null != concreteSelectedRowItem && !concreteSelectedRowItem.IsActive)
{
dgvMyDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGray;
}
}
What if u use scrollIntoView function?
var elmntToView = document.getElementById("sectionId");
elmntToView.scrollIntoView();
Has {behavior: "smooth"} too.... ;) https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
-- ### Six of one half dozen of another. Another method assuming MsSql
Declare @MonthStart datetime = convert(DateTime,'07/01/2016')
Declare @MonthEnd datetime = convert(DateTime,'07/31/2016')
Declare @DayCount_int Int = 0
Declare @WhileCount_int Int = 0
set @DayCount_int = DATEDIFF(DAY, @MonthStart, @MonthEnd)
select @WhileCount_int
WHILE @WhileCount_int < @DayCount_int + 1
BEGIN
print convert(Varchar(24),DateAdd(day,@WhileCount_int,@MonthStart),101)
SET @WhileCount_int = @WhileCount_int + 1;
END;
(Neither IN
nor ANY
is an "operator". A "construct" or "syntax element".)
Logically, quoting the manual:
IN
is equivalent to= ANY
.
But there are two syntax variants of IN
and two variants of ANY
. Details:
IN
taking a set is equivalent to = ANY
taking a set, as demonstrated here:
But the second variant of each is not equivalent to the other. The second variant of the ANY
construct takes an array (must be an actual array type), while the second variant of IN
takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:
ANY
is more versatileThe ANY
construct is far more versatile, as it can be combined with various operators, not just =
. Example:
SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');
For a big number of values, providing a set scales better for each:
Related:
"Find rows where id
is in the given array":
SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);
Inversion: "Find rows where id
is not in the array":
SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}'); -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));
All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[]
.
Rows with id IS NULL
do not pass either of these expressions. To include NULL
values additionally:
SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;
You may use:
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:
Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"
The way your question is phrased makes it sound like you think you have to physically resort the data in the table in order to get it back in the order you want. If so, this is not the case, the ORDER BY clause exists for this purpose. The physical order in which the records are stored remains unchanged when using ORDER BY. The records are sorted in memory (or in temporary disk space) before they are returned.
Note that the order that records get returned is not guaranteed without using an ORDER BY clause. So, while any of the the suggestions here may work, there is no reason to think they will continue to work, nor can you prove that they work in all cases with your current database. This is by design - I am assuming it is to give the database engine the freedom do as it will with the records in order to obtain best performance in the case where there is no explicit order specified.
Assuming you wanted the last 5 records sorted by the field Name in ascending order, you could do something like this, which should work in either SQL 2000 or 2005:
select Name
from (
select top 5 Name
from MyTable
order by Name desc
) a
order by Name asc
java.util.UUID
: toString() method
You have to write this code instead of return View(); :
return RedirectToAction("ActionName", "ControllerName");
Swift 3.0 - 4.2
import Foundation
extension String {
func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date?{
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
dateFormatter.locale = Locale(identifier: "fa-IR")
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: self)
return date
}
}
extension Date {
func toString(withFormat format: String = "EEEE ? d MMMM yyyy") -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "fa-IR")
dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
dateFormatter.calendar = Calendar(identifier: .persian)
dateFormatter.dateFormat = format
let str = dateFormatter.string(from: self)
return str
}
}
The best way to modify a Hash's values in place is
hash.update(hash){ |_,v| "%#{v}%" }
Less code and clear intent. Also faster because no new objects are allocated beyond the values that must be changed.
Note also that when you used arrays in C++ you might have had somewhat different needs, which are solved in different ways in Python:
Python solves the need in arrays by NumPy, which, among other neat things, has a way to create an array of known size:
from numpy import *
l = zeros(10)
Try making the field names legal by removing spaces. It's a long shot but it has actually helped me before.
There are no straightforward lifecycle methods to tell you when the whole Application goes background/foreground.
I have done this with simple way. Follow the below instructions to detect application background/foreground phase.
With a little workaround, it is possible. Here, ActivityLifecycleCallbacks comes to the rescue. Let me walk through step-by-step.
First, create a class that extends the android.app.Application and implements the ActivityLifecycleCallbacks interface. In the Application.onCreate(), register the callback.
public class App extends Application implements
Application.ActivityLifecycleCallbacks {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
}
Register the “App” class in the Manifest as below, <application android:name=".App"
.
There will be at least one Activity in the started state when the app is in the foreground and there will be no Activity in the started state when the app is in the background.
Declare 2 variables as below in the “App” class.
private int activityReferences = 0;
private boolean isActivityChangingConfigurations = false;
activityReferences
will keep the count of number of activities in the started state. isActivityChangingConfigurations
is a flag to indicate if the current Activity is going through configuration change like an orientation switch.
Using the following code you can detect if the App comes foreground.
@Override
public void onActivityStarted(Activity activity) {
if (++activityReferences == 1 && !isActivityChangingConfigurations) {
// App enters foreground
}
}
This is how to detect if the App goes background.
@Override
public void onActivityStopped(Activity activity) {
isActivityChangingConfigurations = activity.isChangingConfigurations();
if (--activityReferences == 0 && !isActivityChangingConfigurations) {
// App enters background
}
}
How it works:
This is a little trick done with the way the Lifecycle methods are called in sequence. Let me walkthrough a scenario.
Assume that the user launches the App and the Launcher Activity A is launched. The Lifecycle calls will be,
A.onCreate()
A.onStart() (++activityReferences == 1) (App enters Foreground)
A.onResume()
Now Activity A starts Activity B.
A.onPause()
B.onCreate()
B.onStart() (++activityReferences == 2)
B.onResume()
A.onStop() (--activityReferences == 1)
Then the user navigates back from Activity B,
B.onPause()
A.onStart() (++activityReferences == 2)
A.onResume()
B.onStop() (--activityReferences == 1)
B.onDestroy()
Then the user presses Home button,
A.onPause()
A.onStop() (--activityReferences == 0) (App enters Background)
In case, if the user presses Home button from Activity B instead of Back button, still it will be the same and activityReferences will be 0
. Hence, we can detect as the App entering Background.
So, what’s the role of isActivityChangingConfigurations
? In the above scenario, suppose the Activity B changes the orientation. The callback sequence will be,
B.onPause()
B.onStop() (--activityReferences == 0) (App enters Background??)
B.onDestroy()
B.onCreate()
B.onStart() (++activityReferences == 1) (App enters Foreground??)
B.onResume()
That’s why we have an additional check of isActivityChangingConfigurations
to avoid the scenario when the Activity is going through the Configuration changes.
@Bruno Lavit has a great answer, but if you want you can just access the log and download it as txt file to your workspace from the job's URL:
${BUILD_URL}/consoleText
Then it's only a matter of downloading this page to your ${Workspace}
Invoke ANT
" and use the GET targetGood luck!
Edit:
The actual log file on the file system is not on the slave, but kept in the Master machine. You can find it under: $JENKINS_HOME/jobs/$JOB_NAME/builds/lastSuccessfulBuild/log
If you're looking for another build just replace lastSuccessfulBuild
with the build you're looking for.
Add a form to your HTML, something like this:
<form style="display: none" action="/the/url" method="POST" id="form">
<input type="hidden" id="var1" name="var1" value=""/>
<input type="hidden" id="var2" name="var2" value=""/>
</form>
and use JQuery to fill these values (of course you can also use javascript to do something similar)
$("#var1").val(value1);
$("#var2").val(value2);
Then finally submit the form
$("#form").submit();
on the server side you should be able to get the data you sent by checking var1
and var2
, how to do this depends on what server-side language you are using.
I think you are looking for inputstream.available()
. It does not tell you whether its empty but it can give you an indication as to whether data is there to be read or not.
The difference is that functionOne
is a function expression and so only defined when that line is reached, whereas functionTwo
is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).
For example, a function expression:
// TypeError: functionOne is not a function_x000D_
functionOne();_x000D_
_x000D_
var functionOne = function() {_x000D_
console.log("Hello!");_x000D_
};
_x000D_
And, a function declaration:
// Outputs: "Hello!"_x000D_
functionTwo();_x000D_
_x000D_
function functionTwo() {_x000D_
console.log("Hello!");_x000D_
}
_x000D_
Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.
'use strict'; _x000D_
{ // note this block!_x000D_
function functionThree() {_x000D_
console.log("Hello!");_x000D_
}_x000D_
}_x000D_
functionThree(); // ReferenceError
_x000D_
For C++ (since C++11) adding the test class as a friend works perfectly and does not break production encapsulation.
Let's suppose that we have some class Foo
with some private functions which really require testing, and some class FooTest
that should have access to Foo's private members. Then we should write the following:
// prod.h: some production code header
// forward declaration is enough
// we should not include testing headers into production code
class FooTest;
class Foo
{
// that does not affect Foo's functionality
// but now we have access to Foo's members from FooTest
friend FooTest;
public:
Foo();
private:
bool veryComplicatedPrivateFuncThatReallyRequiresTesting();
}
// test.cpp: some test
#include <prod.h>
class FooTest
{
public:
void complicatedFisture() {
Foo foo;
ASSERT_TRUE(foo.veryComplicatedPrivateFuncThatReallyRequiresTesting());
}
}
int main(int /*argc*/, char* argv[])
{
FooTest test;
test.complicatedFixture(); // and it really works!
}
new ES6:
'import' should be used with 'export' key words to share variables/arrays/objects between js files:
export default myObject;
//....in another file
import myObject from './otherFile.js';
old skool:
'require' should be used with 'module.exports'
module.exports = myObject;
//....in another file
var myObject = require('./otherFile.js');
This is my solution. I Hide and then confirm check
onclick="return ConfirmSubmit(this);" />
function ConfirmSubmit(sender)
{
sender.disabled = true;
var displayValue = sender.style.
sender.style.display = 'none'
if (confirm('Seguro que desea entregar los paquetes?')) {
sender.disabled = false
return true;
}
sender.disabled = false;
sender.style.display = displayValue;
return false;
}
i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.
Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.
.url files can be made by saving a favourite with internet exploiter.
Use Not IsNull(Fields!W_O_Count.Value)
You can use this in your MySQL WHERE clause to return records that were created within the last 7 days/week:
created >= DATE_SUB(CURDATE(),INTERVAL 7 day)
Also use NOW() in the subtraction to give hh:mm:ss resolution. So to return records created exactly (to the second) within the last 24hrs, you could do:
created >= DATE_SUB(NOW(),INTERVAL 1 day)
Error reason: You are trying to use the busy
port number
Two possible solutions for Windows/Mac
Windows
1. netstat -ano | findstr :4200
2. taskkill /PID 5824 /F
Mac
You can try netstat
netstat -vanp tcp | grep 3000
For OSX El Capitan and newer (or if your netstat doesn't support -p), use lsof
sudo lsof -i tcp:3000
if this does not resolve your problem, Mac
users can refer to complete discussion about this issue Find (and kill) process locking port 3000 on Mac
Windows
set PORT=5000
Mac
export PORT=5000
so do the following edit my.cnf:
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = xxx.xxx.xxx.xxx
# skip-networking
after edit hit service mysqld restart
login into mysql and hit this query:
GRANT ALL ON foo.* TO bar@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';
thats it make sure your iptables allow connection from 3306 if not put the following:
iptables -A INPUT -i lo -p tcp --dport 3306 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 3306 -j ACCEPT
try
subtotal.value= 5 // some value
proc = async function(x,y) {_x000D_
let url = "https://server.test-cors.org/server?id=346169&enable=true&status=200&credentials=false&methods=GET&" // some url working in snippet_x000D_
_x000D_
let r= await(await fetch(url+'&prodid=' + x + '&qbuys=' + y)).json(); // return json-object_x000D_
console.log(r);_x000D_
_x000D_
subtotal.value= r.length; // example value from json_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<form name="yoh" method="get"> _x000D_
Product id: <input type="text" id="pid" value=""><br/>_x000D_
_x000D_
Quantity to buy:<input type="text" id="qtytobuy" value="" onkeyup="proc(pid.value, this.value);"></br>_x000D_
_x000D_
Subtotal:<input type="text" name="subtotal" id="subtotal" value=""></br>_x000D_
<div id="compz"></div>_x000D_
_x000D_
</form>
_x000D_
Recommend you use FREQUENCY
rather than using COUNTIF
.
In your front sheet; enter 01/04/2014
into E5
, 01/05/2014
into E6
etc.
Select the range of adjacent cells you want to populate. Enter:
=FREQUENCY(2013!!$A$2:$A$50,'2013 Metrics'!E5:EN)
(where N is the final row reference in your range)
Hit Ctrl + Shift + Enter
You could also do something like this:
SELECT tb1.* FROM Table tb1 WHERE id = (SELECT MAX(tb2.id) FROM Table tb2);
Its useful when you want to make some joins.
You can also add a UIGestureRecognizer. It does not require you to add an additional element in your view hierarchy, but still provides you will all the nicely written code for handling touch events with a fairly simple interface:
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(handleSwipe:)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[imgView_ addGestureRecognizer:swipeRight];
[swipeRight release];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(handleSwipe:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[imgView_ addGestureRecognizer:swipeLeft];
[swipeLeft release];
for (Map.Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
System.out.println( entry.getKey());
System.out.println( entry.getValue());//Returns the list of values
}
Steps to follow:
Open the Visual Basic Editor. In Excel, hit Alt+F11 if on Windows, Fn+Option+F11 if on a Mac.
Insert a new module. From the menu: Insert -> Module (Don't skip this!).
Create a Public
function. Example:
Public Function findArea(ByVal width as Double, _
ByVal height as Double) As Double
' Return the area
findArea = width * height
End Function
Then use it in any cell like you would any other function: =findArea(B12,C12)
.
We have this working using wildcard DNS in our local DNS server: add an A
record something like *.local -> 127.0.0.1
I think that your network settings will need to have the chosen domain suffix in the domain suffix search list for machines on the network, so you might want to replace .local
with your company's internal domain (e.g. .int
) and then add a subdomain like .localhost.int
to make it clear what it's for.
So *.localhost.int
would resolve to 127.0.0.1
for everybody on the network, and config file settings for all developers would "just work" if endpoints hang off that subdomain e.g. site1.localhost.int
, site2.localhost.int
This is pretty much the scheme we have introduced.
dnsmasq also looks nice, but I have not tried it yet: http://ihaveabackup.net/2012/06/28/using-wildcards-in-the-hosts-file/
@Arnon Rotem-Gal-Oz answer is right for the most part. But I would like to point out the difference between df['year']=df['year'].astype(int)
and df.year.astype(int)
. df.year.astype(int)
returns a view of the dataframe and doesn't not explicitly change the type, atleast in pandas 0.24.2. df['year']=df['year'].astype(int)
explicitly change the type because it's an assignment. I would argue that this is the safest way to permanently change the dtype of a column.
Example:
df = pd.DataFrame({'Weed': ['green crack', 'northern lights', 'girl scout
cookies'], 'Qty':[10,15,3]})
df.dtypes
Weed object, Qty int64
df['Qty'].astype(str)
df.dtypes
Weed object, Qty int64
Even setting the inplace arg to True doesn't help at times. I don't know why this happens though. In most cases inplace=True equals an explicit assignment.
df['Qty'].astype(str, inplace = True)
df.dtypes
Weed object, Qty int64
Now the assignment,
df['Qty'] = df['Qty'].astype(str)
df.dtypes
Weed object, Qty object
You're probably targeting the Client Profile, in which System.Web.dll
is not available.
You can target the full framework in project's Properties.
To get current date/time in javascript:
var date = new Date();
If you need milliseconds for easy server-side interpretation use
var value = date.getTime();
For formatting dates into a user readable string see this
Then just write to hidden field:
document.getElementById("DATE").value = value;
Jon skeet said:
The documentation seems pretty clear to me: "Base implementation of HttpClient that also implements Closeable" - HttpClient is an interface; CloseableHttpClient is an abstract class, but because it implements AutoCloseable you can use it in a try-with-resources statement.
But then Jules asked:
@JonSkeet That much is clear, but how important is it to close HttpClient instances? If it's important, why is the close() method not part of the basic interface?
Answer for Jules
close need not be part of basic interface since underlying connection is released back to the connection manager automatically after every execute
To accommodate the try-with-resources statement. It is mandatory to implement Closeable. Hence included it in CloseableHttpClient.
Note:
close method in AbstractHttpClient which is extending CloseableHttpClient is deprecated, I was not able to find the source code for that.
You are importing the module datetime, which doesn't have a strptime
function.
That module does have a datetime
object with that method though:
import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")
Alternatively you can import the datetime
object from the module:
from datetime import datetime
dtDate = datetime.strptime(sDate, "%m/%d/%Y")
Note that the strptime
method was added in python 2.5; if you are using an older version use the following code instead:
import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])
Just for fun, here is a solution using ed
which does not have the problem of not working on an empty file. You can put it into a shell script just like any other answer to this question.
ed Test <<EOF
a
.
0i
<added text>
.
1,+1 j
$ g/^$/d
wq
EOF
The above script adds the text to insert to the first line, and then joins the first and second line. To avoid ed exiting on error with an invalid join, it first creates a blank line at the end of the file and remove it later if it still exists.
Limitations: This script does not work if <added text>
is exactly equal to a single period.
How about
apply(df, 1, function(r) any(r %in% c("M017", "M018")))
The ith element will be TRUE
if the ith row contains one of the values, and FALSE
otherwise. Or, if you want just the row numbers, enclose the above statement in which(...)
.
Download desired version of hadoop folder (Say if you are installing spark on Windows then hadoop version for which your spark is built for) from this link as zip.
Extract the zip to desired directory.
You need to have directory of the form hadoop\bin
(explicitly create such hadoop\bin
directory structure if you want) with bin
containing all the files contained in bin
folder of the downloaded hadoop. This will contain many files such as hdfs.dll, hadoop.dll etc. in addition to winutil.exe.
Now create environment variable HADOOP_HOME
and set it to <path-to-hadoop-folder>\hadoop
. Then add ;%HADOOP_HOME%\bin;
to PATH
environment variable.
Open a "new command prompt" and try rerunning your command.
Try this --
fseek(fp, 0, SEEK_END);
unsigned long int file_size = ftell(fp);
rewind(fp);
What this does is first, seek to the end of the file; then, report where the file pointer is. Lastly (this is optional) it rewinds back to the beginning of the file. Note that fp
should be a binary stream.
file_size contains the number of bytes the file contains. Note that since (according to climits.h) the unsigned long type is limited to 4294967295 bytes (4 gigabytes) you'll need to find a different variable type if you're likely to deal with files larger than that.
You can send your data like the "POST" request through the "HEADERS".
Something like this:
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
headers: ['id1':1, 'id2':2, 'id3':3],
data: "",
contentType: "text/plain",
dataType: "json",
success: onSuccess,
error: onError
});
You can make use of
display: flex;
align-items: center;
justify-content: center;
on your parent component
The code of @ThePracticalOne is great for showing the usage except for one thing:
Somtimes the output would be incomplete.(session.recv_ready()
turns true after the if session.recv_ready():
while session.recv_stderr_ready()
and session.exit_status_ready()
turned true before entering next loop)
so my thinking is to retrieving the data when it is ready to exit the session.
while True:
if session.exit_status_ready():
while True:
while True:
print "try to recv stdout..."
ret = session.recv(nbytes)
if len(ret) == 0:
break
stdout_data.append(ret)
while True:
print "try to recv stderr..."
ret = session.recv_stderr(nbytes)
if len(ret) == 0:
break
stderr_data.append(ret)
break
select * from table
where date between
(date_add (CURRENT_DATE, INTERVAL(1 - DAYOFMonth(CURRENT_DATE)) day)) and current_date;
You're close. This should do the trick:
new {items = new [] {
new {name = "command" , index = "X", optional = "0"},
new {name = "command" , index = "X", optional = "0"}
}}
If your source was an enumerable of some sort, you might want to do this:
new {items = source.Select(item => new
{
name = item.Name, index = item.Index, options = item.Optional
})};
Sometimes this could happen during service deletion via PowerShell remote session script, especially when you are trying to delete service several times. In this case, try to recreate a session before the deletion:
Remove-PSSession -Session $session
$newSession = New-PSSession -ComputerName $Name -Credential $creds -ErrorAction Stop
Enter-PSSession $newSession
Quoting from Import the SQLPS Module on MSDN,
The recommended way to manage SQL Server from PowerShell is to import the sqlps module into a Windows PowerShell 2.0 environment.
So, yes, you could use the Add-PSSnapin
approach detailed by Christian, but it is also useful to appreciate the recommended sqlps module approach.
The simplest case assumes you have SQL Server 2012: sqlps is included in the installation so you simply load the module like any other (typically in your profile) via Import-Module sqlps
. You can check if the module is available on your system with Get-Module -ListAvailable
.
If you do not have SQL Server 2012, then all you need do is download the sqlps module into your modules directory so Get-Module/Import-Module will find it. Curiously, Microsoft does not make this module available for download! However, Chad Miller has kindly packaged up the requisite pieces and provided this module download. Unzip it under your ...Documents\WindowsPowerShell\Modules directory and proceed with the import.
It is interesting to note that the module approach and the snapin approach are not identical. If you load the snapins then run Get-PSSnapin
(without the -Registered parameter, to show only what you have loaded) you will see the SQL snapins. If, on the other hand, you load the sqlps module Get-PSSnapin
will not show the snapins loaded, so the various blog entries that test for the Invoke-Sqlcmd
cmdlet by only examining snapins could be giving a false negative result.
2012.10.06 Update
For the complete story on the sqlps module vs. the sqlps mini-shell vs. SQL Server snap-ins, take a look at my two-part mini-series Practical PowerShell for SQL Server Developers and DBAs recently published on Simple-Talk.com where I have, according to one reader's comment, successfully "de-confused" the issue. :-)
It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.
If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.
You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)
If the input video has multiple audio tracks and you need to add one more then use the following command:
ffmpeg -i input_video_with_audio.avi -i new_audio.ac3 -map 0 -map 1 -codec copy output_video.avi
-map 0
means to copy (include) all streams from the first input file (input_video_with_audio.avi
) and -map 1
means to include all streams (in this case one) from the second input file (new_audio.ac3
).
You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.
import React from "react";
const sizeToLetterMap = {
small_square: 's',
large_square: 'q',
thumbnail: 't',
small_240: 'm',
small_320: 'n',
medium_640: 'z',
medium_800: 'c',
large_1024: 'b',
large_1600: 'h',
large_2048: 'k',
original: 'o'
};
class PhotoComponent extends React.Component {
constructor(args) {
super(args);
}
photoUrl(image, size_text) {
return (<span>
Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
</span>);
}
render() {
return (
<div className="photo-wrapper">
The url is: {this.photoUrl(this.props.image, this.props.size_text)}
</div>
)
}
}
export default PhotoComponent;
// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";
1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J
2. Remember to set the classpath to include the path of the connector jar file.
If we don't set it correctly, below errors can occur:
No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development
java.lang.ClassNotFoundException: com.mysql.jdbc:Driver
Method 1: set the CLASSPATH variable.
export CLASSPATH=".:mysql-connector-java-VERSION.jar"
java MyClassFile
In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile
command executed, java application launcher will try to load all the Java class in CLASSPATH.
And it found the Drive
class => BOOM errors was gone.
Method 2:
java -cp .:mysql-connector-java-VERSION.jar MyClassFile
Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.
Hope this can help someone!
Another solution is by using .animate() and appropriate CSS.
e.g.
$('#mydiv').animate({ marginLeft: "100%"} , 4000);
Perhaps try:
var body = document.getElementsByTagName('body')[0];
body.setAttribute("data-body","");
If you don't want to change the authentication method (ident) and mess with pg_hba.conf use this:
First login as the default user
sudo su - posgres
then access psql and create a user with the same name as the one you are login in
postgres=# CREATE USER userOS WITH PASSWORD 'garbage' CREATEDB;
you can verify your user with the corresponding roles with
postgres=# \du
Afer this you can create your database and verify it with
psql -d dbName
\l
\q
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
A more elegant way I found to achieve this behaviour is simply:
<div id="{{ 'object-' + myScopeObject.index }}"></div>
For my implementation I wanted each input element in a ng-repeat to each have a unique id to associate the label with. So for an array of objects contained inside myScopeObjects one could do this:
<div ng-repeat="object in myScopeObject">
<input id="{{object.name + 'Checkbox'}}" type="checkbox">
<label for="{{object.name + 'Checkbox'}}">{{object.name}}</label>
</div>
Being able to generate unique ids on the fly can be pretty useful when dynamically adding content like this.
First of all create on file and then convert your xml data in array and retrieve that data in json format for ajax success response.
Try as below:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "sample.php",
success: function (response) {
var obj = $.parseJSON(response);
for(var i=0;i<obj.length;i++){
// here you can add html through loop
}
}
});
});
sample.php
$xml = "YOUR XML FILE PATH";
$json = json_encode((array)simplexml_load_string($xml)),1);
echo $json;
I use the following method:
public static <T> T getBean(final String beanName, final Class<T> clazz) {
ELContext elContext = FacesContext.getCurrentInstance().getELContext();
return (T) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, beanName);
}
This allows me to get the returned object in a typed manner.
You can also use Url.Action for the path instead like so:
$.ajax({
url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",
type: "GET",
success: function (partialViewResult) {
$("#refTable").html(partialViewResult);
}
});
If you think you can use Javascript, then since jQuery support last-child
, you can use jQuery's css method and the good thing it will support almost all the browsers
Example Code:
$(function(){
$("#nav li:last-child").css("border-bottom","1px solid #b5b5b5")
})
You can find more info about here : http://api.jquery.com/css/#css2
This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.
tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000
This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.
I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:
#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000
Edit:
This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
You can use this ObjectFilter:
public class ObjectFilter : ActionFilterAttribute {
public string Param { get; set; }
public Type RootType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
object o =
new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;
}
}
}
You can then apply it to your controller methods like so:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.
This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.
See, for example, the code samples here:
Let's look at the example you posted:
function loadUser(req, res, next) {
if (req.session.user_id) {
User.findById(req.session.user_id, function(user) {
if (user) {
req.currentUser = user;
return next();
} else {
res.redirect('/sessions/new');
}
});
} else {
res.redirect('/sessions/new');
}
}
app.get('/documents.:format?', loadUser, function(req, res) {
// ...
});
The loadUser
function expects a function in its third argument, which is bound to the name next
. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser
is done (unless a user could not be found).
There's nothing special about the name next
in this example; we could have named it anything.
To select 50 random key values from a dictionary set dict_data
:
sample = random.sample(set(dict_data.keys()), 50)
this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case:
you specify
transaction_status varchar(10)
but you actually trying to store
_transaction_status
which contain 19 characters.
that's why you faced this type of error in this code..
^(0|[1-9][0-9]*)$
This is the way:
kill -9 $(pgrep -d' ' -f chrome)
Use stored procedures.
And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".
Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.
Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.
Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.
On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)
The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.
Jake
put a int
infront of the all the voxelCoord
's...Like this below :
patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]
Libraries cannot be directly used in any program if not properly added to the project gradle files.
This can easily be done in smart IDEs like inteli J.
1) First as a convention add a folder names 'libs' under your project src file. (this can easily be done using the IDE itself)
2) then copy or add your library file (eg: .jar file) to the folder named 'libs'
3) now you can see the library file inside the libs folder. Now right click on the file and select 'add as library'. And this will fix all the relevant files in your program and library will be directly available for your use.
Please note:
Whenever you are adding libraries to a project, make sure that the project supports the library
Use cmd prompt and type
java -jar exapmple.jar
To run your jar file.
for more information refer to this link it describes how to properly open the jar file. https://superuser.com/questions/745112/how-do-i-run-a-jar-file-without-installing-java
Or better
window.location.assign("relative or absolute address");
that tends to work best across all browsers and mobile
UPDATE:
After all the details summarized and discussed, I spent 2 fair hours in checking the options, and this update is to dot all i
s.
First of all, I performed a clean Office 2010 x86 install on Clean Win7 SP1 Ultimate x64 virtual machine powered by VMWare (this is usual routine for my everyday testing tasks, so I have many of them deployed).
Then, I changed only the following Excel options (i.e. all the other are left as is after installation):
Advanced > General > Ask to update automatic links
checked:Trust Center > Trust Center Settings... > External Content > Enable All...
(although that one that relates to Data Connections is most likely not important for the case):I prepared and placed to C:\
a workbook exactly as per @Siddharth Rout
suggestions in his updated answer (shared for your convenience): https://www.dropbox.com/s/mv88vyc27eljqaq/Book1withLinkToBook2.xlsx Linked book was then deleted so that link in the shared book is unavailable (for sure).
The above shared file shows on opening (having the above listed Excel options) 2 warnings - in the order of appearance:
WARNING #1
After click on Update
I expectedly got another:
WARNING #2
So, I suppose my testing environment is now pretty much similar to OP
's) So far so good, we finally go to
Now I'll try all possible options step by step to make the picture clear. I'll share only relevant lines of code for simplicity (complete sample file with code will be shared in the end).
1. Simple Application.Workbooks.Open
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
No surprise - this produces BOTH warnings, as for manual opening above.
2. Application.DisplayAlerts = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
This code ends up with WARNING #1, and either option clicked (Update
/ Don't Update
) produces NO further warnings, i.e. Application.DisplayAlerts = False
suppresses WARNING #2.
3. Application.AskToUpdateLinks = False
Application.AskToUpdateLinks = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.AskToUpdateLinks = True
Opposite to DisplayAlerts
, this code ends up with WARNING #2 only, i.e. Application.AskToUpdateLinks = False
suppresses WARNING #1.
4. Double False
Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Apparently, this code ends up with suppressing BOTH WARNINGS.
5. UpdateLinks:=False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=False
Finally, this 1-line solution (originally proposed by @brettdj
) works the same way as Double False: NO WARNINGS are shown!
Except a good testing practice and very important solved case (I may face such issues everyday while sending my workbooks to 3rd party, and now I'm prepared), 2 more things learned:
Thanks very much to everyone who contributed to the solution, and especially OP who raised the question. Hope my investigations and thoroughly described testing steps were helpful not only for me)
Sample file with the above code samples is shared (many lines are commented deliberately): https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm
Original answer (tested for Excel 2007 with certain options):
This code works fine for me - it loops through ALL Excel files specified using wildcards in the InputFolder
:
Sub WorkbookOpening2007()
Dim InputFolder As String
Dim LoopFileNameExt As String
InputFolder = "D:\DOCUMENTS\" 'Trailing "\" is required!
LoopFileNameExt = Dir(InputFolder & "*.xls?")
Do While LoopFileNameExt <> ""
Application.DisplayAlerts = False
Application.Workbooks.Open (InputFolder & LoopFileNameExt)
Application.DisplayAlerts = True
LoopFileNameExt = Dir
Loop
End Sub
I tried it with books with unavailable external links - no warnings.
Sample file: https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm