This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.
RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"
Just to update this answer for the sake of others who happen to end up on this page.
In Rails 3, you just need to create a file at views/users/show.json.erb
. The @user
object will be available to the view (just like it would be for html.) You don't even need to_json
anymore.
To summarize, it's just
# users contoller
def show
@user = User.find( params[:id] )
respond_to do |format|
format.html
format.json
end
end
and
/* views/users/show.json.erb */
{
"name" : "<%= @user.name %>"
}
Use a case
switch to translate the codes into numbers that can be sorted:
ORDER BY
case x_field
when 'f' then 1
when 'p' then 2
when 'i' then 3
when 'a' then 4
else 5
end
Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:
int *fun()
{
int *point;
*point=12; <<<<<< your program crashed here.
return point;
}
The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.
Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.
int *fun()
{
int point;
point = 12;
return (&point);
}
or almost identically:
int *fun()
{
int point;
int *point_ptr;
point_ptr = &point;
*point_ptr = 12;
return (point_ptr);
}
Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:
int *fun()
{
static int point;
int *point_ptr;
point_ptr = &point;
*point_ptr = 12;
return (point_ptr);
}
or
int *fun()
{
static int point;
point = 12;
return (&point);
}
As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.
Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:
^([A-Z]{3})$
The {3}
indicates that the [A-Z]
must appear exactly 3 times.
for Laravel 5.4
for gmail
in .env file
MAIL_DRIVER=mail
MAIL_HOST=mail.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<username>@gmail.com
MAIL_PASSWORD=<password>
MAIL_ENCRYPTION=tls
in config/mail.php
'driver' => env('MAIL_DRIVER', 'mail'),
'from' => [
'address' => env(
'MAIL_FROM_ADDRESS', '<username>@gmail.com'
),
'name' => env(
'MAIL_FROM_NAME', '<from_name>'
),
],
Try smallR for writing quick R scripts in the command line:
http://code.google.com/p/simple-r/
(r
command in the directory)
Plotting from the command line using smallR would look like this:
r -p file.txt
All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
I use this routine to find the count of data rows. There is a minimum of overhead required, but by counting using a decreasing scale, even a very large result requires few iterations. For example, a result of 28,395 would only require 2 + 8 + 3 + 9 + 5, or 27 times through the loop, instead of a time-expensive 28,395 times.
Even were we to multiply that by 10 (283,950), the iteration count is the same 27 times.
Dim lWorksheetRecordCountScaler as Long
Dim lWorksheetRecordCount as Long
Const sDataColumn = "A" '<----Set to column that has data in all rows (Code, ID, etc.)
'Count the data records
lWorksheetRecordCountScaler = 100000 'Begin by counting in 100,000-record bites
lWorksheetRecordCount = lWorksheetRecordCountScaler
While lWorksheetRecordCountScaler >= 1
While Sheets("Sheet2").Range(sDataColumn & lWorksheetRecordCount + 2).Formula > " "
lWorksheetRecordCount = lWorksheetRecordCount + lWorksheetRecordCountScaler
Wend
'To the beginning of the previous bite, count 1/10th of the scale from there
lWorksheetRecordCount = lWorksheetRecordCount - lWorksheetRecordCountScaler
lWorksheetRecordCountScaler = lWorksheetRecordCountScaler / 10
Wend
lWorksheetRecordCount = lWorksheetRecordCount + 1 'Final answer
Just download "node.exe" from http://nodejs.org/dist/, select your favorite "node.js" version or take the latest. You can also take 64-bits version from "x64" sub-directory.
Then, go to http://nodejs.org/dist/npm/ to retrieve Zip-archive of your favorite "npm" version (recommanded : 1.4.10
). Extract the archive along "node.exe".
Finally, it is recommanded to add "node.js" directory to the PATH for convenience.
EDIT: I recommande to update npm using npm install npm -g
because versions provided by nodejs.org are very old.
If you want to keep original npm version, don't put npm alongside "node.exe"
. Just create a directory and use the same command with "global" flag, then copy .\node_modules\.bin\npm.cmd
to the new directory :
mkdir c:\app\npm\_latest
cd c:\app\npm\_latest
<NPM_ORIGINAL_PATH>\npm install npm
cp node_modules\.bin\npm.cmd npm.cmd
Finally change your PATH to use c:\app\npm\_latest
I ran into this problem on Windows 10 (N) with a new Anaconda installation based on Python 3.7 (OpenCV version 4.0). None of the above advice helped (such as installing OpenCV from the unofficial site nor installing VC Redistributable).
I checked DLL dependencies of ...\AppData\Local\conda\conda\envs\foo\Lib\site-packages\cv2\cv2.cp37-win_amd64.pyd
using dumpbin.exe
according to this github issue. I noticed a library MF.dll
, which I figured out belongs to Windows Media Foundation.
So I installed Media Feature Pack for N versions of Windows 10 and voilà, the issue was resolved!
You also can take an array of keys with type []Value
by method MapKeys
of struct Value
from package "reflect":
package main
import (
"fmt"
"reflect"
)
func main() {
abc := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
keys := reflect.ValueOf(abc).MapKeys()
fmt.Println(keys) // [a b c]
}
Use a delegated event handler bound to the container:
$('#pg_menu_content').on('click', '#btn_a', function(){
console.log(this.value);
});
That is, bind to an element that exists at the moment that the JS runs (I'm assuming #pg_menu_content
exists when the page loads), and supply a selector in the second parameter to .on()
. When a click occurs on #pg_menu_content
element jQuery checks whether it applied to a child of that element which matches the #btn_a
selector.
Either that or bind a standard (non-delegated) click handler after creating the button.
Either way, within the click handler this
will refer to the button in question, so this.value
will give you its value.
--simple codes--
#region odd / even numbers order by desc
//declaration of integer
int TotalCount = 50;
int loop;
Console.WriteLine("\n---------Odd Numbers -------\n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 == 0)
{
Console.WriteLine("Even numbers : #{0}", loop);
}
}
Console.WriteLine("\n---------Even Numbers -------\n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 != 0)
{
Console.WriteLine("odd numbers : #{0}", loop);
}
}
Console.ReadLine();
#endregion
Depending on your use case, you can use an image which has already been created and specify it's name in docker-compose
.
We have a production use case where our CI server builds a named Docker image. (docker build -t <specific_image_name> .
). Once the named image is specified, our docker-compose
always builds off of the specific image. This allows a couple of different possibilities:
1- You can ensure that where ever you run your docker-compose
from, you will always be using the latest version of that specific image.
2- You can specify multiple named images in your docker-compose
file and let them be auto-wired through the previous build step.
So, if your image is already built, you can name the image with docker-compose
. Remove build
and specify image:
wildfly:
image: my_custom_wildfly_image
container_name: wildfly_server
ports:
- 9990:9990
- 80:8080
environment:
- MYSQL_HOST=mysql_server
- MONGO_HOST=mongo_server
- ELASTIC_HOST=elasticsearch_server
volumes:
- /Volumes/CaseSensitive/development/wildfly/deployments/:/opt/jboss/wildfly/standalone/deployments/
links:
- mysql:mysql_server
- mongo:mongo_server
- elasticsearch:elasticsearch_server
If your variable is not declared nor defined:
if ( typeof query !== 'undefined' ) { ... }
If your variable is declared but undefined. (assuming the case here is that the variable might not be defined but it can be any other falsy value like false
or ""
)
if ( query ) { ... }
If your variable is declared but can be undefined
or null
:
if ( query != null ) { ... } // undefined == null
Try:
cursor.column_names
mysql connector version:
mysql.connector.__version__
'2.2.9'
<div class="form-group">
<label class="font-normal MyText">MyText to copy</label>
<button type="button" class="btn btn-default btn-xs btnCopy" data="MyText">Copy</button>
</div>
$(".btnCopy").click(function () {
var element = $(this).attr("data");
copyToClipboard($('.' + element));
});
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
Here is my solution. I can pad any character and it is fast. Went with simplicity. You can change variable size to meet your needs.
Updated with a parameter to handle what to return if null: null will return a null if null
CREATE OR ALTER FUNCTION code.fnConvert_PadLeft(
@in_str nvarchar(1024),
@pad_length int,
@pad_char nchar(1) = ' ',
@rtn_null NVARCHAR(1024) = '')
RETURNS NVARCHAR(1024)
AS
BEGIN
DECLARE @rtn NCHAR(1024) = ' '
RETURN RIGHT(REPLACE(@rtn,' ',@pad_char)+ISNULL(@in_str,@rtn_null), @pad_length)
END
GO
CREATE OR ALTER FUNCTION code.fnConvert_PadRight(
@in_str nvarchar(1024),
@pad_length int,
@pad_char nchar(1) = ' ',
@rtn_null NVARCHAR(1024) = '')
RETURNS NVARCHAR(1024)
AS
BEGIN
DECLARE @rtn NCHAR(1024) = ' '
RETURN LEFT(ISNULL(@in_str,@rtn_null)+REPLACE(@rtn,' ',@pad_char), @pad_length)
END
GO
-- Example
SET STATISTICS time ON
SELECT code.fnConvert_PadLeft('88',10,'0',''),
code.fnConvert_PadLeft(null,10,'0',''),
code.fnConvert_PadLeft(null,10,'0',null),
code.fnConvert_PadRight('88',10,'0',''),
code.fnConvert_PadRight(null,10,'0',''),
code.fnConvert_PadRight(null,10,'0',NULL)
0000000088 0000000000 NULL 8800000000 0000000000 NULL
Your code works fine. You can verify the RGB colors with Iconfactory's xScope. Just compare it to [UIColor whiteColor]
.
See http://ruby-doc.org/core/classes/Range.html#M000695 for the full API.
Basically you use the step()
method. For example:
(10..100).step(10) do |n|
# n = 10
# n = 20
# n = 30
# ...
end
malloc
is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:
char *literal = "foo";
However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc
:
char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);
You can achieve this by using few lines of code. So why you are going to stuck in third party library or UI. Pull to refresh is built in iOS. You could do this in swift like
var pullControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
pullControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
pullControl.addTarget(self, action: #selector(pulledRefreshControl(_:)), for: UIControl.Event.valueChanged)
tableView.addSubview(pullControl) // not required when using UITableViewController
}
@objc func pulledRefreshControl(sender:AnyObject) {
// Code to refresh table view
}
I was running create-react-app server. Simply stopped the server and everything worked just fine.
They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.
To answer your question posted in the title of this topic...
Step 1--> Right Click on Java Project, Select the option "Properties"
Step 2--> Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder"
Step 3--> Click the option "Create New Folder..." available at the bottom of the window
Step 4--> Enter the name of the new folder as "resources" and then click "Finish"
Step 5--> Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"
Final Step --> Now you should be able to see the new folder "resources" under your java project
if(StartDate < EndDate)
{}
DateTime supports normal comparision operators.
If you want to use ssh credentials,
git(
url: '[email protected]<repo_name>.git',
credentialsId: 'xpc',
branch: "${branch}"
)
if you want to use username and password credentials, you need to use http clone as @Serban mentioned.
git(
url: 'https://github.com/<repo_name>.git',
credentialsId: 'xpc',
branch: "${branch}"
)
Once when I was interviewing for Microsoft in college, the guy asked me how to detect a cycle in a linked list.
Having discussed in class the prior week the optimal solution to the problem, I started to tell him.
He told me, "No, no, everybody gives me that solution. Give me a different one."
I argued that my solution was optimal. He said, "I know it's optimal. Give me a sub-optimal one."
At the same time, it's a pretty good problem.
Vanilla JS solution:
var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));
Note that dispatchEvent
doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).
So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for:
typeof document.body.dispatchEvent === 'function'
.
1) Change your .net profile from Client profile to to .Net Framework 4.0 http://msdn.microsoft.com/en-us/library/bb398202.aspx
2) Check your Embed Interop Types flag
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
How about calling the .NET Framework methods?
You can do ANYTHING with them... :
[System.IO.File]::Copy($src, $dest, $true);
The $true
argument makes it overwrite.
For ordinary table markup, here's a short solution that works on all devices/browsers on BrowserStack, except IE 7 and below:
table { border-collapse: collapse; }
td + td,
th + th { border-left: 1px solid; }
tr + tr { border-top: 1px solid; }
For IE 7 support, add this:
tr + tr > td,
tr + tr > th { border-top: 1px solid; }
A test case can be seen here: http://codepen.io/dalgard/pen/wmcdE
Unfortunately, the DateTime class doesn't have the convenience methods available in the Time class to do this. You can convert any DateTime object into UTC like this:
d = DateTime.now
d.new_offset(Rational(0, 24))
You can switch back from UTC to localtime using:
d.new_offset(DateTime.now.offset)
where d
is a DateTime object in UTC time. If you'd like these as convenience methods, then you can create them like this:
class DateTime
def localtime
new_offset(DateTime.now.offset)
end
def utc
new_offset(Rational(0, 24))
end
end
You can see this in action in the following irb session:
d = DateTime.now.new_offset(Rational(-4, 24))
=> #<DateTime: 106105391484260677/43200000000,-1/6,2299161>
1.8.7 :185 > d.to_s
=> "2012-08-03T15:42:48-04:00"
1.8.7 :186 > d.localtime.to_s
=> "2012-08-03T12:42:48-07:00"
1.8.7 :187 > d.utc.to_s
=> "2012-08-03T19:42:48+00:00"
As you can see above, the initial DateTime object has a -04:00 offset (Eastern Time). I'm in Pacific Time with a -07:00 offset. Calling localtime
as described previously properly converts the DateTime object into local time. Calling utc
on the object properly converts it to a UTC offset.
Can be done via changing the Collation. By default it is case insensitive.
Excerpt from the link:
SELECT 1
FROM dbo.Customers
WHERE CustID = @CustID COLLATE SQL_Latin1_General_CP1_CS_AS
AND CustPassword = @CustPassword COLLATE SQL_Latin1_General_CP1_CS_AS
Had the same problem. A colleague solved this with jQuery.Globalize.
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/globalize.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/cultures/globalize.culture.nl.js"></script>
<script type="text/javascript">
var lang = 'nl';
$(function () {
Globalize.culture(lang);
});
// fixing a weird validation issue with dates (nl date notation) and Google Chrome
$.validator.methods.date = function(value, element) {
var d = Globalize.parseDate(value);
return this.optional(element) || !/Invalid|NaN/.test(d);
};
</script>
I am using jQuery Datepicker for selecting the date.
This method works for Excel 2016, and calculates on cell value, so can be used on formula arrays (i.e. it will ignore blank cells that contain a formula).
Note: Len(#)>0 be altered to only select cell values above a certain length.
Note 2: '#' must not be an absolute reference (i.e. shouldn't contain '$').
dynamic_cast
can determine if the type contains the target type anywhere in the inheritance hierarchy (yes, it's a little-known feature that if B
inherits from A
and C
, it can turn an A*
directly into a C*
). typeid()
can determine the exact type of the object. However, these should both be used extremely sparingly. As has been mentioned already, you should always be avoiding dynamic type identification, because it indicates a design flaw. (also, if you know the object is for sure of the target type, you can do a downcast with a static_cast
. Boost offers a polymorphic_downcast
that will do a downcast with dynamic_cast
and assert
in debug mode, and in release mode it will just use a static_cast
).
For recent hadoop versions (I'm using 2.7.1)
The start\stop scripts are located in the sbin
folder. The scripts are:
I didn't have to do anything with yarn though to get the NameNodeServer instance running.
Now my mistake was that I didn't format the NameNodeServer HDFS.
bin/hdfs namenode -format
I'm not quite sure what that does at the moment but it obviously prepares the space on which the NameNodeServer will use to operate.
foreach($shipmentarr as $index=>$val){
$additionalService = array();
foreach($additionalService[$index] as $key => $value) {
array_push($additionalService,$value);
}
}
import { Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'my-app',
template:
`
<input #inputEl value="hithere">
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild('inputEl') inputEl:ElementRef;
ngAfterViewInit() {
console.log(this.inputEl);
}
}
#inputEl
on the <input>
tag.ngAfterViewInit
lifecycle hook.Note:
If you want to manipulate the DOM elements use the Renderer2 API instead of accessing the elements directly. Permitting direct access to the DOM can make your application more vulnerable to XSS attacks
I have tried the following option in Helios Version of Eclipse. Simply press CTRL+F you will get the "Find/Replace" Window on your screen
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
I had a fully working project to which I was doing a minor change when this occured after updateting the SDK. Eclipse updated the SDK and the ADT but I could still not build the project. Exlipse said there were no further updates available.
The problem persisted until I manually uninstalled the ADT from eclipse and re-installed it. Only then would my project build. I had restarted eclipse inbetween each step.
In order to call this you will have to store a reference to your form and pass the reference to the run method. Then you can call this in an actionhandler.
public partial class Form1 : Form
{
public void ChangeSize(int width, int height)
{
this.Size = new Size(width, height);
}
}
Try this:
Get-WmiObject -Class "Win32_computersystem" | Format-List *
Get-WmiObject -Class "Win32_computersystem" | Format-List -Property *
For certain objects, PowerShell provides a set of formatting instructions that can affect either the table or list formats. These are usually meant to limit the display of reams of properties down to just the essential properties. However there are times when you really want to see everything. In those cases Format-List *
will show all the properties. Note that in the case where you're trying to view a PowerShell error record, you need to use "Format-List * -Force" to truly see all the error information, for example,
$error[0] | Format-List * -force
Note that the wildcard can be used like a traditional wilcard this:
Get-WmiObject -Class "Win32_computersystem" | Format-List M*
Using filter function:
>>> def get_values(iterables, key_to_find):
return list(filter(lambda x:key_to_find in x, iterables)) >>> a = [(1,2),(1,4),(3,5),(5,7)] >>> get_values(a, 1) >>> [(1, 2), (1, 4)]
From Angular 6.1, you can now avoid the hassle and pass extraOptions
to your RouterModule.forRoot()
as a second parameter and can specify scrollPositionRestoration: enabled
to tell Angular to scroll to top whenever the route changes.
By default you will find this in app-routing.module.ts
:
const routes: Routes = [
{
path: '...'
component: ...
},
...
];
@NgModule({
imports: [
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled', // Add options right here
})
],
exports: [RouterModule]
})
export class AppRoutingModule { }
Since you're writing a calculator that would presumably also accept floats (1.5, 0.03
), a more robust way would be to use this simple helper function:
def convertStr(s):
"""Convert string to either int or float."""
try:
ret = int(s)
except ValueError:
#Try float.
ret = float(s)
return ret
That way if the int conversion doesn't work, you'll get a float returned.
Edit: Your division
function might also result in some sad faces if you aren't fully aware of how python 2.x handles integer division.
In short, if you want 10/2
to equal 2.5
and not 2
, you'll need to do from __future__ import division
or cast one or both of the arguments to float, like so:
def division(a, b):
return float(a) / float(b)
Wildcards can only be used in the ServerAlias
rather than the ServerName
. Something which had me stumped.
For your use case, the following should suffice
<VirtualHost *:80>
ServerAlias *.example.com
VirtualDocumentRoot /var/www/%1/
</VirtualHost>
The title of the question leads people here, so I decided to answer that question for everyone else since the OP's described case was so limited.
I finally settled on writing a function.
0
in case of non-int:int(){ printf '%d' ${1:-} 2>/dev/null || :; }
int(){ expr 0 + ${1:-} 2>/dev/null||:; }
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
# This is a combination of numbers 1 and 2
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
If you want to get a non-zero status code on non-int, remove the ||:
(aka or true
) but leave the ;
# Wrapped in parens to call a subprocess and not `set` options in the main bash process
# In other words, you can literally copy-paste this code block into your shell to test
( set -eu;
tests=( 4 "5" "6foo" "bar7" "foo8.9bar" "baz" " " "" )
test(){ echo; type int; for test in "${tests[@]}"; do echo "got '$(int $test)' from '$test'"; done; echo "got '$(int)' with no argument"; }
int(){ printf '%d' ${1:-} 2>/dev/null||:; };
test
int(){ expr 0 + ${1:-} 2>/dev/null||:; }
test
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
test
int(){ printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null)||:; }
test
# unexpected inconsistent results from `bc`
int(){ bc<<<"${1:-}" 2>/dev/null||:; }
test
)
int is a function
int ()
{
printf '%d' ${1:-} 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '0' from '6foo'
got '0' from 'bar7'
got '0' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument
int is a function
int ()
{
expr 0 + ${1:-} 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '' from 'bar7'
got '' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument
int is a function
int ()
{
expr ${1:-} : '[^0-9]*\([0-9]*\)' 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument
int is a function
int ()
{
printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null) || :
}
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument
int is a function
int ()
{
bc <<< "${1:-}" 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '0' from 'bar7'
got '' from 'foo8.9bar'
got '0' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument
I got sent down this rabbit hole because the accepted answer is not compatible with set -o nounset
(aka set -u
)
# This works
$ ( number="3"; string="foo"; echo $((number)) $((string)); )
3 0
# This doesn't
$ ( set -u; number="3"; string="foo"; echo $((number)) $((string)); )
-bash: foo: unbound variable
This problem occurs when you do not declare at the top of your HTML file in HEDER this tag.
<link rel="icon" href="your_address_icon" type="image/x-icon">
I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).
Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:
#container {
height:100%;
width:100%;
overflow:hidden;
/* for IE */
zoom:1;
}
There is also a compact form for that, if you do not want to rely on strlen. Assuming that the character array you are considering is "msg":
unsigned int len=0;
while(*(msg+len) ) len++;
With default Github repository import it is possible, but just make sure the two factor authentication is not enabled in Gitlab.
Thanks
Project Structure
(?;) > Modules
> YOUR MODULE
-> Language
level: set 9, in your case.Even though Sheena's answer does the job, pip
doesn't stop just there.
From Sheena's answer:
- Download the package
- unzip it if it is zipped
- cd into the directory containing setup.py
- If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
- type in
python setup.py install
At the end of this, you'll end up with a .egg
file in site-packages
.
As a user, this shouldn't bother you. You can import
and uninstall
the package normally. However, if you want to do it the pip
way, you can continue the following steps.
In the site-packages
directory,
unzip <.egg file>
EGG-INFO
directory as <pkg>-<version>.dist-info
<pkg-directory>
find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD
. The >>
is to prevent overwrite.Now, looking at the site-packages
directory, you'll never realize you installed without pip
. To uninstall
, just do the usual pip uninstall <pkg>
.
In your case it's definitely the crawler instance is having more Xdebug limit to trace error and debug info.
But, in other cases also errors like on PHP or core files like CodeIgniter libraries will create such a case and if you even increase the x-debug level setting it would not vanish.
So, look into your code carefully :) .
Here was the issue in my case.
I had a service class which is library in CodeIgniter. Having a function inside like this.
class PaymentService {
private $CI;
public function __construct() {
$this->CI =& get_instance();
}
public function process(){
//lots of Ci referencing here...
}
My controller as follow:
$this->load->library('PaymentService');
$this->process_(); // see I got this wrong instead it shoud be like
Function call on last line was wrong because of the typo, instead it should have been like below:
$this->Payment_service->process(); //the library class name
Then I was keeping getting the exceed error message. But I disabled XDebug but non helped. Any way please check you class name or your code for proper function calling.
Here's a method that worked for me. When you type into the field, it puts that text into the hidden span, then gets its new width and applies it to the input field. It grows and shrinks with your input, with a safeguard against the input virtually disappearing when you erase all input. Tested in Chrome. (EDIT: works in Safari, Firefox and Edge at the time of this edit)
function travel_keyup(e)_x000D_
{_x000D_
if (e.target.value.length == 0) return;_x000D_
var oSpan=document.querySelector('#menu-enter-travel span');_x000D_
oSpan.textContent=e.target.value;_x000D_
match_span(e.target, oSpan);_x000D_
}_x000D_
function travel_keydown(e)_x000D_
{_x000D_
if (e.key.length == 1)_x000D_
{_x000D_
if (e.target.maxLength == e.target.value.length) return;_x000D_
var oSpan=document.querySelector('#menu-enter-travel span');_x000D_
oSpan.textContent=e.target.value + '' + e.key;_x000D_
match_span(e.target, oSpan);_x000D_
}_x000D_
}_x000D_
function match_span(oInput, oSpan)_x000D_
{_x000D_
oInput.style.width=oSpan.getBoundingClientRect().width + 'px';_x000D_
}_x000D_
_x000D_
window.addEventListener('load', function()_x000D_
{_x000D_
var oInput=document.querySelector('#menu-enter-travel input');_x000D_
oInput.addEventListener('keyup', travel_keyup);_x000D_
oInput.addEventListener('keydown', travel_keydown);_x000D_
_x000D_
match_span(oInput, document.querySelector('#menu-enter-travel span'));_x000D_
});
_x000D_
#menu-enter-travel input_x000D_
{_x000D_
width: 8px;_x000D_
}_x000D_
#menu-enter-travel span_x000D_
{_x000D_
visibility: hidden;_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
}
_x000D_
<div id="menu-enter-travel">_x000D_
<input type="text" pattern="^[0-9]{1,4}$" maxlength="4">KM_x000D_
<span>9</span>_x000D_
</div>
_x000D_
The idea is that the response body gives you a page that links you to the thing:
201 Created
The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.
This means that you would include a Location
in the response header that gives the URL of where you can find the newly created thing:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
They then go on to mention what you should include in the response body:
The 201 response payload typically describes and links to the resource(s) created.
For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: text/html
Your answer has been saved!
Click <A href="/a/36373586/12597">here</A> to view it.
If the page will only be used by a robot, the it makes sense to have the response be computer readable:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/xml
<createdResources>
<questionID>1860645</questionID>
<answerID>36373586</answerID>
<primary>/a/36373586/12597</primary>
<additional>
<resource>http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586</resource>
<resource>http://stackoverflow.com/a/1962757/12597</resource>
</additional>
</createdResource>
Or, if you prefer:
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/json
{
"questionID": 1860645,
"answerID": 36373586,
"primary": "/a/36373586/12597",
"additional": [
"http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586",
"http://stackoverflow.com/a/36373586/12597"
]
}
The response is entirely up to you; it's arbitrarily what you'd like.
Finally there's the optimization that I can pre-cache the created resource (because I already have the content; I just uploaded it). The server can return a date or ETag which I can store with the content I just uploaded:
See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.
HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/23704283/12597
Content-Type: text/html
ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4
Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT
Your answer has been saved!
Click <A href="/a/36373586/12597">here</A> to view it.
And ETag
s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The ETag is usually a hash (e.g. SHA2). But it can be a database rowversion
, or an incrementing revision number. Anything that will change when the thing changes.
If you're running into this error from a downloaded powershell script, you can unblock the script this way:
Right-click on the .ps1
file in question, and select Properties
Click Unblock in the file properties
Click OK
According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData});
Codetoffel answer does work just fine for me though.
I have found that the following implementations are effective:
$('#freeform_first_name').removeAttr('required');
$('#freeform_first_name').attr('required', 'required');
These commands (attr, removeAttr, prop) behave differently depending on the version of JQuery you are using. Please reference the documentation here: https://api.jquery.com/attr/
This line:
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:
setContentView(new GraphTemperature(getApplicationContext()));
And i'm guessing that new "graphTemperature" does not set anything with that id.
It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).
The nullpointer will be thrown because the layout you're looking for isn't found, so
layout.addView(buyButton);
Throws that exception.
addition: Now if you want to get that view from an XML, you should use an inflater:
layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);
assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"
Why does PHP turn the JSON Object into a class?
Take a closer look at the output of the encoded JSON, I've extended the example the OP is giving a little bit:
$array = array(
'stuff' => 'things',
'things' => array(
'controller', 'playing card', 'newspaper', 'sand paper', 'monitor', 'tree'
)
);
$arrayEncoded = json_encode($array);
echo $arrayEncoded;
//prints - {"stuff":"things","things":["controller","playing card","newspaper","sand paper","monitor","tree"]}
The JSON format was derived from the same standard as JavaScript (ECMAScript Programming Language Standard) and if you would look at the format it looks like JavaScript. It is a JSON object ({}
= object) having a property "stuff" with value "things" and has a property "things" with it's value being an array of strings ([]
= array).
JSON (as JavaScript) doesn't know associative arrays only indexed arrays. So when JSON encoding a PHP associative array, this will result in a JSON string containing this array as an "object".
Now we're decoding the JSON again using json_decode($arrayEncoded)
. The decode function doesn't know where this JSON string originated from (a PHP array) so it is decoding into an unknown object, which is stdClass
in PHP. As you will see, the "things" array of strings WILL decode into an indexed PHP array.
Also see:
Thanks to https://www.randomlists.com/things for the 'things'
You should pass length into fwrite instead of sizeof(buffer).
I faced this issue today, and I resolved it by doing the following steps:
1) manually inserting that troubling user providing value of mandatory fields into mysql.user
mysql> insert into user(Host, User, Password, ssl_type)
values ('localhost', 'jack', 'jack', 'ANY');
2)
mysql> select * from user where User = 'jack';
1 row in set (0.00 sec)
3) A.
mysql> drop user jack;
Query OK, 0 rows affected (0.00 sec)
B. mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
C. mysql> create user 'jack' identified by 'jack';
Query OK, 0 rows affected (0.00 sec)
D. mysql> select Host, User, Password, ssl_type from user where User = 'jack';
+-----------+-----------+-------------------------------------------+----------+
| Host | User | Password | ssl_type |
+-----------+-----------+-------------------------------------------+----------+
| localhost | jack | jack | ANY |
| % | jack | *45BB7035F11303D8F09B2877A00D2510DCE4D758 | |
+-----------+-----------+-------------------------------------------+----------+
2 rows in set (0.00 sec)
4) A.
mysql> delete from user
where User = 'nyse_user' and
Host = 'localhost' and
Password ='nyse';
Query OK, 1 row affected (0.00 sec)
B.
mysql> select Host, User, Password, ssl_type from user where User = 'jack';
+------+-----------+-------------------------------------------+----------+
| Host | User | Password | ssl_type |
+------+-----------+-------------------------------------------+----------+
| % | jack | *45BB7035F11303D8F09B2877A00D2510DCE4D758 | |
+------+-----------+-------------------------------------------+----------+
1 row in set (0.00 sec)
Hope this helps.
If it is just one instance that needs to be wrapped over 2 or 3 lines I would just use a few <wbr>
in the string. It will treat those just like <br>
but it wont insert the line break if it isn't necessary.
<div id="w74" class="dpinfo">
adsfadsadsads<wbr>fadsadsadsfadsadsa<wbr>dsfadsadsadsfadsadsads<wbr>fadsadsadsfadsadsadsfa<wbr>dsadsadsfadsadsadsfadsad<wbr>sadsfadsadsads<wbr>fadsadsadsfadsads adsfadsads
</div>
Here is a fiddle.
Because you're not specifying a precision and a rounding-mode. BigDecimal is complaining that it could use 10, 20, 5000, or infinity decimal places, and it still wouldn't be able to give you an exact representation of the number. So instead of giving you an incorrect BigDecimal, it just whinges at you.
However, if you supply a RoundingMode and a precision, then it will be able to convert (eg. 1.333333333-to-infinity to something like 1.3333 ... but you as the programmer need to tell it what precision you're 'happy with'.
Set your HTML as
<div id="body" hidden="">
<h1>Numbers</h1>
</div>
<div id="body1" hidden="hidden">
Body 1
</div>
And now set the javascript as
function changeDiv()
{
document.getElementById('body').hidden = "hidden"; // hide body div tag
document.getElementById('body1').hidden = ""; // show body1 div tag
document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked";
// display text if JavaScript worked
}
Setting windowLightStatusBar
to true
not works with Mi phones, some Meizu phones, Blackview phones, WileyFox etc.
I've found such hack for Mi and Meizu devices. This is not a comprehensive solution of this perfomance problem, but maybe it would be useful to somebody.
And I think, it would be better to tell your customer that coloring status bar (for example) white - is not a good idea. instead of using different hacks it would be better to define appropriate colorPrimaryDark
according to the guidelines
This worked for me:
.env
file and be sure APP_DEBUG=true
.env
file) change reemplace 127.0.0.1
for localhost
for check if your DB credential are corrects. config
folder and do. the step #2.No import is necessary as long as you declare both a.go
and b.go
to be in the same package. Then, you can use go run
to recognize multiple files with:
$ go run a.go b.go
You can define a table dynamically just as you are inserting into it dynamically, but the problem is with the scope of temp tables. For example, this code:
DECLARE @sql varchar(max)
SET @sql = 'CREATE TABLE #T1 (Col1 varchar(20))'
EXEC(@sql)
INSERT INTO #T1 (Col1) VALUES ('This will not work.')
SELECT * FROM #T1
will return with the error "Invalid object name '#T1'." This is because the temp table #T1 is created at a "lower level" than the block of executing code. In order to fix, use a global temp table:
DECLARE @sql varchar(max)
SET @sql = 'CREATE TABLE ##T1 (Col1 varchar(20))'
EXEC(@sql)
INSERT INTO ##T1 (Col1) VALUES ('This will work.')
SELECT * FROM ##T1
Hope this helps, Jesse
I like the "find" example above for the recursive application. To adapt it to be non-recursive, only changing files in the current directory that match a wildcard, the shell glob expansion can be sufficient for small amounts of files:
ls *.java | awk '{print "expand -t 4 ", $0, " > /tmp/e; mv /tmp/e ", $0}' | sh -v
If you want it silent after you trust that it works, just drop the -v
on the sh
command at the end.
Of course you can pick any set of files in the first command. For example, list only a particular subdirectory (or directories) in a controlled manner like this:
ls mod/*/*.php | awk '{print "expand -t 4 ", $0, " > /tmp/e; mv /tmp/e ", $0}' | sh
Or in turn run find(1) with some combination of depth parameters etc:
find mod/ -name '*.php' -mindepth 1 -maxdepth 2 | awk '{print "expand -t 4 ", $0, " > /tmp/e; mv /tmp/e ", $0}' | sh
In the layout (app/design/frontend/your_theme/layout/default.xml):
<default>
<cms_page> <!-- need to be redefined for your needs -->
<reference name="content">
<block type="cms/block" name="cms_newest_product" as="cms_newest_product">
<action method="setBlockId"><block_id>newest_product</block_id></action>
</block>
</reference>
</cms_page>
</default>
In your phtml template:
<?php echo $this->getChildHtml('newest_product'); ?>
Don't forget about cache cleaning.
I think it help.
Under HTML5 you are be able to do this:
document.getElementById('test').selectedOptions[0].text
MDN's documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions indicates full cross-browser support (as of at least December 2017), including Chrome, Firefox, Edge and mobile browsers, but excluding Internet Explorer.
The manner I have used before is to use a wild color (a color no one in their right mind would use) for the BackColor and then set the transparency key to that.
this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;
There are only minor error.Use MM instead of mm ,so it will be effective write as below:
@DateTime.Now.ToString("dd/MM/yyy")
Reflection.
using System.Reflection;
Vendor vendor = new Vendor();
object tag = vendor.Tag;
Type tagt = tag.GetType();
FieldInfo field = tagt.GetField("test");
string value = field.GetValue(tag);
Use the power wisely. Don't forget error checking. :)
First off, it's not JSON: JSON mandates that all keys must be strings.
Secondly, regular arrays do what you want:
var Game = {
status: [
[
"val",
"val",
"val"
],
[
"val",
"val",
"val"
]
}
will work, if you use Game.status[0][0]
. You cannot use numbers with the dot notation (.0
).
Alternatively, you can quote the numbers (i.e. { "0": "val" }...
); you will have plain objects instead of Arrays, but the same syntax will work.
islice
has the advantage that it doesn't need to copy part of the list
from itertools import islice
for day in islice(days, 1, None):
...
Store them in a file outside web root.
An alternative to the answer of asselin for use with ES2015 classes
class InvalidArgumentException extends Error {
constructor(message) {
super();
Error.captureStackTrace(this, this.constructor);
this.name = "InvalidArgumentException";
this.message = message;
}
}
I found out that single quote > double quote > wrapped in ampersands did work. So, for me it looks like this:
=QUERY('Youth Conference Registration'!C:Y,"select C where Y = '"&A1&"'", 0)
Note : This is by no means the best possible way to do it!
Situation : I had to do the same thign only i was not able to add any extra divs, therefore i was stuck with what i had and rather than removing innerHTML and creating another via javascript almost like 2 renders i needed to have the content at the bottom (animated bar).
Solution: Given how tired I was at the time its seems normal to even think of such a method however I knew i had a parent DOM element which the bar's height was starting from.
Rather than messing with the javascript any further i used a (NOT ALWAYS GOOD IDEA) CSS answer! :)
-moz-transform:rotate(180deg);
-webkit-transform:rotate(180deg);
-ms-transform:rotate(180deg);
Yes thats correct, instead of positioning the DOM, i turned its parent upside down in css.
For my scenario it will work! Possibly for others too ! No Flame! :)
I assume you have proper xml encoding and matching with Schema.
If you still get this error, check code that unmarshalls the xml and input type you have used. Because XML documents declare their own encoding, it is preferable to create a StreamSource object from an InputStream instead of from a Reader, so that XML processor can correctly handle the declared encoding [Ref Book: Java in A Nutshell ]
Hope this helps!
<<
is a binary shift, shifting 1 to the left 8 places.
4'b0001 << 1 => 4'b0010
>>
is a binary right shift adding 0's to the MSB.
>>>
is a signed shift which maintains the value of the MSB if the left input is signed.
4'sb1011 >> 1 => 0101
4'sb1011 >>> 1 => 1101
Three ways to indicate left operand is signed:
module shift;
logic [3:0] test1 = 4'b1000;
logic signed [3:0] test2 = 4'b1000;
initial begin
$display("%b", $signed(test1) >>> 1 ); //Explicitly set as signed
$display("%b", test2 >>> 1 ); //Declared as signed type
$display("%b", 4'sb1000 >>> 1 ); //Signed constant
$finish;
end
endmodule
Okay, I just found the answer (on Stackoverflow, no less).
Eclipse has an option so that copy-paste of multi-line text into String literals will result in quoted newlines:
Preferences/Java/Editor/Typing/ "Escape text when pasting into a string literal"
My solution uses string literal Find out more...
// Declare Date as d_x000D_
var d = new Date()_x000D_
_x000D_
// Inline formatting of Date_x000D_
const exampleOne = `${d.getDay()}-${d.getMonth() + 1}-${d.getFullYear()}`_x000D_
// January is 0 so +1 is required_x000D_
_x000D_
// With Breaklines and Operators_x000D_
const exampleTwo = `+++++++++++_x000D_
With Break Lines and Arithmetic Operators Example_x000D_
Year on newline: ${d.getFullYear()}_x000D_
Year minus(-) 30 years: ${d.getFullYear() - 30}_x000D_
You get the idea..._x000D_
+++++++++++`_x000D_
_x000D_
console.log('=============')_x000D_
console.log(exampleOne)_x000D_
console.log('=============')_x000D_
_x000D_
console.log(exampleTwo)
_x000D_
For method decorator declaration
with configuration "noImplicitAny": true,
you can specify type of this variable explicitly depends on @tony19's answer
function logParameter(this:any, target: Object, propertyName: string) {
//...
}
Another example:
double d = 0;
for (int i = 1; i <= 10; i++) {
d += 0.1;
}
System.out.println(d); // prints 0.9999999999999999 not 1.0
Use BigDecimal instead.
EDIT:
Also, just to point out this isn't a 'Java' rounding issue. Other languages exhibit similar (though not necessarily consistent) behaviour. Java at least guarantees consistent behaviour in this regard.
To reset window scroll back to top, $(window).scrollTop(0)
in the beforeunload event does the tricks, however, I tested in Chrome 80 it will go back to the old location after the reload.
To prevent that, set the history.scrollRestoration
to "manual"
.
//Reset scroll top
history.scrollRestoration = "manual";
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});
Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.
string startTime = "7:00 AM";
string endTime = "2:00 PM";
TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
Console.WriteLine(duration);
Console.ReadKey();
Will output: 07:00:00.
It also works if the user input military time:
string startTime = "7:00";
string endTime = "14:00";
TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
Console.WriteLine(duration);
Console.ReadKey();
Outputs: 07:00:00.
To change the format: duration.ToString(@"hh\:mm")
More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx
Addendum:
Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".
Set your PERL_UNICODE
envariable to AS
. This makes all Perl scripts decode @ARGV
as UTF-8 strings, and sets the encoding of all three of stdin, stdout, and stderr to UTF-8. Both these are global effects, not lexical ones.
At the top of your source file (program, module, library, do
hickey), prominently assert that you are running perl version 5.12 or better via:
use v5.12; # minimal for unicode string feature
use v5.14; # optimal for unicode string feature
Enable warnings, since the previous declaration only enables strictures and features, not warnings. I also suggest promoting Unicode warnings into exceptions, so use both these lines, not just one of them. Note however that under v5.14, the utf8
warning class comprises three other subwarnings which can all be separately enabled: nonchar
, surrogate
, and non_unicode
. These you may wish to exert greater control over.
use warnings;
use warnings qw( FATAL utf8 );
Declare that this source unit is encoded as UTF-8. Although once upon a time this pragma did other things, it now serves this one singular purpose alone and no other:
use utf8;
Declare that anything that opens a filehandle within this lexical scope but not elsewhere is to assume that that stream is encoded in UTF-8 unless you tell it otherwise. That way you do not affect other module’s or other program’s code.
use open qw( :encoding(UTF-8) :std );
Enable named characters via \N{CHARNAME}
.
use charnames qw( :full :short );
If you have a DATA
handle, you must explicitly set its encoding. If you want this to be UTF-8, then say:
binmode(DATA, ":encoding(UTF-8)");
There is of course no end of other matters with which you may eventually find yourself concerned, but these will suffice to approximate the state goal to “make everything just work with UTF-8”, albeit for a somewhat weakened sense of those terms.
One other pragma, although it is not Unicode related, is:
use autodie;
It is strongly recommended.
My own boilerplate these days tends to look like this:
use 5.014;
use utf8;
use strict;
use autodie;
use warnings;
use warnings qw< FATAL utf8 >;
use open qw< :std :utf8 >;
use charnames qw< :full >;
use feature qw< unicode_strings >;
use File::Basename qw< basename >;
use Carp qw< carp croak confess cluck >;
use Encode qw< encode decode >;
use Unicode::Normalize qw< NFD NFC >;
END { close STDOUT }
if (grep /\P{ASCII}/ => @ARGV) {
@ARGV = map { decode("UTF-8", $_) } @ARGV;
}
$0 = basename($0); # shorter messages
$| = 1;
binmode(DATA, ":utf8");
# give a full stack dump on any untrapped exceptions
local $SIG{__DIE__} = sub {
confess "Uncaught exception: @_" unless $^S;
};
# now promote run-time warnings into stack-dumped
# exceptions *unless* we're in an try block, in
# which case just cluck the stack dump instead
local $SIG{__WARN__} = sub {
if ($^S) { cluck "Trapped warning: @_" }
else { confess "Deadly warning: @_" }
};
while (<>) {
chomp;
$_ = NFD($_);
...
} continue {
say NFC($_);
}
__END__
Saying that “Perl should [somehow!] enable Unicode by default” doesn’t even start to begin to think about getting around to saying enough to be even marginally useful in some sort of rare and isolated case. Unicode is much much more than just a larger character repertoire; it’s also how those characters all interact in many, many ways.
Even the simple-minded minimal measures that (some) people seem to think they want are guaranteed to miserably break millions of lines of code, code that has no chance to “upgrade” to your spiffy new Brave New World modernity.
It is way way way more complicated than people pretend. I’ve thought about this a huge, whole lot over the past few years. I would love to be shown that I am wrong. But I don’t think I am. Unicode is fundamentally more complex than the model that you would like to impose on it, and there is complexity here that you can never sweep under the carpet. If you try, you’ll break either your own code or somebody else’s. At some point, you simply have to break down and learn what Unicode is about. You cannot pretend it is something it is not.
goes out of its way to make Unicode easy, far more than anything else I’ve ever used. If you think this is bad, try something else for a while. Then come back to : either you will have returned to a better world, or else you will bring knowledge of the same with you so that we can make use of your new knowledge to make better at these things.
At a minimum, here are some things that would appear to be required for to “enable Unicode by default”, as you put it:
All source code should be in UTF-8 by default. You can get that with use utf8
or export PERL5OPTS=-Mutf8
.
The DATA
handle should be UTF-8. You will have to do this on a per-package basis, as in binmode(DATA, ":encoding(UTF-8)")
.
Program arguments to scripts should be understood to be UTF-8 by default. export PERL_UNICODE=A
, or perl -CA
, or export PERL5OPTS=-CA
.
The standard input, output, and error streams should default to UTF-8. export PERL_UNICODE=S
for all of them, or I
, O
, and/or E
for just some of them. This is like perl -CS
.
Any other handles opened by should be considered UTF-8 unless declared otherwise; export PERL_UNICODE=D
or with i
and o
for particular ones of these; export PERL5OPTS=-CD
would work. That makes -CSAD
for all of them.
Cover both bases plus all the streams you open with export PERL5OPTS=-Mopen=:utf8,:std
. See uniquote.
You don’t want to miss UTF-8 encoding errors. Try export PERL5OPTS=-Mwarnings=FATAL,utf8
. And make sure your input streams are always binmode
d to :encoding(UTF-8)
, not just to :utf8
.
Code points between 128–255 should be understood by to be the corresponding Unicode code points, not just unpropertied binary values. use feature "unicode_strings"
or export PERL5OPTS=-Mfeature=unicode_strings
. That will make uc("\xDF") eq "SS"
and "\xE9" =~ /\w/
. A simple export PERL5OPTS=-Mv5.12
or better will also get that.
Named Unicode characters are not by default enabled, so add export PERL5OPTS=-Mcharnames=:full,:short,latin,greek
or some such. See uninames and tcgrep.
You almost always need access to the functions from the standard Unicode::Normalize
module various types of decompositions. export PERL5OPTS=-MUnicode::Normalize=NFD,NFKD,NFC,NFKD
, and then always run incoming stuff through NFD and outbound stuff from NFC. There’s no I/O layer for these yet that I’m aware of, but see nfc, nfd, nfkd, and nfkc.
String comparisons in using eq
, ne
, lc
, cmp
, sort
, &c&cc are always wrong. So instead of @a = sort @b
, you need @a = Unicode::Collate->new->sort(@b)
. Might as well add that to your export PERL5OPTS=-MUnicode::Collate
. You can cache the key for binary comparisons.
built-ins like printf
and write
do the wrong thing with Unicode data. You need to use the Unicode::GCString
module for the former, and both that and also the Unicode::LineBreak
module as well for the latter. See uwc and unifmt.
If you want them to count as integers, then you are going to have to run your \d+
captures through the Unicode::UCD::num
function because ’s built-in atoi(3) isn’t currently clever enough.
You are going to have filesystem issues on filesystems. Some filesystems silently enforce a conversion to NFC; others silently enforce a conversion to NFD. And others do something else still. Some even ignore the matter altogether, which leads to even greater problems. So you have to do your own NFC/NFD handling to keep sane.
All your code involving a-z
or A-Z
and such MUST BE CHANGED, including m//
, s///
, and tr///
. It’s should stand out as a screaming red flag that your code is broken. But it is not clear how it must change. Getting the right properties, and understanding their casefolds, is harder than you might think. I use unichars and uniprops every single day.
Code that uses \p{Lu}
is almost as wrong as code that uses [A-Za-z]
. You need to use \p{Upper}
instead, and know the reason why. Yes, \p{Lowercase}
and \p{Lower}
are different from \p{Ll}
and \p{Lowercase_Letter}
.
Code that uses [a-zA-Z]
is even worse. And it can’t use \pL
or \p{Letter}
; it needs to use \p{Alphabetic}
. Not all alphabetics are letters, you know!
If you are looking for variables with /[\$\@\%]\w+/
, then you have a problem. You need to look for /[\$\@\%]\p{IDS}\p{IDC}*/
, and even that isn’t thinking about the punctuation variables or package variables.
If you are checking for whitespace, then you should choose between \h
and \v
, depending. And you should never use \s
, since it DOES NOT MEAN [\h\v]
, contrary to popular belief.
If you are using \n
for a line boundary, or even \r\n
, then you are doing it wrong. You have to use \R
, which is not the same!
If you don’t know when and whether to call Unicode::Stringprep, then you had better learn.
Case-insensitive comparisons need to check for whether two things are the same letters no matter their diacritics and such. The easiest way to do that is with the standard Unicode::Collate module. Unicode::Collate->new(level => 1)->cmp($a, $b)
. There are also eq
methods and such, and you should probably learn about the match
and substr
methods, too. These are have distinct advantages over the built-ins.
Sometimes that’s still not enough, and you need the Unicode::Collate::Locale module instead, as in Unicode::Collate::Locale->new(locale => "de__phonebook", level => 1)->cmp($a, $b)
instead. Consider that Unicode::Collate::->new(level => 1)->eq("d", "ð")
is true, but Unicode::Collate::Locale->new(locale=>"is",level => 1)->eq("d", " ð")
is false. Similarly, "ae" and "æ" are eq
if you don’t use locales, or if you use the English one, but they are different in the Icelandic locale. Now what? It’s tough, I tell you. You can play with ucsort to test some of these things out.
Consider how to match the pattern CVCV (consonsant, vowel, consonant, vowel) in the string “niño”. Its NFD form — which you had darned well better have remembered to put it in — becomes “nin\x{303}o”. Now what are you going to do? Even pretending that a vowel is [aeiou]
(which is wrong, by the way), you won’t be able to do something like (?=[aeiou])\X)
either, because even in NFD a code point like ‘ø’ does not decompose! However, it will test equal to an ‘o’ using the UCA comparison I just showed you. You can’t rely on NFD, you have to rely on UCA.
And that’s not all. There are a million broken assumptions that people make about Unicode. Until they understand these things, their code will be broken.
Code that assumes it can open a text file without specifying the encoding is broken.
Code that assumes the default encoding is some sort of native platform encoding is broken.
Code that assumes that web pages in Japanese or Chinese take up less space in UTF-16 than in UTF-8 is wrong.
Code that assumes Perl uses UTF-8 internally is wrong.
Code that assumes that encoding errors will always raise an exception is wrong.
Code that assumes Perl code points are limited to 0x10_FFFF is wrong.
Code that assumes you can set $/
to something that will work with any valid line separator is wrong.
Code that assumes roundtrip equality on casefolding, like lc(uc($s)) eq $s
or uc(lc($s)) eq $s
, is completely broken and wrong. Consider that the uc("s")
and uc("?")
are both "S"
, but lc("S")
cannot possibly return both of those.
Code that assumes every lowercase code point has a distinct uppercase one, or vice versa, is broken. For example, "ª"
is a lowercase letter with no uppercase; whereas both "?"
and "?"
are letters, but they are not lowercase letters; however, they are both lowercase code points without corresponding uppercase versions. Got that? They are not \p{Lowercase_Letter}
, despite being both \p{Letter}
and \p{Lowercase}
.
Code that assumes changing the case doesn’t change the length of the string is broken.
Code that assumes there are only two cases is broken. There’s also titlecase.
Code that assumes only letters have case is broken. Beyond just letters, it turns out that numbers, symbols, and even marks have case. In fact, changing the case can even make something change its main general category, like a \p{Mark}
turning into a \p{Letter}
. It can also make it switch from one script to another.
Code that assumes that case is never locale-dependent is broken.
Code that assumes Unicode gives a fig about POSIX locales is broken.
Code that assumes you can remove diacritics to get at base ASCII letters is evil, still, broken, brain-damaged, wrong, and justification for capital punishment.
Code that assumes that diacritics \p{Diacritic}
and marks \p{Mark}
are the same thing is broken.
Code that assumes \p{GC=Dash_Punctuation}
covers as much as \p{Dash}
is broken.
Code that assumes dash, hyphens, and minuses are the same thing as each other, or that there is only one of each, is broken and wrong.
Code that assumes every code point takes up no more than one print column is broken.
Code that assumes that all \p{Mark}
characters take up zero print columns is broken.
Code that assumes that characters which look alike are alike is broken.
Code that assumes that characters which do not look alike are not alike is broken.
Code that assumes there is a limit to the number of code points in a row that just one \X
can match is wrong.
Code that assumes \X
can never start with a \p{Mark}
character is wrong.
Code that assumes that \X
can never hold two non-\p{Mark}
characters is wrong.
Code that assumes that it cannot use "\x{FFFF}"
is wrong.
Code that assumes a non-BMP code point that requires two UTF-16 (surrogate) code units will encode to two separate UTF-8 characters, one per code unit, is wrong. It doesn’t: it encodes to single code point.
Code that transcodes from UTF-16 or UTF-32 with leading BOMs into UTF-8 is broken if it puts a BOM at the start of the resulting UTF-8. This is so stupid the engineer should have their eyelids removed.
Code that assumes the CESU-8 is a valid UTF encoding is wrong. Likewise, code that thinks encoding U+0000 as "\xC0\x80"
is UTF-8 is broken and wrong. These guys also deserve the eyelid treatment.
Code that assumes characters like >
always points to the right and <
always points to the left are wrong — because they in fact do not.
Code that assumes if you first output character X
and then character Y
, that those will show up as XY
is wrong. Sometimes they don’t.
Code that assumes that ASCII is good enough for writing English properly is stupid, shortsighted, illiterate, broken, evil, and wrong. Off with their heads! If that seems too extreme, we can compromise: henceforth they may type only with their big toe from one foot. (The rest will be duct taped.)
Code that assumes that all \p{Math}
code points are visible characters is wrong.
Code that assumes \w
contains only letters, digits, and underscores is wrong.
Code that assumes that ^
and ~
are punctuation marks is wrong.
Code that assumes that ü
has an umlaut is wrong.
Code that believes things like ?
contain any letters in them is wrong.
Code that believes \p{InLatin}
is the same as \p{Latin}
is heinously broken.
Code that believe that \p{InLatin}
is almost ever useful is almost certainly wrong.
Code that believes that given $FIRST_LETTER
as the first letter in some alphabet and $LAST_LETTER
as the last letter in that same alphabet, that [${FIRST_LETTER}-${LAST_LETTER}]
has any meaning whatsoever is almost always complete broken and wrong and meaningless.
Code that believes someone’s name can only contain certain characters is stupid, offensive, and wrong.
Code that tries to reduce Unicode to ASCII is not merely wrong, its perpetrator should never be allowed to work in programming again. Period. I’m not even positive they should even be allowed to see again, since it obviously hasn’t done them much good so far.
Code that believes there’s some way to pretend textfile encodings don’t exist is broken and dangerous. Might as well poke the other eye out, too.
Code that converts unknown characters to ?
is broken, stupid, braindead, and runs contrary to the standard recommendation, which says NOT TO DO THAT! RTFM for why not.
Code that believes it can reliably guess the encoding of an unmarked textfile is guilty of a fatal mélange of hubris and naïveté that only a lightning bolt from Zeus will fix.
Code that believes you can use printf
widths to pad and justify Unicode data is broken and wrong.
Code that believes once you successfully create a file by a given name, that when you run ls
or readdir
on its enclosing directory, you’ll actually find that file with the name you created it under is buggy, broken, and wrong. Stop being surprised by this!
Code that believes UTF-16 is a fixed-width encoding is stupid, broken, and wrong. Revoke their programming licence.
Code that treats code points from one plane one whit differently than those from any other plane is ipso facto broken and wrong. Go back to school.
Code that believes that stuff like /s/i
can only match "S"
or "s"
is broken and wrong. You’d be surprised.
Code that uses \PM\pM*
to find grapheme clusters instead of using \X
is broken and wrong.
People who want to go back to the ASCII world should be whole-heartedly encouraged to do so, and in honor of their glorious upgrade they should be provided gratis with a pre-electric manual typewriter for all their data-entry needs. Messages sent to them should be sent via an ??????s telegraph at 40 characters per line and hand-delivered by a courier. STOP.
I don’t know how much more “default Unicode in ” you can get than what I’ve written. Well, yes I do: you should be using Unicode::Collate
and Unicode::LineBreak
, too. And probably more.
As you see, there are far too many Unicode things that you really do have to worry about for there to ever exist any such thing as “default to Unicode”.
What you’re going to discover, just as we did back in 5.8, that it is simply impossible to impose all these things on code that hasn’t been designed right from the beginning to account for them. Your well-meaning selfishness just broke the entire world.
And even once you do, there are still critical issues that require a great deal of thought to get right. There is no switch you can flip. Nothing but brain, and I mean real brain, will suffice here. There’s a heck of a lot of stuff you have to learn. Modulo the retreat to the manual typewriter, you simply cannot hope to sneak by in ignorance. This is the 21?? century, and you cannot wish Unicode away by willful ignorance.
You have to learn it. Period. It will never be so easy that “everything just works,” because that will guarantee that a lot of things don’t work — which invalidates the assumption that there can ever be a way to “make it all work.”
You may be able to get a few reasonable defaults for a very few and very limited operations, but not without thinking about things a whole lot more than I think you have.
As just one example, canonical ordering is going to cause some real headaches. "\x{F5}"
‘õ’, "o\x{303}"
‘õ’, "o\x{303}\x{304}"
‘?’, and "o\x{304}\x{303}"
‘o~’ should all match ‘õ’, but how in the world are you going to do that? This is harder than it looks, but it’s something you need to account for.
If there’s one thing I know about Perl, it is what its Unicode bits do and do not do, and this thing I promise you: “ _?_?_?_?_?_ _?_s_ _?_?_ _U_?_?_?_?_?_?_ _?_?_?_?_?_ _?_?_?_?_?_?_ _ ”
You cannot just change some defaults and get smooth sailing. It’s true that I run with PERL_UNICODE
set to "SA"
, but that’s all, and even that is mostly for command-line stuff. For real work, I go through all the many steps outlined above, and I do it very, ** very** carefully.
Maybe it's the best possiblity to create a TimerTask that sets the received Location to a certain value (null?) regularly. If a new value is received by the GPSListener it will update the location with the current data.
I think that would be a working solution.
Here is the query that brings the week number on whatever the startday
and endday
of the week it may be.
SET DATEFIRST 2
DECLARE @FROMDATE DATE='12-JAN-2015'
-- Get the first day of month
DECLARE @ALLDATE DATE=DATEADD(month, DATEDIFF(month, 0, @FROMDATE), 0)
DECLARE @FIRSTDATE DATE
;WITH CTE as
(
-- Get all dates in that month
SELECT 1 RNO,CAST(@ALLDATE AS DATE) as DATES
UNION ALL
SELECT RNO+1, DATEADD(DAY,1,DATES )
FROM CTE
WHERE DATES < DATEADD(MONTH,1,@ALLDATE)
)
-- Retrieves the first day of week, ie, if first day of week is Tuesday, it selects first Tuesday
SELECT TOP 1 @FIRSTDATE = DATES
FROM CTE
WHERE DATEPART(W,DATES)=1
SELECT (DATEDIFF(DAY,@FIRSTDATE,@FROMDATE)/7)+1 WEEKNO
For more information I have answered for the below question. Can check that.
// Prefs.h
extern NSString * const RAHUL;
// Prefs.m
NSString * const RAHUL = @"rahul";
Import the root module with importlib.import_module
and load the class by its name using getattr
function:
# Standard import
import importlib
# Load "module.submodule.MyClass"
MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
# Instantiate the class (pass arguments to the constructor, if needed)
instance = MyClass()
You probably don't want to use __import__
to dynamically import a module by name, as it does not allow you to import submodules:
>>> mod = __import__("os.path")
>>> mod.join
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'join'
Here is what the python doc says about __import__
:
Note: This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().
Instead, use the standard importlib
module to dynamically import a module by name. With getattr
you can then instantiate a class by its name:
import importlib
my_module = importlib.import_module("module.submodule")
MyClass = getattr(my_module, "MyClass")
instance = MyClass()
You could also write:
import importlib
module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
MyClass = getattr(importlib.import_module(module_name), class_name)
instance = MyClass()
This code is valid in python = 2.7 (including python 3).
The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.
Conclusion
Let's me explain more detail:
Question: How many Transaction we have? Answer: Only one
Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.
Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction
Go to the catch outside
Spring will set the rollBackOnly to true -> it determine we must
rollback the caller (processNextRegistrationMessage) also.
The persist() will rollback itself first.
Question: Why we change PROPAGATION to REQUIRES_NEW, it works?
Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.
Thanks
use global scope on your $con and put it inside your getPosts() function like so.
function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}
It is now much easier to map the Caps Lock key to Esc with macOS Sierra.
Open System Preferences ? Keyboard.
Click the Modifier Keys button in the bottom right-hand corner.
Click the drop down box next to the hardware key that you’d like to remap, and select Escape.
Click OK and close System Preferences.
$(".container > #first");
or
$(".container").children("#first");
or since IDs should be unique within a single document:
$("#first");
The last one is of course the fastest.
Since you're saying that you don't know their ID top couple of the upper selectors (where #first
is written), can be changed to:
$(".container > div");
$(".container").children("div");
The last one (of the first three selectors) that only uses ID is of course not possible to be changed in this way.
If you also need to filter out only those child DIV
elements that define ID attribute you'd write selectors down this way:
$(".container > div[id]");
$(".container").children("div[id]");
Add the following code to attach click handler to any of your preferred selector:
// use selector of your choice and call 'click' on it
$(".container > div").click(function(){
// if you need element's ID
var divID = this.id;
cache your element if you intend to use it multiple times
var clickedDiv = $(this);
// add CSS class to it
clickedDiv.addClass("add-some-class");
// do other stuff that needs to be done
});
I would also like to point you to CSS3 selector specification that jQuery uses. It will help you lots in the future because there may be some selectors you're not aware of at all and could make your life much much easier.
I'm not completey sure that I know what you're after even though you've written some pseudo code... Anyway. Some parts can still be answered:
$(".container > div[id]").each(function(){
var context = $(this);
// get menu parent element: Sub: Show Grid
// maybe I'm not appending to the correct element here but you should know
context.appendTo(context.parent().parent());
context.text("Show #" + this.id);
context.attr("href", "");
context.click(function(evt){
evt.preventDefault();
$(this).toggleClass("showgrid");
})
});
the last thee context
usages could be combined into a single chained one:
context.text(...).attr(...).click(...);
You can always get the underlaying DOM element from the jQuery result set.
$(...).get(0)
// or
$(...)[0]
will get you the first DOM element from the jQuery result set. jQuery result is always a set of elements even though there's none in them or only one.
But when I used .each()
function and provided an anonymous function that will be called on each element in the set, this
keyword actually refers to the DOM element.
$(...).each(function(){
var DOMelement = this;
var jQueryElement = $(this);
...
});
I hope this clears some things for your.
Any of these three commands will print the character you want in a console, provided the console do accept UTF-8 characters (most current ones do):
echo -e "SKULL AND CROSSBONES (U+2620) \U02620"
echo $'SKULL AND CROSSBONES (U+2620) \U02620'
printf "%b" "SKULL AND CROSSBONES (U+2620) \U02620\n"
SKULL AND CROSSBONES (U+2620) ?
After, you could copy and paste the actual glyph (image, character) to any (UTF-8 enabled) text editor.
If you need to see how such Unicode Code Point is encoded in UTF-8, use xxd (much better hex viewer than od):
echo $'(U+2620) \U02620' | xxd
0000000: 2855 2b32 3632 3029 20e2 98a0 0a (U+2620) ....
That means that the UTF8 encoding is: e2 98 a0
Or, in HEX to avoid errors: 0xE2 0x98 0xA0. That is, the values between the space (HEX 20) and the Line-Feed (Hex 0A).
If you want a deep dive into converting numbers to chars: look here to see an article from Greg's wiki (BashFAQ) about ASCII encoding in Bash!
A very general command prompt how to for java is
javac mainjava.java
java mainjava
You'll very often see people doing
javac *.java
java mainjava
As for the subclass problem that's probably occurring because a path is missing from your class path, the -c flag I believe is used to set that.
du -h --max-depth=0 * | sort -hr
3,5M asdf.6000.gz
3,4M asdf.4000.gz
3,2M asdf.2000.gz
2,5M xyz.PT.gz
136K xyz.6000.gz
116K xyz.6000p.gz
88K test.4000.gz
76K test.4000p.gz
44K test.2000.gz
8,0K desc.common.tcl
8,0K wer.2000p.gz
8,0K wer.2000.gz
4,0K ttree.3
du
displays "disk usage"h
is for "human readable" (both, in sort and in du)max-depth=0
means du
will not show sizes of subfolders (remove that if you want to show all sizes of every file in every sub-, subsub-, ..., folder)r
is for "reverse" (biggest file first)When I came to this question, I wanted to clean up my file system. The command line tool ncdu
is way better suited to this task.
Installation on Ubuntu:
$ sudo apt-get install ncdu
Usage:
Just type ncdu [path]
in the command line. After a few seconds for analyzing the path, you will see something like this:
$ ncdu 1.11 ~ Use the arrow keys to navigate, press ? for help
--- / ---------------------------------------------------------
. 96,1 GiB [##########] /home
. 17,7 GiB [# ] /usr
. 4,5 GiB [ ] /var
1,1 GiB [ ] /lib
732,1 MiB [ ] /opt
. 275,6 MiB [ ] /boot
198,0 MiB [ ] /storage
. 153,5 MiB [ ] /run
. 16,6 MiB [ ] /etc
13,5 MiB [ ] /bin
11,3 MiB [ ] /sbin
. 8,8 MiB [ ] /tmp
. 2,2 MiB [ ] /dev
! 16,0 KiB [ ] /lost+found
8,0 KiB [ ] /media
8,0 KiB [ ] /snap
4,0 KiB [ ] /lib64
e 4,0 KiB [ ] /srv
! 4,0 KiB [ ] /root
e 4,0 KiB [ ] /mnt
e 4,0 KiB [ ] /cdrom
. 0,0 B [ ] /proc
. 0,0 B [ ] /sys
@ 0,0 B [ ] initrd.img.old
@ 0,0 B [ ] initrd.img
@ 0,0 B [ ] vmlinuz.old
@ 0,0 B [ ] vmlinuz
Delete the currently highlighted element with d, exit with CTRL + c
Lodash has many isMethods so if you're using Lodash maybe a mixin like this can be useful:
// Mixin for identifying a Javascript Object
_.mixin({
'identify' : function(object) {
var output;
var isMethods = ['isArguments', 'isArray', 'isArguments', 'isBoolean', 'isDate', 'isArguments',
'isElement', 'isError', 'isFunction', 'isNaN', 'isNull', 'isNumber',
'isPlainObject', 'isRegExp', 'isString', 'isTypedArray', 'isUndefined', 'isEmpty', 'isObject']
this.each(isMethods, function (method) {
if (this[method](object)) {
output = method;
return false;
}
}.bind(this));
return output;
}
});
It adds a method to lodash called "identify" which works as follow:
console.log(_.identify('hello friend')); // isString
It's been awhile since I've done anything with batch files but I think that the following works:
find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done
This is really a proof of concept; clean up as it suits your needs. The key is that find
returns an errorlevel
of 1
if string
is not in file
. We branch to notfound
in this case otherwise we handle the found
case.
Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.
Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:
$('body :not(script)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace('-9o0-9909','The new string');
});
this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.
sudo -i -u postgres
createuser --interactive
createdb <username_from_step_3>
psql
at the command prompt.psql (x.x.x) Type "help" for help.
Less efficient, but simpler-looking:
m0 = re.match("I love (\w+)", statement)
m1 = re.match("Ich liebe (\w+)", statement)
m2 = re.match("Je t'aime (\w+)", statement)
if m0:
print "He loves",m0.group(1)
elif m1:
print "Er liebt",m1.group(1)
elif m2:
print "Il aime",m2.group(1)
The problem with the Perl stuff is the implicit updating of some hidden variable. That's simply hard to achieve in Python because you need to have an assignment statement to actually update any variables.
The version with less repetition (and better efficiency) is this:
pats = [
("I love (\w+)", "He Loves {0}" ),
("Ich liebe (\w+)", "Er Liebe {0}" ),
("Je t'aime (\w+)", "Il aime {0}")
]
for p1, p3 in pats:
m= re.match( p1, statement )
if m:
print p3.format( m.group(1) )
break
A minor variation that some Perl folk prefer:
pats = {
"I love (\w+)" : "He Loves {0}",
"Ich liebe (\w+)" : "Er Liebe {0}",
"Je t'aime (\w+)" : "Il aime {0}",
}
for p1 in pats:
m= re.match( p1, statement )
if m:
print pats[p1].format( m.group(1) )
break
This is hardly worth mentioning except it does come up sometimes from Perl programmers.
If you want the max for array or list indices (equivalent to size_t
in C/C++), you can use numpy:
np.iinfo(np.intp).max
This is same as sys.maxsize
however advantage is that you don't need import sys just for this.
If you want max for native int on the machine:
np.iinfo(np.intc).max
You can look at other available types in doc.
For floats you can also use sys.float_info.max
.
Not exactly like that, but there are workarounds. There's a section in React's docs about conditional rendering that you should take a look. Here's an example of what you could do using inline if-else.
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}
You can also deal with it inside the render function, but before returning the jsx.
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
It's also worth mentioning what ZekeDroid brought up in the comments. If you're just checking for a condition and don't want to render a particular piece of code that doesn't comply, you can use the && operator
.
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.
It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!
Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.
#include <stdlib.h>
int main()
{
int x;
x = rand(6);
printf("%d", x);
}
Especially as a beginner, you should ask your compiler to print every warning about bad code that it can generate. Modern compilers know lots of different warnings which help you to program better. For example, when you compile this program with the GNU C Compiler:
$ gcc -W -Wall rand.c
rand.c: In function `main':
rand.c:5: error: too many arguments to function `rand'
rand.c:6: warning: implicit declaration of function `printf'
You get two warnings here. The first one says that the rand
function only takes zero arguments, not one as you tried. To get a random number between 0 and n
, you can use the expression rand() % n
, which is not perfect but ok for small n
. The resulting random numbers are normally not evenly distributed; smaller values are returned more often.
The second warning tells you that you are calling a function that the compiler doesn't know at that point. You have to tell the compiler by saying #include <stdio.h>
. Which include files are needed for which functions is not always simple, but asking the Open Group specification for portable operating systems works in many cases: http://www.google.com/search?q=opengroup+rand.
These two warnings tell you much about the history of the C programming language. 40 years back, the definition of a function didn't include the number of parameters or the types of the parameters. It was also ok to call an unknown function, which in most cases worked. If you want to write code today, you should not rely on these old features but instead enable your compiler's warnings, understand the warnings and then fix them properly.
Committing in git can be a multiple step process or one step depending on the situation.
This situation is where you have multiple file updated and wants to commit:
You have to add all the modified files before you commit anything.
git add -A
or
git add --all
After that you can use commit all the added files
git commit
with this you have to add the message for this commit.
For Sql server you can try this one.
SELECT ISNULL([NAME],'SUM'),Count([NAME]) AS COUNT
FROM TABLENAME
GROUP BY [NAME] WITH CUBE
grep -E -o ".{0,5}test_pattern.{0,5}" test.txt
This will match up to 5 characters before and after your pattern. The -o switch tells grep to only show the match and -E to use an extended regular expression. Make sure to put the quotes around your expression, else it might be interpreted by the shell.
SelectionChange is the event built into the Excel Object model for this. It should do exactly as you want, firing any time the user clicks anywhere...
I'm not sure that I understand your objections to global variables here, you would only need 1 if you use the Application.SelectionChange event. However, you wouldn't need any if you utilize the Workbook class code behind (to trap the Workbook.SelectionChange event) or the Worksheet class code behind (to trap the Worksheet.SelectionChange) event. (Unless your issue is the "global variable reset" problem in VBA, for which there is only one solution: error handling everywhere. Do not allow any unhandled errors, instead log them and/or "soft-report" an error as a message box to the user.)
You might also need to trap the Worksheet.Activate() and Worksheet.Deactivate() events (or the equivalent in the Workbook class) and/or the Workbook.Activate and Workbook.Deactivate() events so that you know when the user has switched worksheets and/or workbooks. The Window activate and deactivate events should make this approach complete. They could all call the same exact procedure, however, they all denote the same thing: the user changed the "focus", if you will.
If you don't like VBA, btw, you can do the same using VB.NET or C#.
[Edit: Dbb makes a very good point about the SelectionChange event not picking up a click when the user clicks within the currently selected cell. If you need to pick that up, then you would need to use subclassing.]
Be careful when using the MAC address as an identifier. I've experienced several gotchas:
Even with the above issues, I still think it's the best pure Java approach to hardware locking a license.
@NicoLwk You should remove elements with splice, that will shift your array back. So:
var a=['a','b','c'];
a.splice(0,1);
for(var i in a){console.log(i+' '+a[i]);}
This may help with the problem:
var d = new Date();_x000D_
_x000D_
var options = { _x000D_
day: 'numeric',_x000D_
month: 'long', _x000D_
year: 'numeric'_x000D_
};_x000D_
_x000D_
console.log(d.toLocaleDateString('en-ZA', options));
_x000D_
In case anyone's curious, the ultimate reason is that HTML was originally a dialect of SGML, which is XML's weird older brother. In SGML-land, elements can be specified in the DTD as either self-closing (e.g. BR, HR, INPUT), implicitly closeable (e.g. P, LI, TD), or explicitly closeable (e.g. TABLE, DIV, SCRIPT). XML, of course, has no concept of this.
The tag-soup parsers used by modern browsers evolved out of this legacy, although their parsing model isn't pure SGML anymore. And of course, your carefully-crafted XHTML is being treated as badly-written SGML-inspired tag-soup unless you send it with an XML mime type. This is also why...
<p><div>hello</div></p>
...gets interpreted by the browser as:
<p></p><div>hello</div><p></p>
...which is the recipe for a lovely obscure bug that can throw you into fits as you try to code against the DOM.
It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:
public class ImageHandler : IHttpHandler
{
byte[] bytes;
public void ProcessRequest(HttpContext context)
{
int param;
if (int.TryParse(context.Request.QueryString["id"], out param))
{
using (var db = new MusicLibContext())
{
if (param == -1)
{
bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));
context.Response.ContentType = "image/png";
}
else
{
var data = (from x in db.Images
where x.ImageID == (short)param
select x).FirstOrDefault();
bytes = data.ImageData;
context.Response.ContentType = "image/" + data.ImageFileType;
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
}
else
{
//image not found
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
In the view, i added the ID of the photo to the query string of the handler.
Using cin's >> operator will drop leading whitespace and stop input at the first trailing whitespace. To grab an entire line of input, including spaces, try cin.getline()
. To grab one character at a time, you can use cin.get()
.
Just do:
sudo apt-get install python-lxml
For Python 2 (e.g., required by Inkscape):
sudo apt-get install python2-lxml
If you are planning to install from source, then albertov's answer will help. But unless there is a reason, don't, just install it from the repository.
I tried everything, nothing worked.then I tried the following steps and it worked
close Android studio
go to "My Documents"
delete the following folders a).android, b).androidstudio1.5, c).gradle
start Android studio and enjoy...
It seems stupid but works...
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Timeconversion {
private DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm", Locale.ENGLISH); //Specify your locale
public long timeConversion(String time) {
long unixTime = 0;
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:30")); //Specify your timezone
try {
unixTime = dateFormat.parse(time).getTime();
unixTime = unixTime / 1000;
} catch (ParseException e) {
e.printStackTrace();
}
return unixTime;
}
}
You should use method array_push to add value or array to array exists
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
/** GENERATED OUTPUT
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
*/
% is a special character you put in format strings, for example in C language printf and scanf (and family), that basically says "this is a placeholder for something else, not to be printed/read literally."
For example, a
(%02d)
in a format string for printf is a placeholder for an integer variable that will be printed in decimal(%02d)
and padded to at least two digits, with zeros if necessary.The actual integer is supplied by you in an an argument to the function, e.g.
printf("%02d",5);
would print05
on screen,(%01d)
also works similarly
Same hold for Java and other languages too :)
If you're going to raise an exception, you might raise a StopIteration exception. That will at least make the intent obvious.
The other approach would be to allocate one contiguous chunk of memory comprising header block for pointers to rows as well as body block to store actual data in rows. Then just mark up memory by assigning addresses of memory in body to the pointers in header on per-row basis. It would look like follows:
int** 2dAlloc(int rows, int* columns) {
int header = rows * sizeof(int*);
int body = 0;
for(int i=0; i<rows; body+=columnSizes[i++]) {
}
body*=sizeof(int);
int** rowptr = (int**)malloc(header + body);
int* buf = (int*)(rowptr + rows);
rowptr[0] = buf;
int k;
for(k = 1; k < rows; ++k) {
rowptr[k] = rowptr[k-1] + columns[k-1];
}
return rowptr;
}
int main() {
// specifying column amount on per-row basis
int columns[] = {1,2,3};
int rows = sizeof(columns)/sizeof(int);
int** matrix = 2dAlloc(rows, &columns);
// using allocated array
for(int i = 0; i<rows; ++i) {
for(int j = 0; j<columns[i]; ++j) {
cout<<matrix[i][j]<<", ";
}
cout<<endl;
}
// now it is time to get rid of allocated
// memory in only one call to "free"
free matrix;
}
The advantage of this approach is elegant freeing of memory and ability to use array-like notation to access elements of the resulting 2D array.
You can do it with ViewModels like how you passed data from your controller to view.
Assume you have a viewmodel like this
public class ReportViewModel
{
public string Name { set;get;}
}
and in your GET Action,
public ActionResult Report()
{
return View(new ReportViewModel());
}
and your view must be strongly typed to ReportViewModel
@model ReportViewModel
@using(Html.BeginForm())
{
Report NAme : @Html.TextBoxFor(s=>s.Name)
<input type="submit" value="Generate report" />
}
and in your HttpPost action method in your controller
[HttpPost]
public ActionResult Report(ReportViewModel model)
{
//check for model.Name property value now
//to do : Return something
}
OR Simply, you can do this without the POCO classes (Viewmodels)
@using(Html.BeginForm())
{
<input type="text" name="reportName" />
<input type="submit" />
}
and in your HttpPost action, use a parameter with same name as the textbox name.
[HttpPost]
public ActionResult Report(string reportName)
{
//check for reportName parameter value now
//to do : Return something
}
EDIT : As per the comment
If you want to post to another controller, you may use this overload of the BeginForm method.
@using(Html.BeginForm("Report","SomeOtherControllerName"))
{
<input type="text" name="reportName" />
<input type="submit" />
}
You can use the same view model, simply set the property values in your GET action method
public ActionResult Report()
{
var vm = new ReportViewModel();
vm.Name="SuperManReport";
return View(vm);
}
and in your view
@model ReportViewModel
<h2>@Model.Name</h2>
<p>Can have input field with value set in action method</p>
@using(Html.BeginForm())
{
@Html.TextBoxFor(s=>s.Name)
<input type="submit" />
}
Make sure you don't add or uncomment the AllowNoPassword option after the $i++ line.
/* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
If you don't need to change something onMeasure - there's absolutely no need for you to override it.
Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).
You can check the onMeasure method here :
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
Overriding SDK code to be replaced with the exact same code makes no sense.
This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.
For Red Hat :
sudo yum install libstdc++.i686
sudo yum install libstdc++-devel.i686
Firstly, DO NOT USE IT IN PRODUCTION
If you are using AddHttpClient middleware this will be usefull. I think it is needed for development purpose not production. Until you create a valid certificate you could use this Func.
Func<HttpMessageHandler> configureHandler = () =>
{
var bypassCertValidation = Configuration.GetValue<bool>("BypassRemoteCertificateValidation");
var handler = new HttpClientHandler();
//!DO NOT DO IT IN PRODUCTION!! GO AND CREATE VALID CERTIFICATE!
if (bypassCertValidation)
{
handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, x509Certificate2, x509Chain, sslPolicyErrors) =>
{
return true;
};
}
return handler;
};
and apply it like
services.AddHttpClient<IMyClient, MyClient>(x => { x.BaseAddress = new Uri("https://localhost:5005"); })
.ConfigurePrimaryHttpMessageHandler(configureHandler);
My OneLiner:
var MyList = new List<MyType>(MyDico.Values);
When you first set up this package, I am guessing that either a one or two digit number was the first value in the ShipTo column. Your package reading from the Excel picked a numeric type for that input field and the word "ALL" fails the package since the input spec for that field is numeric. There are several ways to fix this beforehand, but to fix it after the fact, the easiest way is to right click the Excel Source and choose Show Advanced Editor... From there, choose the tab that says Input and Output Properties. In the topmost part of the inputs and outputs section of that dialog box, find the column ShipTo. You will have to drill down to find it. Set the DataType to "string [DT_STR]" and the length to 20.
Click OK then attempt to run your package again.
Flexbox can do this with just two css rules on a surrounding div.
.social-media{_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="social-media">_x000D_
<a href="mailto:[email protected]">_x000D_
<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">_x000D_
<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
</div>
_x000D_
How about something like this?
<html>
<head>
<script type="text/javascript">
var HoverListener = {
addElem: function( elem, callback, delay )
{
if ( delay === undefined )
{
delay = 1000;
}
var hoverTimer;
addEvent( elem, 'mouseover', function()
{
hoverTimer = setTimeout( callback, delay );
} );
addEvent( elem, 'mouseout', function()
{
clearTimeout( hoverTimer );
} );
}
}
function tester()
{
alert( 'hi' );
}
// Generic event abstractor
function addEvent( obj, evt, fn )
{
if ( 'undefined' != typeof obj.addEventListener )
{
obj.addEventListener( evt, fn, false );
}
else if ( 'undefined' != typeof obj.attachEvent )
{
obj.attachEvent( "on" + evt, fn );
}
}
addEvent( window, 'load', function()
{
HoverListener.addElem(
document.getElementById( 'test' )
, tester
);
HoverListener.addElem(
document.getElementById( 'test2' )
, function()
{
alert( 'Hello World!' );
}
, 2300
);
} );
</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>
SQL is a standard and there are many database vendors like Microsoft,Oracle who implements this standard using their own proprietary language.
Microsoft uses T-SQL to implement SQL standard to interact with data whereas oracle uses PL/SQL.
You could use an extension method to get notified about changed property of an item in a collection in a generic way.
public static class ObservableCollectionExtension
{
public static void NotifyPropertyChanged<T>(this ObservableCollection<T> observableCollection, Action<T, PropertyChangedEventArgs> callBackAction)
where T : INotifyPropertyChanged
{
observableCollection.CollectionChanged += (sender, args) =>
{
//Does not prevent garbage collection says: http://stackoverflow.com/questions/298261/do-event-handlers-stop-garbage-collection-from-occuring
//publisher.SomeEvent += target.SomeHandler;
//then "publisher" will keep "target" alive, but "target" will not keep "publisher" alive.
if (args.NewItems == null) return;
foreach (T item in args.NewItems)
{
item.PropertyChanged += (obj, eventArgs) =>
{
callBackAction((T)obj, eventArgs);
};
}
};
}
}
public void ExampleUsage()
{
var myObservableCollection = new ObservableCollection<MyTypeWithNotifyPropertyChanged>();
myObservableCollection.NotifyPropertyChanged((obj, notifyPropertyChangedEventArgs) =>
{
//DO here what you want when a property of an item in the collection has changed.
});
}
Create Proc[usp_mquestions]
(
@title nvarchar(500), --0
@tags nvarchar(max), --1
@category nvarchar(200), --2
@ispoll char(1), --3
@descriptions nvarchar(max), --4
)
AS
BEGIN TRY
BEGIN
DECLARE @message varchar(1000);
DECLARE @tempid bigint;
IF((SELECT count(id) from [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN
if @id=0
begin
select @tempid =id from [xyz] where id=@id;
if @tempid is null
BEGIN
INSERT INTO xyz
(entrydate,updatedate)
VALUES
(GETDATE(),GETDATE())
SET @tempid=@@IDENTITY;
END
END
ELSE
BEGIN
set @tempid=@id
END
if @tempid>0
BEGIN
-- Updation of table begin--
UPDATE tab_questions
set title=@title, --0
tags=@tags, --1
category=@category, --2
ispoll=@ispoll, --3
descriptions=@descriptions, --4
status=@status, --5
WHERE id=@tempid ; --9 ;
IF @id=0
BEGIN
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END
ELSE
BEGIN
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)
END
END
ELSE
BEGIN
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END
END
END
END TRY
BEGIN CATCH
SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;
This is pretty ridiculous, but I got the 403 Forbidden when the file I was trying to download wasn't there on the filesystem. The apache error is not very accurate in this case, and the whole thing worked after I simply put the file where it was supposed to be.
I know when you said "contents" you didn't mean this, but if you want to find all the values of all the attributes of a webelement this is a pretty nifty way to do that with javascript in python:
everything = b.execute_script(
'var element = arguments[0];'
'var attributes = {};'
'for (index = 0; index < element.attributes.length; ++index) {'
' attributes[element.attributes[index].name] = element.attributes[index].value };'
'var properties = [];'
'properties[0] = attributes;'
'var element_text = element.textContent;'
'properties[1] = element_text;'
'var styles = getComputedStyle(element);'
'var computed_styles = {};'
'for (index = 0; index < styles.length; ++index) {'
' var value_ = styles.getPropertyValue(styles[index]);'
' computed_styles[styles[index]] = value_ };'
'properties[2] = computed_styles;'
'return properties;', element)
you can also get some extra data with element.__dict__
.
I think this is about all the data you'd ever want to get from a webelement.
You can also add Facebook's Stetho and look at the network traces in Chrome: http://facebook.github.io/stetho/
final OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
builder.networkInterceptors().add(new StethoInterceptor());
}
Then open "chrome://inspect" in Chrome...
This behavior is easy explained by:
So:
def x(a=0, b=[], c=[], d=0):
a = a + 1
b = b + [1]
c.append(1)
print a, b, c
a
doesn't change - every assignment call creates new int object - new object is printedb
doesn't change - new array is build from default value and printedc
changes - operation is performed on same object - and it is printedI could not use localStorage
directly in the Firefox (v27) console. I got the error:
[Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: debugger eval code :: :: line 1" data: no]
What worked was:
window.content.localStorage
Instead of
formGroupName="i"
You must use:
[formGroupName]="i"
Tips:
Since you're looping over the controls, you've already the variable area
, so you can replace this:
*ngIf="areasForm.get('areas').controls[i].name.hasError('required')"
by:
*ngIf="area.hasError('required', 'name')"
The basic questions that differentiate implementations of "CopyStream" are:
The answers to these questions result in vastly different implementations of CopyStream and are dependent on what kind of streams you have and what you are trying to optimize. The "best" implementation would even need to know what specific hardware the streams were reading and writing to.
Use range() instead, like the following :
for i in range(len(words)):
...
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
== typeof(List<>))
{
Type itemType = type.GetGenericArguments()[0]; // use this...
}
More generally, to support any IList<T>
, you need to check the interfaces:
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
Type itemType = type.GetGenericArguments()[0];
// do something...
break;
}
}
This is somewhat related and might help others, I had a corrupt version of some of my plugins so I was able to just delete the entire contents of the plugins folder. Note, all references are still in the package.json and config.xml files to the plugins. So then when I removed and added the Android platform, it re-installed the uncorrupted versions of the plugins and fixed my problem.
You can simply do that:
<html>
<table>
<tr>
<td>one</td>
<td width="10px"></td>
<td>two</td>
</tr>
</table>
</html>
No CSS is required :) This 10px is your space.
This is how I usually do it. A simple number of days perspective of B minus A.
DATE_PART('day', MAX(joindate) - MIN(joindate)) as date_diff
You can add/remove Appender programmatically to Log4j:
ConsoleAppender console = new ConsoleAppender(); //create appender
//configure the appender
String PATTERN = "%d [%p|%c|%C{1}] %m%n";
console.setLayout(new PatternLayout(PATTERN));
console.setThreshold(Level.FATAL);
console.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(console);
FileAppender fa = new FileAppender();
fa.setName("FileLogger");
fa.setFile("mylog.log");
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fa.setThreshold(Level.DEBUG);
fa.setAppend(true);
fa.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(fa);
//repeat with all other desired appenders
I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with
Logger.getRootLogger().getLoggerRepository().resetConfiguration();
and start with adding your own. You need log4j in the classpath of course for this to work.
Remark:
You can take any Logger.getLogger(...)
you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).
If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:
Logger fizz = LoggerFactory.getLogger("com.fizz")
will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to
Logger.getLogger("com.fizz").addAppender(newAppender)
then logging from fizz
will be handled by alle the appenders from the root logger and the newAppender
.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.
you can use
style="display:none"
Ex:
<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>
IF EXISTS (SELECT * FROM [Table] WHERE ID = rowID)
UPDATE [Table] SET propertyOne = propOne, property2 . . .
ELSE
INSERT INTO [Table] (propOne, propTwo . . .)
Edit:
Alas, even to my own detriment, I must admit the solutions that do this without a select seem to be better since they accomplish the task with one less step.
// this will give all the forms on the page.
$('form')
// If you know the name of form then.
$('form[name="myFormName"]')
// If you don't know know the name but the position (starts with 0)
$('form:eq(1)') // 2nd form will be fetched.
Just because int.TryParse
gives you the value doesn't mean you need to keep it; you can quite happily do this:
int temp;
if (int.TryParse(inputString, out temp))
{
// do stuff
}
You can ignore temp
entirely if you don't need it. If you do need it, then hey, it's waiting for you when you want it.
As for the internals, as far as I remember it attempts to read the raw bytes of the string as an int and tests whether the result is valid, or something; it's not as simple as iterating through looking for non-numeric characters.
My solution was simple! I was actually having this error when checked out a repo from a svn server. I took following steps to remove error
Pretty simple but another said you dont pass session variables through the url bar
1.You dont need to because a session is passed throughout the whole website from header when you put in header file
2.security risks
Here is first page code
$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);
2nd page when getting the variables from the url bar is:
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['eventid']) && !empty($_GET['eventid'])){
////do whatever here
}
Now if you want to do it the proper way of using the session you created then ignore my above code and call the session variables on the second page for instance create a session on the first page lets say for example:
$_SESSION['WEB_SES'] = $email_address . "^" . $event_id;
obvious that you would have already assigned values to the session variables in the code above, you can call the session name whatever you want to i just used the example web_ses , the second page all you need to do is start a session and see if the session is there and check the variables and do whatever with them, example:
session_start();
if (isset($_SESSION['WEB_SES'])){
$Array = explode("^", $_SESSION['WEB_SES']);
$email = $Array[0];
$event_id = $Array[1]
echo "$email";
echo "$event_id";
}
Like I said before the good thing about sessions are they can be carried throughout the entire website if this type of code in put in the header file that gets called upon on all pages that load, you can simple use the variable wherever and whenever. Hope this helps :)
I had this problem because of a trigger not working..Worked after I deleted the trigger.
I would also highly recommend Adminer - http://www.adminer.org/
It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.
For me, I just had to put a -X flag with mvn
. Look at the debug log; there was an issue with Spring while locating the .properties file.
See man git-add
:
-f, --force
Allow adding otherwise ignored files.
So run this
git add --force my/ignore/file.foo
@RequestMapping(path="/apps/add", method=RequestMethod.POST)
public String addApps(String appUrl, Model model, final RedirectAttributes redirectAttrs) {
if (!validate(appUrl)) {
redirectAttrs.addFlashAttribute("error", "Validation failed");
}
return "redirect:/apps/add"
}
@RequestMapping(path="/apps/add", method=RequestMethod.GET)
public String addAppss(Model model) {
String error = model.asMap().get("error");
}
At the end of foo()
, create a Timer
which calls foo()
itself after 10 seconds.
Because, Timer
create a new thread
to call foo()
.
You can do other stuff without being blocked.
import time, threading
def foo():
print(time.ctime())
threading.Timer(10, foo).start()
foo()
#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011
You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-
last_list.append(p.last)
if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.
Another way is to use a lambda expression. Depending on interpreter version and whether you wish to create a sorted dictionary or sorted key-value tuples (as the OP does), this may even be faster than the accepted answer.
d = {'aa': 3, 'bb': 4, 'cc': 2, 'dd': 1}
s = sorted(d.items(), key=lambda x: x[1], reverse=True)
for k, v in s:
print(k, v)
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '@Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
instead of using this
Vue.component('tabs', {
template: `
<div class="tabs">
<ul>
<li class="is-active"><a>Pictures</a></li>
<li><a>Music</a></li>
<li><a>Videos</a></li>
<li><a>Documents</a></li>
</ul>
</div>
<div class="tabs-content">
<slot></slot>
</div>
`,
});
you should use
Vue.component('tabs', {
template: `
<div>
<div class="tabs">
<ul>
<li class="is-active"><a>Pictures</a></li>
<li><a>Music</a></li>
<li><a>Videos</a></li>
<li><a>Documents</a></li>
</ul>
</div>
<div class="tabs-content">
<slot></slot>
</div>
</div>
`,
});
-Covert .jar file to .zip (In windows just change the extension) -Unzip the .zip folder -You will get complete .java files
For video streaming bandwidth is likely the constraint on the system. Using multicast you can greatly reduce the amount of upstream bandwidth used. With UDP you can easily multicast your packets to all connected terminals. You could also use a reliable multicast protocol, one is called Pragmatic General Multicast (PGM), I don't know anything about it and I guess it isn't widespread in its use.
For Xcode 7, you have a much simpler solution. The only extra work is that you have to create a configuration plist file for exporting archive.
(Compared to Xcode 6, in the results of xcrun xcodebuild -help
, -exportFormat
and -exportProvisioningProfile
options are not mentioned any more; the former is deleted, and the latter is superseded by -exportOptionsPlist
.)
Step 1, change directory to the folder including .xcodeproject or .xcworkspace file.
cd MyProjectFolder
Step 2, use Xcode or /usr/libexec/PlistBuddy exportOptions.plist
to create export options plist file. By the way, xcrun xcodebuild -help
will tell you what keys you have to insert to the plist file.
Step 3, create .xcarchive file (folder, in fact) as follows(build/ directory will be automatically created by Xcode right now),
xcrun xcodebuild -scheme MyApp -configuration Release archive -archivePath build/MyApp.xcarchive
Step 4, export as .ipa file like this, which differs from Xcode6
xcrun xcodebuild -exportArchive -exportPath build/ -archivePath build/MyApp.xcarchive/ -exportOptionsPlist exportOptions.plist
Now, you get an ipa file in build/ directory. Just send it to apple App Store.
By the way, the ipa file created by Xcode 7 is much larger than by Xcode 6.
To anyone reading this in 2017, this is how I've done something similar.
DELETE pets, pets_activities FROM pets inner join pets_activities
on pets_activities.id = pets.id WHERE pets.`order` > :order AND
pets.`pet_id` = :pet_id
Generally, to delete rows from multiple tables, the syntax I follow is given below. The solution is based on an assumption that there is some relation between the two tables.
DELETE table1, table2 FROM table1 inner join table2 on table2.id = table1.id
WHERE [conditions]
"argument is of length zero" is a very specific problem that comes from one of my least-liked elements of R. Let me demonstrate the problem:
> FALSE == "turnip"
[1] FALSE
> TRUE == "turnip"
[1] FALSE
> NA == "turnip"
[1] NA
> NULL == "turnip"
logical(0)
As you can see, comparisons to a NULL not only don't produce a boolean value, they don't produce a value at all - and control flows tend to expect that a check will produce some kind of output. When they produce a zero-length output... "argument is of length zero".
(I have a very long rant about why this infuriates me so much. It can wait.)
So, my question; what's the output of sum(is.null(data[[k]]))
? If it's not 0, you have NULL values embedded in your dataset and will need to either remove the relevant rows, or change the check to
if(!is.null(data[[k]][[k2]]) & temp > data[[k]][[k2]]){
#do stuff
}
Hopefully that helps; it's hard to tell without the entire dataset. If it doesn't help, and the problem is not a NULL value getting in somewhere, I'm afraid I have no idea.
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
For those using Gradle (instead of Maven) :
springBoot {
mainClass = "com.example.Main"
}
For me helped only this code line:
Assembly.Load("System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
Try only using -e
(--execute
) option:
$ mysql -u root -proot -e "SHOW GLOBAL VARIABLES LIKE 'PORT';" (8s 26ms)
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port | 3306 |
+---------------+-------+
Replace root
by your "username" and "password"
SELECT * FROM table ORDER BY id DESC LIMIT 50
save resources make one query, there is no need to make nested queries
OK Here is a Good And Proper Solution
You have a Div call with an id="myDiv"
so the function goes.
function GetScrollerEndPoint()
{
var scrollHeight = $("#myDiv").prop('scrollHeight');
var divHeight = $("#myDiv").height();
var scrollerEndPoint = scrollHeight - divHeight;
var divScrollerTop = $("#myDiv").scrollTop();
if(divScrollerTop === scrollerEndPoint)
{
//Your Code
//The Div scroller has reached the bottom
}
}
It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.
In browsers supporting the File API, you can use the FileReader constructor to read files once they have been selected by the user.
document.getElementById('picField').onchange = function (evt) {
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
// FileReader support
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
document.getElementById(outImage).src = fr.result;
}
fr.readAsDataURL(files[0]);
}
// Not supported
else {
// fallback -- perhaps submit the input to an iframe and temporarily store
// them on the server until the user's session ends.
}
}
Where the File API is unsupported, you cannot (in most security conscious browsers) get the full path of a file from a file input box, nor can you access the data. The only viable solution would be to submit the form to a hidden iframe and have the file pre-uploaded to the server. Then, when that request completes you could set the src of the image to the location of the uploaded file.
SYSDATE
and GETDATE
perform identically.
SYSDATE
is compatible with Oracle syntax, and GETDATE
is compatible with Microsoft SQL Server syntax.
a = double.Parse(Console.ReadLine());
Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.
Edit:
To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.
If you'd like to perform some sort of error checking, simply do this:
if ( double.TryParse(Console.ReadLine(), out a) ) {
Console.Writeline("Sonuç "+ a * Math.PI;);
}
else {
Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}
Thanks to Öyvind and abatischev for helping me refine my answer.
For people in the future seeing this, postgres
is in the /usr/lib/postgresql/10/bin
on my Ubuntu server.
I added it to the PATH in my .bashrc file, and add this line at the end
PATH=$PATH:/usr/lib/postgresql/10/bin
then on the command line
$> source ./.bashrc
I refreshed my bash environment. Now I can use postgres -D /wherever
from any directory
The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.
Hence let's create an HTTP entity and send the headers and parameter in body.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
In matplotlib it would be:
import matplotlib.pyplot as plt
data = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
x_val = [x[0] for x in data]
y_val = [x[1] for x in data]
print x_val
plt.plot(x_val,y_val)
plt.plot(x_val,y_val,'or')
plt.show()
which would produce:
In case if you are still stumbling over this question. Nowadays things look nicer with Java 8:
try {
Files.lines(Paths.get(targetsFile)).forEach(
s -> {
System.out.println(s);
// do more stuff with s
}
);
} catch (IOException exc) {
exc.printStackTrace();
}
I think it should be
verify(mockBar, times(2)).doSomething(...)
Sample from mockito javadoc:
ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
verify(mock, times(2)).doSomething(peopleCaptor.capture());
List<Person> capturedPeople = peopleCaptor.getAllValues();
assertEquals("John", capturedPeople.get(0).getName());
assertEquals("Jane", capturedPeople.get(1).getName());
Perhaps I misunderstood the question but doesn't this do it?
int NumDigits(int x)
{
x = abs(x);
return (x < 10 ? 1 :
(x < 100 ? 2 :
(x < 1000 ? 3 :
(x < 10000 ? 4 :
(x < 100000 ? 5 :
(x < 1000000 ? 6 :
(x < 10000000 ? 7 :
(x < 100000000 ? 8 :
(x < 1000000000 ? 9 :
10)))))))));
}