Changing text color of button
Because this method is now deprecated
button.setTextColor(getResources().getColor(R.color.your_color));
I use the following:
button.setTextColor(ContextCompat.getColor(mContext, R.color.your_color));
The rule of thumb is to use the function most suited to your needs.
If you just want the keys and do not plan to ever read any of the values, use keys():
foreach my $key (keys %hash) { ... }
If you just want the values, use values():
foreach my $val (values %hash) { ... }
If you need the keys and the values, use each():
keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop
while(my($k, $v) = each %hash) { ... }
If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():
%h = (a => 1, b => 2);
foreach my $k (keys %h)
{
$h{uc $k} = $h{$k} * 2;
}
producing the expected resulting hash:
(a => 1, A => 2, b => 2, B => 4)
But using each() to do the same thing:
%h = (a => 1, b => 2);
keys %h;
while(my($k, $v) = each %h)
{
$h{uc $k} = $h{$k} * 2; # BAD IDEA!
}
produces incorrect results in hard-to-predict ways. For example:
(a => 1, A => 2, b => 2, B => 8)
This, however, is safe:
keys %h;
while(my($k, $v) = each %h)
{
if(...)
{
delete $h{$k}; # This is safe
}
}
All of this is described in the perl documentation:
% perldoc -f keys
% perldoc -f each
This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.
You can fork this and use it as a great starting point for your specific expectations:
Here are two screenshots I took for you... wide and thin:
To fit to the visible markers only, I've this method.
fitMapBounds() {
// Get all visible Markers
const visibleMarkers = [];
this.map.eachLayer(function (layer) {
if (layer instanceof L.Marker) {
visibleMarkers.push(layer);
}
});
// Ensure there's at least one visible Marker
if (visibleMarkers.length > 0) {
// Create bounds from first Marker then extend it with the rest
const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
visibleMarkers.forEach((marker) => {
markersBounds.extend(marker.getLatLng());
});
// Fit the map with the visible markers bounds
this.map.flyToBounds(markersBounds, {
padding: L.point(36, 36), animate: true,
});
}
}
in iterm2
fn + leftArraw or fn + rightArrow
this worked for me
Here's a reusable Angular directive that will hide and show a Bootstrap modal.
app.directive("modalShow", function () {
return {
restrict: "A",
scope: {
modalVisible: "="
},
link: function (scope, element, attrs) {
//Hide or show the modal
scope.showModal = function (visible) {
if (visible)
{
element.modal("show");
}
else
{
element.modal("hide");
}
}
//Check to see if the modal-visible attribute exists
if (!attrs.modalVisible)
{
//The attribute isn't defined, show the modal by default
scope.showModal(true);
}
else
{
//Watch for changes to the modal-visible attribute
scope.$watch("modalVisible", function (newValue, oldValue) {
scope.showModal(newValue);
});
//Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
element.bind("hide.bs.modal", function () {
scope.modalVisible = false;
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
}
}
};
});
Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition
<div modal-show class="modal fade"> ...bootstrap modal... </div>
Usage Example #2 - this uses an Angular expression in the modal-visible attribute
<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>
Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.
$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)
I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal
Hope this helps.
I had the same problem and changed my configuration in application-test.properties to this:
#Test Properties
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
And my dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.198</version>
<scope>test</scope>
</dependency>
And the annotations used on test class:
@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("test")
public class CommentServicesIntegrationTests {
...
}
I think you cannot just delete the tables property what if this is actual production data, just delete the contents that dont affect the table schema.
This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:
<table>
<tr>
<td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
Hello World
</td>
</tr>
</table>
I was able to fix the error by
A little history of this case and observations:
In a word, you can't.
3.65
cannot be represented exactly as a float
. The number that you're getting is the nearest number to 3.65
that has an exact float
representation.
The difference between (older?) Python 2 and 3 is purely due to the default formatting.
I am seeing the following both in Python 2.7.3 and 3.3.0:
In [1]: 3.65
Out[1]: 3.65
In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'
For an exact decimal datatype, see decimal.Decimal
.
The given example(s) use one dialog with id '#dialog', i needed a solution that close any dialog:
$.extend($.ui.dialog.prototype.options, {
modal: true,
open: function(object) {
jQuery('.ui-widget-overlay').bind('click', function() {
var id = jQuery(object.target).attr('id');
jQuery('#'+id).dialog('close');
})
}
});
Thanks to my colleague Youri Arkesteijn for the suggestion of using prototype.
Usually when I use a select menu, each option has a value associated with it. For example
<select id="nfl">
<option value="Bears Still...">Chicago Bears</option>
<option selected="selected" value="Go Pack">Green Bay Packers</option>
</select>
console.log($('#nfl').val()) logs "Go Pack" to the console
Set the value to an empty string $('#nfl').val("")
console.log($('#nfl').val()) logs "" to the console
Now this doesn't remove the selected attribute from the option but all I really want is the value.
I use RStudio or Emacs and always use the editor shortcuts available to comment regions. If this is not a possibility then you could use Paul's answer but this only works if your code is syntactically correct.
Here is another dirty way I came up with, wrap it in scan()
and remove the result. It does store the comment in memory for a short while so it will probably not work with very large comments. Best still is to just put #
signs in front of every line (possibly with editor shortcuts).
foo <- scan(what="character")
These are comments
These are still comments
Can also be code:
x <- 1:10
One line must be blank
rm(foo)
Find in the below code which enables to perform the date validation for any of the supplied format to validate start/from and end/to dates. There could be some better approaches but have come up with this. Note supplied date format and date string go hand in hand.
<script type="text/javascript">
function validate() {
var format = 'yyyy-MM-dd';
if(isAfterCurrentDate(document.getElementById('start').value, format)) {
alert('Date is after the current date.');
} else {
alert('Date is not after the current date.');
}
if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
alert('Date is before current date.');
} else {
alert('Date is not before current date.');
}
if(isCurrentDate(document.getElementById('start').value, format)) {
alert('Date is current date.');
} else {
alert('Date is not a current date.');
}
if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Start/Effective Date cannot be greater than End/Expiration Date');
} else {
alert('Valid dates...');
}
if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('End/Expiration Date cannot be less than Start/Effective Date');
} else {
alert('Valid dates...');
}
if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Dates are equals...');
} else {
alert('Dates are not equals...');
}
if (isDate(document.getElementById('start').value, format)) {
alert('Is valid date...');
} else {
alert('Is invalid date...');
}
}
/**
* This method gets the year index from the supplied format
*/
function getYearIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'YYYY'
|| tokens[0] === 'yyyy') {
return 0;
} else if (tokens[1]=== 'YYYY'
|| tokens[1] === 'yyyy') {
return 1;
} else if (tokens[2] === 'YYYY'
|| tokens[2] === 'yyyy') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the year string located at the supplied index
*/
function getYear(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the month index from the supplied format
*/
function getMonthIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'MM'
|| tokens[0] === 'mm') {
return 0;
} else if (tokens[1] === 'MM'
|| tokens[1] === 'mm') {
return 1;
} else if (tokens[2] === 'MM'
|| tokens[2] === 'mm') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the month string located at the supplied index
*/
function getMonth(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the date index from the supplied format
*/
function getDateIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'DD'
|| tokens[0] === 'dd') {
return 0;
} else if (tokens[1] === 'DD'
|| tokens[1] === 'dd') {
return 1;
} else if (tokens[2] === 'DD'
|| tokens[2] === 'dd') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the date string located at the supplied index
*/
function getDate(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method returns true if date1 is before date2 else return false
*/
function isBefore(date1, date2, format) {
// Validating if date1 date is greater than the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
> new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method returns true if date1 is after date2 else return false
*/
function isAfter(date1, date2, format) {
// Validating if date2 date is less than the date1 date
if (new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()
< new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
) {
return true;
}
return false;
}
/**
* This method returns true if date1 is equals to date2 else return false
*/
function isEquals(date1, date2, format) {
// Validating if date1 date is equals to the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
=== new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date is
* equals to the current date.
*/
function isCurrentDate(date, format) {
// Validating if the supplied date is the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
=== new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is before the current date.
*/
function isBeforeCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
< new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is after the current date.
*/
function isAfterCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
> new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method splits the supplied date OR format based
* on non alpha numeric characters in the supplied string.
*/
function splitDateFormat(dateFormat) {
// Spliting the supplied string based on non characters
return dateFormat.split(/\W/);
}
/*
* This method validates if the supplied value is a valid date.
*/
function isDate(date, format) {
// Validating if the supplied date string is valid and not a NaN (Not a Number)
if (!isNaN(new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))))) {
return true;
}
return false;
}
</script>
Below is the HTML snippet
<input type="text" name="start" id="start" size="10" value="" />
<br/>
<input type="text" name="end" id="end" size="10" value="" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate();" />
Check this.
The infamous AngularJS if|else
statement!!!
When I started using Angularjs, I was a bit surprised that I couldn’t find an if/else statement.
So I was working on a project and I noticed that when using the if/else statement, the condition shows while loading. You can use ng-cloak to fix this.
<div class="ng-cloak">
<p ng-show="statement">Show this line</span>
<p ng-hide="statement">Show this line instead</span>
</div>
.ng-cloak { display: none }
Thanks amadou
it is wrong. correct will be
P3 P2 P4 P5 P1 0 3 4 6 10 as the correct difference are these
Waiting Time (0+3+4+6+10)/5 = 4.6
Ref: http://www.it.uu.se/edu/course/homepage/oskomp/vt07/lectures/scheduling_algorithms/handout.pdf
try this example
function toggleRed() {_x000D_
var text = $('.editable').text();_x000D_
$('.editable').html('<p style="color:red">' + text + '</p>');_x000D_
}_x000D_
_x000D_
function toggleItalic() {_x000D_
var text = $('.editable').text();_x000D_
$('.editable').html("<i>" + text + "</i>");_x000D_
}_x000D_
_x000D_
$('.bold').click(function() {_x000D_
toggleRed();_x000D_
});_x000D_
_x000D_
$('.italic').click(function() {_x000D_
toggleItalic();_x000D_
});
_x000D_
.editable {_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
border: 1px solid #ccc;_x000D_
padding: 5px;_x000D_
resize: both;_x000D_
overflow: auto;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="editable" contenteditable="true"></div>_x000D_
<button class="bold">toggle red</button>_x000D_
<button class="italic">toggle italic</button>
_x000D_
If you already have the border from shape just add elevation:
<LinearLayout
android:id="@+id/layout"
...
android:elevation="2dp"
android:background="@drawable/rectangle" />
It's simple:
Edit ~/.profile and put your variables as follow
$ vim ~/.profile
In file put:
MY_ENV_VAR=value
Save ( :wq )
Restart the terminal (Quit and open it again)
Make sure that`s all be fine:
$ echo $MY_ENV_VAR
$ value
"Default Namespace textbox in project properties is disabled" Same with me (VS 2010). I edited the project file ("xxx.csproj") and tweaked the item. That changed the default namespace.
Copy-pasted from here:
/* localtime example */
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
(just add void
to the main()
arguments list in order for this to work in C)
There are plenty of clients actually. One of them is Pest - check this out. And keep in mind that these REST calls are simple http request with various methods: GET, POST, PUT and DELETE.
One good solution is to run only desired services like this:
docker-compose up --build $(<services.txt)
and services.txt file look like this:
services1 services2, etc
of course if dependancy (depends_on), need to run related services together.
--build is optional, just for example.
You can use the CheckedChanged event for all your RadioButtons. Sender
will be the unchecked and checked RadioButtons.
Use the built in function zip
property_asel = [a for (a, truth) in zip(property_a, good_objects) if truth]
Just looking at the new features of 2.7. There is now a function in the itertools module which is similar to the above code.
http://docs.python.org/library/itertools.html#itertools.compress
itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
A, C, E, F
When I try:
<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!" />
It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.
Pls try:
<script type="text/javascript">
function moreFields() {
alert("The text will be show");
}
</script>
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
Hope it helped.
Per the developers, this error is not an actual failure, but rather "misleading error reports". This bug is fixed in version 40, which is available on the canary and dev channels as of 25 Oct.
For me it was a permission problem.
enter:
mysqld --verbose --help | grep -A 1 "Default options"
[Warning] World-writable config file '/etc/mysql/my.cnf' is ignored.
So try to execute the following, and then restart the server
chmod 644 '/etc/mysql/my.cnf'
It will give mysql access to read and write to the file.
Typically, git commit
brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR
environment variable) for you to edit your commit message in. When you save and exit, the commit completes.
You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.
The way you have added a row into the table layout you can add multiple TableRow
instances into your tableLayout
object
tl.addView(row1);
tl.addView(row2);
etc...
I need to do "fluid" rectangles not squares.... so THANKS to JOPL .... didn't take but a minute....
#map_container {
position: relative;
width: 100%;
padding-bottom: 75%;
}
#map {
position:absolute;
width:100%;
height:100%;
}
perhaps making mvcc permanent could solve it (as opposed to specific batch only: SET TRANSACTION ISOLATION LEVEL SNAPSHOT):
ALTER DATABASE yourDbNameHere SET READ_COMMITTED_SNAPSHOT ON;
[EDIT: October 14]
After reading this: Better concurrency in Oracle than SQL Server? and this: http://msdn.microsoft.com/en-us/library/ms175095.aspx
When the READ_COMMITTED_SNAPSHOT database option is set ON, the mechanisms used to support the option are activated immediately. When setting the READ_COMMITTED_SNAPSHOT option, only the connection executing the ALTER DATABASE command is allowed in the database. There must be no other open connection in the database until ALTER DATABASE is complete. The database does not have to be in single-user mode.
i've come to conclusion that you need to set two flags in order to activate mssql's MVCC permanently on a given database:
ALTER DATABASE yourDbNameHere SET ALLOW_SNAPSHOT_ISOLATION ON;
ALTER DATABASE yourDbNameHere SET READ_COMMITTED_SNAPSHOT ON;
If you are using application.yml and spring version above 2.0 then configure in below manner.
server:
port: 8081
servlet:
context-path: /demo-api
Now all the api call will be like http://localhost:8081/demo-api/
Make sure you are in the project directory before running bundle install
. For example, after running rails new myproject
, you will want to cd myproject
before running bundle install
.
In Twitter Bootstrap bootstrap 3.0.0, Twitter button is flat. You can customize it from http://getbootstrap.com/customize. Button color, border radious etc.
Also you can find the HTML code and others functionality http://twitterbootstrap.org/bootstrap-css-buttons.
Bootstrap 2.3.2 button is gradient but 3.0.0 ( new release ) flat and looks more cool.
and also you can find to customize the entire bootstrap looks and style form this resources: http://twitterbootstrap.org/top-5-customizing-bootstrap-resources/
Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.
The main advantage of numpy matrices is that they provide a convenient notation
for matrix multiplication: if a and b are matrices, then a*b
is their matrix
product.
import numpy as np
a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
print(a)
# [[4 3]
# [2 1]]
print(b)
# [[1 2]
# [3 4]]
print(a*b)
# [[13 20]
# [ 5 8]]
On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @
operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python >= 3.5.
import numpy as np
a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print(a@b)
# [[13 20]
# [ 5 8]]
Both matrix objects and ndarrays have .T
to return the transpose, but matrix
objects also have .H
for the conjugate transpose, and .I
for the inverse.
In contrast, numpy arrays consistently abide by the rule that operations are
applied element-wise (except for the new @
operator). Thus, if a
and b
are numpy arrays, then a*b
is the array
formed by multiplying the components element-wise:
c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
# [6 4]]
To obtain the result of matrix multiplication, you use np.dot
(or @
in Python >= 3.5, as shown above):
print(np.dot(c,d))
# [[13 20]
# [ 5 8]]
The **
operator also behaves differently:
print(a**2)
# [[22 15]
# [10 7]]
print(c**2)
# [[16 9]
# [ 4 1]]
Since a
is a matrix, a**2
returns the matrix product a*a
.
Since c
is an ndarray, c**2
returns an ndarray with each component squared
element-wise.
There are other technical differences between matrix objects and ndarrays
(having to do with np.ravel
, item selection and sequence behavior).
The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work -- you have to learn matrix object operations, and ndarray operations.
Writing a program that mixes both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don't expect.
In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.
If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python >= 3.5), then I think NumPy arrays are definitely the way to go.
PS. Of course, you really don't have to choose one at the expense of the other,
since np.asmatrix
and np.asarray
allow you to convert one to the other (as
long as the array is 2-dimensional).
There is a synopsis of the differences between NumPy arrays
vs NumPy matrix
es here.
To Install cURL 7.49.0 on Ubuntu 16.04 and Derivatives
wget http://curl.haxx.se/download/curl-7.49.0.tar.gz
tar -xvf curl-7.49.0.tar.gz
cd curl-7.49.0/
./configure
make
sudo make install
Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.
Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).
Example:
System.Diagnostics.Process.Start("mspaint.exe");
Compiling the Code
Copy the code and paste it into the Main method of a console application. Replace "mspaint.exe" with the path to the application you want to run.
Try with an API lvl 28 emulator (Android 9). I was trying with api lvl 29 and kept getting errors.
readlines() reads the entire input file into a list and is not a good performer. Just iterate through the lines in the file. I used 'with' on output.txt so that it is automatically closed when done. That's not needed on 'list1.txt' because it will be closed when the for loop ends.
#!/usr/bin/env python
with open('output.txt', 'a') as f1:
for line in open('list1.txt'):
if 'tests/file/myword' in line:
f1.write(line)
You could use overloads:
public static string BuildClause(List<string> l){...}
public static string BuildClause(List<int> l){...}
public static string BuildClause<T>(List<T> l){...}
Or you could inspect the type of the generic parameter:
Type listType = typeof(T);
if(listType == typeof(int)){...}
This is what I needed:
public static byte[] encode(byte[] arr, String fromCharsetName) {
return encode(arr, Charset.forName(fromCharsetName), Charset.forName("UTF-8"));
}
public static byte[] encode(byte[] arr, String fromCharsetName, String targetCharsetName) {
return encode(arr, Charset.forName(fromCharsetName), Charset.forName(targetCharsetName));
}
public static byte[] encode(byte[] arr, Charset sourceCharset, Charset targetCharset) {
ByteBuffer inputBuffer = ByteBuffer.wrap( arr );
CharBuffer data = sourceCharset.decode(inputBuffer);
ByteBuffer outputBuffer = targetCharset.encode(data);
byte[] outputData = outputBuffer.array();
return outputData;
}
Simplest and best:
i = 0
while not there_is_reason_to_break(i):
# some code here
i += 1
It may be tempting to choose the closest analogy to the C code possible in Python:
from itertools import count
for i in count():
if thereIsAReasonToBreak(i):
break
But beware, modifying i
will not affect the flow of the loop as it would in C. Therefore, using a while
loop is actually a more appropriate choice for porting that C code to Python.
Putting plot.tight_layout()
after all changes on the graph, just before show()
or savefig()
will solve the problem.
You can do sizeof($Contents)
or count($Contents)
also this
$count = 0;
foreach($Contents as $items) {
$count++;
$items[number];
}
if your tags are sortable:
git tag --merged $YOUR_BRANCH_NAME | grep "prefix/" | sort | tail -n 1
Either encode the needed XML entities or use CDATA.
<arg0>
<!--Optional:-->
<parameter1><test>like this</test></parameter1>
<!--Optional:-->
<parameter2><![CDATA[<test>or like this</test>]]></parameter2>
</arg0>
If website on small devices behavior like desktop screen then you have to put this meta tag into header before
<meta name="viewport" content="width=device-width, initial-scale=1">
For media queries you can set this as
this will cover your all mobile/cellphone widths
@media only screen and (min-width: 200px) and (max-width: 767px) {
//Put your CSS here for 200px to 767px width devices (cover all width between 200px to 767px //
}
For iPad and iPad pro you have to use
@media only screen and (min-width: 768px) and (max-width: 1024px) {
//Put your CSS here for 768px to 1024px width devices(covers all width between 768px to 1024px //
}
If you want to add css for Landscape mode you can add this
and (orientation : landscape)
@media only screen and (min-width: 200px) and (max-width: 767px) and (orientation : portrait) {
//Put your CSS here for 200px to 767px width devices (cover all mobile portrait width //
}
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
Use onunload.
For jQuery, I think this works like so:
$(window).unload(function() {
alert("Unloading");
return falseIfYouWantToButBeCareful();
});
1.Right click to Gitbash shortcut choose Properties
2.Choose "Shortcut" tab
3.Type your starting directory to "Start in" field
4.Remove "--cd-to-home" part from "Target" field
You can get free Virtual Machine and many more things online for 3 months provided by Microsoft Azure. I guess you need VPN for learning purpose. For that it would suffice.
you are confusing the concept of appending and prepending. the following code is prepending:
sys.path.insert(1,'/thePathToYourFolder/')
it places the new information at the beginning (well, second, to be precise) of the search sequence that your interpreter will go through. sys.path.append()
puts things at the very end of the search sequence.
it is advisable that you use something like virtualenv
instead of manually coding your package directories into the PYTHONPATH
everytime. for setting up various ecosystems that separate your site-packages and possible versions of python, read these two blogs:
if you do decide to move down the path to environment isolation you would certainly benefit by looking into virtualenvwrapper: http://www.doughellmann.com/docs/virtualenvwrapper/
Properties in your object are value types and you can use the shallow copy in such situation like that:
obj myobj2 = (obj)myobj.MemberwiseClone();
But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization
and Deserialization
techniques with the help of BinaryFormatter
class:
public static T DeepCopy<T>(T other)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Context = new StreamingContext(StreamingContextStates.Clone);
formatter.Serialize(ms, other);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
The purpose of setting StreamingContext
:
We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable
interface or using built-in attributes like OnDeserialized
, OnDeserializing
, OnSerializing
, OnSerialized
. In all cases StreamingContext
will be passed as an argument to the methods(and to the special constructor in case of ISerializable
interface). With setting ContextState
to Clone
, we are just giving hint to that method about the purpose of the serialization.
Additional Info: (you can also read this article from MSDN)
Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.
Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.
Using modal.hide would only hide the modal. If you are using overlay underneath the modal, it would still be there. use click call to actually close the modal and remove the overlay.
$("#modalID .close").click()
I think that there isn't a official naming convention to JSON, but you can follow some industry leaders to see how it is working.
Google, which is one of the biggest IT company of the world, has a JSON style guide: https://google.github.io/styleguide/jsoncstyleguide.xml
Taking advantage, you can find other styles guide, which Google defines, here: https://github.com/google/styleguide
There are a few answers outlining differences between <depedencies>
and <dependencyManagement>
tags with maven.
However, few points elaborated below in a concise way:
<dependencyManagement>
allows to consolidate all dependencies (used at child pom level) used across different modules -- clarity, central dependency version management<dependencyManagement>
allows to easily upgrade/downgrade dependencies based on need, in other scenario this needs to be exercised at every child pom level -- consistency<dependencies>
tag is always imported, while dependencies provided at <dependencyManagement>
in parent pom will be imported only if child pom has respective entry in its <dependencies>
tag.There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
There's no exact answer to this.
Generally speaking, composer shouldn't be doing what the build system is meant to be doing and you shouldn't be putting composer.lock in VCS. Composer might strangely have it backwards. End users rather than produces shouldn't be using lock files. Usually your build system keeps snapshots, reusable dirs, etc rather than an empty dir each time. People checkout out a lib from composer might want that lib to use a lock so that the dependencies that lib loads have been tested against.
On the other hand that significantly increases the burden of version management, where you'd almost certainly want multiple versions of every library as dependencies will be strictly locked. If every library is likely to have a slightly different version then you need some multiple library version support and you can also quickly see the size of dependencies needed flair out, hence the advise to keep it on the leaf.
Taking that on board, I really don't find lock files to be useful either libraries or your own workdirs. It's only use for me is in my build/testing platform which persists any externally acquired assets only updating them when requested, providing repeatable builds for testing, build and deploy. While that can be kept in VCS it's not always kept with the source tree, the build trees will either be elsewhere in the VCS structure or managed by another system somewhere else. If it's stored in a VCS it's debatable whether or not to keep it in the same repo as source trees because otherwise every pull can bring in a mass of build assets. I quite like having things all in a well arranged repo with the exception of production/sensitive credentials and bloat.
SVN can do it better than git as it doesn't force you to acquire the entire repo (though I suspect that's not actually strictly needed for git either but support for that is limited and it's not commonly used). Simple build repos are usually just an overlay branch you merge/export the build tree into. Some people combine exernal resources in their source tree or separate further, external, build and source trees. It usually serves two purposes, build caching and repeatable builds but sometimes keeping it separate on at least some level also permits fresh/blank builds and multiple builds easily.
There are a number of strategies for this and none of them particularly work well with persisting the sources list unless you're keeping external source in your source tree.
They also have things like hashes in of the file, how do that merge when two people update packages? That alone should make you think maybe this is misconstrued.
The arguments people are putting forward for lock files are cases where they've taken a very specific and restrictive view of the problem. Want repeatable builds and consistent builds? Include the vendor folder in VCS. Then you also speed up fetching assets as well as not having to depend on potentially broken external resources during build. None of the build and deploy pipelines I create require external access unless absolutely necessary. If you do have to update an external resource it's once and only once. What composer is trying to achieve makes sense for a distributed system except as mentioned before it makes no sense because it would end up with library dependency hell for library updates with common clashes and updates being as slow as the slowest to update package.
Additionally I update ferociously. Every time I develop I update and test everything. There's a very very tiny window for significant version drift to sneak in. Realistically as well, when semantic versioning is upheld, which is tends to be for composer, you're not suppose to have that many compatibility issues or breakages.
In composer.json you put the packages you require and their versions. You can lock the versions there. However those packages also have dependencies with dynamic versions that wont be locked by composer.json (though I don't see why your couldn't also put them there yourself if you do want them to be version locked) so someone else running composer install gets something different without the lock. You might not care a great deal about that or you might care, it depends. Should you care? Probably at least a little, enough to ensure you're aware of it in any situation and potential impact, but it might not be a problem either if you always have the time to just DRY run first and fix anything that got updated.
The hassle composer is trying to avoid sometimes just isn't there and the hassle having composer lock files can make is significant. They have absolutely no right to tell users what they should or shouldn't do regarding build versus source assets (whether to join of separate in VCS) as that's none of their business, they're not the boss of you or me. "Composer says" isn't an authority, they're not your superior officer nor do they give anyone any superiority on this subject. Only you know your real situation and what's best for that. However, they might advise a default course of action for users that don't understand how things work in which case you might want to follow that but personally I don't think that's a real substitute for knowing how things work and being able to properly workout your requirements. Ultimately, their answer to that question is a best guess. The people who make composer do not know where you should keep your composer.lock nor should they. Their only responsibility is to tell you what it is and what it does. Outside of that you need to decide what's best for you.
Keeping the lock file in is problematic for usability because composer is very secretive about whether it uses lock or JSON and doesn't always to well to use both together. If you run install it only uses the lock file it would appear so if you add something to composer.json then it wont be installed because it's not in your lock. It's not intuitive at all what operations really do and what they're doing in regards to the json/lock file and sometimes don't appear to even make sense (help says install takes a package name but on trying to use it it says no).
To update the lock or basically apply changes from the json you have to use update and you might not want to update everything. The lock takes precedence for choosing what should be installed. If there's a lock file, it's what's used. You can restrict update somewhat but the system is still just a mess.
Updating takes an age, gigs of RAM. I suspect as well if you pick up a project that's not been touched for a while that it looked from the versions it has up, which there will be more of over time and it probably doesn't do that efficiently which just strangles it.
They're very very sneaky when it comes to having secret composite commands you couldn't expect to be composite. By default the composer remove command appears to maps to composer update and composer remove for example.
The question you really need to be asking is not if you should keep the lock in your source tree or alternatively whether you should persist it somewhere in some fashion or not but rather you should be asking what it actually does, then you can decide for yourself when you need to persist it and where.
I will point out that having the ability to have the lock is a great convenience when you have a robust external dependency persistence strategy as it keeps track of you the information useful for tracking that (the origins) and updating it but if you don't then it's neither here not there. It's not useful when it's forced down your throat as a mandatory option to have it polluting your source trees. It's a very common thing to find in legacy codebases where people have made lots of changes to composer.json which haven't really been applied and are broken when people try to use composer. No composer.lock, no desync problem.
Do you mean something like this?
In [39]: df2.pivot_table(values='X', rows='Y', cols='Z',
aggfunc=lambda x: len(x.unique()))
Out[39]:
Z Z1 Z2 Z3
Y
Y1 1 1 NaN
Y2 NaN NaN 1
Note that using len
assumes you don't have NA
s in your DataFrame. You can do x.value_counts().count()
or len(x.dropna().unique())
otherwise.
Or, written in one line:
std::cout << std::distance(sampleArray.begin(),std::max_element(sampleArray.begin(), sampleArray.end()));
if you do not want to be bothered by the date format, you could compare the column with the general date format, for example
select *
From table
where cast (RegistrationDate as date) between '20161201' and '20161220'
make sure the date is in DATE format, otherwise cast (col as DATE)
No, there's no direct not operator. At least not the way you hope for.
You can use a zero-width negative lookahead, however:
\((?!2001)[0-9a-zA-z _\.\-:]*\)
The (?!...)
part means "only match if the text following (hence: lookahead) this doesn't (hence: negative) match this. But it doesn't actually consume the characters it matches (hence: zero-width).
There are actually 4 combinations of lookarounds with 2 axes:
Here is example how you can do localization without some extra library.
jQuery(function($) {_x000D_
$('input.datetimepicker').datepicker({_x000D_
duration: '',_x000D_
changeMonth: false,_x000D_
changeYear: false,_x000D_
yearRange: '2010:2020',_x000D_
showTime: false,_x000D_
time24h: true_x000D_
});_x000D_
_x000D_
$.datepicker.regional['cs'] = {_x000D_
closeText: 'Zavrít',_x000D_
prevText: '<Dríve',_x000D_
nextText: 'Pozdeji>',_x000D_
currentText: 'Nyní',_x000D_
monthNames: ['leden', 'únor', 'brezen', 'duben', 'kveten', 'cerven', 'cervenec', 'srpen',_x000D_
'zárí', 'ríjen', 'listopad', 'prosinec'_x000D_
],_x000D_
monthNamesShort: ['led', 'úno', 'bre', 'dub', 'kve', 'cer', 'cvc', 'srp', 'zár', 'ríj', 'lis', 'pro'],_x000D_
dayNames: ['nedele', 'pondelí', 'úterý', 'streda', 'ctvrtek', 'pátek', 'sobota'],_x000D_
dayNamesShort: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
dayNamesMin: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
weekHeader: 'Týd',_x000D_
dateFormat: 'dd/mm/yy',_x000D_
firstDay: 1,_x000D_
isRTL: false,_x000D_
showMonthAfterYear: false,_x000D_
yearSuffix: ''_x000D_
};_x000D_
_x000D_
$.datepicker.setDefaults($.datepicker.regional['cs']);_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link data-require="jqueryui@*" data-semver="1.10.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" />_x000D_
<script data-require="jqueryui@*" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>_x000D_
<script src="datepicker-cs.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
console.log("test");_x000D_
$("#test").datepicker({_x000D_
dateFormat: "dd.m.yy",_x000D_
minDate: 0,_x000D_
showOtherMonths: true,_x000D_
firstDay: 1_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>Here is your datepicker</h1>_x000D_
<input id="test" type="text" />_x000D_
</body>_x000D_
</html>
_x000D_
Luckily git stash pop
does not change the stash in the case of a conflict!
So nothing, to worry about, just clean up your code and try it again.
Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop
again and you get the same stash, that conflicted before.
Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.
The main difference when working on arrays is that array_key_exists
returns true
when the value is null
, while isset
will return false
when the array value is set to null
.
See isset on the PHP documentation site.
id
is the method you want to use: to convert it to hex:
hex(id(variable_here))
For instance:
x = 4
print hex(id(x))
Gave me:
0x9cf10c
Which is what you want, right?
(Fun fact, binding two variables to the same int
may result in the same memory address being used.)
Try:
x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))
This gave me identical pairs, even for the large integers.
Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:
git reset
This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run
git add -p
which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached
), you can commit, and then
git reset --hard
to destroy all the unwanted changes in your working directory.
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
It looks like you're using the wrong tool there. Grep isn't that sophisticated, I think you want to step up to awk as the tool for the job:
awk '/blah/ { getline; print $0 }' logfile
If you get any problems let me know, I think its well worth learning a bit of awk, its a great tool :)
p.s. This example doesn't win a 'useless use of cat award' ;) http://porkmail.org/era/unix/award.html
I know the topic is old, but I just fell on it after a google search so... here is another solution:
$array_merged = array_merge($array_going_first, $array_going_second);
This one seems pretty clean to me, it works just fine!
Yup! That's very straight forward and that's where the package strategy comes into play. there are three ways to my knowledge. folder structure:
GOPATH/src/ github.com/ abc/ myproject/ adapter/ main.go pkg1 pkg2 warning: adapter can contain package main only and sun directories
go build main.go
go build main.go
go build myproject/adapter
exe file will be created at the directory you are currently at.
Interpreted language is executed at the run time according to the instructions like in shell scripting and compiled language is one which is compiled (changed into Assembly language, which CPU can understand ) and then executed like in c++.
Before doing so please read this other question too:
android.os.Process.killProcess(android.os.Process.myPid());
EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'
; worked for me.
closing the varchar
/string
with two pairs of single quotes did the trick. Other option could be to use using
keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'
; Remember using
keyword will not work, if you are using EXECUTE IMMEDIATE
to execute DDL's with parameters, however, using quotes will work for DDL's.
copy the column paste it into notepad copy it again paste special as Text
First to answer your question, you set a variable to true or false by assigning True
or False
to it:
myFirstVar = True
myOtherVar = False
If you have a condition that is basically like this though:
if <condition>:
var = True
else:
var = False
then it is much easier to simply assign the result of the condition directly:
var = <condition>
In your case:
match_var = a == b
Just eliminate the word "User". It will work.
Go to Tools >> Preferences >> IPython console >> Graphics >> Backend:Inline, change "Inline" to "Automatic", click "OK"
Reset the kernel at the console, and the plot will appear in a separate window
I want to say something about the "G" status,
G: Changes on the repo were automatically merged into the working copy
I think the above definition is not cleary, it can generate a little confusion, because all files are automatically merged in to working copy, the correct one should be:
U = item (U)pdated to repository version
G = item’s local changes mer(G)ed with repository
C = item’s local changes (C)onflicted with repository
D = item (D)eleted from working copy
A = item (A)dded to working copy
If lists always have the same structure, as in the example, then a simpler solution is
mapply(c, first, second, SIMPLIFY=FALSE)
Not necessarily better, but since it's nice to have options here's how to do it using Jinja statements:
- debug:
msg: "{% for address in network.addresses.private_man %}\
{% if address.type == 'fixed' %}\
{{ address.addr }}\
{% endif %}\
{% endfor %}"
Or if you prefer to put it all on one line:
- debug:
msg: "{% for address in network.addresses.private_man if address.type == 'fixed' %}{{ address.addr }}{% endfor %}"
Which returns:
ok: [localhost] => {
"msg": "172.16.1.100"
}
I had similar problem it was caused by MS UNIT Test DLL. My WPF application was compiled as x86 but unit test DLL (referenced EXE file) as "Any CPU". I changed unit test DLL to be compiled for x86 (same as EXE) and it was resovled.
You can do :
1) javac -cp /path/to/jar/file Myprogram.java
2) java -cp .:/path/to/jar/file Myprogram
So, lets suppose your current working directory
in terminal is src/Report/
javac -cp src/external/myfile.jar Reporter.java
java -cp .:src/external/myfile.jar Reporter
Take a look here to setup Classpath
Here is an answer: http://www.dba-oracle.com/concepts/synonyms.htm
An Oracle synonym basically allows you to create a pointer to an object that exists somewhere else. You need Oracle synonyms because when you are logged into Oracle, it looks for all objects you are querying in your schema (account). If they are not there, it will give you an error telling you that they do not exist.
Escape characters are dependent on whatever system is interpreting them. \n
is interpreted as a newline character by many programming languages, but that doesn't necessarily hold true for the other utilities you mention. Even if they do treat \n
as newline, there may be some other techniques to get them to behave how you want. You would have to consult their documentation (or see other answers here).
For DOS/Windows systems, the newline is actually two characters: Carriage Return (ASCII 13, AKA \r
), followed by Line Feed (ASCII 10). On Unix systems (including Mac OSX) it's just Line Feed. On older Macs it was a single Carriage Return.
Here's a suggestion for getting the first and last days of the week for a month:
-- Build a temp table with all the dates of the month
drop table #tmp_datesforMonth
go
declare @begDate datetime
declare @endDate datetime
set @begDate = '6/1/13'
set @endDate = '6/30/13';
WITH N(n) AS
( SELECT 0
UNION ALL
SELECT n+1
FROM N
WHERE n <= datepart(dd,@enddate)
)
SELECT DATEADD(dd,n,@BegDate) as dDate
into #tmp_datesforMonth
FROM N
WHERE MONTH(DATEADD(dd,n,@BegDate)) = MONTH(@BegDate)
--- pull results showing the weeks' dates and the week # for the month (not the week # for the current month)
select MIN(dDate) as BegOfWeek
, MAX(dDate) as EndOfWeek
, datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, dDate), 0)), 0), dDate) as WeekNumForMonth
from #tmp_datesforMonth
group by datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, dDate), 0)), 0), dDate)
order by 3, 1
Use this code if you have nested objects or if you have nested array obj.
var sortObjectByKey = function(obj){
var keys = [];
var sorted_obj = {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
keys.push(key);
}
}
// sort keys
keys.sort();
// create new array based on Sorted Keys
jQuery.each(keys, function(i, key){
var val = obj[key];
if(val instanceof Array){
//do for loop;
var arr = [];
jQuery.each(val,function(){
arr.push(sortObjectByKey(this));
});
val = arr;
}else if(val instanceof Object){
val = sortObjectByKey(val)
}
sorted_obj[key] = val;
});
return sorted_obj;
};
A. Make sure your other activity is declared in manifest:
<activity
android:name="MyOtherActivity"
android:label="@string/app_name">
</activity>
All activities must be declared in manifest, even if they do not have an intent filter assigned to them.
B. In your MainActivity do something like this:
Button btn = (Button)findViewById(R.id.open_activity_button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
}
});
This should work for any table, instead of hard-coding the columns.
//Source details_x000D_
String sourceUrl = "jdbc:oracle:thin:@//server:1521/db";_x000D_
String sourceUserName = "src";_x000D_
String sourcePassword = "***";_x000D_
_x000D_
// Destination details_x000D_
String destinationUserName = "dest";_x000D_
String destinationPassword = "***";_x000D_
String destinationUrl = "jdbc:mysql://server:3306/db";_x000D_
_x000D_
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);_x000D_
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);_x000D_
_x000D_
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");_x000D_
ResultSet rs = sourceStatement.executeQuery();_x000D_
rs.setFetchSize(1000); // not needed_x000D_
_x000D_
_x000D_
ResultSetMetaData meta = rs.getMetaData();_x000D_
_x000D_
_x000D_
_x000D_
List<String> columns = new ArrayList<>();_x000D_
for (int i = 1; i <= meta.getColumnCount(); i++)_x000D_
columns.add(meta.getColumnName(i));_x000D_
_x000D_
try (PreparedStatement destStatement = destConnection.prepareStatement(_x000D_
"INSERT INTO dest_table ("_x000D_
+ columns.stream().collect(Collectors.joining(", "))_x000D_
+ ") VALUES ("_x000D_
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))_x000D_
+ ")"_x000D_
)_x000D_
)_x000D_
{_x000D_
int count = 0;_x000D_
while (rs.next()) {_x000D_
for (int i = 1; i <= meta.getColumnCount(); i++) {_x000D_
destStatement.setObject(i, rs.getObject(i));_x000D_
}_x000D_
_x000D_
destStatement.addBatch();_x000D_
count++;_x000D_
}_x000D_
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed_x000D_
System.out.println("done " + count);_x000D_
_x000D_
}
_x000D_
If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.
The innerHtml property did not work for me. So I experimented with ...
<div id=successAndErrorMessages-1>100% OK</div>
<div id=successAndErrorMessages-2>This is an error mssg!</div>
and toggled one of the two on/off ...
$("#successAndErrorMessages-1").css('display', 'none')
$("#successAndErrorMessages-2").css('display', '')
For some reason I had to fiddle around with the ordering before it worked in all types of browsers.
How about?
while BoolIter(N, default=True, falseIndex=N-1):
print 'some thing'
or in a more ugly way:
for _ in BoolIter(N):
print 'doing somthing'
or if you want to catch the last time through:
for lastIteration in BoolIter(N, default=False, trueIndex=N-1):
if not lastIteration:
print 'still going'
else:
print 'last time'
where:
class BoolIter(object):
def __init__(self, n, default=False, falseIndex=None, trueIndex=None, falseIndexes=[], trueIndexes=[], emitObject=False):
self.n = n
self.i = None
self._default = default
self._falseIndexes=set(falseIndexes)
self._trueIndexes=set(trueIndexes)
if falseIndex is not None:
self._falseIndexes.add(falseIndex)
if trueIndex is not None:
self._trueIndexes.add(trueIndex)
self._emitObject = emitObject
def __iter__(self):
return self
def next(self):
if self.i is None:
self.i = 0
else:
self.i += 1
if self.i == self.n:
raise StopIteration
if self._emitObject:
return self
else:
return self.__nonzero__()
def __nonzero__(self):
i = self.i
if i in self._trueIndexes:
return True
if i in self._falseIndexes:
return False
return self._default
def __bool__(self):
return self.__nonzero__()
I had the same issue today. The only thing that worked for me was to explicitly login to "docker.io":
docker login docker.io
I tried various other names, and the login would appear to work, but it would later result in the following error.
requested access to the resource is denied
You can use pageshow
event to handle situation when browser navigates to your page through history traversal:
window.addEventListener( "pageshow", function ( event ) {
var historyTraversal = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( historyTraversal ) {
// Handle page restore.
window.location.reload();
}
});
Note that HTTP cache may be involved too. You need to set proper cache related HTTP headers on server to cache only those resources that need to be cached. You can also do forced reload to instuct browser to ignore HTTP cache: window.location.reload( true )
. But I don't think that it is best solution.
For more information check:
You can use regular expressions to get the occurrences:
>>> import re
>>> print(re.findall(r'( |t)', to_search_in)) # searches for t or space
['t', ' ', 't', ' ', ' ']
A rewrite of the answer by Sarfraz would be something like this, I think:
<script>
document.getElementById('change').onclick = changeColor;
function changeColor() {
document.body.style.color = "purple";
return false;
}
</script>
You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );
Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc();
the function would actually execute when the handler is being set.
And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)
I Usually go for 422 (Unprocessable entity) if something in the required parameters didn't match what the API endpoint required (like a too short password) but for a missing parameter i would go for 406 (Unacceptable).
For having hover effect you can simply try this code
import React from "react";
import "./styles.css";
export default function App() {
function MouseOver(event) {
event.target.style.background = 'red';
}
function MouseOut(event){
event.target.style.background="";
}
return (
<div className="App">
<button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
</div>
);
}
Or if you want to handle this situation using useState() hook then you can try this piece of code
import React from "react";
import "./styles.css";
export default function App() {
let [over,setOver]=React.useState(false);
let buttonstyle={
backgroundColor:''
}
if(over){
buttonstyle.backgroundColor="green";
}
else{
buttonstyle.backgroundColor='';
}
return (
<div className="App">
<button style={buttonstyle}
onMouseOver={()=>setOver(true)}
onMouseOut={()=>setOver(false)}
>Hover over me!</button>
</div>
);
}
Both of the above code will work for hover effect but first procedure is easier to write and understand
if you are not using model as per your question you can do like this
@Html.Hidden("hdnFlag" , new {id = "hdnFlag", value = "hdnFlag_value" })
else if you are using model (considering passing model has hdnFlag property), you can use this approch
@Html.HiddenFor(model => model.hdnFlag, new { value = Model.hdnFlag})
Starting with Google Play 4.9, the app info display has been changed and the promo graphic is displayed at the top.
The promo graphic will be required soon.
The promo text has turned into a short description and is now shown on the main info page, before the user presses it to view the full description.
try changing that line-height change to a margin-top or padding-top change instead
#btnhome:active{
margin-top : 25px;
}
Edit: You could also try adding a span inside the button
<div id="header">
<button id="btnhome"><span>Home</span></button>
<button id="btnabout">About</button>
<button id="btncontact">Contact</button>
<button id="btnsup">Help Us</button>
</div>
Then style that
#btnhome span:active { padding-top:25px;}
You can try Out this Custom AGTableView
To Set a TableView Height Constraint Using storyboard or programmatically. (This class automatically fetch a height constraint and set content view height to yourtableview height).
class AGTableView: UITableView {
fileprivate var heightConstraint: NSLayoutConstraint!
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.associateConstraints()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.associateConstraints()
}
override open func layoutSubviews() {
super.layoutSubviews()
if self.heightConstraint != nil {
self.heightConstraint.constant = self.contentSize.height
}
else{
self.sizeToFit()
print("Set a heightConstraint to Resizing UITableView to fit content")
}
}
func associateConstraints() {
// iterate through height constraints and identify
for constraint: NSLayoutConstraint in constraints {
if constraint.firstAttribute == .height {
if constraint.relation == .equal {
heightConstraint = constraint
}
}
}
}
}
Note If any problem to set a Height then yourTableView.layoutSubviews()
.
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
In Windows 10, I had to run the windows command prompt (cmd) as administrator. Doing that solved this problem for me.
Converting a date String of the format "2011-06-23T15:11:32" to our time zone.
private String getDate(String ourDate)
{
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(ourDate);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy HH:mm"); //this format changeable
dateFormatter.setTimeZone(TimeZone.getDefault());
ourDate = dateFormatter.format(value);
//Log.d("ourDate", ourDate);
}
catch (Exception e)
{
ourDate = "00-00-0000 00:00";
}
return ourDate;
}
Since .NET 4.7.1, you can use the side-effect free Prepend()
and Append()
. The output is going to be an IEnumerable.
// Creating an array of numbers
var ti = new List<int> { 1, 2, 3 };
// Prepend and Append any value of the same type
var results = ti.Prepend(0).Append(4);
// output is 0, 1, 2, 3, 4
Console.WriteLine(string.Join(", ", results ));
Try this code.
For showing Softkeyboard:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
For Hiding SoftKeyboard -
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
The easiest way I have found to do this is to just use require
and the path to your JSON file.
For example, suppose you have the following JSON file.
test.json
{
"firstName": "Joe",
"lastName": "Smith"
}
You can then easily load this in your node.js application using require
var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);
break
interacts solely with the closest enclosing loop or switch, whether it be a for
, while
or do .. while
type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:
for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:
while (B) D; // Simply doesn't have A or C
do { D; } while (B); // Omits initial goto test
continue; // goto iter;
break; // goto end;
The difference is, continue
and break
interact with virtual labels automatically placed by the compiler. This is similar to what return
does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.
The programming error the notice refers to is misunderstanding break
as interacting with an enclosing block rather than an enclosing loop. Consider:
for (A; B; C) {
D;
if (E) {
F;
if (G) break; // Incorrectly assumed to break if(E), breaks for()
H;
}
I;
}
J;
Someone thought, given such a piece of code, that G
would cause a jump to I
, but it jumps to J
. The intended function would use if (!G) H;
instead.
In the build.gradle(Module:app) file, insert the code below into defaultConfig :
defaultConfig {
applicationId "com.***.****"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
multiDexEnabled true
}
and insert into to dependencies :
implementation 'com.android.support:multidex:2.0.1'
Then add code to manifest :
<application
android:name="android.support.multidex.MultiDexApplication"
I found the solution Do change in your cordovaLib file build.gradle file
dependencies { classpath 'com.android.tools.build:gradle:3.1.0' }
and now make changes in you,
platforms\android\gradle\wrapper\gradle-wrapper.properties
distributionUrl=\
https://services.gradle.org/distributions/gradle-4.4-all.zip
this works for.
Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.
There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.
If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.
Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh
after the last command of st_new.sh
has finished.
Now there is a special command which messes this up: &
cmd &
means: "Start a new background process and execute cmd
in it. After starting the background process, immediately continue with the next command in the script."
That means &
doesn't wait for cmd
to do it's work. My guess is that st_new.sh
contains such a command. If that is the case, then you need to modify the script:
cmd &
BACK_PID=$!
This puts the process ID (PID) of the new background process in the variable BACK_PID
. You can then wait for it to end:
while kill -0 $BACK_PID ; do
echo "Process is still active..."
sleep 1
# You can add a timeout here if you want
done
or, if you don't want any special handling/output simply
wait $BACK_PID
Note that some programs automatically start a background process when you run them, even if you omit the &
. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's &
command instead to get the PID.
I would suggest using the String.Compare method. Using that method you can also control whether to to have it perform case-sensitive comparisons or not.
Sample:
Dim str1 As String = "String one"
Dim str2 As String = str1
Dim str3 As String = "String three"
Dim str4 As String = str3
If String.Compare(str1, str2) = 0 And String.Compare(str3, str4) = 0 Then
MessageBox.Show("str1 = str2 And str3 = str4")
Else
MessageBox.Show("Else")
End If
Edit: if you want to perform a case-insensitive search you can use the StringComparison parameter:
If String.Compare(str1, str2, StringComparison.InvariantCultureIgnoreCase) = 0 And String.Compare(str3, str4, StringComparison.InvariantCultureIgnoreCase) = 0 Then
.container {
height: 200px;
width: 500px;
display: -moz-box;
display: -webkit-flexbox;
display: -ms-flexbox;
display: -webkit-flex;
display: -moz-flex;
display: flex;
-webkit-flex-direction: row;
-moz-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
}
.flex-1 {
flex:1 0 100px;
background-color: blue;
}
.flex-2 {
-moz-box-flex: 1;
-webkit-flex: 1;
-moz-flex: 1;
-ms-flex: 1;
flex: 1 0 100%;
background-color: red;
}
.flex-2-child {
flex: 1 0 100%;
height: 100%;
background-color: green;
}
_x000D_
<div class="container">
<div class="flex-1"></div>
<div class="flex-2">
<div class="flex-2-child"></div>
</div>
</div>
_x000D_
git pull origin master
will pull changes from the origin
remote, master
branch and merge them to the local checked-out branch.
git pull origin/master
will pull changes from the locally stored branch origin/master
and merge that to the local checked-out branch. The origin/master
branch is essentially a "cached copy" of what was last pulled from origin
, which is why it's called a remote branch in git parlance. This might be somewhat confusing.
You can see what branches are available with git branch
and git branch -r
to see the "remote branches".
use this code this might help you to get tab like behaviour when user presses enter
Private Sub TxtSearch_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TxtSearch.KeyPress
Try
If e.KeyChar = Convert.ToChar(13) Then
nexttextbox.setfoucus
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This will return the timestamp in UTC:
var utc = new Date(new Date().toUTCString()).getTime();
_x000D_
Put
compile 'com.google.zxing:core:2.3.0'
into your Gradle dependencies. As easy as that. Prior to using Android Studio and Gradle build system.
Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.
function getUserHome() {
return process.env.HOME || process.env.USERPROFILE;
}
EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()
).
in viewDidLoad add this line
yourUiTextField.becomeFirstResponder()
static void Main(string[] args)
{
Console.WriteLine("geef een leeftijd");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("geef een leeftijd");
int b = Convert.ToInt32(Console.ReadLine());
int einde = Sum(a, b);
Console.WriteLine(einde);
}
static int Sum(int x, int y)
{
int result = x + y;
return result;
this.getClass().getClassLoader().getResource("").getPath()
I prefer using Hamcrest because it gives much better output in case of a failure
Assert.assertThat(listUnderTest,
IsIterableContainingInOrder.contains(expectedList.toArray()));
Instead of reporting
expected true, got false
it will report
expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."
IsIterableContainingInOrder.contain
According to the Javadoc:
Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items
So the listUnderTest
must have the same number of elements and each element must match the expected values in order.
You could get the first element in the array_keys()
function as well. Or array_search()
the keys for the "index" of a key. If you are inside a foreach
loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.
<?php
$array = array('test', '1', '2');
$keys = array_keys($array);
var_dump($keys[0]); // int(0)
$array = array('test'=>'something', 'test2'=>'something else');
$keys = array_keys($array);
var_dump(array_search("test2", $keys)); // int(1)
var_dump(array_search("test3", $keys)); // bool(false)
In Python 2.7 adding this to the end of my py file (if __name__ == '__main__':
) works:
closeInput = raw_input("Press ENTER to exit")
print "Closing..."
If you open your resource file and change the access modifier to public or internal it will generate a class from your resource file which allows you to create strongly typed resource references.
Which means you can do something like this instead (using C# 6.0). Then you dont have to remember if firstname was lowercased or camelcased. And you can see if other properties use the same resource value with a find all references.
[Display(Name = nameof(PropertyNames.FirstName), ResourceType = typeof(PropertyNames))]
public string FirstName { get; set; }
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
I would use a change event not a click like this:
$('input[name="name-of-radio-group"]').change( function() {
alert($(this).val())
})
Note: This question is related to the jQuery form plugin. If you are searching for a pure jQuery solution, start here. There is no overall jQuery solution for all browser. So you have to use a plugin. I am using dropzone.js, which have an easy fallback for older browsers. Which plugin you prefer depends on your needs. There are a lot of good comparing post out there.
From the examples:
jQuery:
$(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
html:
<form action="file-echo2.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
you have to style the progressbar with css...
The problem is with sprintf
sprintf(aa,"%lf",a);
%lf says to interpet "a" as a "long double" (16 bytes) but it is actually a "double" (8 bytes). Use this instead:
sprintf(aa, "%f", a);
More details here on cplusplus.com
not sure if it works outside of firefox:
callback (event){
if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
// do something
}
}
if not, replace event.DOM_VK_BACK_SPACE
with 8
and event.DOM_VK_DELETE
with 46
or define them as constant (for better readability)
Just for the sake of completeness you can just take the wanted data type and add brackets with the number of elements like so:
x <- character(10)
No.
It's generally more useful to learn C++ because it's closer to the most modern OO-based languages, like Eiffel or C#.
If your goal is to learn C++, learn modern, standard C++ in the first place. Leave the mallocs aside.
But Steve Rowe has a point...
This should do the job
//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");
//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
read.csv
without the url
function just works fine. Probably I am missing something if Dirk Eddelbuettel included it in his answer:
ad <- read.csv("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(ad)
X TV radio newspaper sales
1 1 230.1 37.8 69.2 22.1
2 2 44.5 39.3 45.1 10.4
3 3 17.2 45.9 69.3 9.3
4 4 151.5 41.3 58.5 18.5
5 5 180.8 10.8 58.4 12.9
6 6 8.7 48.9 75.0 7.2
Another options using two popular packages:
library(data.table)
ad <- fread("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(ad)
V1 TV radio newspaper sales
1: 1 230.1 37.8 69.2 22.1
2: 2 44.5 39.3 45.1 10.4
3: 3 17.2 45.9 69.3 9.3
4: 4 151.5 41.3 58.5 18.5
5: 5 180.8 10.8 58.4 12.9
6: 6 8.7 48.9 75.0 7.2
library(readr)
ad <- read_csv("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(ad)
# A tibble: 6 x 5
X1 TV radio newspaper sales
<int> <dbl> <dbl> <dbl> <dbl>
1 1 230.1 37.8 69.2 22.1
2 2 44.5 39.3 45.1 10.4
3 3 17.2 45.9 69.3 9.3
4 4 151.5 41.3 58.5 18.5
5 5 180.8 10.8 58.4 12.9
6 6 8.7 48.9 75.0 7.2
Depending on what you're doing in the loop, the fact that the %in%
operator returns a vector might be an issue; consider a simple example:
c1 <- c("one","two","three","more","more")
c2 <- c("seven","five","three")
if(c1%in%c2) {
print("hello")
}
then the following warning is issued:
Warning message:
In if (c1 %in% c2) { :
the condition has length > 1 and only the first element will be used
if something in your if statement is dependent on a specific number of elements, and they don't match, then it is possible to obtain the error you see
You are using prettyfaces too? Then set dispatcher to FORWARD:
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
For a new project select the home directory of the jdk
eg C:\Java\jdk1.7.0_99
or C:\Program Files\Java\jdk1.7.0_99
For an existing project.
1) You need to have a jdk
installed on the system.
for instance in
C:\Java\jdk1.7.0_99
2) go to project structure
under File
menu ctrl+alt+shift+S
3) SDKs
is located under Platform Settings
. Select it.
4) click the green +
up the top of the window.
5) select JDK
(I have to use keyboard to select it do not know why).
select the home directory for your jdk installation.
should be good to go.
What you could do is copy the code from tkinter.py
into a file called mytkinter.py
, then do this code:
import tkinter, mytkinter
root = tkinter.Tk()
window = mytkinter.Tk()
button = mytkinter.Button(window, text="Search", width = 7,
command=cmd)
button2 = tkinter.Button(root, text="Search", width = 7,
command=cmdtwo)
And you have two windows which don't collide!
From R 3.0.0 onwards mean(<data.frame>)
is defunct (and passing a data.frame to mean
will give the error you state)
A data frame is a list of variables of the same number of rows with unique row names, given class "data.frame".
In your case, result has two variables (if your description is correct) . You could obtain the column means by using any of the following
lapply(results, mean, na.rm = TRUE)
sapply(results, mean, na.rm = TRUE)
colMeans(results, na.rm = TRUE)
Newer versions: (from 8.4 - mentioned in release notes)
TABLE mytablename;
Longer but works on all versions:
SELECT * FROM mytablename;
You may wish to use \x
first if it's a wide table, for readability.
For long data:
SELECT * FROM mytable LIMIT 10;
or similar.
For wide data (big rows), in the psql
command line client, it's useful to use \x
to show the rows in key/value form instead of tabulated, e.g.
\x
SELECT * FROM mytable LIMIT 10;
Note that in all cases the semicolon at the end is important.
What is the synchronized keyword?
Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.
Synchronized blocks or methods prevents thread interference and make sure that data is consistent. At any point of time, only one thread can access a synchronized block or method (critical section) by acquiring a lock. Other thread(s) will wait for release of lock to access critical section.
When are methods synchronized?
Methods are synchronized when you add synchronized
to method definition or declaration. You can also synchronize a particular block of code with-in a method.
What does it mean pro grammatically and logically?
It means that only one thread can access critical section by acquiring a lock. Unless this thread release this lock, all other thread(s) will have to wait to acquire a lock. They don't have access to enter critical section with out acquiring lock.
This can't be done with a magic. It's programmer responsibility to identify critical section(s) in application and guard it accordingly. Java provides a framework to guard your application, but where and what all sections to be guarded is the responsibility of programmer.
More details from java documentation page
Intrinsic Locks and Synchronization:
Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them.
A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock.
Making methods synchronized has two effects:
First, it is not possible for two invocations of synchronized methods on the same object to interleave.
When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object.
This guarantees that changes to the state of the object are visible to all threads.
Look for other alternatives to synchronization in :
In my case, I've had to click on my project, then go to File
> Properties
> *servlet name*
and click Restart servlet
.
I think you can use REGEXP instead of LIKE
SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')
I got the error with a space in a Sheet Name:
using (var range = _excelApp.Range["Sheet Name Had Space!$A$1"].WithComCleanup())
I fixed it by putting single quotes around Sheet Names with spaces:
using (var range = _excelApp.Range["'Sheet Name Had Space'!$A$1"].WithComCleanup())
This code will not work (throw an error when clicked):
$timeout(function() {
angular.element('#btn2').triggerHandler('click');
});
You need to use the querySelector as follows:
$timeout(function() {
angular.element(document.querySelector('#btn2')).triggerHandler('click');
});
I know others have answered this already. But a very important factor here that may help other people experiencing similar issue:
You must have an onChange
handler added in your input field (e.g. textField, checkbox, radio, etc). Always handle activity through the onChange
handler.
Example:
<input ... onChange={ this.myChangeHandler} ... />
When you are working with checkbox you may need to handle its checked
state with !!
.
Example:
<input type="checkbox" checked={!!this.state.someValue} onChange={.....} >
Reference: https://github.com/facebook/react/issues/6779#issuecomment-326314716
It's actually a sensible question. Here's the answer from Excel 2010 help:
"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."
So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:
Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")
Obviously, you'll need a rooted android device. Then set up an FTP server and transfer the files.
1) Remember the main reason to separate .h and .cpp files is to hide the class implementation as a separately-compiled Obj code that can be linked to the user’s code that included a .h of the class.
2) Non-template classes have all variables concretely and specifically defined in .h and .cpp files. So the compiler will have the need information about all data types used in the class before compiling/translating ? generating the object/machine code Template classes have no information about the specific data type before the user of the class instantiate an object passing the required data type:
TClass<int> myObj;
3) Only after this instantiation, the complier generate the specific version of the template class to match the passed data type(s).
4) Therefore, .cpp Can NOT be compiled separately without knowing the users specific data type. So it has to stay as source code within “.h” until the user specify the required data type then, it can be generated to a specific data type then compiled
Your way is correct, and here is another way you can do it:
update Table1
set Description = t2.Description
from Table1 t1
inner join Table2 t2
on t1.DescriptionID = t2.ID
The nested select is the long way of just doing a join.
If you use the gson.JsonObject you can have something like that:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)
You can write your own WriteLine method-
public static void WriteLine<T>(T obj)
{
var t = typeof(T);
var props = t.GetProperties();
StringBuilder sb = new StringBuilder();
foreach (var item in props)
{
sb.Append($"{item.Name}:{item.GetValue(obj,null)}; ");
}
sb.AppendLine();
Console.WriteLine(sb.ToString());
}
Use it like-
WriteLine(myObject);
To write a collection we can use-
var ifaces = t.GetInterfaces();
if (ifaces.Any(o => o.Name.StartsWith("ICollection")))
{
dynamic lst = t.GetMethod("GetEnumerator").Invoke(obj, null);
while (lst.MoveNext())
{
WriteLine(lst.Current);
}
}
The method may look like-
public static void WriteLine<T>(T obj)
{
var t = typeof(T);
var ifaces = t.GetInterfaces();
if (ifaces.Any(o => o.Name.StartsWith("ICollection")))
{
dynamic lst = t.GetMethod("GetEnumerator").Invoke(obj, null);
while (lst.MoveNext())
{
WriteLine(lst.Current);
}
}
else if (t.GetProperties().Any())
{
var props = t.GetProperties();
StringBuilder sb = new StringBuilder();
foreach (var item in props)
{
sb.Append($"{item.Name}:{item.GetValue(obj, null)}; ");
}
sb.AppendLine();
Console.WriteLine(sb.ToString());
}
}
Using if, else if
and checking interfaces, attributes, base type, etc. and recursion (as this is a recursive method) in this way we may achieve an object dumper, but it is tedious for sure. Using the object dumper from Microsoft's LINQ Sample would save your time.
The function I use currently:
/**
* Serializes form or any other element with jQuery.serialize
* @param el
*/
serialize: function(el) {
var serialized = $(el).serialize();
if (!serialized) // not a form
serialized = $(el).
find('input[name],select[name],textarea[name]').serialize();
return serialized;
}
Use the following syntax:
ALTER TABLE your_table
MODIFY COLUMN column1 datatype,
MODIFY COLUMN column2 datatype,
... ... ... ... ...
... ... ... ... ...
Based on that, your ALTER
command should be:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100)
Note that:
MODIFY
statements.MODIFY
statements for two separate columns.This is the standard format of the MODIFY
statement for an ALTER
command on multiple columns in a MySQL table.
Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement
I've been able to solve this by using a hack involving import *
. It even works for both named and default exports!
For a named export:
// dependency.js
export const doSomething = (y) => console.log(y)
// myModule.js
import { doSomething } from './dependency';
export default (x) => {
doSomething(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.doSomething = jest.fn(); // Mutate the named export
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
Or for a default export:
// dependency.js
export default (y) => console.log(y)
// myModule.js
import dependency from './dependency'; // Note lack of curlies
export default (x) => {
dependency(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.default = jest.fn(); // Mutate the default export
myModule(2);
expect(dependency.default).toBeCalledWith(4); // Assert against the default
});
});
As Mihai Damian quite rightly pointed out below, this is mutating the module object of dependency
, and so it will 'leak' across to other tests. So if you use this approach you should store the original value and then set it back again after each test.
To do this easily with Jest, use the spyOn() method instead of jest.fn()
, because it supports easily restoring its original value, therefore avoiding before mentioned 'leaking'.
Yup, there's the convert_tz
function.
Try this
$(function() {
$('input[type="checkbox"]').bind('click',function() {
$('input[type="checkbox"]').not(this).prop("checked", false);
});
});
This works for me:
yarn add --dev tsconfig-paths
ts-node -r tsconfig-paths/register <your-index-file>.ts
This loads all paths in tsconfig.json. A sample tsconfig.json:
{
"compilerOptions": {
{…}
"baseUrl": "./src",
"paths": {
"assets/*": [ "assets/*" ],
"styles/*": [ "styles/*" ]
}
},
}
Make sure you have both baseUrl and paths for this to work
And then you can import like :
import {AlarmIcon} from 'assets/icons'
cp -rv `ls -A | grep -vE "dirToExclude|targetDir"` targetDir
Edit: forgot to exclude the target path as well (otherwise it would recursively copy).
imgtag.group(0)
or imgtag.group()
. This returns the entire match as a string. You are not capturing anything else either.
You should write a kind of template into the @RequestMapping
:
http://localhost:8080/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}
Now define your business method like following:
@RequestMapping("/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}")
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "search") String search,
@RequestParam(value = "nd") int nd,
@RequestParam(value = "rows") int rows,
@RequestParam(value = "page") int page,
@RequestParam(value = "sidx") int sidx,
@RequestParam(value = "sort") Sort sort) {
...............
}
So, framework will map ${foo}
to appropriate @RequestParam
.
Since sort may be either asc or desc I'd define it as a enum:
public enum Sort {
asc, desc
}
Spring deals with enums very well.
You can use below query to find running last request:
SELECT
der.session_id
,est.TEXT AS QueryText
,der.status
,der.blocking_session_id
,der.cpu_time
,der.total_elapsed_time
FROM sys.dm_exec_requests AS der
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS est
Using below script you can also find number of connection per database:
SELECT
DB_NAME(DBID) AS DataBaseName
,COUNT(DBID) AS NumberOfConnections
,LogiName
FROM sys.sysprocesses
WHERE DBID > 0
GROUP BY DBID, LogiName
For more details please visit: http://www.dbrnd.com/2015/06/script-to-find-running-process-session-logged-user-in-sql-server/
Using set bg=dark
with a white background can produce nearly unreadable text in some syntax highlighting schemes. Instead, you can change the overall colorscheme to something that looks good in your terminal. The colorscheme file should set the background attribute for you appropriately. Also, for more information see:
:h color
You can find more methods and functions related to Python strings in section 5.6.1. String Methods of the documentation.
w.strip(',.').lower()
Take a look at BackgroundWorker Class, with the OnRunWorkerCompleted you can do it.
Upgrading NPM to the latest version can greatly help with this. dule's answer above is right to say that dependency management is a bit broken, but it seems that this is mainly for older versions of npm.
The command npm list
gives you a list of all installed node_modules
. When I upgraded from version 1.4.2 to version 2.7.4, many modules that were previously flagged with WARN unmet dependency
were no longer noted as such.
To update npm, you should type npm install -g npm
on MacOSX or Linux. On Windows, I found that re-downloading and re-running the nodejs installer was a more effective way to update npm.
If you have a list and you want to know where within the list an element exists that matches a given criteria, you can use the FindIndex
instance method. Such as
int index = list.FindIndex(f => f.Bar == 17);
Where f => f.Bar == 17
is a predicate with the matching criteria.
In your case you might write
int index = pricePublicList.FindIndex(item => item.Size == 200);
if (index >= 0)
{
// element exists, do what you need
}
var1='hello'
var2='world'
var3=$var1" "$var2
echo $var3
And for PHP 5.3, you can use this function, which can be embedded in a class or used in procedural style:
http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php
You can create another script file separately for the functions and invoke the script file whenever you want to call the function. This will help you to keep your code clean.
Function Definition : Create a new script file
Function Call : Invoke the script file
Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.
In your posted question, there is one extra space after try:
, and there are 12 extra spaces after pass
:
>>> post_text = '''\
... if self.tagname and self.tagname2 in list1:
... try:
... question = soup.find("div", "post-text")
... title = soup.find("a", "question-hyperlink")
... self.list2.append(str(title)+str(question)+url)
... current += 1
... except AttributeError:
... pass
... logging.info("%s questions passed, %s questions \
... collected" % (count, current))
... count += 1
... return self.list2
... '''
>>> for line in post_text.splitlines():
... if line.rstrip() != line:
... print(repr(line))
...
' try: '
' pass '
See where the strings end? There are spaces before the lines (indentation), but also spaces after.
Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.
You can also find the PID of a java program with the task manager. You enable the PID and Command Line columns View -> Select Columns
and are then able to find the right process.
Your result will be something like this :
Since python 3.4 you should use pathlib
to "touch" files.
It is a much more elegant solution than the proposed ones in this thread.
from pathlib import Path
filename = Path('myfile.txt')
filename.touch(exist_ok=True) # will create file, if it exists will do nothing
file = open(filename)
Same thing with directories:
filename.mkdir(parents=True, exist_ok=True)
Well, to get rid of this you need to set phpMyadmin variable to either 0 that is unlimited or whichever value in seconds you find suitable for your needs. Or you could always use CLI(command line interface) to not even get such errors(For which you would like to take a look at this link.
Now about the error here, first on the safe side make sure you have set PHP parameters properly so that you can upload large files and can use maximum execution time from that end. If not, go ahead and set below three parameters from php.ini file,
Once that's done get back to finding phpMyadmin config file named something like "config.default.php". On XAMPP you will find it under "C:\xampp\phpMyAdmin\libraries" folder. Open the file called config.default.php
and set :
$cfg['ExecTimeLimit'] = 0;
Once set, restart your MySQL and Apache and go import your database.
Enjoy... :)
Add the following code in .htaccess file.
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
URLs redirect tutorial can be found from here - Redirect non-www to www & HTTP to HTTPS using .htaccess file
Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js
node_modules/
app/
index.html
server.js
After printing out the __dirname
path, I realized that the __dirname
path was where my server was running (app/
).
So, the answer to your question is this:
If your server.js
file is in the same folder as the files you are trying to render, then
app.use( express.static( path.join( application_root, 'site') ) );
should actually be
app.use(express.static(application_root));
The only time you would want to use the original syntax that you had would be if you had a folder tree like so:
app/
index.html
node_modules
server.js
where index.html
is in the app/
directory, whereas server.js
is in the root directory (i.e. the same level as the app/
directory).
Side note: Intead of calling the path
utility, you can use the syntax application_root + 'site'
to join a path.
Overall, your code could look like:
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//Don't change anything here...
//Where to serve static content
app.use( express.static( application_root ) );
//Nothing changes here either...
});
//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
I would use something like this:
String.format("%tF %<tT.%<tL", dateTime);
Variable dateTime
could be any date and/or time value, see JavaDoc for Formatter
.
for n in 1..6
h{n}
font: 32px/42px trajan-pro-1,trajan-pro-2;
Ahh, it is really simple
just add
white-space:pre-wrap;
to your displaying element css
I mean if you are showing result using <p>
then your css should be
p{
white-space:pre-wrap;
}
Just after running mysql query from php
get it by
$lastid=mysql_insert_id();
this give you the alst auto increment id value
This question doesn't really have anything to do with how require()
works. Basically, whatever you set module.exports
to in your module will be returned from the require()
call for it.
This would be equivalent to:
var square = function(width) {
return {
area: function() {
return width * width;
}
};
}
There is no need for the new
keyword when calling square
. You aren't returning the function instance itself from square
, you are returning a new object at the end. Therefore, you can simply call this function directly.
For more intricate arguments around new
, check this out: Is JavaScript's "new" keyword considered harmful?
First make sure that Dog
class implements the method public String toString()
then use
System.out.println(list.get(index))
where index is the position inside the list. Of course since you provide your implementation you can decide how dog prints itself.
Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.
I reccomend you to use the following tools for online base64 encoding/decoding:
Check the "Format as Data URL" option to format as a Data URL.
For Java version 7
You can follow Oracle documentation: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
X - is used for ISO 8601 time zone
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
System.out.println(nowAsISO);
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
//nowAsISO = "2013-05-31T00:00:00Z";
Date finalResult = df1.parse(nowAsISO);
System.out.println(finalResult);
You can use "await" in an "async function".
app.controller('MainCtrl', async function($scope, $q, $timeout) {
...
var all = await $q.all([one.promise, two.promise, three.promise]);
...
}
NOTE: I'm not 100% sure you can call an async function from a non-async function and have the right results.
That said this wouldn't ever be used on a website. But for load-testing/integration test...maybe.
Example code:
async function waitForIt(printMe) {_x000D_
console.log(printMe);_x000D_
console.log("..."+await req());_x000D_
console.log("Legendary!")_x000D_
}_x000D_
_x000D_
function req() {_x000D_
_x000D_
var promise = new Promise(resolve => {_x000D_
setTimeout(() => {_x000D_
resolve("DARY!");_x000D_
}, 2000);_x000D_
_x000D_
});_x000D_
_x000D_
return promise;_x000D_
}_x000D_
_x000D_
waitForIt("Legen-Wait For It");
_x000D_
Im sure this problem is related to the files and folders permissions.
For my mac osx Eclipse, I followed following steps:
Gradle put the fun back into building/assembling software. I used ant to build software my entire career and I have always considered the actual "buildit" part of the dev work being a necessary evil. A few months back our company grew tired of not using a binary repo (aka checking in jars into the vcs) and I was given the task to investigate this. Started with ivy since it could be bolted on top of ant, didn't have much luck getting my built artifacts published like I wanted. I went for maven and hacked away with xml, worked splendid for some simple helper libs but I ran into serious problems trying to bundle applications ready for deploy. Hassled quite a while googling plugins and reading forums and wound up downloading trillions of support jars for various plugins which I had a hard time using. Finally I went for gradle (getting quite bitter at this point, and annoyed that "It shouldn't be THIS hard!")
But from day one my mood started to improve. I was getting somewhere. Took me like two hours to migrate my first ant module and the build file was basically nothing. Easily fitted one screen. The big "wow" was: build scripts in xml, how stupid is that? the fact that declaring one dependency takes ONE row is very appealing to me -> you can easily see all dependencies for a certain project on one page. From then on I been on a constant roll, for every problem I faced so far there is a simple and elegant solution. I think these are the reasons:
Now I spend my days trying to think up new features to add to our build process. How sick is that?
Couple of typos:
while((c = getchar())!= EOF)
in place of:
while((c = getchar() != EOF))
Also getchar() treats a return key as a valid input, so you need to buffer it too.EOF is a marker to indicate end of input. Generally it is an int with all bits set.
#include <stdio.h>
int main()
{
int c;
while((c = getchar())!= EOF)
{
if( getchar() == EOF )
break;
printf(" %d\n", c);
}
printf("%d %u %x- at EOF\n", c , c, c);
}
prints:
49 50 -1 4294967295 ffffffff- at EOF
for input:
1 2 <ctrl-d>
The problem here is in your interpretation of the article you link.
This article is about somebody that is having problems correctly defining the bool relationship operators.
The operator:
These operators should return a bool as they are comparing two objects of the same type. It is usually easiest to define these operators as part of the class. This is because a class is automatically a friend of itself so objects of type Paragraph can examine each other (even each others private members).
There is an argument for making these free standing functions as this lets auto conversion convert both sides if they are not the same type, while member functions only allow the rhs to be auto converted. I find this a paper man argument as you don't really want auto conversion happening in the first place (usually). But if this is something you want (I don't recommend it) then making the comparators free standing can be advantageous.
The stream operators:
When you use these as stream operators (rather than binary shift) the first parameter is a stream. Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you.
It is also traditional for these objects to return a reference to a stream object so you can chain stream operations together.
#include <iostream>
class Paragraph
{
public:
explicit Paragraph(std::string const& init)
:m_para(init)
{}
std::string const& to_str() const
{
return m_para;
}
bool operator==(Paragraph const& rhs) const
{
return m_para == rhs.m_para;
}
bool operator!=(Paragraph const& rhs) const
{
// Define != operator in terms of the == operator
return !(this->operator==(rhs));
}
bool operator<(Paragraph const& rhs) const
{
return m_para < rhs.m_para;
}
private:
friend std::ostream & operator<<(std::ostream &os, const Paragraph& p);
std::string m_para;
};
std::ostream & operator<<(std::ostream &os, const Paragraph& p)
{
return os << p.to_str();
}
int main()
{
Paragraph p("Plop");
Paragraph q(p);
std::cout << p << std::endl << (p == q) << std::endl;
}
There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)