To find a div
of a certain class that contains a span
at any depth containing certain text, try:
//div[contains(@class, 'measure-tab') and contains(.//span, 'someText')]
That said, this solution looks extremely fragile. If the table happens to contain a span
with the text you're looking for, the div
containing the table will be matched, too. I'd suggest to find a more robust way of filtering the elements. For example by using IDs or top-level document structure.
I got this error when attempting to build with Xcode 10. It appears to be a bug in the Swift compiler. Building with Whole Module Optimization
on, resolves the issue: https://forums.swift.org/t/illegal-instruction-4-when-trying-to-compile-project/16118
This is not an ideal solution, I will continue to use Xcode 9.4.1 until this issue is resolved.
I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange=""
attribute to the input tag:
<input type='file' onchange='getFilename(this)'/>
function getFileName(elm) {
var fn = $(elm).val();
....
}
EDIT:
function getFileName(elm) {
var fn = $(elm).val();
var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
alert(filename);
}
Here is a more complete example:
import csv
import numpy as np
with open('filename','rb') as csvfile:
cdl = list( csv.reader(csvfile,delimiter='\t'))
print "Number of records = " + str(len(cdl))
#then later
npcdl = np.array(cdl)
Hope this helps!!
beside the answer of @MantasD I would like to offer comprehensive customized Laravel pagination. Assuming using Laravel 5.2 and the following included view:
@include('pagination.default', ['pager' => $users])
Features
default.blade.php
@if($pager->lastPage() != 1)
<ul class="pagination">
@unless($pager->currentPage() < 3)
<li class="paginate_button previous">
<a href="{{ $pager->url(1) }}" title="First Page"><i class="fa fa-angle-double-left"></i></a>
</li>
@endunless
<li class="paginate_button previous @unless($pager->previousPageUrl())disabled @endunless">
<a href="{{ $pager->previousPageUrl() }}"><i class="fa fa-angle-left"></i></a>
</li>
@while($pager->paging++ < $pager->lastPage())
@if (abs($pager->paging - $pager->currentPage()) >= 2)
{{-- Generate relative links (eg. +10,etc) --}}
@if(in_array(abs($pager->paging - $pager->currentPage()), array(10, 50, 100, 500, 1000))
and $pager->paging != 1 and $pager->paging != $pager->lastPage())
<li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
<a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
<!-- + {{ $pager->paging - $pager->currentPage() }} -->{{ $pager->paging }}
</a>
</li>
@endif
@else
<li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
<a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
{{ $pager->paging }}
</a>
</li>
@endif
@endwhile
<li class="paginate_button next @unless($pager->nextPageUrl())disabled @endunless">
<a href="{{ $pager->nextPageUrl() }}"><i class="fa fa-angle-right"></i></a>
</li>
@unless($pager->lastPage() - $pager->currentPage() < 2)
<li class="paginate_button next">
<a href="{{ $pager->url($pager->lastPage()) }}" title="Last Page"><i class="fa fa-angle-double-right"></i></a>
</li>
@endunless
</ul>
@endif
PaginationStartEnd function
if (!function_exists('PaginationStartEnd')) {
function PaginationStartEnd($currentPage, $perPage, $total)
{
$pageStart = number_format( $perPage * ($currentPage - 1));
$pageEnd = $pageStart + $perPage;
if ($pageEnd > $total)
$pageEnd = $total;
$pageStart++;
return array('start' => number_format($pageStart), 'end' => number_format($pageEnd));
}
}
You can use and customize this more as you wish.
Note: $pager->paging is variable set to 0 declared in the controller action
Interceptors
I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined
for the promise:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
For Xcode 8 you gotta download a package named Additional Tools for Xcode 8
For other versions (8.1, 8.2) get the package here
Double click and open the dmg
and go to Hardware
directory. Double click on Network Link Conditioner.prefPane
.
Click on install
Now Network Link Conditioner will be available in System Preferences.
For versions older than Xcode 8, the package to be downloaded is called Hardware IO Tools for Xcode
. Get it from this page
Add a Console.ReadKey
call to your program to force it to wait for you to press a key before exiting.
Try this :
ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it
Image newimg = image.getScaledInstance(120, 120, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way
imageIcon = new ImageIcon(newimg); // transform it back
(found it here)
Looks like people like doing spoonfeeding, so I have decided to post the worst solution to an easy task:
public static boolean isNumber(String s) throws Exception {
boolean result = false;
byte[] bytes = s.getBytes("ASCII");
int tmp, i = bytes.length;
while (i >0 && (result = ((tmp = bytes[--i] - '0') >= 0) && tmp <= 9));
return result;
}
About the worst code I could imagine, but there might be other people here who can come up with even worse solutions.
Hm, containsNumber is worse:
public static boolean containsNumber(String s) throws Exception {
boolean result = false;
byte[] bytes = s.getBytes("ASCII");
int tmp, i = bytes.length;
while (i >0 && (true | (result |= ((tmp = bytes[--i] - '0') >= 0) && tmp <= 9)));
return result;
}
This will also work in Visual Studio 2010 (Beta 2), as long as you install Paul Harrington's extension to enable the guidelines from the VSGallery or from the extension manager inside VS2010. Since this is version 10.0, you should use the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor
Also, Paul wrote an extension that adds entries to the editor's context menu for adding/removing the entries without needing to edit the registry directly. You can find it here: http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91
'-2147217887' message 'IDispatch error #3105' source 'Microsoft OLE DB Service Components' description 'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.'."
This is what I was also facing. The problem came from the fact that I changed my SQLOLEDB.1 provider to SQLNCLI11 without mentioning the compatibility mode in the connection string.
When I set this DataTypeCompatibility=80;
in the connection string, I got the problem solved.
I love Richard Nienaber's answer, but as Chuu pointed out, it really doesn't tell how to accomplish what Richard is refering to as a solution. Therefore I have chosen to provide you with the way I ended up doing this, ending with the result Richard is talking about.
In this case I'm creating a greeting widget that needs to know which options it has to greet in. This may be an over-engineered solution to OPs question as I am also creating an container for possible future widgets.
First I set up my collection to handle the different greetings
public class GreetingWidgetCollection : System.Configuration.ConfigurationElementCollection
{
public List<IGreeting> All { get { return this.Cast<IGreeting>().ToList(); } }
public GreetingElement this[int index]
{
get
{
return base.BaseGet(index) as GreetingElement;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new GreetingElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((GreetingElement)element).Greeting;
}
}
Then we create the acutal greeting element and it's interface
(You can omit the interface, that's just the way I'm always doing it.)
public interface IGreeting
{
string Greeting { get; set; }
}
public class GreetingElement : System.Configuration.ConfigurationElement, IGreeting
{
[ConfigurationProperty("greeting", IsRequired = true)]
public string Greeting
{
get { return (string)this["greeting"]; }
set { this["greeting"] = value; }
}
}
The greetingWidget property so our config understands the collection
We define our collection GreetingWidgetCollection
as the ConfigurationProperty
greetingWidget
so that we can use "greetingWidget" as our container in the resulting XML.
public class Widgets : System.Configuration.ConfigurationSection
{
public static Widgets Widget => ConfigurationManager.GetSection("widgets") as Widgets;
[ConfigurationProperty("greetingWidget", IsRequired = true)]
public GreetingWidgetCollection GreetingWidget
{
get { return (GreetingWidgetCollection) this["greetingWidget"]; }
set { this["greetingWidget"] = value; }
}
}
The resulting XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<widgets>
<greetingWidget>
<add greeting="Hej" />
<add greeting="Goddag" />
<add greeting="Hello" />
...
<add greeting="Konnichiwa" />
<add greeting="Namaskaar" />
</greetingWidget>
</widgets>
</configuration>
And you would call it like this
List<GreetingElement> greetings = Widgets.GreetingWidget.All;
Check out Android Documentation Managing Virtual Devices
To just find the number of days: timedelta has a 'days' attribute. You can simply query that.
>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13
You didn't specify how the order is determined, but this will give you a rank value in MySQL:
SELECT t.*,
@rownum := @rownum +1 AS rank
FROM TBL_FOO t
JOIN (SELECT @rownum := 0) r
WHERE t.name = 'sarmen'
Then you can pick out what rows you want, based on the rank value.
Only one option doesn't mentioned in the answers. You can de-normalize your DB design. So you need two tables. One table contains proper list, one item per row, another table contains whole list in one column (coma-separated, for example).
Here it is 'traditional' DB design:
List(ListID, ListName)
Item(ItemID,ItemName)
List_Item(ListID, ItemID, SortOrder)
Here it is de-normalized table:
Lists(ListID, ListContent)
The idea here - you maintain Lists table using triggers or application code. Every time you modify List_Item content, appropriate rows in Lists get updated automatically. If you mostly read lists it could work quite fine. Pros - you can read lists in one statement. Cons - updates take more time and efforts.
I seem to find the trick:
Just remove the form target
attribute, then use a submit button to validate the form and show hints, check if form valid via JavaScript, and then post whatever. The following code works for me:
<form>
<input name="foo" required>
<button id="submit">Submit</button>
</form>
<script>
$('#submit').click( function(e){
var isValid = true;
$('form input').map(function() {
isValid &= this.validity['valid'] ;
}) ;
if (isValid) {
console.log('valid!');
// post something..
} else
console.log('not valid!');
});
</script>
composer update
Above command worked for me.
Whenever you make new migration in la-ravel you need to refresh classmap
in composer.json
file .
Add
background-size:100% 100%;
to your css underneath background-image.
You can also specify exact dimensions, i.e.:
background-size: 30px 40px;
Here: JSFiddle
If you are looking to do your own ORM or generate code from a given table, then this might be what you are looking form:
declare @table varchar(100) = 'mytable';
with cte as
(
select
tc.CONSTRAINT_SCHEMA
, tc.CONSTRAINT_TYPE
, tc.TABLE_NAME
, ccu.COLUMN_NAME
, IS_NULLABLE
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, NUMERIC_PRECISION
from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu on tc.TABLE_NAME=ccu.TABLE_NAME and tc.TABLE_SCHEMA=ccu.TABLE_SCHEMA
inner join information_schema.COLUMNS c on ccu.COLUMN_NAME=c.COLUMN_NAME and ccu.TABLE_NAME=c.TABLE_NAME and ccu.TABLE_SCHEMA=c.TABLE_SCHEMA
where
tc.table_name=@table
and
ccu.CONSTRAINT_NAME=tc.CONSTRAINT_NAME
union
select TABLE_SCHEMA,'COLUMN', TABLE_NAME, COLUMN_NAME, IS_NULLABLE, DATA_TYPE,CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@table
and COLUMN_NAME not in (select COLUMN_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = @table)
)
select
cast(iif(CONSTRAINT_TYPE='PRIMARY KEY',1,0) as bit) PrimaryKey
,cast(iif(CONSTRAINT_TYPE='FOREIGN KEY',1,0) as bit) ForeignKey
,cast(iif(CONSTRAINT_TYPE='COLUMN',1,0) as bit) NotKey
,COLUMN_NAME
,cast(iif(is_nullable='NO',0,1) as bit) IsNullable
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, NUMERIC_PRECISION
from
cte
order by
case CONSTRAINT_TYPE
when 'PRIMARY KEY' then 1
when 'FOREIGN KEY' then 2
else 3 end
, COLUMN_NAME
Here is what the result would look like:
<table cellspacing=0 border=1>_x000D_
<tr>_x000D_
<td style=min-width:50px>PrimaryKey</td>_x000D_
<td style=min-width:50px>ForeignKey</td>_x000D_
<td style=min-width:50px>NotKey</td>_x000D_
<td style=min-width:50px>COLUMN_NAME</td>_x000D_
<td style=min-width:50px>IsNullable</td>_x000D_
<td style=min-width:50px>DATA_TYPE</td>_x000D_
<td style=min-width:50px>CHARACTER_MAXIMUM_LENGTH</td>_x000D_
<td style=min-width:50px>NUMERIC_PRECISION</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>LectureNoteID</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>int</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
<td style=min-width:50px>10</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>LectureId</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>int</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
<td style=min-width:50px>10</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>NoteTypeID</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>int</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
<td style=min-width:50px>10</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>Body</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>nvarchar</td>_x000D_
<td style=min-width:50px>-1</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>DisplayOrder</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>int</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
<td style=min-width:50px>10</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
See some example in http://www.sitepoint.com/understanding-sql-joins-mysql-database/
You can use 'USING' instead of 'ON' as in the query
SELECT * FROM table1 LEFT JOIN table2 USING (id);
A few answers here seem incomplete. Here are several variations:
<style>
.box {
height: 200px;
width: 200px;
border: 4px solid gray;
}
</style>
<!-- This works: .container>.row>.center-block.box -->
<div class="container">
<div class="row">
<div class="center-block bg-primary box">This div is centered with .center-block</div>
</div>
</div>
<!-- This does not work -->
<div class="container">
<div class="row">
<div class="center-block bg-primary box col-xs-4">This div is centered with .center-block</div>
</div>
</div>
<!-- This is the hybrid solution from other answers:
.container>.row>.col-xs-6>.center-block.box
-->
<div class="container">
<div class="row">
<div class="col-xs-6 bg-info">
<div class="center-block bg-primary box">This div is centered with .center-block</div>
</div>
</div>
</div>
To make it work with col-* classes, you need to wrap the .center-block inside a .col-* class, but remember to either add another class that sets the width (.box in this case), or to alter the .center-block itself by giving it a width.
Check it out on bootply.
With string type columns like character(2)
(as you mentioned later), the displayed concatenation just works because, quoting the manual:
[...] the string concatenation operator (
||
) accepts non-string input, so long as at least one input is of a string type, as shown in Table 9.8. For other cases, insert an explicit coercion totext
[...]
Bold emphasis mine. The 2nd example (select a||', '||b from foo
) works for any data types since the untyped string literal ', '
defaults to type text
making the whole expression valid in any case.
For non-string data types, you can "fix" the 1st statement by casting at least one argument to text
. (Any type can be cast to text
):
SELECT a::text || b AS ab FROM foo;
Judging from your own answer, "does not work" was supposed to mean "returns NULL". The result of anything concatenated to NULL is NULL. If NULL values can be involved and the result shall not be NULL, use concat_ws()
to concatenate any number of values (Postgres 9.1 or later):
SELECT concat_ws(', ', a, b) AS ab FROM foo;
Or concat()
if you don't need separators:
SELECT concat(a, b) AS ab FROM foo;
No need for type casts here since both functions take "any"
input and work with text representations.
More details (and why COALESCE
is a poor substitute) in this related answer:
+
is not a valid operator for string concatenation in Postgres (or standard SQL). It's a private idea of Microsoft to add this to their products.
There is hardly any good reason to use (synonym: character(n)
). Use char(n)
text
or varchar
. Details:
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
Following are some things I found in my collection of obscure Ruby.
So, in Ruby, a simple no-bells implementation of the Unix command cat
would be:
#!/usr/bin/env ruby
puts ARGF.read
ARGF
is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.
ARGF.each_with_index do |line, idx|
print ARGF.filename, ":", idx, ";", line
end
# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
puts line if line =~ /login/
end
Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF
as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i
) to every file mentioned on the command-line:
#!/usr/bin/env ruby -i
Header = DATA.read
ARGF.each_line do |e|
puts Header if ARGF.pos - e.length == 0
puts e
end
__END__
#--
# Copyright (C) 2007 Fancypants, Inc.
#++
Credit to:
i wrote a simple function for this:
Function (stringVar param)
(
Local stringVar oneChar := '0';
Local numberVar strLen := Length(param);
Local numberVar index := strLen;
oneChar = param[strLen];
while index > 0 and oneChar = '0' do
(
oneChar := param[index];
index := index - 1;
);
Left(param , index + 1);
)
I need to somehow query Google and ask: Is this access token valid for [email protected]?
No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.
The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.
So you need be from same domain as 'public interface'.
And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.
Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.
You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.
You could do an outer loop over the array
$.each(data.programs, function(index) {
// then loop over the object elements
$.each(data.programs[index], function(key, value) {
console.log(key + ": " + value);
}
}
The accepted answer has a couple of shortcomings:
Considering the above, your options could even have different values, but toggle the same class:
<select class="div-toggle" data-target=".my-info-1">
<option value="orange" data-show=".citrus">Orange</option>
<option value="lemon" data-show=".citrus">Lemon</option>
<option value="apple" data-show=".pome">Apple</option>
<option value="pear" data-show=".pome">Pear</option>
</select>
<div class="my-info-1">
<div class="citrus hide">Citrus is...</div>
<div class="pome hide">A pome is...</div>
</div>
jQuery:
$(document).on('change', '.div-toggle', function() {
var target = $(this).data('target');
var show = $("option:selected", this).data('show');
$(target).children().addClass('hide');
$(show).removeClass('hide');
});
$(document).ready(function(){
$('.div-toggle').trigger('change');
});
CSS:
.hide {
display: none;
}
Here's a JSFiddle to see it in action.
In Expression Language you can just use the ==
or eq
operator to compare object values. Behind the scenes they will actually use the Object#equals()
. This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).
So the particular line
<c:when test="${lang}.equals(${pageLang})">
should be written as (note that the whole expression is inside the {
and }
)
<c:when test="${lang == pageLang}">
or, equivalently
<c:when test="${lang eq pageLang}">
Both are behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))
If you want to compare constant String
values, then you need to quote it
<c:when test="${lang == 'en'}">
or, equivalently
<c:when test="${lang eq 'en'}">
which is behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals("en")
This happens when you move your main class location manually because Netbeans doesn't refresh one of its property files. Open nbproject/project.properties and change the value of main.class to the correct package location.
Follow the steps to display Progress of Ajax Request:
To make it easy I recommend you using JS Classes for dynamically Displaying & Hiding the spinner for this purpose.
I Hope this helps!
I have solved following this way
import { Router, ActivatedRoute } from '@angular/router';
constructor(private router: Router
, private activeRoute: ActivatedRoute) {
}
reloadCurrentPage(){
let currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
To go the full manual route: This method converts doubles to strings by shifting the number's decimal point around and using floor (to long) and modulus to extract the digits. Also, it uses counting by base division to figure out the place where the decimal point belongs. It can also "delete" higher parts of the number once it reaches the places after the decimal point, to avoid losing precision with ultra-large doubles. See commented code at the end. In my testing, it is never less precise than the Java float representations themselves, when they actually show these imprecise lower decimal places.
/**
* Convert the given double to a full string representation, i.e. no scientific notation
* and always twelve digits after the decimal point.
* @param d The double to be converted
* @return A full string representation
*/
public static String fullDoubleToString(final double d) {
// treat 0 separately, it will cause problems on the below algorithm
if (d == 0) {
return "0.000000000000";
}
// find the number of digits above the decimal point
double testD = Math.abs(d);
int digitsBeforePoint = 0;
while (testD >= 1) {
// doesn't matter that this loses precision on the lower end
testD /= 10d;
++digitsBeforePoint;
}
// create the decimal digits
StringBuilder repr = new StringBuilder();
// 10^ exponent to determine divisor and current decimal place
int digitIndex = digitsBeforePoint;
double dabs = Math.abs(d);
while (digitIndex > 0) {
// Recieves digit at current power of ten (= place in decimal number)
long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
repr.append(digit);
--digitIndex;
}
// insert decimal point
if (digitIndex == 0) {
repr.append(".");
}
// remove any parts above the decimal point, they create accuracy problems
long digit = 0;
dabs -= (long)Math.floor(dabs);
// Because of inaccuracy, move to entirely new system of computing digits after decimal place.
while (digitIndex > -12) {
// Shift decimal point one step to the right
dabs *= 10d;
final var oldDigit = digit;
digit = (long)Math.floor(dabs) % 10;
repr.append(digit);
// This may avoid float inaccuracy at the very last decimal places.
// However, in practice, inaccuracy is still as high as even Java itself reports.
// dabs -= oldDigit * 10l;
--digitIndex;
}
return repr.insert(0, d < 0 ? "-" : "").toString();
}
Note that while StringBuilder is used for speed, this method can easily be rewritten to use arrays and therefore also work in other languages.
A Problem with csgillespie solution appears, when You have an logarithmic X axis. The you will have a different length of the small bars on the right an the left side (the epsilon follows the x-values).
You should better use the errbar
function from the Hmisc
package:
d = data.frame(
x = c(1:5)
, y = c(1.1, 1.5, 2.9, 3.8, 5.2)
, sd = c(0.2, 0.3, 0.2, 0.0, 0.4)
)
##install.packages("Hmisc", dependencies=T)
library("Hmisc")
# add error bars (without adjusting yrange)
plot(d$x, d$y, type="n")
with (
data = d
, expr = errbar(x, y, y+sd, y-sd, add=T, pch=1, cap=.1)
)
# new plot (adjusts Yrange automatically)
with (
data = d
, expr = errbar(x, y, y+sd, y-sd, add=F, pch=1, cap=.015, log="x")
)
If each file in your program is first compiled to an object file, then the object files are linked together, you need extern
. It tells the compiler "This function exists, but the code for it is somewhere else. Don't panic."
In case someone wanted an example using variables...
#!/bin/bash
# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"
if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi
import shutil
shutil.rmtree(dest, ignore_errors=True)
In the case that you not only want to exclude a list of special characters, but to exclude all characters that are not letters or numbers, I would suggest that you use a char type comparison approach.
For each character in the String, I would check if the unicode character is between "A" and "Z", between "a" and "z" or between "0" and "9". This is the vba code:
Function cleanString(text As String) As String
Dim output As String
Dim c 'since char type does not exist in vba, we have to use variant type.
For i = 1 To Len(text)
c = Mid(text, i, 1) 'Select the character at the i position
If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
output = output & c 'add the character to your output.
Else
output = output & " " 'add the replacement character (space) to your output
End If
Next
cleanString = output
End Function
The Wikipedia list of Unicode characers is a good quick-start if you want to customize this function a little more.
This solution has the advantage to be functionnal even if the user finds a way to introduce new special characters. It also faster than comparing two lists together.
Other posters have addressed the question about how contains() works.
An equally important aspect of your question is how to properly implement equals(). And the answer to this is really dependent on what constitutes object equality for this particular class. In the example you provided, if you have two different objects that both have x=5, are they equal? It really depends on what you are trying to do.
If you are only interested in object equality, then the default implementation of .equals() (the one provided by Object) uses identity only (i.e. this == other). If that's what you want, then just don't implement equals() on your class (let it inherit from Object). The code you wrote, while kind of correct if you are going for identity, would never appear in a real class b/c it provides no benefit over using the default Object.equals() implementation.
If you are just getting started with this stuff, I strongly recommend the Effective Java book by Joshua Bloch. It's a great read, and covers this sort of thing (plus how to correctly implement equals() when you are trying to do more than identity based comparisons)
The build path should contain the path 'till before' that of the package name.
For eg, if the folder structure is: src/main/java/com/example/dao
If the class containing the import statement'package com.example.dao'
complains of the incorrect package error, then, the build path should include:src/main/java
This should solve the issue.
It sounds like you want to convert the rownames to a proper column of the data.frame. eg:
# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF
# Row.Names id val vr2
# row_one row_one A 1 23
# row_two row_two A 2 24
# row_three row_three B 3 25
# row_four row_four C 4 26
If you want to then remove the original rownames:
rownames(myDF) <- NULL
myDF
# Row.Names id val vr2
# 1 row_one A 1 23
# 2 row_two A 2 24
# 3 row_three B 3 25
# 4 row_four C 4 26
Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames
myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat
# Names.of.Rows id val vr2
# row_one "A" "1" "23"
# row_two "A" "2" "24"
# row_three "B" "3" "25"
# row_four "C" "4" "26"
I came across this interesting article by UncleBob The Little Mocker. It explains all the terminology in a very easy to understand manner, so its useful for beginners. Martin Fowlers article is a hard read especially for beginners like me.
The character 0x0C is be invalid in XML 1.0 but would be a valid character in XML 1.1. So unless the xml file specifies the version as 1.1 in the prolog it is simply invalid and you should complain to the producer of this file.
Be sure to fully qualify your sheets with which workbook they are referencing!
mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name
simply create two list in adapter one orignal and one temp and implements Filterable.
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<T> results = new ArrayList<>();
if (origList == null)
origList = new ArrayList<>(itemList);
if (constraint != null && constraint.length() > 0) {
if (origList != null && origList.size() > 0) {
for (final T cd : origList) {
if (cd.getAttributeToSearch().toLowerCase()
.contains(constraint.toString().toLowerCase()))
results.add(cd);
}
}
oReturn.values = results;
oReturn.count = results.size();//newly Aded by ZA
} else {
oReturn.values = origList;
oReturn.count = origList.size();//newly added by ZA
}
return oReturn;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(final CharSequence constraint,
FilterResults results) {
itemList = new ArrayList<>((ArrayList<T>) results.values);
// FIXME: 8/16/2017 implement Comparable with sort below
///Collections.sort(itemList);
notifyDataSetChanged();
}
};
}
where
public GenericBaseAdapter(Context mContext, List<T> itemList) {
this.mContext = mContext;
this.itemList = itemList;
this.origList = itemList;
}
The @RequestBody
javadoc states
Annotation indicating a method parameter should be bound to the body of the web request.
It uses registered instances of HttpMessageConverter
to deserialize the request body into an object of the annotated parameter type.
And the @RequestParam
javadoc states
Annotation which indicates that a method parameter should be bound to a web request parameter.
Spring binds the body of the request to the parameter annotated with @RequestBody
.
Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name
, to map the parameter.
Parameters are resolved in order. The @RequestBody
is processed first. Spring will consume all the HttpServletRequest
InputStream
. When it then tries to resolve the @RequestParam
, which is by default required
, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.
The handler for @RequestParam
acts first, reading what it can of the HttpServletRequest
InputStream
to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc
mapped to the parameter name
. When the handler for @RequestBody
runs, there's nothing left in the request body, so the argument used is the empty string.
The handler for @RequestBody
reads the body and binds it to the parameter. The handler for @RequestParam
can then get the request parameter from the URL query string.
The handler for @RequestParam
reads from both the body and the URL query String. It would usually put them in a Map
, but since the parameter is of type String
, Spring will serialize the Map
as comma separated values. The handler for @RequestBody
then, again, has nothing left to read from the body.
The last question has an easy answer:
> .Machine$sizeof.pointer
[1] 8
Meaning I am running R64. If I were running 32 bit R it would return 4. Just because you are running a 64 bit OS does not mean you will be running 64 bit R, and from the error message it appears you are not.
EDIT: If the package has binaries, then they are in separate directories. The specifics will depend on the OS. Notice that your LoadLibrary error occurred when it attempted to find the dll in ...rJava/libs/x64/...
On my MacOS system the ...rJava/libs/...` folder has 3 subdirectories: i386, ppc, and x86_64. (The ppc files are obviously useless baggage.)
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
TextBox1.Select()
End Sub
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
if faceing that error like geocoding access denied : so you can enable geocoding api service from getKey account.enter image description here
You can enable a general query log for that sort of diagnostic. Generally you don't log all SELECT queries on a production server though, it's a performance killer.
Edit your MySQL config, e.g. /etc/mysql/my.cnf - look for, or add, a line like this
[mysqld]
log = /var/log/mysql/mysql.log
Restart mysql to pick up that change, now you can
tail -f /var/log/mysql/mysql.log
Hey presto, you can watch the queries as they come in.
After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.
It's incorrect to use zeros in date or in datetime, just put null instead of zeros.
In my case, the auto-generated project appcompat_v7 was closed. So just open up that project in Package Explorer.
Hope this help.
To edit:
crontab -e
Add this command line:
30 2 * * * /your/command
MIN HOUR DOM MON DOW CMD
MIN Minute field 0 to 59
HOUR Hour field 0 to 23
DOM Day of Month 1-31
MON Month field 1-12
DOW Day Of Week 0-6
CMD Command Any command to be executed.
Restart cron with latest data:
service crond restart
you can use substring()
method. ex,
var x = "Hello world"
var x = x.substring(0, i) + 'h' + x.substring(i+1);
What you need to do is as follows:
That's it!
Object.keys(obj).forEach(key =>
console.log(`key=${key} value=${obj[key]}`)
);
What do you mean "not working"?
jQuery detects that you're trying to create a SCRIPT element and will automatically run the contents of the element within the global context. Are you telling me that this doesn't work for you? -
$('#someElement').append('<script>alert("WORKING");</script>');
Edit: If you're not seeing the SCRIPT element in the DOM (in Firebug for example) after you run the command that's because jQuery, like I said, will run the code and then will delete the SCRIPT element - I believe that SCRIPT elements are always appended to the body... but anyway - placement has absolutely no bearing on code execution in this situation.
In your User
model, add the following line in the User
class:
public $timestamps = true;
Now, whenever you save or update a user, Laravel will automatically update the created_at
and updated_at
fields.
Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s
. The problem is that the format you have used is not the same as Laravel uses for the created_at
field.
Update: Nov 2018 Laravel 5.6
"message": "Access level to App\\Note::$timestamps must be public",
Make sure you have the proper access level as well. Laravel 5.6 is public
.
Here is a function that even supports clockwise/anticlockwise drawing do that you control fills with the non-zero winding rule.
Here is a full article on how it works and more.
// Defines a path for any regular polygon with the specified number of sides and radius,
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise
function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.moveTo(radius,0);
for (var i = 1; i < sides; i++) {
ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
}
ctx.closePath();
ctx.restore();
}
// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false
.
ExecuteScalar()
is what you need here
It's probably more than solved. Just want to contribute with another simple solution:
var text = 'uololooo';
// With ES6
[...text].forEach(c => console.log(c))
// With the `of` operator
for (const c of text) {
console.log(c)
}
// With ES5
for (var x = 0, c=''; c = text.charAt(x); x++) {
console.log(c);
}
// ES5 without the for loop:
text.split('').forEach(function(c) {
console.log(c);
});
Finally can also be used when you want to run "optional" code before running the code for your main work and that optional code may fail for various reasons.
In the following example, we don't know precisely what kind of exceptions store_some_debug_info
might throw.
We could run:
try:
store_some_debug_info()
except Exception:
pass
do_something_really_important()
But, most linters will complain about catching too vague of an exception. Also, since we're choosing to just pass
for errors, the except
block doesn't really add value.
try:
store_some_debug_info()
finally:
do_something_really_important()
The above code has the same effect as the 1st block of code but is more concise.
Perhaps you don't have to include the single quotes:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"
Update: Reading curl's manual, you could actually separate both fields with two --data:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"
You could also try --data-binary:
curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"
And --data-urlencode:
curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"
I went through the Word to PDF pain when someone dumped me with 10000 word files to convert to PDF. Now I did it in C# and used Word interop but it was slow and crashed if I tried to use PC at all.. very frustrating.
This lead me to discovering I could dump interops and their slowness..... for Excel I use (EPPLUS) and then I discovered that you can get a free tool called Spire that allows converting to PDF... with limitations!
http://www.e-iceblue.com/Introduce/free-doc-component.html#.VtAg4PmLRhE
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
This is really simple, since OS 3.0 just set the background color of the cell in the willDisplayCell method. You must not set the color in the cellForRowAtIndexPath.
This works for both the plain and grouped style :
Code:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [UIColor redColor];
}
P.S: Here the documentation extract for willDisplayCell :
"A table view sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. This method gives the delegate a chance to override state-based properties set earlier by the table view, such as selection and background color. After the delegate returns, the table view sets only the alpha and frame properties, and then only when animating rows as they slide in or out."
I've found this information in this post from colionel. Thank him!
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
Here is a concrete example with the delegation pattern.
Setup your Protocol:
@objc protocol MyProtocol:class
{
func requiredMethod()
optional func optionalMethod()
}
class MyClass: NSObject
{
weak var delegate:MyProtocol?
func callDelegate()
{
delegate?.requiredMethod()
delegate?.optionalMethod?()
}
}
Set the delegate to a class and implement the Protocol. See that the optional method does not need to be implemented.
class AnotherClass: NSObject, MyProtocol
{
init()
{
super.init()
let myInstance = MyClass()
myInstance.delegate = self
}
func requiredMethod()
{
}
}
One important thing is that the optional method is optional and needs a "?" when calling. Mention the second question mark.
delegate?.optionalMethod?()
A non conventional method to separate javascript from the view, but still use razor in it is to make a Scripts.cshtml
file and place your mixed javascript/razor there.
Index.cshtml
<div id="Result">
</div>
<button id="btnLoad">Click me</button>
@section scripts
{
@Html.Partial("Scripts")
}
Scripts.cshtml
<script type="text/javascript">
var url = "@Url.Action("Index", "Home")";
$(document).ready(function() {
$("#btnLoad").click(function() {
$.ajax({
type: "POST",
url: url ,
data: {someParameter: "some value"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").text(msg.d);
}
});
});
});
</script>
It's time to check the latest release/s for Visual Studio, folks. The most suggested solution that did not work for some of you before might work now.
In Visual Studio 2017 (Release Version 15.4.2 and above), going to Tools > Options > Debugging > General > (Check Box) Redirect all Output Window text to Immediate Window
has worked for me.
Few Notes:
Best wishes!
For those using zsh, you'll have to use the following:
git reset --soft HEAD\^
Explained here: https://github.com/robbyrussell/oh-my-zsh/issues/449
In case the URL becomes dead, the important part is:
Escape the ^ in your command
You can alternatively can use HEAD~ so that you don't have to escape it each time.
The .bashrc file is in your user home directory (~/.bashrc or ~vagrant/.bashrc both resolve to the same path), inside the VM's filesystem. This file is invisible on the host machine, so you can't use any Windows editors to edit it directly.
You have two simple choices:
Learn how to use a console-based text editor. My favourite is vi (or vim), which takes 15 minutes to learn the basics and is much quicker for simple edits than anything else.
vi .bashrc
Copy .bashrc out to /vagrant (which is a shared directory) and edit it using your Windows editors. Make sure not to save it back with any extensions.
cp .bashrc /vagrant ... edit using your host machine ... cp /vagrant/.bashrc .
I'd recommend getting to know the command-line based editors. Once you're working inside the VM, it's best to stay there as otherwise you might just get confused.
You (the vagrant user) are the owner of your home .bashrc so you do have permissions to edit it.
Once edited, you can execute it by typing source .bashrc I prefer to logout and in again (there may be more than one file executed on login).
In case you need a declarative solution, you can use dict.update()
to change values in a dict.
Either like this:
my_dict.update({'key1': 'value1', 'key2': 'value2'})
or like this:
my_dict.update(key1='value1', key2='value2')
Since Python 3.5 you can also use dictionary unpacking for this:
my_dict = { **my_dict, 'key1': 'value1', 'key2': 'value2'}
Note: This creates a new dictionary.
Since Python 3.9 you can also use the merge operator on dictionaries:
my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}
Note: This creates a new dictionary.
Or you can use the update operator:
my_dict |= {'key1': 'value1', 'key2': 'value2'}
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
your MAIL_PASSWORD=must a APPpasword
after change the .env stop the server then clear configuratios cahce php artisan config:cahce and start the server again
reference Cannot send message without a sender address in laravel 5.2 I have set .env and mail.php both
Is it very expensive to do this by json convert? But at least you have a 2 line solution and its generic. It does not matter eather if your datatable contains more or less fields than the object class:
Dim sSql = $"SELECT '{jobID}' AS ConfigNo, 'MainSettings' AS ParamName, VarNm AS ParamFieldName, 1 AS ParamSetId, Val1 AS ParamValue FROM StrSVar WHERE NmSp = '{sAppName} Params {jobID}'"
Dim dtParameters As DataTable = DBLib.GetDatabaseData(sSql)
Dim paramListObject As New List(Of ParameterListModel)()
If (Not dtParameters Is Nothing And dtParameters.Rows.Count > 0) Then
Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(dtParameters).ToString()
paramListObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of ParameterListModel))(json)
End If
Add into ~/.Rprofile
local({r <- getOption("repos")
r["CRAN"] <- "mirror_site" #for example, https://mirrors.ustc.edu.cn/CRAN/
options(repos=r)
options(BioC_mirror="bioc_mirror_site") #if using biocLite
})
I usually use keys
and I can't think of the last time I used or read a use of each
.
Don't forget about map
, depending on what you're doing in the loop!
map { print "$_ => $hash{$_}\n" } keys %hash;
In summary: similarities and differences are:
java beans: Pojo:
-must extends serializable -no need to extends or implement.
or externalizable.
-must have public class . - must have public class
-must have private instance variables. -can have any access specifier variables.
-must have public setter and getter method. - may or may not have setter or getter method.
-must have no-arg constructor. - can have constructor with agruments.
All JAVA Beans are POJO but not all POJOs are JAVA Beans.
Basically to resolve this we need to have some set up like
The connection string used with Windows authentication include either Trusted_Connection=Yes
attribute or the equivalent attribute Integrated Security=SSPI
in Web.config
file
My database connection is in Windows Authentication mode. So I resolved it by simply changing the Application Pools Identity from ApplicationPoolIdentity to my domain log in credentials DomainName\MyloginId
Step:
Select Name of your application
Go to Advanced Setting
For me it was resolved.
Note: In Production or IT environment, you might have service account under same domain for app pool identity. If so, use service account instead of your login.
TIMTOWTDI!
perl -pe 's/\r\n/\n/; s/([^\n])\z/$1\n/ if eof' PCfile.txt
Based on @GordonDavisson
One must consider the possibility of [noeol]
...
setState
is being invoked immediately due to the parenthesis! Wrap it in an anonymous function, then call it:
setTimeout(function() {
this.setState({position: 1})
}.bind(this), 3000);
$myarray = array(
'test1' => 'foo',
'test2' => 'bar',
'test3' => 'baz',
'test4' => 'waldo'
);
$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);
// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
Since array_pop
works on the temporary array created by array_keys
it doesn't modify the original array at all.
$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz
Tested this in IE, Chrome, Safari, Firefox (latest versions 2012-11-27):
Works in all of them...
For repeating task you can use
new Timer().scheduleAtFixedRate(task, runAfterADelayForFirstTime, repeaingTimeInterval);
call it like
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
}
},500,1000);
The above code will run first time after half second(500) and repeat itself after each second(1000)
Where
task being the method to be executed
after the time to initial execution
(interval the time for repeating the execution)
Secondly
And you can also use CountDownTimer if you want to execute a Task number of times.
new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
}
}.start();
//Above codes run 40 times after each second
And you can also do it with runnable. create a runnable method like
Runnable runnable = new Runnable()
{
@Override
public void run()
{
}
};
And call it in both these ways
new Handler().postDelayed(runnable, 500 );//where 500 is delayMillis // to work on mainThread
OR
new Thread(runnable).start();//to work in Background
Need to specify two attributes, table-layout:fixed
on table
and white-space:nowrap;
on the cells. You also need to move the overflow:hidden;
to the cells too
table { width:250px;table-layout:fixed; }
table tr { height:1em; }
td { overflow:hidden;white-space:nowrap; }
Here's a Demo . Tested in Firefox 3.5.3 and IE 7
An alternative to the answer provided by @Marc
SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100)
FROM YOUR_TABLE
WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND
CHARINDEX(';', YOUR_FIELD) > 0;
This makes sure the delimiters exist, and solves an issue with the currently accepted answer where doing the LEFT last is working with the position of the last delimiter in the original string, rather than the revised substring.
What you are trying to deserialize to a Dictionary is actually a Javascript object serialized to JSON. In Javascript, you can use this object as an associative array, but really it's an object, as far as the JSON standard is concerned.
So you would have no problem deserializing what you have with a standard JSON serializer (like the .net ones, DataContractJsonSerializer and JavascriptSerializer) to an object (with members called AppName, AnotherAppName, etc), but to actually interpret this as a dictionary you'll need a serializer that goes further than the Json spec, which doesn't have anything about Dictionaries as far as I know.
One such example is the one everybody uses: JSON .net
There is an other solution if you don't want to use an external lib, which is to convert your Javascript object to a list before serializing it to JSON.
var myList = [];
$.each(myObj, function(key, value) { myList.push({Key:key, Value:value}) });
now if you serialize myList to a JSON object, you should be capable of deserializing to a List<KeyValuePair<string, ValueDescription>>
with any of the aforementioned serializers. That list would then be quite obvious to convert to a dictionary.
Note: ValueDescription being this class:
public class ValueDescription
{
public string Description { get; set; }
public string Value { get; set; }
}
To pass some context data to javascript code, you have to serialize it in a way it will be "understood" by javascript (namely JSON). You also need to mark it as safe using the safe
Jinja filter, to prevent your data from being htmlescaped.
You can achieve this by doing something like that:
import json
@app.route('/')
def my_view():
data = [1, 'foo']
return render_template('index.html', data=json.dumps(data))
<script type="text/javascript">
function test_func(data) {
console.log(data);
}
test_func({{ data|safe }})
</script>
So, to achieve exactly what you want (loop over a list of items, and pass them to a javascript function), you'd need to serialize every item in your list separately. Your code would then look like this:
import json
@app.route('/')
def my_view():
data = [1, "foo"]
return render_template('index.html', data=map(json.dumps, data))
{% for item in data %}
<span onclick=someFunction({{ item|safe }});>{{ item }}</span>
{% endfor %}
In my example, I use Flask
, I don't know what framework you're using, but you got the idea, you just have to make it fit the framework you use.
NEVER EVER DO THIS WITH USER-SUPPLIED DATA, ONLY DO THIS WITH TRUSTED DATA!
Otherwise, you would expose your application to XSS vulnerabilities!
Just a follow up to @LisaD's answer.
As of 2016 (Django 1.9
), you need to type:
heroku pg:reset DATABASE_URL
heroku run python manage.py makemigrations
heroku run python manage.py migrate
This will give you a fresh new database within Heroku.
Maven Dependencies: What solved it for me in Eclipse? I added the dependency in the "pom" file. I did a build, but could not see the Maven Dependency in the Eclipse. Next Step: Closed the project. Then Reopened the project. I could see the Maven dependencies.
frame.setLocationRelativeTo(null);
Full example:
public class BorderLayoutPanel {
private JFrame mainFrame;
private JButton btnLeft, btnRight, btnTop, btnBottom, btnCenter;
public BorderLayoutPanel() {
mainFrame = new JFrame("Border Layout Example");
btnLeft = new JButton("LEFT");
btnRight = new JButton("RIGHT");
btnTop = new JButton("TOP");
btnBottom = new JButton("BOTTOM");
btnCenter = new JButton("CENTER");
}
public void SetLayout() {
mainFrame.add(btnTop, BorderLayout.NORTH);
mainFrame.add(btnBottom, BorderLayout.SOUTH);
mainFrame.add(btnLeft, BorderLayout.EAST);
mainFrame.add(btnRight, BorderLayout.WEST);
mainFrame.add(btnCenter, BorderLayout.CENTER);
// mainFrame.setSize(200, 200);
// or
mainFrame.pack();
mainFrame.setVisible(true);
//take up the default look and feel specified by windows themes
mainFrame.setDefaultLookAndFeelDecorated(true);
//make the window startup position be centered
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);
}
}
i used this code and it works fine for me, just change +92xxxxxxxxxx to your valid whatsapp number, with country code
<script type="text/javascript">
(function () {
var options = {
whatsapp: "+92xxxxxxxxxx", // WhatsApp number
call_to_action: "Message us", // Call to action
position: "right", // Position may be 'right' or 'left'
};
var proto = document.location.protocol, host = "whatshelp.io", url = proto + "//static." + host;
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
})();
</script>
All above questions are correct but if you want the hostname and domain name try this:
[System.Net.DNS]::GetHostByName('').HostName
The link to a function in a dynamic library is resolved when the library is loaded or at run time. Therefore, both the executable file and dynamic library are loaded into memory when the program is run. The memory address at which a dynamic library is loaded cannot be determined in advance, because a fixed address might clash with another dynamic library requiring the same address.
There are two commonly used methods for dealing with this problem:
1.Relocation. All pointers and addresses in the code are modified, if necessary, to fit the actual load address. Relocation is done by the linker and the loader.
2.Position-independent code. All addresses in the code are relative to the current position. Shared objects in Unix-like systems use position-independent code by default. This is less efficient than relocation if program run for a long time, especially in 32-bit mode.
The name "position-independent code" actually implies following:
The code section contains no absolute addresses that need relocation, but only self relative addresses. Therefore, the code section can be loaded at an arbitrary memory address and shared between multiple processes.
The data section is not shared between multiple processes because it often contains writeable data. Therefore, the data section may contain pointers or addresses that need relocation.
All public functions and public data can be overridden in Linux. If a function in the main executable has the same name as a function in a shared object, then the version in main will take precedence, not only when called from main, but also when called from the shared object. Likewise, when a global variable in main has the same name as a global variable in the shared object, then the instance in main will be used, even when accessed from the shared object.
This so-called symbol interposition is intended to mimic the behavior of static libraries.
A shared object has a table of pointers to its functions, called procedure linkage table (PLT) and a table of pointers to its variables called global offset table (GOT) in order to implement this "override" feature. All accesses to functions and public variables go through this tables.
p.s. Where dynamic linking cannot be avoided, there are various ways to avoid the timeconsuming features of the position-independent code.
You can read more from this article: http://www.agner.org/optimize/optimizing_cpp.pdf
You should put the parameter gravity to bottom not in the textview but in the Linear Layout. Like this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom|end">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Something"/>
</LinearLayout>
This is a new feature of C# 6 called an expression bodied member that allows you to define a getter only property using a lambda like function.
While it is considered syntactic sugar for the following, they may not produce identical IL:
public int MaxHealth
{
get
{
return Memory[Address].IsValid
? Memory[Address].Read<int>(Offs.Life.MaxHp)
: 0;
}
}
It turns out that if you compile both versions of the above and compare the IL generated for each you'll see that they are NEARLY the same.
Here is the IL for the classic version in this answer when defined in a class named TestClass
:
.property instance int32 MaxHealth()
{
.get instance int32 TestClass::get_MaxHealth()
}
.method public hidebysig specialname
instance int32 get_MaxHealth () cil managed
{
// Method begins at RVA 0x2458
// Code size 71 (0x47)
.maxstack 2
.locals init (
[0] int32
)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
IL_0007: ldarg.0
IL_0008: ldfld int64 TestClass::Address
IL_000d: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
IL_0012: ldfld bool MemoryAddress::IsValid
IL_0017: brtrue.s IL_001c
IL_0019: ldc.i4.0
IL_001a: br.s IL_0042
IL_001c: ldarg.0
IL_001d: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
IL_0022: ldarg.0
IL_0023: ldfld int64 TestClass::Address
IL_0028: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
IL_002d: ldarg.0
IL_002e: ldfld class Offs TestClass::Offs
IL_0033: ldfld class Life Offs::Life
IL_0038: ldfld int64 Life::MaxHp
IL_003d: callvirt instance !!0 MemoryAddress::Read<int32>(int64)
IL_0042: stloc.0
IL_0043: br.s IL_0045
IL_0045: ldloc.0
IL_0046: ret
} // end of method TestClass::get_MaxHealth
And here is the IL for the expression bodied member version when defined in a class named TestClass
:
.property instance int32 MaxHealth()
{
.get instance int32 TestClass::get_MaxHealth()
}
.method public hidebysig specialname
instance int32 get_MaxHealth () cil managed
{
// Method begins at RVA 0x2458
// Code size 66 (0x42)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
IL_0006: ldarg.0
IL_0007: ldfld int64 TestClass::Address
IL_000c: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
IL_0011: ldfld bool MemoryAddress::IsValid
IL_0016: brtrue.s IL_001b
IL_0018: ldc.i4.0
IL_0019: br.s IL_0041
IL_001b: ldarg.0
IL_001c: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
IL_0021: ldarg.0
IL_0022: ldfld int64 TestClass::Address
IL_0027: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
IL_002c: ldarg.0
IL_002d: ldfld class Offs TestClass::Offs
IL_0032: ldfld class Life Offs::Life
IL_0037: ldfld int64 Life::MaxHp
IL_003c: callvirt instance !!0 MemoryAddress::Read<int32>(int64)
IL_0041: ret
} // end of method TestClass::get_MaxHealth
See https://msdn.microsoft.com/en-us/magazine/dn802602.aspx for more information on this and other new features in C# 6.
See this post Difference between Property and Field in C# 3.0+ on the difference between a field and a property getter in C#.
Update:
Note that expression-bodied members were expanded to include properties, constructors, finalizers and indexers in C# 7.0.
Use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet()
For more detail, see Class LinkedHashMap
Just another idea:
>>> bin(6)[2:].zfill(8)
'00000110'
Shorter way via string interpolation (Python 3.6+):
>>> f'{6:08b}'
'00000110'
There are 2 annotations in Spring: @RequestBody and @ResponseBody. These annotations consumes, respectively produces JSONs. Some more info here.
complete.cases
gives TRUE
when all values in a row are not NA
DF[!complete.cases(DF), ]
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
This is what I did on the controller
var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive
I ended up formatting the date to my desired pattern on the directive as follows.
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dates');
data.addColumn('number', 'Upper Normal');
data.addColumn('number', 'Result');
data.addColumn('number', 'Lower Normal');
data.addRows(scope.rows);
var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}
//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
chart.draw(data, options);
This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.
You are reducing the length of your list l
as you iterate over it, so as you approach the end of your indices in the range statement, some of those indices are no longer valid.
It looks like what you want to do is:
l = [x for x in l if x != 0]
which will return a copy of l
without any of the elements that were zero (that operation is called a list comprehension, by the way). You could even shorten that last part to just if x
, since non-zero numbers evaluate to True
.
There is no such thing as a loop termination condition of i < len(l)
, in the way you've written the code, because len(l)
is precalculated before the loop, not re-evaluated on each iteration. You could write it in such a way, however:
i = 0
while i < len(l):
if l[i] == 0:
l.pop(i)
else:
i += 1
Personally, one of the things I love about python is the tuple-dict combination. What you have here is effectively a 2d array (where x = fruit name and y = color), and I am generally a supporter of the dict of tuples for implementing 2d arrays, at least when something like numpy
or a database isn't more appropriate. So in short, I think you've got a good approach.
Note that you can't use dicts as keys in a dict without doing some extra work, so that's not a very good solution.
That said, you should also consider namedtuple(). That way you could do this:
>>> from collections import namedtuple
>>> Fruit = namedtuple("Fruit", ["name", "color"])
>>> f = Fruit(name="banana", color="red")
>>> print f
Fruit(name='banana', color='red')
>>> f.name
'banana'
>>> f.color
'red'
Now you can use your fruitcount dict:
>>> fruitcount = {Fruit("banana", "red"):5}
>>> fruitcount[f]
5
Other tricks:
>>> fruits = fruitcount.keys()
>>> fruits.sort()
>>> print fruits
[Fruit(name='apple', color='green'),
Fruit(name='apple', color='red'),
Fruit(name='banana', color='blue'),
Fruit(name='strawberry', color='blue')]
>>> fruits.sort(key=lambda x:x.color)
>>> print fruits
[Fruit(name='banana', color='blue'),
Fruit(name='strawberry', color='blue'),
Fruit(name='apple', color='green'),
Fruit(name='apple', color='red')]
Echoing chmullig, to get a list of all colors of one fruit, you would have to filter the keys, i.e.
bananas = [fruit for fruit in fruits if fruit.name=='banana']
Since Python 3.3, you can use the class ExitStack
from the contextlib
module to safely
open an arbitrary number of files.
It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
If you are interested in the details, here is a generic example in order to explain how ExitStack
operates:
from contextlib import ExitStack
class X:
num = 1
def __init__(self):
self.num = X.num
X.num += 1
def __repr__(self):
cls = type(self)
return '{cls.__name__}{self.num}'.format(cls=cls, self=self)
def __enter__(self):
print('enter {!r}'.format(self))
return self.num
def __exit__(self, exc_type, exc_value, traceback):
print('exit {!r}'.format(self))
return True
xs = [X() for _ in range(3)]
with ExitStack() as stack:
print(len(stack._exit_callbacks)) # number of callbacks called on exit
nums = [stack.enter_context(x) for x in xs]
print(len(stack._exit_callbacks))
print(len(stack._exit_callbacks))
print(nums)
Output:
0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]
If you have an element that does not have a specific selector and you still want to check if it is a descendant of another element, you can use jQuery.contains()
jQuery.contains( container, contained )
Description: Check to see if a DOM element is a descendant of another DOM element.
You can pass the parent element and the element that you want to check to that function and it returns if the latter is a descendant of the first.
Here is the way to do it:
#!/bin/sh
abort()
{
echo >&2 '
***************
*** ABORTED ***
***************
'
echo "An error occurred. Exiting..." >&2
exit 1
}
trap 'abort' 0
set -e
# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0
echo >&2 '
************
*** DONE ***
************
'
I recorded a macro making a hiperlink. This resulted.
ActiveCell.FormulaR1C1 = "=HYPERLINK(""[Workbook.xlsx]Sheet1!A1"",""CLICK HERE"")"
If keyCode
is not caught, catch which
:
$('#formid').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
EDIT: missed it, it's better to use keyup
instead of keypress
EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.
EDIT 3: Changed bind()
to on()
If installed as an admin, use:-
uname - admin
pw - the passkey that was generated during installation
Try using this, this worked fine for me.
json_encode(unserialize(serialize($array)));
You can use this
 
or  
It works on Visual Studio
If you are using a database that supports map-reduce, like couchdb, storing tags in a plain text field or list field is indeed the best way. Example:
tagcloud: {
map: function(doc){
for(tag in doc.tags){
emit(doc.tags[tag],1)
}
}
reduce: function(keys,values){
return values.length
}
}
Running this with group=true will group the results by tag name, and even return a count of the number of times that tag was encountered. It's very similar to counting the occurrences of a word in text.
Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator
Give full access of .composer to user.
sudo chown -R 'user-name' /home/'user-name'/.composer
or
sudo chmod 777 -R /home/'user-name'/.composer
user-name
is your system user-name.
to get user-name type "whoami" in terminal:
It's not necessary to convert to timestamp to do the comparison, given that the strings are validated as dates in 'YYYY-MM-DD' canonical format.
This test will work:
( ( $date_from_user >= $start_date ) && ( $date_from_user <= $end_date ) )
given:
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
NOTE: Comparing strings like this does allow for "non-valid" dates e.g. (December 32nd ) '2009-13-32' and for weirdly formatted strings '2009/3/3', such that a string comparison will NOT be equivalent to a date or timestamp comparison. This works ONLY if the date values in the strings are in a CONSISTENT and CANONICAL format.
EDIT to add a note here, elaborating on the obvious.
By CONSISTENT, I mean for example that the strings being compared must be in identical format: the month must always be two characters, the day must always be two characters, and the separator character must always be a dash. We can't reliably compare "strings" that aren't four character year, two character month, two character day. If we had a mix of one character and two character months in the strings, for example, we'd get unexpected result when we compared, '2009-9-30'
to '2009-10-11'
. We humanly see "9" as being less than "10", but a string comparison will see '2009-9'
as greater than '2009-1'
. We don't necessarily need to have a dash separator characters; we could just as reliably compare strings in 'YYYYMMDD'
format; if there is a separator character, it has to always be there and always be the same.
By CANONICAL, I mean that a format that will result in strings that will be sorted in date order. That is, the string will have a representation of "year" first, then "month", then "day". We can't reliably compare strings in 'MM-DD-YYYY'
format, because that's not canonical. A string comparison would compare the MM
(month) before it compared YYYY
(year) since the string comparison works from left to right.) A big benefit of the 'YYYY-MM-DD' string format is that it is canonical; dates represented in this format can reliably be compared as strings.
[ADDENDUM]
If you do go for the php timestamp conversion, be aware of the limitations.
On some platforms, php does not support timestamp values earlier than 1970-01-01 and/or later than 2038-01-19. (That's the nature of the unix timestamp 32-bit integer.) Later versions pf php (5.3?) are supposed to address that.
The timezone can also be an issue, if you aren't careful to use the same timezone when converting from string to timestamp and from timestamp back to string.
HTH
I know this is a bit late, but if this helps anybody, I think you could add a column to your data that calculates if the probability is ">='PivotSheet'$D$2"
(reference a cell on the pivot table
sheet).
Then, add that column to your pivot table and use the new column as a true/false
filter.
You can then change the value stored in the referenced cell to update your probability threshold.
If I understood your question right, this may get you what you wanted. The filter value would be displayed on the sheet with the pivot and can be changed to suit any quick changes to your probability threshold. The T/F Filter can be labeled "Above/At Probability Threshold" or something like that.
I've used this to do something similar. It was handy to have the cell reference on the Pivot table sheet so I could update the value and refresh the pivot to quickly modify the results. The people I did that for couldn't make up their minds on what that threshold should be.
According to this documentation (a place full of goodies:)):
driver.current_url
or, see official documentation: https://seleniumhq.github.io/docs/site/en/webdriver/browser_manipulation/#get-current-url
In order to simulate the issue that you are facing, I created the following sample using SSIS 2008 R2
with SQL Server 2008 R2
backend. The example is based on what I gathered from your question. This example doesn't provide a solution but it might help you to identify where the problem could be in your case.
Created a simple CSV file with two columns namely order number and order date. As you had mentioned in your question, values of both the columns are qualified with double quotes (") and also the lines end with Line Feed (\n) with the date being the last column. The below screenshot was taken using Notepad++, which can display the special characters in a file. LF in the screenshot denotes Line Feed.
Created a simple table named dbo.Destination
in the SQL Server database to populate the CSV file data using SSIS package. Create script for the table is given below.
CREATE TABLE [dbo].[Destination](
[OrderNumber] [varchar](50) NULL,
[OrderDate] [date] NULL
) ON [PRIMARY]
GO
On the SSIS package, I created two connection managers. SQLServer was created using the OLE DB Connection to connect to the SQL Server database. FlatFile is a flat file connection manager.
Flat file connection manager was configured to read the CSV file and the settings are shown below. The red arrows indicate the changes made.
Provided a name to the flat file connection manager. Browsed to the location of the CSV file and selected the file path. Entered the double quote ("
) as the text qualifier. Changed the Header row delimiter from {CR}{LF} to {LF}
. This header row delimiter change also reflects on the Columns section.
No changes were made in the Columns section.
Changed the column name from Column0 to OrderNumber
.
Changed the column name from Column1 to OrderDate
and also changed the data type to date [DT_DATE]
Preview of the data within the flat file connection manager looks good.
On the Control Flow
tab of the SSIS package, placed a Data Flow Task
.
Within the Data Flow Task, placed a Flat File Source
and an OLE DB Destination
.
The Flat File Source
was configured to read the CSV file data using the FlatFile connection manager. Below three screenshots show how the flat file source component was configured.
The OLE DB Destination
component was configured to accept the data from Flat File Source and insert it into SQL Server database table named dbo.Destination
. Below three screenshots show how the OLE DB Destination component was configured.
Using the steps mentioned in the below 5 screenshots, I added a data viewer on the flow between the Flat File Source and OLE DB Destination.
Before running the package, I verified the initial data present in the table. It is currently empty because I created this using the script provided at the beginning of this post.
Executed the package and the package execution temporarily paused to display the data flowing from Flat File Source to OLE DB Destination in the data viewer. I clicked on the run button to proceed with the execution.
The package executed successfully.
Flat file source data was inserted successfully into the table dbo.Destination
.
Here is the layout of the table dbo.Destination. As you can see, the field OrderDate is of data type date and the package still continued to insert the data correctly.
This post even though is not a solution. Hopefully helps you to find out where the problem could be in your scenario.
This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.
<LimitExcept OPTIONS>
AuthType Basic
AuthName <AUTH_NAME>
Require valid-user
AuthUserFile <FILE_PATH>
</LimitExcept>
You can get element count of list by following two ways:
>>> l = ['a','b','c']
>>> len(l)
3
>>> l.__len__()
3
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
If you are on OSX, then it's ~/.profile
<asp:RadioButtonList ID="rbn" runat="server" RepeatLayout="Table" RepeatColumns="2"
Width="100%" >
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
<asp:ListItem Text="3"></asp:ListItem>
<asp:ListItem Text="4"></asp:ListItem>
</asp:RadioButtonList>
Slide animation can be applied to activity transitions by calling overridePendingTransition and passing animation resources for enter and exit activities.
Slide animations can be slid right, slide left, slide up and slide down.
Slide up
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<scale
android:duration="800"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
Slide down
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<scale
android:duration="800"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
overridePendingTransition(R.anim.slide_down, R.anim.slide_up);
See activity transition animation examples for more activity transition examples.
@Martijn your order of function calls is slightly off. Try this instead:
x=-3:0.1:3;
y = x.^3;
plot(x,y), hold on
plot([-3 3], [0 0], 'k:')
hold off
No need to add any extra base64 library. Simple 5 line solution -
var img = new Image();
img.src = path.resolve('sample.jpg');
var doc = new jsPDF('p', 'mm', 'a3'); // optional parameters
doc.addImage(img, 'JPEG', 1, 2);
doc.save("new.pdf");
If you are using react you can use the as
operator.
let inputValue = (document.getElementById(elementId) as HTMLInputElement).value;
With that level of accuracy, it would be better to reason in CPU tick rather than in system call like clock(). And do not forget that if it takes more than one nanosecond to execute an instruction... having a nanosecond accuracy is pretty much impossible.
Still, something like that is a start:
Here's the actual code to retrieve number of 80x86 CPU clock ticks passed since the CPU was last started. It will work on Pentium and above (386/486 not supported). This code is actually MS Visual C++ specific, but can be probably very easy ported to whatever else, as long as it supports inline assembly.
inline __int64 GetCpuClocks()
{
// Counter
struct { int32 low, high; } counter;
// Use RDTSC instruction to get clocks count
__asm push EAX
__asm push EDX
__asm __emit 0fh __asm __emit 031h // RDTSC
__asm mov counter.low, EAX
__asm mov counter.high, EDX
__asm pop EDX
__asm pop EAX
// Return result
return *(__int64 *)(&counter);
}
This function has also the advantage of being extremely fast - it usually takes no more than 50 cpu cycles to execute.
Using the Timing Figures:
If you need to translate the clock counts into true elapsed time, divide the results by your chip's clock speed. Remember that the "rated" GHz is likely to be slightly different from the actual speed of your chip. To check your chip's true speed, you can use several very good utilities or the Win32 call, QueryPerformanceFrequency().
The fastest way I have found is to resolve the conflict, then do git add -u
, and then do git reset HEAD
, that doesn't even involve a commit.
This will happen if we use any of the in built classes in the php library. I used the class name as Directory and I got the same error. If you get error first make sure that the class name you use is not one of the in built classes.
For window users, I found cmd eval `ssh-agent -s`
didn't work, but using git bash worked a treat eval `ssh-agent -s`; ssh-add KEY_LOCATION
, and making sure the windows service "OpenSSH Key Management" wasn't disabled
Swift 5:
If you have UILabel and someway boundingRect isn't working for you (I faced this problem. It always returned 1 line height.) there is an extension to easily calculate label size.
extension UILabel {
func getSize(constrainedWidth: CGFloat) -> CGSize {
return systemLayoutSizeFitting(CGSize(width: constrainedWidth, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
}
}
You can use it like this:
let label = UILabel()
label.text = "My text\nIs\nAwesome"
let labelSize = label.getSize(constrainedWidth:200.0)
Works for me
QEMU has a fantastic utility called qmeu-img that will translate between all manner of disk image formats. An article on this process is at http://thedarkmaster.wordpress.com/2007/03/12/vmware-virtual-machine-to-virtual-box-conversion-how-to/
I recall in my head that I used qemu-img to roll multiple VMDKs into one, but I don't have that computer with me to retest the process. Even if I'm wrong, the article above includes a section that describes how to convert them with your VMWare tools.
public function index() {
$user = $this->session->userdata("username");
$file_path = "./images/" . $user . '/';
if (isset($_FILES['multipleUpload'])) {
if (!is_dir('images/' . $user)) {
mkdir('./images/' . $user, 0777, TRUE);
}
$files = $_FILES;
$cpt = count($_FILES ['multipleUpload'] ['name']);
for ($i = 0; $i < $cpt; $i ++) {
$name = time().$files ['multipleUpload'] ['name'] [$i];
$_FILES ['multipleUpload'] ['name'] = $name;
$_FILES ['multipleUpload'] ['type'] = $files ['multipleUpload'] ['type'] [$i];
$_FILES ['multipleUpload'] ['tmp_name'] = $files ['multipleUpload'] ['tmp_name'] [$i];
$_FILES ['multipleUpload'] ['error'] = $files ['multipleUpload'] ['error'] [$i];
$_FILES ['multipleUpload'] ['size'] = $files ['multipleUpload'] ['size'] [$i];
$this->upload->initialize($this->set_upload_options($file_path));
if(!($this->upload->do_upload('multipleUpload')) || $files ['multipleUpload'] ['error'] [$i] !=0)
{
print_r($this->upload->display_errors());
}
else
{
$this->load->model('uploadModel','um');
$this->um->insertRecord($user,$name);
}
}
} else {
$this->load->view('uploadForm');
}
}
public function set_upload_options($file_path) {
// upload an image options
$config = array();
$config ['upload_path'] = $file_path;
$config ['allowed_types'] = 'gif|jpg|png';
return $config;
}
Here's how I do it. You could do it the same way, or use this code for ideas.
let s = "www.stackoverflow.com"
s.substringWithRange(0..<s.lastIndexOf("."))
Here are the extensions I use:
import Foundation
extension String {
var length: Int {
get {
return countElements(self)
}
}
func indexOf(target: String) -> Int {
var range = self.rangeOfString(target)
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func indexOf(target: String, startIndex: Int) -> Int {
var startRange = advance(self.startIndex, startIndex)
var range = self.rangeOfString(target, options: NSStringCompareOptions.LiteralSearch, range: Range<String.Index>(start: startRange, end: self.endIndex))
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func lastIndexOf(target: String) -> Int {
var index = -1
var stepIndex = self.indexOf(target)
while stepIndex > -1 {
index = stepIndex
if stepIndex + target.length < self.length {
stepIndex = indexOf(target, startIndex: stepIndex + target.length)
} else {
stepIndex = -1
}
}
return index
}
func substringWithRange(range:Range<Int>) -> String {
let start = advance(self.startIndex, range.startIndex)
let end = advance(self.startIndex, range.endIndex)
return self.substringWithRange(start..<end)
}
}
Credit albertbori / Common Swift String Extensions
Generally I am a strong proponent of extensions, especially for needs like string manipulation, searching, and slicing.
Your server may read a different my.cnf
than the one you're editing (unless you specified it when starting mysqld).
From the MySQL Certification Study Guide:
The search order includes two general option files,
/etc/my.cnf
and$MYSQL_HOME/my.cnf
. The second file is used only if theMYSQL_HOME
environment variable is set. Typically, you seet it to the MySQL installation directory. (The mysqld_safe script attempts to setMYSQL_HOME
if it is not set before starting the server.) The option file search order also includes~/.my.cnf
(that is the home directory). This isn't an especially suitable location for server options. (Normally, you invoke the server asmysql
, or asroot
with a--user=mysql
option. The user-specific file read by the server would depend on which login account you invoke it from, possibly leading to inconsistent sets of options being used.)
Another possibility is of course, that your sql-mode
option gets overwritten further down in the same file. Multiple options have to be separated by ,
in the same line.
P.S.: And you need the quotes, IIRC. Now that you've tried it without quotes, I'm pretty sure, you're editing the wrong file, since MySQL doesn't start when there's an error in the option file.
P.P.S.: Had a look at my config files again, there it's
[mysqld]
sql_mode = "NO_ENGINE_SUBSTITUTION"
and it's working.
I just had the same problem with Parent/Child collections and found that post which has solved my case. I Only wanted to show the List of parent collection items and didn't need any of the child data, therefore i used the following and it worked fine:
JsonConvert.SerializeObject(ResultGroups, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
JSON.NET Error Self referencing loop detected for type
it also referes to the Json.NET codeplex page at:
http://json.codeplex.com/discussions/272371
Documentation: ReferenceLoopHandling setting
Json.NET does this...
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = JsonConvert.SerializeObject(values);
// {
// "key1": "value1",
// "key2": "value2"
// }
More examples: Serializing Collections with Json.NET
Just copy the App.config file from the service project to the console host application and paste here and then delete it from the service project.
I used the command
ansible -i inventory example -m ping -u <your_user_name> --ask-pass
And it will ask for your password.
For anyone who gets the error:
to use the 'ssh' connection type with passwords, you must install the sshpass program
On MacOS, you can follow below instructions to install sshpass:
For a single file you can use -O
instead of -o filename
to use the last segment of the URL path as the filename. Example:
curl http://example.com/folder/big-file.iso -O
will save the results to a new file named big-file.iso in the current folder. In this way it works similar to wget but allows you to specify other curl options that are not available when using wget.
:set list
in Vim will show whitespace. End of lines show as '$
' and carriage returns usually show as '^M
'.
Underline to multiple strings in a sentence.
extension UILabel {
func underlineMyText(range1:String, range2:String) {
if let textString = self.text {
let str = NSString(string: textString)
let firstRange = str.range(of: range1)
let secRange = str.range(of: range2)
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: firstRange)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: secRange)
attributedText = attributedString
}
}
}
Use by this way.
lbl.text = "By continuing you agree to our Terms of Service and Privacy Policy."
lbl.underlineMyText(range1: "Terms of Service", range2: "Privacy Policy.")
The Distinct()
is going to mess up the ordering, so you'll have to the sorting after that.
var uniqueColors =
(from dbo in database.MainTable
where dbo.Property == true
select dbo.Color.Name).Distinct().OrderBy(name=>name);
Have a look at
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array
for documentation on JavaScript Arrays.
jQuery is a library which adds some magic to JavaScript which is a capable and featurefull scripting language. The libraries just fill in the gaps - get to know the core!
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
Since that method is static, it already has everything you need to use it, so it defeats the purpose of mocking. Mocking the static methods is considered to be a bad practice.
If you try to do that, it means there is something wrong with the way you want to perform testing.
Of course you can use PowerMockito or any other framework capable of doing that, but try to rethink your approach.
For example: try to mock/provide the objects, which that static method consumes instead.
You do not have to use final
, but the final
is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.
Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.
An aspect the other answers are missing out unfortunately, is that using the combination of public final
needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public
).
Here's why:
final
, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.public
, the compiler will also inline this value into any other compile unit. That means other classes using this field.What are the consequences?
Imagine you have this:
class Foo {
public static final String VERSION = "1.0";
}
class Bar {
public static void main(String[] args) {
System.out.println("I am using version " + Foo.VERSION);
}
}
After compiling and running Bar
, you'll get:
I am using version 1.0
Now, you improve Foo
and change the version to "1.1".
After recompiling Foo
, you run Bar
and get this wrong output:
I am using version 1.0
This happens, because VERSION
is declared final
, so the actual value of it was already in-lined in Bar
during the first compile run. As a consequence, to let the example of a public static final ...
field propagate properly after actually changing what was declared final
(you lied!;), you'd need to recompile every class using it.
I've seen this a couple of times and it is really hard to debug.
If by final
you mean a constant that might change in later versions of your program, a better solution would be this:
class Foo {
private static String version = "1.0";
public static final String getVersion() {
return version;
}
}
The performance penalty of this is negligible, since JIT code generator will inline it at run-time.
The comm command (short for "common") may be useful comm - compare two sorted files line by line
#find lines only in file1
comm -23 file1 file2
#find lines only in file2
comm -13 file1 file2
#find lines common to both files
comm -12 file1 file2
The man
file is actually quite readable for this.
import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)
Just my 2 cents here. Mostly this will work for you, as it did for me.
body > .row {
margin-left: 0px;
margin-right: 0px;
}
It's an eclipse setup issue, not a Jersey issue.
From this thread ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
Right click your eclipse project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Gradle Dependencies -> Finish.
So Eclipse wasn't using the Gradle dependencies when Apache was starting .
As wizzard pointed out, the correct method is,
new Date().getTime();
or under Javascript 1.5, just
Date.now();
From the documentation,
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
If you wanted to make a time stamp without milliseconds you can use,
Math.floor(Date.now() / 1000);
I wanted to make this an answer so the correct method is more visible.
You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s
on a Unix terminal.
String foo = "title part1.txt";
foo = foo.substring(0, foo.lastIndexOf('.'));
As none of the answers above are straight forward:
Backslash escape \ is what you need:
myscript \"test\"
In IE11, you can see local storage in console on dev tools:
localStorage
and press EnterAlso, if you need to clear the localStorage, type localStorage.clear()
on console.
If you want to start with a file you can do this
[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName
Here's what I used:
In JavaScript:
var url = "http://www.mynewsfeed.com/articles/index.php?id=17";
var encoded_url = encodeURIComponent(url);
var decoded_url = decodeURIComponent(encoded_url);
In PHP:
$url = "http://www.mynewsfeed.com/articles/index.php?id=17";
$encoded_url = url_encode(url);
$decoded_url = url_decode($encoded_url);
You can also try it online here: http://www.mynewsfeed.x10.mx/articles/index.php?id=17
gtools/smartbind didnt like working with Dates, probably because it was as.vectoring. So here's my solution...
sbind = function(x, y, fill=NA) {
sbind.fill = function(d, cols){
for(c in cols)
d[[c]] = fill
d
}
x = sbind.fill(x, setdiff(names(y),names(x)))
y = sbind.fill(y, setdiff(names(x),names(y)))
rbind(x, y)
}
"location" : null // this is not really an array it's a null object
"location" : [] // this is an empty array
It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.
notepad filename.extension will open notepad editor
As on 2014, I can finally say that LINQ is finally there in java 8.So no need to find an alternative of LINQ anymore.
DateTimePicker1.value = Format(Date.Now)
From what I've been able to piece together, you have to add the view using LayoutParams.
LinearLayout linearLayout = new LinearLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
parentView.addView(linearLayout, relativeParams);
All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.
TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);
Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());
If you want to split only by newlines, you can use str.splitlines():
Example:
>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
With str.split() your case also works:
>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.split()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
However if you have spaces (or tabs) it will fail:
>>> data = """
... a, eqw, qwe
... v, ewr, err
... """
>>> data
'\na, eqw, qwe\nv, ewr, err\n'
>>> data.split()
['a,', 'eqw,', 'qwe', 'v,', 'ewr,', 'err']
heikkim is right, here is some sample code adapted from some code I have:
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
...
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
row = sheet.getRow(rowIndex);
if (row != null) {
Cell cell = row.getCell(colIndex);
if (cell != null) {
// Found column and there is value in the cell.
cellValueMaybeNull = cell.getStringCellValue();
// Do something with the cellValueMaybeNull here ...
// break; ???
}
}
}
For the colCount
use something like row.getPhysicalNumberOfCells()
Use it like this:
$("#searchField").focus(function() {
$(this).val("");
});
It has to work. Otherwise it probably never gets focused.
Try this:
package example.spin.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
</RelativeLayout>
var dtRegex = new RegExp(/[1-9\-]{4}[0-9\-]{2}[0-9\-]{2}/);
if(dtRegex.test(date) == true){
var evalDate = date.split('-');
if(evalDate[0] != '0000' && evalDate[1] != '00' && evalDate[2] != '00'){
return true;
}
}
You can use default values for the parameters of stored procedures:
CREATE PROCEDURE MyTestProcedure ( @MyParam1 INT,
@MyParam2 VARCHAR(20) = ‘ABC’,
@MyParam3 INT = NULL)
AS
BEGIN
-- Procedure body here
END
If @MyParam2 is not supplied, it will have the 'ABC' value...
In the accepted answer
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
should be
public Node(T data, Node<T> parent) {
this.data = data;
this.setParent(parent);
}
otherwise the parent does not have the child in its children list
Add this code in your validate method:
errorLabelContainer: '#errors'
and in your html, put simply this where you want to catch the error:
<div id="errors"></div>
All the errors will be held in the div, independently of your input box.
It worked very fine for me.
On the link put a hash:
<a href="otherpage.html#elementID">Jump</a>
And on other page, you can do:
$('html,body').animate({
scrollTop: $(window.location.hash).offset().top
});
On other page, you should have element with id set to elementID
to scroll to. Of course you can change the name of it.
XML file:
<Spinner
android:id="@+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Java file:
public class SpinnerExample extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] arraySpinner = new String[] {
"1", "2", "3", "4", "5", "6", "7"
};
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arraySpinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
}
}
You forgot to add a position property to the .dummy-wrap
class, and the top/left/bottom/right values don't apply to statically positioned elements (the default)
For UNIX:
As Stephen C has suggested, changing the maximum file descriptor value to a higher value avoids this problem.
Try looking at your present file descriptor capacity:
$ ulimit -n
Then change the limit according to your requirements.
$ ulimit -n <value>
Note that this just changes the limits in the current shell and any child / descendant process. To make the change "stick" you need to put it into the relevant shell script or initialization file.
Use command
google-chrome-stable
We can also use command
google-chrome
To open terminal but in my case when I make an interrupt ctrl + c
then it get closed so I would recommend to use google-chrome-stable
instead of google-chrome
Just create a class or structure that has two members, one List(Of OneItem)
and the other Integer
and send in an instance of that class.
Edit: Sorry, missed that you had problems with one parameter as well. Just look at Thread Constructor (ParameterizedThreadStart) and that page includes a simple sample.
If you want to learn, REALLY want to learn, then time is not of consequence. Just move forward everyday. Let your passion for this stuff drive you forward. And one day you'll see that you are good at C#/.NET.
This was a major problem for me and I found the following link with a relatively simple answer. Thanks Voyager!!!
Note that I named the range I wanted others to be able to sort
http://answers.yahoo.com/question/index?qid=20090419000032AAs5VRR
Other answers already provide information for iOS 7 and older, however UIAlertView
is deprecated in iOS 8.
In iOS 8+ you should use UIAlertController
. It is a replacement for both UIAlertView
and UIActionSheet
. Documentation: UIAlertController Class Reference. And a nice article on NSHipster.
To create a simple Alert View you can do the following:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title"
message:@"Message"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
Swift 3 / 4 / 5:
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: "OK",
style: .default,
handler: nil) //You can use a block here to handle a press on this button
alertController.addAction(actionOk)
self.present(alertController, animated: true, completion: nil)
Note, that, since it was added in iOS 8, this code won't work on iOS 7 and older. So, sadly, for now we have to use version checks like so:
NSString *alertTitle = @"Title";
NSString *alertMessage = @"Message";
NSString *alertOkButtonText = @"Ok";
if (@available(iOS 8, *)) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:alertOkButtonText, nil];
[alertView show];
}
else {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:alertOkButtonText
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
Swift 3 / 4 / 5:
let alertTitle = "Title"
let alertMessage = "Message"
let alertOkButtonText = "Ok"
if #available(iOS 8, *) {
let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: alertOkButtonText,
style: .default,
handler: nil) //You can use a block here to handle a press on this button
alertController.addAction(actionOk)
self.present(alertController, animated: true, completion: nil)
}
else {
let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText)
alertView.show()
}
UPD: updated for Swift 5. Replaced outdated class presence check with availability check in Obj-C.
Just add a .
to it:
svn checkout file:///home/landonwinters/svn/waterproject/trunk .
That means: check out to current directory.
I faced the same issue. Our application running on four application servers and due to invalid schema location mentioned on one of the web service WSDL, hung threads are generated on the servers . The appliucations got down frequently. After corrected the schema Location , the issue got resolved.
Because of the condition in while
, the loop might never break:
while (entry != null) {
// If entry never becomes null here, loop will never break.
}
Instead of the null
check there, you can try this:
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
// Rest of your code
}
Use Aptana Studio 3, it's upgraded now.
You can either choose
Try online Aloha WYSIWYG Editor
But as a web-developer, I still prefer Notepad++, it has necessary code assists.
This might be late answer, yeah very late answer, but surely will help someone
Download "Eclipse IDE for Java EE Developers" Latest Stable Version
Download Google Plugin for Eclipse.zip
Select your download according to your Eclipse Version
After Downloading (don't Unzip)
Open Eclipse
Help > Install New Software > Add > Archive > Select the Downloaded Plug-in.zip
in the field "Name" enter "Google Plugin" Click ok.
How to use Google Plugin for Eclipse
File > New > Other > Web > Static Web Project > Enter Project name
Create New HTML File
Name to index.html
Select Properties of HTML File
Hit Ctrl+Space
similarly create new *.css file
Right Click on the css file > Properties > Web Content Settings > Select CSS3 Profile > ok
Hit CTRL+Space
Wooo, Yeah Start Coding.!
It is not automatic. Your top function looks ok.
Set the Credentials property before sending the message.
I had the same issue!
I had installed the ADT bundle 64-bit, so I downloaded Java 64-bit. I messed around with paths and things, but the thing that fixed it in the end was installing Java 32-bit.
The easy fix is to install both versions. You can download them manually here.
Good luck!
ngClick directive (as well as all other event directives) creates $event
variable which is available on same scope. This variable is a reference to JS event
object and can be used to call stopPropagation()
:
<table>
<tr ng-repeat="user in users" ng-click="showUser(user)">
<td>{{user.firstname}}</td>
<td>{{user.lastname}}</td>
<td>
<button class="btn" ng-click="deleteUser(user.id, $index); $event.stopPropagation();">
Delete
</button>
</td>
</tr>
</table>