Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.
On PSv5.1 or higher, where >
and >>
are effectively aliases of Out-File
, you can set the default encoding for >
/ >>
/ Out-File
via the $PSDefaultParameterValues
preference variable:
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
On PSv5.0 or below, you cannot change the encoding for >
/ >>
, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File
.
(The $PSDefaultParameterValues
preference variable was introduced in PSv3.0).
On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
an -Encoding
parameter (which in PSv5.1+ includes >
and >>
), use:
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
If you place this command in your $PROFILE
, cmdlets such as Out-File
and Set-Content
will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding
parameter.
Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues
:
$PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }
Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.
For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.
The automatic $OutputEncoding
variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.
PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.
This means that source-code files without a BOM are assumed to be UTF-8, and using >
/ Out-File
/ Set-Content
defaults to BOM-less UTF-8; explicit use of the utf8
-Encoding
argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom
value.
If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1
file will typically not have a UTF-8 pseudo-BOM:
Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat
, sed
, and awk
- and even some editors such as gedit
- to pass the pseudo-BOM through, i.e., to treat it as data.
bash
with, say, text=$(cat file)
or text=$(<file)
- the resulting variable will contain the pseudo-BOM as the first 3 bytes.Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.
Note:
The following doesn't aspire to cover all standard cmdlets.
Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.
As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.
Cmdlets that write:
Out-File
and >
/ >>
create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content
/ Add-Content
(see next point); New-ModuleManifest
and Export-CliXml
also create UTF-16LE files.
Set-Content
(and Add-Content
if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default
).
Export-Csv
indeed creates ASCII files, as documented, but see the notes re -Append
below.
Export-PSSession
creates UTF-8 files with BOM by default.
New-Item -Type File -Value
currently creates BOM-less(!) UTF-8.
The Send-MailMessage
help topic also claims that ASCII encoding is the default - I have not personally verified that claim.
Start-Transcript
invariably creates UTF-8 files with BOM, but see the notes re -Append
below.
Re commands that append to an existing file:
>>
/ Out-File -Append
make no attempt to match the encoding of a file's existing content.
That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding
, which is not an option with >>
(except indirectly in PSv5.1+, via $PSDefaultParameterValues
, as shown above).
In short: you must know the encoding of an existing file's content and append using that same encoding.
Add-Content
is the laudable exception: in the absence of an explicit -Encoding
argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.
This inconsistency between Out-File -Append
/ >>
and Add-Content
, which also affects PowerShell Core, is discussed in this GitHub issue.
Export-Csv -Append
partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append
assumes UTF-8 is, whereas Add-Content
assumes ANSI.
Start-Transcript -Append
partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.
Cmdlets that read (that is, the encoding used in the absence of a BOM):
Get-Content
and Import-PowerShellDataFile
default to ANSI (Default
), which is consistent with Set-Content
.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.
By contrast, Import-Csv
, Import-CliXml
and Select-String
assume UTF-8 in the absence of a BOM.
You can also modify your config/routes.rb file like:
get 'ajax/:action', to: 'ajax#:action', :defaults => { :format => 'json' }
Which will default the format to json. It is working fine for me in Rails 4.
Or if you want to go even further and you are using namespaces, you can cut down the duplicates:
namespace :api, defaults: {format: 'json'} do
#your controller routes here ...
end
with the above everything under /api
will be formatted as json by default.
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
I was uninstalled compass 1.0.1 and install compass 0.12.7, this fix problem for me
$ sudo gem uninstall compass
$ sudo gem install compass -v 0.12.7
This happens when postgres server is not running. Steps to properly install Postgres via Homebrew on MAC :
brew install postgres
initdb /Users/<username>/db -E utf8
[This initializes postgres to use the given directory as the database directory. Normally it is not adviced to use the user directory for database storage. Edit sudoers file to add initdb and similar commands and then run initdb on /usr/local/var/postgres]
pg_ctl -D /Users/<username>/db -l logfile start
[After getting success with step 2 it will prompt to run step 3. This command manually starts the server.]
That's a specific case of the rule that you shouldn't catch any exception you don't know how to handle. If you don't know how to handle it, it's always better to let some other part of the system catch and handle it.
Make sure to delete ~/.bash_profile and ~/.bash_login so that .profile can work. This worked for me http://johnnywey.wordpress.com/2008/04/17/fixing-bash-profile-in-os-x/
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
You can use the below syntax -
from FolderName.FileName import Classname
use the following function:
def is_numeric? val
return val.try(:to_f).try(:to_s) == val
end
so,
is_numeric? "1.2f"
= false
is_numeric? "1.2"
= true
is_numeric? "12f"
= false
is_numeric? "12"
= true
you can force UTF8 with force_encoding(Encoding::UTF_8)
:
Example:
<%= yield.force_encoding(Encoding::UTF_8) %>
Yes, ensure
like finally
guarantees that the block will be executed. This is very useful for making sure that critical resources are protected e.g. closing a file handle on error, or releasing a mutex.
If you want your block to return a useful value (e.g. when using #map
, #inject
, etc.), next
and break
also accept an argument.
Consider the following:
def contrived_example(numbers)
numbers.inject(0) do |count, x|
if x % 3 == 0
count + 2
elsif x.odd?
count + 1
else
count
end
end
end
The equivalent using next
:
def contrived_example(numbers)
numbers.inject(0) do |count, x|
next count if x.even?
next (count + 2) if x % 3 == 0
count + 1
end
end
Of course, you could always extract the logic needed into a method and call that from inside your block:
def contrived_example(numbers)
numbers.inject(0) { |count, x| count + extracted_logic(x) }
end
def extracted_logic(x)
return 0 if x.even?
return 2 if x % 3 == 0
1
end
In my own experience where I needed to try and find out what some old VB6 programs were doing, I turned to Process Explorer (Sysinternals). I did the following:
This didn't show the actual functions, but it listed their names, folders of where files were being copied from and to and if it accessed a DB it would also display the connection string. Enough to help you get an idea, but may be useless for complex programs. The programs I was looking at were pretty basic (no pun intended).
YMMV.
Try like
$('.printMe').click(function(){
window.print();
});
or if you want to print selected area try like
$('.printMe').click(function(){
$("#outprint").print();
});
$unixtime_to_date = date('jS F Y h:i:s A (T)', $unixtime);
This should work to.
function myFunction() {_x000D_
document.getElementById("text").value='male'_x000D_
document.getElementById("myCheck_2").checked = false;_x000D_
var checkBox = document.getElementById("myCheck");_x000D_
var text = document.getElementById("text");_x000D_
if (checkBox.checked == true){_x000D_
text.style.display = "block";_x000D_
} else {_x000D_
text.style.display = "none";_x000D_
}_x000D_
}_x000D_
function myFunction_2() {_x000D_
document.getElementById("text").value='female'_x000D_
document.getElementById("myCheck").checked = false;_x000D_
var checkBox = document.getElementById("myCheck_2");_x000D_
var text = document.getElementById("text");_x000D_
if (checkBox.checked == true){_x000D_
text.style.display = "block";_x000D_
} else {_x000D_
text.style.display = "none";_x000D_
}_x000D_
}
_x000D_
Male: <input type="checkbox" id="myCheck" onclick="myFunction()">_x000D_
Female: <input type="checkbox" id="myCheck_2" onclick="myFunction_2()">_x000D_
_x000D_
<input type="text" id="text" placeholder="Name">
_x000D_
try this:
Using jQuery:
You can reset the entire form with:
$("#myform")[0].reset();
Or just the specific field with:
$('#form-id').children('input').val('')
Using JavaScript Without jQuery
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
function submitForm() {
// Get the first form with the name
// Hopefully there is only one, but there are more, select the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit
frm.reset(); // Reset
return false; // Prevent page refresh
}
An easy way to have access to the token, is to put the token in the LocalStorage or the AsyncStorage with React Native.
Below an example with a React Native project
authReducer.js
import { AsyncStorage } from 'react-native';
...
const auth = (state = initialState, action) => {
switch (action.type) {
case SUCCESS_LOGIN:
AsyncStorage.setItem('token', action.payload.token);
return {
...state,
...action.payload,
};
case REQUEST_LOGOUT:
AsyncStorage.removeItem('token');
return {};
default:
return state;
}
};
...
and api.js
import axios from 'axios';
import { AsyncStorage } from 'react-native';
const defaultHeaders = {
'Content-Type': 'application/json',
};
const config = {
...
};
const request = axios.create(config);
const protectedRequest = options => {
return AsyncStorage.getItem('token').then(token => {
if (token) {
return request({
headers: {
...defaultHeaders,
Authorization: `Bearer ${token}`,
},
...options,
});
}
return new Error('NO_TOKEN_SET');
});
};
export { request, protectedRequest };
For web you can use Window.localStorage
instead of AsyncStorage
The same problem. Python3.5 and pip 8.0.2 installed from Linux rpm
's.
I did not find a primary cause and cannot give a proper answer. It looks like there are multiple possible causes.
However, I hope I can help with sharing my observation and a workaround.
pyvenv
with --system-site-packages
./bin
does not contain pip
, pip
is available from system site packagespyvenv
without --system-site-packages
pip
gets installed into ./bin
, but it's a different version (from ensurepip
)Obvious workaround for pyvenv
with --system-site-packages
:
--system-site-packages
optioninclude-system-site-packages = false
to true
in pyvenv.cfg
filepredQuery[preId]=='undefined'
You're testing against the string 'undefined'
; you've confused this test with the typeof
test which would return a string. You probably mean to be testing against the special value undefined
:
predQuery[preId]===undefined
Note the strict-equality operator to avoid the generally-unwanted match null==undefined
.
However there are two ways you can get an undefined
value: either preId
isn't a member of predQuery
, or it is a member but has a value set to the special undefined
value. Often, you only want to check whether it's present or not; in that case the in
operator is more appropriate:
!(preId in predQuery)
Use angular-ui-bootstrap's typehead.
It had great support for $http and promises. Also, it doesn't include any JQuery at all, pure AngularJS.
(I always prefer using existing libraries and if they are missing something to open an issue or pull request, much better then creating your own again)
Just:
Timestamp timestamp = new Timestamp(long);
Date date = new Date(timestamp.getTime());
You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.
I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.
Here is an example of how to do it using extension methods:
using System;
using System.Globalization;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToMonthName());
Console.WriteLine(DateTime.Now.ToShortMonthName());
Console.Read();
}
}
static class DateTimeExtensions
{
public static string ToMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
}
public static string ToShortMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
}
}
Hope this helps!
@Mahender, you probably meant the difference between \W
(instead of \w
) and \b
. If not, then I would agree with @BoltClock and @jwismar above. Otherwise continue reading.
\W
would match any non-word character and so its easy to try to use it to match word boundaries. The problem is that it will not match the start or end of a line. \b
is more suited for matching word boundaries as it will also match the start or end of a line. Roughly speaking (more experienced users can correct me here) \b
can be thought of as (\W|^|$)
. [Edit: as @?mega mentions below, \b
is a zero-length match so (\W|^|$)
is not strictly correct, but hopefully helps explain the diff]
Quick example: For the string Hello World
, .+\W
would match Hello_
(with the space) but will not match World
. .+\b
would match both Hello
and World
.
To note it in the languages you mentioned:
Java:
String str = new String("Hello");
Python:
str = "Hello"
Both Java and Python have the concept of a "string", C does not have the concept of a "string". C has character arrays which can come in "read only" or manipulatable.
C:
char * str = "Hello"; // the string "Hello\0" is pointed to by the character pointer
// str. This "string" can not be modified (read only)
or
char str[] = "Hello"; // the characters: 'H''e''l''l''o''\0' have been copied to the
// array str. You can change them via: str[x] = 't'
A character array is a sequence of contiguous characters with a unique sentinel character at the end (normally a NULL terminator '\0'
). Note that the sentinel character is auto-magically appended for you in the cases above.
If you need to just empty the style
of an element then:
element.style.cssText = null;
This should do good. Hope it helps!
How about some examples to show it in action...
@Test
public void isInstanceOf() {
Exception anEx1 = new Exception("ex");
Exception anEx2 = new RuntimeException("ex");
RuntimeException anEx3 = new RuntimeException("ex");
//Base case, handles inheritance
Assert.assertTrue(anEx1 instanceof Exception);
Assert.assertTrue(anEx2 instanceof Exception);
Assert.assertTrue(anEx3 instanceof Exception);
//Other cases
Assert.assertFalse(anEx1 instanceof RuntimeException);
Assert.assertTrue(anEx2 instanceof RuntimeException);
Assert.assertTrue(anEx3 instanceof RuntimeException);
}
@Test
public void isAssignableFrom() {
Exception anEx1 = new Exception("ex");
Exception anEx2 = new RuntimeException("ex");
RuntimeException anEx3 = new RuntimeException("ex");
//Correct usage = The base class goes first
Assert.assertTrue(Exception.class.isAssignableFrom(anEx1.getClass()));
Assert.assertTrue(Exception.class.isAssignableFrom(anEx2.getClass()));
Assert.assertTrue(Exception.class.isAssignableFrom(anEx3.getClass()));
//Incorrect usage = Method parameter is used in the wrong order
Assert.assertTrue(anEx1.getClass().isAssignableFrom(Exception.class));
Assert.assertFalse(anEx2.getClass().isAssignableFrom(Exception.class));
Assert.assertFalse(anEx3.getClass().isAssignableFrom(Exception.class));
}
Y = y.values[:,0]
Y - formated_train_y
y - train_y
r
for read
w
for write
r+
for read/write without deleting the original content if file exists, otherwise raise exception
w+
for delete the original content then read/write if file exists, otherwise create the file
For example,
>>> with open("file1.txt", "w") as f:
... f.write("ab\n")
...
>>> with open("file1.txt", "w+") as f:
... f.write("c")
...
$ cat file1.txt
c$
>>> with open("file2.txt", "r+") as f:
... f.write("ab\n")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'file2.txt'
>>> with open("file2.txt", "w") as f:
... f.write("ab\n")
...
>>> with open("file2.txt", "r+") as f:
... f.write("c")
...
$ cat file2.txt
cb
$
Docker now (version 1.13 or 17.06 and higher) has support for managing secret information. Here's an overview and more detailed documentation
Similar feature exists in kubernetes and DCOS
VCRUNTIME140.dll error
This error means you don't have required Visual C++ packages installed in your computer.
If you have installed wampserver then firstly uninstall wampserver.
Download the VC packages
Download all these VC packages and install all of them. You should install both 64 bit and 32 bit version.
-- VC9 Packages (Visual C++ 2008 SP1)--
http://www.microsoft.com/en-us/download/details.aspx?id=5582
http://www.microsoft.com/en-us/download/details.aspx?id=2092
-- VC10 Packages (Visual C++ 2010 SP1)--
http://www.microsoft.com/en-us/download/details.aspx?id=8328
http://www.microsoft.com/en-us/download/details.aspx?id=13523
-- VC11 Packages (Visual C++ 2012 Update 4)--
The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page
http://www.microsoft.com/en-us/download/details.aspx?id=30679
-- VC13 Packages] (Visual C++ 2013)--
The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page
https://www.microsoft.com/en-us/download/details.aspx?id=40784
-- VC14 Packages (Visual C++ 2015)--
The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page
http://www.microsoft.com/en-us/download/details.aspx?id=48145
install packages with admin priviliges
Right click->Run as Administrator
install wampserver again
After you installed both 64bits and 32 bits version of VC packages then install wampserver again.
Also had this error when accidentally fed a database connection string to the readonly mirror - not the primary database in a HA setup.
Set This in OkHttpClient.Builder() Object
val httpClient = OkHttpClient.Builder()
httpClient.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES) // read timeout
Alternatively,
<style type="text/css">
#example {
display: block;
width: 30px;
height: 10px;
background: url(../images/example.png) no-repeat;
text-indent: -9999px;
}
</style>
<a href="http://www.example.com" id="example">See an example!</a>
More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.
In a translation unit within the same namespace, usually at the top:
// foo.h
struct foo
{
static const std::string s;
};
// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives
// bar.h
namespace baz
{
struct bar
{
static const float f;
};
}
// bar.cpp
namespace baz
{
const float bar::f = 3.1415926535;
}
After reading your comment on my previous answer I thought I might put this as a separate answer.
Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.
That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with
WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/
This is the jQuery
$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();
$('.active').show();
$('#button-next').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':last-child')) {
$('.sp').first().addClass('active');
}
else{
$('.oldActive').next().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
$('#button-previous').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':first-child')) {
$('.sp').last().addClass('active');
}
else{
$('.oldActive').prev().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
});
So now the explanation.
Stage 1
1) Load the script on document ready.
2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.
3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;
Stage 2
Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.
2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.
3) We remove the class oldActive because it's no longer needed.
4) fadeOut all of the slides
5) fade In the active slides
Step 3
Same as in step two but using some reverse logic for traversing through the elements backwards.
It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.
This is what I did. Most tooltip scripts require you to execute a function that stores the tooltips. This is a jQuery example:
$.when($('*').filter(function() {
return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
$(this).attr('title', $(this).text());
}
})).done(function(){
setupTooltip();
});
If you didn't want to check for ellipsis css, you could simplify like:
$.when($('*').filter(function() {
return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
$(this).attr('title', $(this).text());
})).done(function(){
setupTooltip();
});
I have the "when" around it, so that the "setupTooltip" function doesn't execute until all titles have been updated. Replace the "setupTooltip", with your tooltip function and the * with the elements you want to check. * will go through them all if you leave it.
If you simply want to just update the title attributes with the browsers tooltip, you can simplify like:
$('*').filter(function() {
return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
$(this).attr('title', $(this).text());
}
});
Or without check for ellipsis:
$.when($('*').filter(function() {
return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
$(this).attr('title', $(this).text());
});
In most regex implementations (including Java's), :
has no special meaning, neither inside nor outside a character class.
Your problem is most likely due to the fact the -
acts as a range operator in your class:
[A-Za-z0-9.,-:]*
where ,-:
matches all ascii characters between ','
and ':'
. Note that it still matches the literal ':'
however!
Try this instead:
[A-Za-z0-9.,:-]*
By placing -
at the start or the end of the class, it matches the literal "-"
. As mentioned in the comments by Keoki Zee, you can also escape the -
inside the class, but most people simply add it at the end.
A demo:
public class Test {
public static void main(String[] args) {
System.out.println("8:".matches("[,-:]+")); // true: '8' is in the range ','..':'
System.out.println("8:".matches("[,:-]+")); // false: '8' does not match ',' or ':' or '-'
System.out.println(",,-,:,:".matches("[,:-]+")); // true: all chars match ',' or ':' or '-'
}
}
This may be platform specific, I somehow doubt it, but anyway, the best explanation I've seen is here on this msdn page where they explain about shutdown, linger options, socket closure and general connection termination sequences.
In summary, use shutdown to send a shutdown sequence at the TCP level and use close to free up the resources used by the socket data structures in your process. If you haven't issued an explicit shutdown sequence by the time you call close then one is initiated for you.
If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.
So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.
Example with Digest Authentication:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace NUI
{
public class DigestAuthFixer
{
private static string _host;
private static string _user;
private static string _password;
private static string _realm;
private static string _nonce;
private static string _qop;
private static string _cnonce;
private static DateTime _cnonceDate;
private static int _nc;
public DigestAuthFixer(string host, string user, string password)
{
// TODO: Complete member initialization
_host = host;
_user = user;
_password = password;
}
private string CalculateMd5Hash(
string input)
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = MD5.Create().ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
private string GrabHeaderVar(
string varName,
string header)
{
var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
var matchHeader = regHeader.Match(header);
if (matchHeader.Success)
return matchHeader.Groups[1].Value;
throw new ApplicationException(string.Format("Header {0} not found", varName));
}
private string GetDigestHeader(
string dir)
{
_nc = _nc + 1;
var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
var digestResponse =
CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));
return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
"algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
_user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}
public string GrabResponse(
string dir)
{
var url = _host + dir;
var uri = new Uri(url);
var request = (HttpWebRequest)WebRequest.Create(uri);
// If we've got a recent Auth header, re-use it!
if (!string.IsNullOrEmpty(_cnonce) &&
DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
{
request.Headers.Add("Authorization", GetDigestHeader(dir));
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// Try to fix a 401 exception by adding a Authorization header
if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
_realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
_nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
_qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
_nc = 0;
_cnonce = new Random().Next(123400, 9999999).ToString();
_cnonceDate = DateTime.Now;
var request2 = (HttpWebRequest)WebRequest.Create(uri);
request2.Headers.Add("Authorization", GetDigestHeader(dir));
response = (HttpWebResponse)request2.GetResponse();
}
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
Then you could call it:
DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);
if Url is: http://xyz.rss.com/folder/rss then domain: http://xyz.rss.com (domain part) dir: /folder/rss (rest of the url)
you could also return it as stream and use XmlDocument Load() method.
For ASP.NET on Linux, check out Mono.
That said, thousands of sites run on Windows Server without any issues. A poorly-configured server with any OS will be vulnerable; Linux won't save you from a poor admin.
So I guess my "best practice" for deplying an ASP.NET app would be to use Windows Server 2008 (likely Web edition). And hire a good administrator.
Use __name__
attribute:
# foo.py
def bar():
print(f"my name is {bar.__name__}")
You can easily access function's name from within the function using __name__
attribute.
>>> def bar():
... print(f"my name is {bar.__name__}")
...
>>> bar()
my name is bar
I've come across this question myself several times, looking for the ways to do it. Correct answer is contained in the Python's documentation (see Callable types section).
Every function has a __name__
parameter that returns its name and even __qualname__
parameter that returns its full name, including which class it belongs to (see Qualified name).
You can think of an iframe as an embedded browser window that you can put on an HTML page to show another URL inside it. This URL can be totally distinct from your web site/app.
You can put an iframe in any HTML page, so you could put one inside a contentplaceholder in a webform that has a Masterpage and it will appear with whatever URL you load into it (via Javascript, or C# if you turn your iframe into a server-side control (runat='server'
) on the final HTML page that your webform produces when requested.
And you can load a URL into your iframe that is a .aspx
page.
But - iframes have nothing to do with the ASP.net mechanism. They are HTML elements that can be made to run server-side, but they are essentially 'dumb' and unmanaged/unconnected to the ASP.Net mechanisms - don't confuse a Contentplaceholder with an iframe.
Incidentally, the use of iframes is still contentious - do you really need to use one? Can you afford the negative trade-offs associated with them e.g. lack of navigation history ...?
Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp
for / you would escape with %2F
You also might notice a little lag because 0deg and 360deg are the same spot, so it is going from spot 1 in a circle back to spot 1. It is really insignificant, but to fix it, all you have to do is change 360deg to 359deg
my jsfiddle illustrates your animation:
#myImg {
-webkit-animation: rotation 2s infinite linear;
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(359deg);}
}
Also what might be more resemblant of the apple loading icon would be an animation that transitions the opacity/color of the stripes of gray instead of rotating the icon.
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
Try this in Android DataBinding
FragmentMainBinding binding;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false);
View rootView = binding.getRoot();
initInstances(savedInstanceState);
return rootView;
}
The method getContentAsByteArray() of the Spring class ContentCachingRequestWrapper reads the body multiple times, but the methods getInputStream() and getReader() of the same class do not read the body multiple times:
"This class caches the request body by consuming the InputStream. If we read the InputStream in one of the filters, then other subsequent filters in the filter chain can't read it anymore. Because of this limitation, this class is not suitable in all situations."
In my case more general solution that solved this problem was to add following three classes to my Spring boot project (and the required dependencies to the pom file):
CachedBodyHttpServletRequest.java:
public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
private byte[] cachedBody;
public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
super(request);
InputStream requestInputStream = request.getInputStream();
this.cachedBody = StreamUtils.copyToByteArray(requestInputStream);
}
@Override
public ServletInputStream getInputStream() throws IOException {
return new CachedBodyServletInputStream(this.cachedBody);
}
@Override
public BufferedReader getReader() throws IOException {
// Create a reader from cachedContent
// and return it
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.cachedBody);
return new BufferedReader(new InputStreamReader(byteArrayInputStream));
}
}
CachedBodyServletInputStream.java:
public class CachedBodyServletInputStream extends ServletInputStream {
private InputStream cachedBodyInputStream;
public CachedBodyServletInputStream(byte[] cachedBody) {
this.cachedBodyInputStream = new ByteArrayInputStream(cachedBody);
}
@Override
public boolean isFinished() {
try {
return cachedBodyInputStream.available() == 0;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
throw new UnsupportedOperationException();
}
@Override
public int read() throws IOException {
return cachedBodyInputStream.read();
}
}
ContentCachingFilter.java:
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Component
@WebFilter(filterName = "ContentCachingFilter", urlPatterns = "/*")
public class ContentCachingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
System.out.println("IN ContentCachingFilter ");
CachedBodyHttpServletRequest cachedBodyHttpServletRequest = new CachedBodyHttpServletRequest(httpServletRequest);
filterChain.doFilter(cachedBodyHttpServletRequest, httpServletResponse);
}
}
I also added the following dependencies to pom:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
A tuturial and full source code is located here: https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times
Looking at the error stack trace, it seems your timer is still active. Try to cancel the timer upon closing the form (i.e. in the form's OnClose() method). This looks like the cleanest solution.
in addition,if you try to use CustomActionBarTheme,make sure there is
<application android:theme="@style/CustomActionBarTheme" ... />
in AndroidManifest.xml
not
<application android:theme="@android:style/CustomActionBarTheme" ... />
here another option:
PS II> $f="C:\Downloads\ReSharperSetup.7.0.97.60.msi"
PS II> $f.split('\')[-1] -replace '\.\w+$'
PS II> $f.Substring(0,$f.LastIndexOf('.')).split('\')[-1]
To remove specific key and element from hashmap use
hashmap.remove(key)
full source code is like
import java.util.HashMap;
public class RemoveMapping {
public static void main(String a[]){
HashMap hashMap = new HashMap();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("Original HashMap : "+hashMap);
hashMap.remove(3);
System.out.println("Changed HashMap : "+hashMap);
}
}
I think you hit the same issue as discussed in this post. You forgot to escape your \
character.
I had this error because in my test I had two expectations, one on a mock and one on concrete type
MyClass cls = new MyClass();
MyClass cls2 = Mockito.mock(Myclass.class);
when(foo.bar(cls)).thenReturn(); // cls is not actually a mock
when(foo.baz(cls2)).thenReturn();
I fixed it by changing cls to be a mock as well
Use jQuery for $. I tried and work.
HTML and XML entities are just a way of referencing a Unicode code-point in a way that reliably works regardless of the encoding of the actual page, making them useful for using esoteric Unicode characters in a page using 7-bit ASCII or some other encoding scheme, ideally on a one-off basis. They're also used to escape the <
, >
, "
and &
characters as these are reserved in SGML.
Anyway, Unicode has a number of tick/check characters, as per Wikipedia ( http://en.wikipedia.org/wiki/Tick_(check_mark) ).
Ideally you should save/store your HTML in a Unicode format like UTF-8 or 16, thus obviating the need to use HTML entities to represent a Unicode character. Nonetheless use: ✔
✔.
✔
✔
Is using hex notation and is the same as
$#10004;
(as 2714
in base 16 is the same as 10004
in base 10)
For me none of the solutions here solved it. Frustrated, I restarted my Macbook's iTerm terminal, and voila! My github authorization started working again.
Weird, but maybe iTerm has its own way of handling SSH authorizations or that my terminal session wasn't authorized somehow.
You can set the default search_path
at the database level:
ALTER DATABASE <database_name> SET search_path TO schema1,schema2;
Or at the user or role level:
ALTER ROLE <role_name> SET search_path TO schema1,schema2;
Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.
When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name>
to create your databases.
To add a column I just had to follow these steps :
rails generate migration add_fieldname_to_tablename fieldname:string
Alternative
rails generate migration addFieldnameToTablename
Once the migration is generated, then edit the migration and define all the attributes you want that column added to have.
Note: Table names in Rails are always plural (to match DB conventions). Example using one of the steps mentioned previously-
rails generate migration addEmailToUsers
rake db:migrate
Or
db/schema.rb
, Add the columns you want in the SQL query. Run this command: rake db:schema:load
Warning/Note
Bear in mind that, running rake db:schema:load
automatically wipes all data in your tables.
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
You can create a class level variable to get returned value. I mean
class A {
int k = 0;
private void f(Button b, int a){
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
k = a * 5;
}
});
}
now you can get value of K and use it where you want.
Answer of your why is :
A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).
Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)
The following solution is:
getElementById
is called once at the outset. This may or may not suit your purposes.mydiv = document.getElementById("showmehideme");_x000D_
_x000D_
function showhide(d) {_x000D_
d.style.display = (d.style.display !== "none") ? "none" : "block";_x000D_
}
_x000D_
#mydiv { background-color: #ddd; }
_x000D_
<button id="button" onclick="showhide(mydiv)">Show/Hide</button>_x000D_
<div id="showmehideme">_x000D_
This div will show and hide on button click._x000D_
</div>
_x000D_
For simple situations this works pretty well without using any other library then std::string (which is already in use).
Replace all occurences of character a with character b in some_string:
for (size_t i = 0; i < some_string.size(); ++i) {
if (some_string[i] == 'a') {
some_string.replace(i, 1, "b");
}
}
If the string is large or multiple calls to replace is an issue, you can apply the technique mentioned in this answer: https://stackoverflow.com/a/29752943/3622300
follow this video https://www.youtube.com/watch?v=883HjO06_E0 for how to download and install Android SDK components manually
Try this:
#foo
{
position: absolute;
top: 100%;
right: 0%;
}
Use:
docker start $(docker ps -a -q --filter "status=exited")
This will start all containers which are in the exited state.
docker exec -it <container-id> /bin/bash
This will connect to the particular container.
This is an expansion of one of the solutions provided in Jakub's answer
I was faced with a situation where the commits I needed to roll back were somewhat complex, with several of the commits being merge commits, and I needed to avoid rewriting history. I was not able to use a series of git revert
commands because I eventually ran into conflicts between the reversion changes being added. I ended up using the following steps.
First, check out the contents of the target commit while leaving HEAD at the tip of the branch:
$ git checkout -f <target-commit> -- .
(The -- makes sure <target-commit>
is interpreted as a commit rather than a file; the . refers to the current directory.)
Then, determine what files were added in the commits being rolled back, and thus need to be deleted:
$ git diff --name-status --cached <target-commit>
Files that were added should show up with an "A" at the beginning of the line, and there should be no other differences. Now, if any files need to be removed, stage these files for removal:
$ git rm <filespec>[ <filespec> ...]
Finally, commit the reversion:
$ git commit -m 'revert to <target-commit>'
If desired, make sure that we're back to the desired state:
$git diff <target-commit> <current-commit>
There should be no differences.
Well, both will clean. That means they'll remove the target folder. The real question is what's the difference between package and install?
package
will compile your code and also package it. For example, if your pom says the project is a jar, it will create a jar for you when you package it and put it somewhere in the target directory (by default).
install
will compile and package, but it will also put the package in your local repository. This will make it so other projects can refer to it and grab it from your local repository.
The getItem
method in the WebStorage specification, explicitly returns null
if the item does not exist:
... If the given key does not exist in the list associated with the object then this method must return null. ...
So, you can:
if (localStorage.getItem("infiniteScrollEnabled") === null) {
//...
}
See this related question:
Here is an example of a simple Two-column class:
.two-col {
-moz-column-count: 2;
-moz-column-gap: 20px;
-webkit-column-count: 2;
-webkit-column-gap: 20px;
}
Of which you would apply to a block of text like so:
<p class="two-col">Text</p>
It means "a python object", i.e. not one of the builtin scalar types supported by numpy.
np.array([object()]).dtype
=> dtype('O')
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
Just use var = var1 var2
and it will automatically concatenate the vars var1
and var2
:
awk '{new_var=$1$2; print new_var}' file
You can put an space in between with:
awk '{new_var=$1" "$2; print new_var}' file
Which in fact is the same as using FS
, because it defaults to the space:
awk '{new_var=$1 FS $2; print new_var}' file
$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am
You can play around with it in ideone: http://ideone.com/4u2Aip
There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.
The steps in Excel 2010 are:
In a cell enter a formula like this
=VLOOKUP(A2,$D$3:$E$5,2,FALSE)
which will return the matching value from the second part of your list.
Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.
The steps in Excel 2010 are:
If you need to have production application.yml
completely replaced then put its test version to the same path but in test environment (usually it is src/test/resources/
)
But if you need to override or add some properties then you have few options.
Option 1: put test application.yml
in src/test/resources/config/
directory as @TheKojuEffect suggests in his answer.
Option 2: use profile-specific properties: create say application-test.yml
in your src/test/resources/
folder and:
add @ActiveProfiles
annotation to your test classes:
@SpringBootTest(classes = Application.class)
@ActiveProfiles("test")
public class MyIntTest {
or alternatively set spring.profiles.active
property value in @SpringBootTest
annotation:
@SpringBootTest(
properties = ["spring.profiles.active=test"],
classes = Application.class,
)
public class MyIntTest {
This works not only with @SpringBootTest
but with @JsonTest
, @JdbcTests
, @DataJpaTest
and other slice test annotations as well.
And you can set as many profiles as you want (spring.profiles.active=dev,hsqldb
) - see farther details in documentation on Profiles.
I defined an OnClickListener for ImageView as an OnClickListener for a button and it seems to be working fine. Here's what I had. Please try and let us know if it doesn't work.
final ImageView imageview1 = (ImageView) findViewById(R.id.imageView1);
imageview1.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
try {
Log.i("MyTag","Image button is pressed, visible in LogCat");;
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
});
This is sort of done in parts in some of the other answers.
git clone --mirror git@oldserver:oldproject.git
cd oldproject.git
git remote add new git@newserver:newproject.git
git push --mirror new
The error means pylab is not part of the standard Python libraries. You will need to down-load it and install it. I think it's available Here They have installation instructions here
Use FirebaseMessaging instead
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
I'm a complete noob on Entity but this is how I would do it in theory...
var name = yourDbContext.MyTable.Find(1).Name;
If It's A Primary Key.
-- OR --
var name = yourDbContext.MyTable.SingleOrDefault(mytable => mytable.UserId == 1).Name;
-- OR --
For whole Column:
var names = yourDbContext.MyTable
.Where(mytable => mytable.UserId == 1)
.Select(column => column.Name); //You can '.ToList();' this....
But "oh Geez Rick, What do I know..."
if (!myString.replace(/^\s+|\s+$/g,""))
alert('string is only whitespace');
Closing a SpringApplication
basically means closing the underlying ApplicationContext
. The SpringApplication#run(String...)
method gives you that ApplicationContext
as a ConfigurableApplicationContext
. You can then close()
it yourself.
For example,
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to shut down...
ctx.close();
}
}
Alternatively, you can use the static
SpringApplication.exit(ApplicationContext, ExitCodeGenerator...)
helper method to do it for you. For example,
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to stop...
int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
@Override
public int getExitCode() {
// no errors
return 0;
}
});
// or shortened to
// int exitCode = SpringApplication.exit(ctx, () -> 0);
System.exit(exitCode);
}
}
You need to have a height in the div <div style="overflow:hidden">
else it doesnt know what 100%
is.
set
and get
API has been deprecated *The following code should only be used for version socket.io < 0.9
See: http://socket.io/docs/migrating-from-0-9/
It can be done through the handshake/authorization mechanism.
var cookie = require('cookie');
io.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
// if there is, parse the cookie
data.cookie = cookie.parse(data.headers.cookie);
// note that you will need to use the same key to grad the
// session id, as you specified in the Express setup.
data.sessionID = data.cookie['express.sid'];
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
return accept('No cookie transmitted.', false);
}
// accept the incoming connection
accept(null, true);
});
All the attributes, that are assigned to the data object are now accessible through the handshake attribute of the socket.io connection object.
io.sockets.on('connection', function (socket) {
console.log('sessionID ' + socket.handshake.sessionID);
});
I'm going to approach this as if you have a Users model:
Users.cs
public class Users
{
[Key]
public int UserId { get; set; }
[Required]
public string UserName { get; set; }
public int RoleId { get; set; }
[ForeignKey("RoleId")]
public virtual DbUserRoles DbUserRoles { get; set; }
}
and a DbUserRoles model that represented a table by that name in the database:
DbUserRoles.cs
public partial class DbUserRoles
{
[Key]
public int UserRoleId { get; set; }
[Required]
[StringLength(30)]
public string UserRole { get; set; }
}
Once you had that cleaned up, you should just be able to create and fill a collection of UserRoles, like this, in your Controller:
var userRoleList = GetUserRolesList();
ViewData["userRoles"] = userRolesList;
and have these supporting functions:
private static SelectListItem[] _UserRolesList;
/// <summary>
/// Returns a static category list that is cached
/// </summary>
/// <returns></returns>
public SelectListItem[] GetUserRolesList()
{
if (_UserRolesList == null)
{
var userRoles = repository.GetAllUserRoles().Select(a => new SelectListItem()
{
Text = a.UserRole,
Value = a.UserRoleId.ToString()
}).ToList();
userRoles.Insert(0, new SelectListItem() { Value = "0", Text = "-- Please select your user role --" });
_UserRolesList = userRoles.ToArray();
}
// Have to create new instances via projection
// to avoid ModelBinding updates to affect this
// globally
return _UserRolesList
.Select(d => new SelectListItem()
{
Value = d.Value,
Text = d.Text
})
.ToArray();
}
Repository.cs
My Repository function GetAllUserRoles()
for the function, above:
public class Repository
{
Model1 db = new Model1(); // Entity Framework context
// User Roles
public IList<DbUserRoles> GetAllUserRoles()
{
return db.DbUserRoles.OrderBy(e => e.UserRoleId).ToList();
}
}
AddNewUser.cshtml
Then do this in your View:
<table>
<tr>
<td>
@Html.EditorFor(model => model.UserName,
htmlAttributes: new { @class = "form-control" }
)
</td>
<td>
@Html.DropDownListFor(model => model.RoleId,
new SelectList( (IEnumerable<SelectListItem>)ViewData["userRoles"], "Value", "Text", model.RoleId),
htmlAttributes: new { @class = "form-control" }
)
</td>
</tr>
</table>
To hide status bar in iOS7 you need 2 lines of code
in application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions write
[[UIApplication sharedApplication] setStatusBarHidden:YES];
in info.plist add this
View-Controller Based Status Bar Appearance = NO
Here is the code I've been using for programatically importing .cer files into a new KeyStore.
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
//VERY IMPORTANT. SOME OF THESE EXIST IN MORE THAN ONE PACKAGE!
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
//Put everything after here in your function.
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);//Make an empty store
InputStream fis = /* insert your file path here */;
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
Certificate cert = cf.generateCertificate(bis);
trustStore.setCertificateEntry("fiddler"+bis.available(), cert);
}
Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt")
. The only drawback is that this call requires root privileges on OSX.
Modified versions of http://www.peterbe.com/plog/uniqifiers-benchmark
To preserve the order:
def f(seq): # Order preserving
''' Modified version of Dave Kirby solution '''
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)]
OK, now how does it work, because it's a little bit tricky here if x not in seen and not seen.add(x)
:
In [1]: 0 not in [1,2,3] and not print('add')
add
Out[1]: True
Why does it return True? print (and set.add) returns nothing:
In [3]: type(seen.add(10))
Out[3]: <type 'NoneType'>
and not None == True
, but:
In [2]: 1 not in [1,2,3] and not print('add')
Out[2]: False
Why does it print 'add' in [1] but not in [2]? See False and print('add')
, and doesn't check the second argument, because it already knows the answer, and returns true only if both arguments are True.
More generic version, more readable, generator based, adds the ability to transform values with a function:
def f(seq, idfun=None): # Order preserving
return list(_f(seq, idfun))
def _f(seq, idfun=None):
''' Originally proposed by Andrew Dalke '''
seen = set()
if idfun is None:
for x in seq:
if x not in seen:
seen.add(x)
yield x
else:
for x in seq:
x = idfun(x)
if x not in seen:
seen.add(x)
yield x
Without order (it's faster):
def f(seq): # Not order preserving
return list(set(seq))
You can just use empty() - as seen in the documentation, it will return false if the variable has no value.
An example on that same page:
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>
You can use isset if you just want to know if it is not NULL. Otherwise it seems empty() is just fine to use alone.
$.fn.extend({
id : function() {
return this.attr('id');
}
});
alert( $('#element').id() );
Some checking code required of course, but easily implemented!
You can't do this using forms the normal way. Instead, you want to use AJAX.
A sample function that will submit the data and alert the page response.
function submitForm() {
var http = new XMLHttpRequest();
http.open("POST", "<<whereverTheFormIsGoing>>", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
This is how I used this is as an example:
CAST(vAvgMaterialUnitCost.`avgUnitCost` AS DECIMAL(11,2)) * woMaterials.`qtyUsed` AS materialCost
It is pretty easy to add a collaborator to a free plan.
The added user should now be able to push to your repository on GitHub.
i think you should do:
var myInterval
on.onclick = function() {
myInterval=setInterval(fontChange, 500);
};
off.onclick = function() {
clearInterval(myInterval);
};
To enable GZIP compression, you need to modify the configuration of the embedded Tomcat instance. To do so, you declare a EmbeddedServletContainerCustomizer
bean in your Java configuration and then register a TomcatConnectorCustomizer
with it.
For example:
@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainerFactory factory) {
((TomcatEmbeddedServletContainerFactory) factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
httpProtocol.setCompression("on");
httpProtocol.setCompressionMinSize(64);
}
});
}
};
}
See the Tomcat documentation for more details on the various compression configuration options that are available.
You say that you want to selectively enable compression. Depending on your selection criteria, then the above approach may be sufficient. It enables you to control compression by the request's user-agent, the response's size, and the response's mime type.
If this doesn't meet your needs then I believe you will have to perform the compression in your controller and return a byte[] response with a gzip content-encoding header.
Using Array.from, Array.prototype.forEach(), and arrow functions:
Iterate over the keys:
Array.from(myMap.keys()).forEach(key => console.log(key));
Iterate over the values:
Array.from(myMap.values()).forEach(value => console.log(value));
Iterate over the entries:
Array.from(myMap.entries()).forEach(entry => console.log('Key: ' + entry[0] + ' Value: ' + entry[1]));
Yes. For that ensure that you declare the worksheet
For example
Previous Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet3")
Debug.Print ws.Cells(23, 4).Value
End Sub
New Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet4")
Debug.Print ws.Cells(23, 4).Value
End Sub
Here's how extend
/assign
works: For each property in source, copy its value as-is to destination. if property values themselves are objects, there is no recursive traversal of their properties. Entire object would be taken from source and set in to destination.
Here's how merge
works: For each property in source, check if that property is object itself. If it is then go down recursively and try to map child object properties from source to destination. So essentially we merge object hierarchy from source to destination. While for extend
/assign
, it's simple one level copy of properties from source to destination.
Here's simple JSBin that would make this crystal clear: http://jsbin.com/uXaqIMa/2/edit?js,console
Here's more elaborate version that includes array in the example as well: http://jsbin.com/uXaqIMa/1/edit?js,console
The length of an array in Java is immutable. So, you need to copy the desired part as a new array.
Use copyOfRange
method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
startIndex is the initial index of the range to be copied, inclusive.
endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)
E.g.:
//index 0 1 2 3 4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2); // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4); // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)
Just for information, the below
window.open("data:application/pdf," + encodeURI(pdfString));
does not work anymore in Chrome. Yesterday, I came across with the same issue and tried this solution, but did not work (it is 'Not allowed to navigate top frame to data URL'). You cannot open the data URL directly in a new window anymore. But, you can wrap it in iframe and make it open in a new window like below. =)
let pdfWindow = window.open("")
pdfWindow.document.write(
"<iframe width='100%' height='100%' src='data:application/pdf;base64, " +
encodeURI(yourDocumentBase64VarHere) + "'></iframe>"
)
<?php
header('Content-type: text/plain');
header('Content-Disposition: attachment;
filename="<name for the created file>"');
/*
assign file content to a PHP Variable $content
*/
echo $content;
?>
You can implement the "Comparable" interface on a class whose objects you want to compare.
And also implement the "compareTo" method in that.
Add the instances of the class in an ArrayList
Then the "java.utils.Collections.sort()" method will do the necessary magic.
Here's--->(https://deva-codes.herokuapp.com/CompareOnTwoKeys) a working example where objects are sorted based on two keys first by the id and then by name.
if you also want to compare the order of the answer you can extend the answer to something like this:
Array.prototype.compareTo = function (array2){
var array1 = this;
var difference = [];
$.grep(array2, function(el) {
if ($.inArray(el, array1) == -1) difference.push(el);
});
if( difference.length === 0 ){
var $i = 0;
while($i < array1.length){
if(array1[$i] !== array2[$i]){
return false;
}
$i++;
}
return true;
}
return false;
}
The error is due the fact that you are passing a wrong to strcat()
. Look at strcat()
's prototype:
char *strcat(char *dest, const char *src);
But you pass char
as the second argument, which is obviously wrong.
Use snprintf()
instead.
char str[1024] = "Hello World";
char tmp = '.';
size_t len = strlen(str);
snprintf(str + len, sizeof str - len, "%c", tmp);
As commented by OP:
That was just a example with Hello World to describe the Problem. It must be empty as first in my real program. Program will fill it later. The problem just contains to add a char/int to an char Array
In that case, snprintf()
can handle it easily to "append" integer types to a char buffer too. The advantage of snprintf()
is that it's more flexible to concatenate various types of data into a char buffer.
For example to concatenate a string, char and an int:
char str[1024];
ch tmp = '.';
int i = 5;
// Fill str here
snprintf(str + len, sizeof str - len, "%c%d", str, tmp, i);
Call Batch
file which will run Xcopy
for required files source to destination
call "$(SolutionDir)scripts\copyifnewer.bat"
val host = url.split("/")[2]
SELECT
t.*,
(SELECT COUNT(*) FROM city AS tt WHERE tt.name=t.name) AS count
FROM `city` AS t
WHERE
(SELECT count(*) FROM city AS tt WHERE tt.name=t.name) > 1 ORDER BY count DESC
Collections.reverse()
can do that job for you if you put your numbers in a List
of Integers
.
List<Integer> list = Arrays.asList(1, 4, 9, 16, 9, 7, 4, 9, 11);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);
Output:
[1, 4, 9, 16, 9, 7, 4, 9, 11]
[11, 9, 4, 7, 9, 16, 9, 4, 1]
I find until
very useful with sleep. example:
> time = Time.now
> sleep 2.seconds until Time.now > time + 10.seconds # breaks when true
# or something like
> sleep 1.seconds until !req.loading # suggested by ohsully
If you want to change inputs in an iframe then submit the form from that iframe, do this
...
var el = document.getElementById('targetFrame');
var doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below
if (frame_win) {
doc = (window.contentDocument || window.document);
}
if (doc) {
doc.forms[0].someInputName.value = someValue;
...
doc.forms[0].submit();
}
...
Normally, you can only do this if the page in the iframe is from the same origin, but you can start Chrome in a debug mode to disregard the same origin policy and test this on any page.
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
Instead of 1:nrow(mydata_2)
you can simply use the which()
function: which(mydata_2[,4] == 1578)
Although as it was pointed out above, the 3rd column contains 1578, not the fourth:
which(mydata_2[,3] == 1578)
You can improve the speed of your code if you restrict the items jQuery will look at.
Use the selector :input instead of * to achieve it.
$('#divId :input').serialize()
This will make your code faster because the list of items is shorter.
Use with:
{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}
It's because you're calling doGet()
without actually implementing doGet()
. It's the default implementation of doGet() that throws the error saying the method is not supported.
You do want to add App.config to your tests class library, if you're using a tracer/logger. Otherwise nothing gets logged when you run the test through a test runner such as TestDriven.Net.
For example, I use TraceSource
in my programs, but running tests doesn't log anything unless I add an App.config file with the trace/log configuration to the test class library too.
Otherwise, adding App.config to a class library doesn't do anything.
If you want find the source jar file for any of the artifact manually, go to maven repository location for the particular artifact and in Files click on 'view All'. You can find source jar file.
Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.
Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);
Here the reason to hitting an ClassCastException
is you can't treat an array of Integer
as an array of Object
. Integer[]
is a subtype of Object[]
but Object[]
is not a Integer[]
.
And the following also will not give an ClassCastException
.
Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;
This works for me:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Mobile
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// Wi-Fi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// And then use it like this:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
}
And add this permission:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
It looks like you have everything correct according to Laravel docs, but you have a typo
$item->push($product);
Should be
$items->push($product);
I also want to think the actual method you're looking for is put
$items->put('products', $product);
If you editing info.plist
directly, below should help you, don't key in "YES" as string below:
<key>UIFileSharingEnabled</key>
<string>YES</string>
You should use this:
<key>UIFileSharingEnabled</key>
<true/>
you can use ![ ](any link of image)
Also I would suggest to use https://stackedit.io/ for markdown formating and wring it is much easy than remembering all the markdown syntax
Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh
after the last command of st_new.sh
has finished.
Now there is a special command which messes this up: &
cmd &
means: "Start a new background process and execute cmd
in it. After starting the background process, immediately continue with the next command in the script."
That means &
doesn't wait for cmd
to do it's work. My guess is that st_new.sh
contains such a command. If that is the case, then you need to modify the script:
cmd &
BACK_PID=$!
This puts the process ID (PID) of the new background process in the variable BACK_PID
. You can then wait for it to end:
while kill -0 $BACK_PID ; do
echo "Process is still active..."
sleep 1
# You can add a timeout here if you want
done
or, if you don't want any special handling/output simply
wait $BACK_PID
Note that some programs automatically start a background process when you run them, even if you omit the &
. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's &
command instead to get the PID.
You can try below code :
Path.GetFileName(userpath)
Cannot agree more with the above comments. Above that, there are some more differences like
In Linear Regression, residuals are assumed to be normally distributed. In Logistic Regression, residuals need to be independent but not normally distributed.
Linear Regression assumes that a constant change in the value of the explanatory variable results in constant change in the response variable. This assumption does not hold if the value of the response variable represents a probability (in Logistic Regression)
GLM(Generalized linear models) does not assume a linear relationship between dependent and independent variables. However, it assumes a linear relationship between link function and independent variables in logit model.
Importing inside a function will effectively import the module once.. the first time the function is run.
It ought to import just as fast whether you import it at the top, or when the function is run. This isn't generally a good reason to import in a def. Pros? It won't be imported if the function isn't called.. This is actually a reasonable reason if your module only requires the user to have a certain module installed if they use specific functions of yours...
If that's not he reason you're doing this, it's almost certainly a yucky idea.
public class Organization {
@Id
@Column(name="org_id")
@GeneratedValue
private int id;
@Column(name="org_name")
private String name;
@Column(name="org_office_address1")
private String address1;
@Column(name="org_office_addres2")
private String address2;
@Column(name="city")
private String city;
@Column(name="state")
private String state;
@Column(name="country")
private String country;
@JsonIgnore
@OneToOne
@JoinColumn(name="pkg_id")
private int pkgId;
public int getPkgId() {
return pkgId;
}
public void setPkgId(int pkgId) {
this.pkgId = pkgId;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Column(name="pincode")
private String pincode;
@OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);
@Column(name="status")
private String status = "ACTIVE";
@Column(name="project_id")
private int redmineProjectId;
public int getRedmineProjectId() {
return redmineProjectId;
}
public void setRedmineProjectId(int redmineProjectId) {
this.redmineProjectId = redmineProjectId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Set<OrganizationBranch> getOrganizationBranch() {
return organizationBranch;
}
public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
this.organizationBranch = organizationBranch;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired
Example:
select Table_name as [Table] , column_name as [Column] , Table_catalog as [Database], table_schema as [Schema] from information_schema.columns
where table_schema = 'dbo'
order by Table_name,COLUMN_NAME
Just my code
This works
<a href="#" id="sampleApp" onclick="myFunction(); return false;">Click Here</a>
I just ran into this the other day.
What I did, which seems easier than the above, is to set the pattern on a variable on the scope and refer to it in ng-pattern in the view.
When "the checkbox is unchecked" I simply set the regex value to /.*/ on the onChanged callback (if going to unchecked). ng-pattern picks that change up and says "OK, your value is fine". Form is now valid. I would also remove the bad data from the field so you don't have an apparent bad phone # sitting there.
I had additional issues around ng-required, and did the same thing. Worked like a charm.
Your empList
is object type but you are trying to push strings
Try this
this.empList.push({this.name,this.empoloyeeID});
You can use the report process status ps
command:
ps ax | grep '[m]ysqld'
import com.google.common.base
if(!Strings.isNullOrEmpty(String str)) {
// Do your stuff here
}
I was to dumb to find the Solution...
For me (VB):
Dim string= Datagrid.SelectedCells(0).Item(0).ToString
public static Bitmap resizeBitmapByScale(
Bitmap bitmap, float scale, boolean recycle) {
int width = Math.round(bitmap.getWidth() * scale);
int height = Math.round(bitmap.getHeight() * scale);
if (width == bitmap.getWidth()
&& height == bitmap.getHeight()) return bitmap;
Bitmap target = Bitmap.createBitmap(width, height, getConfig(bitmap));
Canvas canvas = new Canvas(target);
canvas.scale(scale, scale);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
canvas.drawBitmap(bitmap, 0, 0, paint);
if (recycle) bitmap.recycle();
return target;
}
private static Bitmap.Config getConfig(Bitmap bitmap) {
Bitmap.Config config = bitmap.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
return config;
}
## Perfectly Working since Android 1.6 ##
getWindow().setFormat(PixelFormat.TRANSLUCENT);
VideoView videoHolder = new VideoView(this);
//if you want the controls to appear
videoHolder.setMediaController(new MediaController(this));
Uri video = getUriFromRawFile(context, R.raw.your_raw_file);
//if your file is named sherif.mp4 and placed in /raw
//use R.raw.sherif
videoHolder.setVideoURI(video);
setContentView(videoHolder);
videoHolder.start();
And then
public static Uri getUriFromRawFile(Context context, @ResRaw int rawResourceId) {
return Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(context.getPackageName())
.path(String.valueOf(rawResourceId))
.build();
}
it seems with XCode 9.2 the way to import .gpx has changed, I tried the ways described here and did not do. The only way worked for me was to drag and drop the file .gpx to the project navigator window on the left. Then I can choose the country in the simulator item.
Hope this helps to someone.
Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate
as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:
AudioServicesAddSystemSoundCompletion (
kSystemSoundID_Vibrate,
NULL,
NULL,
MyAudioServicesSystemSoundCompletionProc,
NULL
);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Then you define your callback function to replay the vibrate sound again:
#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
);
#pragma mark AudioService callback function implementation
// Callback that gets called after we finish buzzing, so we
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
) {
if (iShouldKeepBuzzing) { // Your logic here...
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
} else {
//Unregister, so we don't get called again...
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
}
Here is another way to find a nested property that doesn't require the string to tell you the nesting path. Credit to Ed S. for the single property method.
public static T FindNestedPropertyValue<T, N>(N model, string propName) {
T retVal = default(T);
bool found = false;
PropertyInfo[] properties = typeof(N).GetProperties();
foreach (PropertyInfo property in properties) {
var currentProperty = property.GetValue(model, null);
if (!found) {
try {
retVal = GetPropValue<T>(currentProperty, propName);
found = true;
} catch { }
}
}
if (!found) {
throw new Exception("Unable to find property: " + propName);
}
return retVal;
}
public static T GetPropValue<T>(object srcObject, string propName) {
return (T)srcObject.GetType().GetProperty(propName).GetValue(srcObject, null);
}
If you have a Red Hat server use yum. apt-get is only for Debian, Ubuntu and some other related linux.
Why would you want to use apt-get anyway? (It seems like you know what yum is.)
I use Apache common's DurationFormatUtils like so:
DurationFormatUtils.formatDuration(millis, "**H:mm:ss**", true);
The variable set by varStatus
is a LoopTagStatus
object, not an int. Use:
<div id="divIDNo${theCount.index}">
To clarify:
${theCount.index}
starts counting at 0
unless you've set the begin
attribute${theCount.count}
starts counting at 1
I think it is because %
has often be associated with the modulus operator in many programming languages.
It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).
If you have access to a compiler that supports variadic templates, you can use this:
#include <iostream>
#include <string>
#include <algorithm>
template<char ... CharacterList>
inline bool check_characters(char c) {
char match_characters[sizeof...(CharacterList)] = { CharacterList... };
for(int i = 0; i < sizeof...(CharacterList); ++i) {
if(c == match_characters[i]) {
return true;
}
}
return false;
}
template<char ... CharacterList>
inline void strip_characters(std::string & str) {
str.erase(std::remove_if(str.begin(), str.end(), &check_characters<CharacterList...>), str.end());
}
int main()
{
std::string str("(555) 555-5555");
strip_characters< '(',')','-' >(str);
std::cout << str << std::endl;
}
Since Java 8, we could use streams instead of for loops. Also, it might be apropriate to return an Optional if the enum does not have an instance with such a name.
I have come up with the following three alternatives on how to look up an enum:
private enum Test {
TEST1, TEST2;
public Test fromNameOrThrowException(String name) {
return Arrays.stream(values())
.filter(e -> e.name().equals(name))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No enum with name " + name));
}
public Test fromNameOrNull(String name) {
return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst().orElse(null);
}
public Optional<Test> fromName(String name) {
return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst();
}
}
Ideally it would return a success/fail response.
Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.
Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).
Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).
Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.
here is my implementation
public static byte[] intToByteArray(int a) {
return BigInteger.valueOf(a).toByteArray();
}
public static int byteArrayToInt(byte[] b) {
return new BigInteger(b).intValue();
}
I had issues like this especially when debugging actively through my phone; at times it took 27 minutes. I did the following things and take note of the explanation under each - one may work for you:
org.gradle.daemon=true
org.gradle.configureondemand=true
org.gradle.parallel=true
android.enableBuildCache=true
org.gradle.caching=true
org.gradle.jvmargs=-Xmx8000m -XX:MaxPermSize=5000m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
File -> Settings/Preferences -> Build, Execution, Deployment -> Gradle
Global Gradle Settings (at the bottom)
Mark the checkbox named: Offline Work.
File -> Settings/Preferences -> Build, Execution, Deployment -> Instant Run
Checked : Enable Instant Run to hot swap code...
Checked: restart activity on code changes ...
The move above was erratic also and therefore I sought to find out if the problem may be the processes/memory that ran directly on either my phone and computer. Here I freed up a little memory space in my phone and storage (which was at 98% utilized - down to 70%) and also on task manager (Windows), increased the priority of both Android Studio and Java.exe to High. Take this step cautiously; depends on your computer's memory.
After all this my build time while debugging actively on my phone at times went down to 1 ~ 2 minutes but at times spiked. I decided to do a hack which surprised me by taking it down to seconds best yet on the same project that gave me 22 - 27 minutes was 12 seconds!:
Connect phone for debugging then click RUN
After it starts, unplug the phone - the build should continue faster and raise an error at the end indicating this : Session 'app': Error Installing APKs
Reconnect back the phone and click on RUN again...
ALTERNATIVELY
If the script/function/method I'm debugging is purely JAVA, not JAVA-android e.g. testing an API with JSONArrays/JSONObjects, I test my java functions/methods on Netbeans which can compile a single file and show the output faster then make necessary changes on my Android Studio files. This also saves me a lot of time.
EDIT
I tried creating a new android project in local storage and copied all my files from the previous project into the new one - java, res, manifest, gradle app and gradle project (with latest gradle classpath dependency). And now I can build on my phone in less than 15 seconds.
I found two links of performance compare among several ways of converting string
to int
.
parseInt(str,10)
parseFloat(str)
str << 0
+str
str*1
str-0
Number(str)
All modules in Python have to have a certain directory structure. You can find details here.
Create an empty file called __init__.py
under the model
directory, such that your directory structure would look something like that:
.
+-- project
+-- src
+-- hello-world.py
+-- model
+-- __init__.py
+-- order.py
Also in your hello-world.py
file change the import statement to the following:
from model.order import SellOrder
That should fix it
P.S.: If you are placing your model
directory in some other location (not in the same directory branch), you will have to modify the python path using sys.path
.
@choz answer is the correct way. If you have many usages and want to make sure it works everywhere without changes you can add these small migration-snippet:
/* Migration jQuery from 1.8 to 3.x */
jQuery.fn.load = function (callback) {
var el = $(this);
el.on('load', callback);
return el;
};
In this case you got no erros on other nodes e.g. on $image
like in @Korsmakolnikov answer!
const $image = $('img.image').load(function() {
$(this).doSomething();
});
$image.doSomethingElseWithTheImage();
From my experience with GCC I know that static
and static inline
differs in a way how compiler issue warnings about unused functions. More precisely when you declare static
function and it isn't used in current translation unit then compiler produce warning about unused function, but you can inhibit that warning with changing it to static inline
.
Thus I tend to think that static
should be used in translation units and benefit from extra check compiler does to find unused functions. And static inline
should be used in header files to provide functions that can be in-lined (due to absence of external linkage) without issuing warnings.
Unfortunately I cannot find any evidence for that logic. Even from GCC documentation I wasn't able to conclude that inline
inhibits unused function warnings. I'd appreciate if someone will share links to description of that.
You can found more information on MSDN - facet of Entity Data Model. http://msdn.microsoft.com/en-us/library/ee382834.aspx Full recommended.
The Node REPL uses the underscore variable to hold the result of the last operation, so it conflicts with the Underscore library's use of the same variable. Try something like this:
Admin-MacBook-Pro:test admin$ node
> _und = require("./underscore-min")
{ [Function]
_: [Circular],
VERSION: '1.1.4',
forEach: [Function],
each: [Function],
map: [Function],
inject: [Function],
(...more functions...)
templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
template: [Function] }
> _und.max([1,2,3])
3
> _und.max([4,5,6])
6
My problem was having type="application/javascript"
on the <script>
tag for jQuery. IE8 does not like this! If your webpage is HTML5 you don't even need to declare the type, otherwise go with type="text/javascript"
instead.
I had a similar problem: I needed a Linux service and cgi plugin which use common constants to cooperate. The 'natural' way to do this is to place them in the init.py of the package, but I cannot start the cgi plugin with the -m parameter.
My final solution was similar to Solution #2 above:
import sys
import pathlib as p
import importlib
pp = p.Path(sys.argv[0])
pack = pp.resolve().parent
pkg = importlib.import_module('__init__', package=str(pack))
The disadvantage is that you must prefix the constants (or common functions) with pkg:
print(pkg.Glob)
According to the docs, you can just do:
select INDEX_NAME, TABLE_OWNER, TABLE_NAME, UNIQUENESS from USER_INDEXES
or
select INDEX_NAME, TABLE_OWNER, TABLE_NAME, UNIQUENESS from ALL_INDEXES
if you want all indexes...
Just pass the object as is. Note you can create the object as follows
var data0 = {numberId: "1", companyId : "531"};
$.ajax({
type: "POST",
url: "TelephoneNumbers.aspx/DeleteNumber",
data: dataO,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('In Ajax');
}
});
UPDATE seems an odd issue with the serializer, maybe it is expecting a string, out of interest can you try the following.
data: "{'numberId':'1', 'companyId ':'531'}",
You will have to save the relationship on the server side. The value is the only part that is transmitted when the form is posted. You could do something nasty like...
<option value="2|Dog">Dog</option>
Then split the result apart if you really wanted to, but that is an ugly hack and a waste of bandwidth assuming the numbers are truly unique and have a one to one relationship with the text.
The best way would be to create an array, and loop over the array to create the HTML. Once the form is posted you can use the value to look up the text in that same array.
What you need is look around assertion like .+? (?=abc)
.
See: Lookahead and Lookbehind Zero-Length Assertions
Be aware that [abc]
isn't the same as abc
. Inside brackets it's not a string - each character is just one of the possibilities. Outside the brackets it becomes the string.
Please try the following way.
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<td colspan="2">Sum: $180</td>
</tr>
</table>
I have researched this a little and from what I have found you have four options:
If you do not mind using the display:table-cell
on your parent div, you can use of the following options:
.area{
height: 100px;
width: 100px;
background: red;
margin:10px;
text-align: center;
display:table-cell;
vertical-align:middle;
}?
.area{
height: 100px;
width: 100px;
background: red;
margin:10px;
text-align: center;
display:block;
}
.content {
height: 100px;
width: 100px;
display:table-cell;
vertical-align:middle;
}?
.area{
background: red;
margin:10px;
text-align: center;
display:block;
float: left;
}
.content {
display:table-cell;
vertical-align:middle;
height: 100px;
width: 100px;
}?
The only problem that I have had with this version is that it seems you will have to create the css for every specific implementation. The reason for this is the content div needs to have the set height that your text will fill and the margin-top will be figured off of that. This issue can be seen in the demo. You can get it to work for every scenario manually by changing the height % of your content div and multiplying it by -.5 to get your margin-top value.
.area{
position:relative;
display:block;
height:100px;
width:100px;
border:1px solid black;
background:red;
margin:10px;
}
.content {
position:absolute;
top:50%;
height:50%;
width:100px;
margin-top:-25%;
text-align:center;
}?
If you feel guilty about faking the user-agent as Mozilla (comment in the top answer from Stefano), it could work with a non-urllib User-Agent as well. This worked for the sites I reference:
req = urlrequest.Request(link, headers={'User-Agent': 'XYZ/3.0'})
urlrequest.urlopen(req, timeout=10).read()
My application is to test validity by scraping specific links that I refer to, in my articles. Not a generic scraper.
A faster solution is provided by Kevin P. Rice here:https://stackoverflow.com/a/11595914/5535820 So here's the code:
function leapYear(year)
{
return (year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0);
}
$0 returns the most recently selected element or JavaScript object, $1 returns the second most recently selected one, and so on.
Refer : Command Line API Reference
In php.ini set :
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT
Note: if you upgrade from spring boot 1 to spring boot 2 there is a ResponseStatusException
which has a Http error code and a description.
So, you can effectively use generics they way it is intended.
The only case which is a bit challenging for me, is the response type for a status 204 (ok with no body). I tend to mark those methods as ResponseEntity<?>
, because ResponseEntity<Void>
is less predictive.
I find redo.el
extremly handy for doing "normal" undo/redo, and I usually bind it to C-S-z and undo to C-z, like this:
(when (require 'redo nil 'noerror)
(global-set-key (kbd "C-S-z") 'redo))
(global-set-key (kbd "C-z") 'undo)
Just download the file, put it in your lisp-path and paste the above in your .emacs
.
We can take a simple example.
Consider a table named TableA
with the following values:
id firstname lastname Mark
-------------------------------------------------------------------
1 arun prasanth 40
2 ann antony 45
3 sruthy abc 41
6 new abc 47
1 arun prasanth 45
1 arun prasanth 49
2 ann antony 49
GROUP BY
The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.
In more simple words GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;
We can apply GROUP BY
in our table:
select SUM(Mark)marksum,firstname from TableA
group by id,firstName
Results:
marksum firstname
----------------
94 ann
134 arun
47 new
41 sruthy
In our real table we have 7 rows and when we apply GROUP BY id
, the server group the results based on id
:
In simple words:
here
GROUP BY
normally reduces the number of rows returned by rolling them up and calculatingSum()
for each row.
PARTITION BY
Before going to PARTITION BY, let us look at the OVER
clause:
According to the MSDN definition:
OVER clause defines a window or user-specified set of rows within a query result set. A window function then computes a value for each row in the window. You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative aggregates, running totals, or a top N per group results.
PARTITION BY will not reduce the number of rows returned.
We can apply PARTITION BY in our example table:
SELECT SUM(Mark) OVER (PARTITION BY id) AS marksum, firstname FROM TableA
Result:
marksum firstname
-------------------
134 arun
134 arun
134 arun
94 ann
94 ann
41 sruthy
47 new
Look at the results - it will partition the rows and returns all rows, unlike GROUP BY.
If you do a
sudo yum list | grep python3
you will see that while they don't have a "python3" package, they do have a "python34" package, or a more recent release, such as "python36". Installing it is as easy as:
sudo yum install python34 python34-pip
.NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
.NET 4.0. TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still can opt in for TLS 1.2 even if your application framework doesn’t support it. The only problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so we’d have to use a numerical representation of this enum value:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
.NET 3.5 or below. TLS 1.2 is not supported. Upgrade your application to more recent version of the framework.
For anyone trying to
...in 2019, it's worth noting some of the code referenced here no longer exists (officially). Google discontinued support for the "MarkerWithLabel" project a long time ago. It was originally hosted on Google code here, now it's unofficially hosted on Github here.
But there is another project Google maintained until 2016, called "MapLabel"s. That approach is different (and arguably better). You create a separate map label object with the same origin as the marker instead of adding a mapLabel option to the marker itself. You can make a marker with label with multiple characters using js-marker-label.
Some people have commented about readability, saying "Oh it doesn't help readability that much, who cares?"
Suppose you need a check before the main code:
if precondition_fails(message): continue
''' main code here '''
Note you can do this after the main code was written without changing that code in anyway. If you diff the code, only the added line with "continue" will be highlighted since there are no spacing changes to the main code.
Imagine if you have to do a breakfix of production code, which turns out to simply be adding a line with continue. It's easy to see that's the only change when you review the code. If you start wrapping the main code in if/else, diff will highlight the newly indented code, unless you ignore spacing changes, which is dangerous particularly in Python. I think unless you've been in the situation where you have to roll out code on short notice, you might not fully appreciate this.
To edit Date in oracle you can try
select to_char(<columnName> + 5 / 24 + 30 / (24 * 60),
'DD/MM/RRRR hh:mi AM') AS <logicalName> from <tableName>
Other variation of Abhishek Bhalani
: You can use Array.map() instead of $.each()
var items = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist');
items.map( (item,i ) => {
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
$('<a class="ui-all">'+ i + ': ' + item.name + '<a/>')
.appendTo(li);
});
If you use echo inside an if with other commands, like "read", it might ignore the setting and it will jump to a new line anyway.
content=`wget -O - $url`
#include <unistd.h>
#include <termios.h>
char getch(void)
{
char buf = 0;
struct termios old = {0};
fflush(stdout);
if(tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if(tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if(read(0, &buf, 1) < 0)
perror("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if(tcsetattr(0, TCSADRAIN, &old) < 0)
perror("tcsetattr ~ICANON");
printf("%c\n", buf);
return buf;
}
Remove the last printf
if you don't want the character to be displayed.
Performance has already been mentioned in several answers as a differentiating factor, but to address the “How much slower is the ArrayList
?” and “Why is it slower overall ?”, have a look below.
Whenever value types are used as elements, performance drops dramatically with ArrayList
. Consider the case of simply adding elements. Due to the boxing going on - as ArrayList
’s Add only takes object
parameters - the Garbage Collector gets triggered into performing a lot more work than with List<T>
.
How much is the time difference ? At least several times slower than with List<T>
. Just take a look at what happens with code adding 10 mil int values to an ArrayList
vs List<T>
:
That’s a run time difference of 5x in the ‘Mean’ column, highlighted in yellow. Note also the difference in the number of garbage collections done for each, highlighted in red (no of GCs / 1000 runs).
Using a profiler to see what’s going on quickly shows that most of the time is spent doing GCs, as opposed to actually adding elements. The brown bars below represent blocking Garbage Collector activity:
I’ve written a detailed analysis of what goes on with the above ArrayList
scenario here https://mihai-albert.com/2019/12/15/boxing-performance-in-c-analysis-and-benchmark/.
Similar findings are in “CLR via C#” by Jeffrey Richter. From chapter 12 (Generics):
[…] When I compile and run a release build (with optimizations turned on) of this program on my computer, I get the following output.
00:00:01.6246959 (GCs= 6) List<Int32>
00:00:10.8555008 (GCs=390) ArrayList of Int32
00:00:02.5427847 (GCs= 4) List<String>
00:00:02.7944831 (GCs= 7) ArrayList of StringThe output here shows that using the generic List algorithm with the Int32 type is much faster than using the non-generic ArrayList algorithm with Int32. In fact, the difference is phenomenal: 1.6 seconds versus almost 11 seconds. That’s ~7 times faster! In addition, using a value type (Int32) with ArrayList causes a lot of boxing operations to occur, which results in 390 garbage collections. Meanwhile, the List algorithm required 6 garbage collections.
There is a concept of a working directory
.
This directory is represented by a .
(dot).
In relative paths, everything else is relative to it.
Simply put the .
(the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\
in your case.
So test\..\test.txt
means: the sub-directory test
in my working directory, then one level up, then the
file test.txt
. This is basically the same as just test.txt
.
For more details check here.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
If you are here because your project fails to build on a build server, but builds fine "manually" on a dev machine, and you are doing xcopy
only for debugging and to emulate a production environment on a dev machine, then you may want to look at this solution:
https://stackoverflow.com/a/1732478/2279059
You simply turn off post build events on the build server using
msbuild foo.sln /p:PostBuildEvent=
This is not good enough if you have other post build events that also need to run on the build server, and it is not a general solution. However, since there are so many different causes of this problem, there cannot be a general solution. One of the many answers to this question (and its duplicates) will probably help, but be careful with approaches that only somehow circumvent error handling (such as xcopy /C
). Those may work for you, particularly also in the build server scenario, but I think this one is more reliable, IF it can be used.
It has also been suggested that with newer versions of Visual Studio, the problem no longer exists, so if you are using an old version, consider updating your build tools.
OpenID and OAuth are each HTTP-based protocols for authentication and/or authorization. Both are intended to allow users to perform actions without giving authentication credentials or blanket permissions to clients or third parties. While they are similar, and there are proposed standards to use them both together, they are separate protocols.
OpenID is intended for federated authentication. A client accepts an identity assertion from any provider (although clients are free to whitelist or blacklist providers).
OAuth is intended for delegated authorization. A client registers with a provider, which provides authorization tokens which it will accept to perform actions on the user's behalf.
OAuth is currently better suited for authorization, because further interactions after authentication are built into the protocol, but both protocols are evolving. OpenID and its extensions could be used for authorization, and OAuth can be used for authentication, which can be thought of as a no-op authorization.
When you have JSON data then the following error appears
A better solution is to assign a var data
for the local json array object,
details see: https://datatables.net/manual/tech-notes/4
This is helps you to display table contents.
$(document).ready(function(){
$('#customer_table').DataTable( {
"aaData": data,
"aoColumns": [{
"mDataProp": "name_en"
}, {
"mDataProp": "phone"
}, {
"mDataProp": "email"
}, {
"mDataProp": "facebook"
}]
});
});
If you want a free simple location map showing a single marked location, for your website, Then
Let me know If this would help..
A working jQuery validate example:
$(function () {
$('input[type=file]').on('change', function() {
var $el = $(this);
var files = this.files;
var image = new Image();
image.onload = function() {
$el
.attr('data-upload-width', this.naturalWidth)
.attr('data-upload-height', this.naturalHeight);
}
image.src = URL.createObjectURL(files[0]);
});
jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
var params = {
imageminwidth: options.params.imageminwidth.split(',')
};
options.rules['imageminwidth'] = params;
if (options.message) {
options.messages['imageminwidth'] = options.message;
}
});
jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
var $el = $(element);
if(!element.files && element.files[0]) return true;
return parseInt($el.attr('data-upload-width')) >= parseInt(param["imageminwidth"][0]);
});
} (jQuery));
Put the value in the plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
The error was use:
<source>${java.version}</source>
<target>${java.version}</target>
If you are in a Linux container, such as on a Chromebook, you will need to manually browse to your localhost's address. I am aware the newer Chrome OS versions no longer have this problem, but on my Chromebook, I still had to manually browse to the localhost's address for your code to work.
To browse to your locahost's address, type this in command line: sudo ifconfig
and note the inet address under eth0.
Otherwise, as others have noted, simply type node.js filename and it will work as long as you point the browser to the proper address.
Hope this helps!
Uncommenting set bell-style none
in /etc/inputrc
and creating a .bash_profile
with setterm -blength 0
didn't stop vim from beeping.
What worked for me was creating a .vimrc
file in my home directory with set visualbell
.
Source: https://linuxconfig.org/turn-off-beep-bell-on-linux-terminal
Use USBDeview, from here, http://www.nirsoft.net/utils/usb_devices_view.html
Run as administrator.
Disconnect your phone.
Delete all the drivers associated with your phone. Some will say Android as well as the name and model of the phone.
Plug your phone back in so that Windows re-installs the drivers.
This worked for me, when the other solutions didn't.
After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).
A quick rerun of your data:
In [25]: df.hist(column='Trip_distance')
Prints out absolutely fine.
The df.hist
function comes with an optional keyword argument bins=10
which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:
In [34]: df.hist(column='Trip_distance', bins=50)
You must sort your data according your needs (es. in reverse order) and use select top query
Ok, so this piece of code should work for you. I changed the names to match your parameter.
inFile.seekg(0, ios::end);
if (inFile.tellg() == 0) {
// ...do something with empty file...
}
Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.
Here is an example :
function delsheets(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
for (pa=numbofsheet-1;pa>0;--pa){
ss.setActiveSheet(ss.getSheets()[pa]);
var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(200);// pause in the loop for 200 milliseconds
}
ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}
You can copy-paste data from en excel-sheet to an SQL-table by doing so:
Note: Often tables have a first column which is an ID-column with an auto generated/incremented ID. When you paste your data it will start inserting the leftmost selected column in Excel into the leftmost column in SSMS thus inserting data into the ID-column. To avoid that keep an empty column at the leftmost part of your selection in order to skip that column in SSMS. That will result in SSMS inserting the default data which is the auto generated ID.
Furthermore you can skip other columns by having empty columns at the same ordinal positions in the Excel sheet selection as those columns to be skipped. That will make SSMS insert the default value (or NULL where no default value is specified).
This should do it. You were missing a )
and you only need """
not 4 of them. Also you don't need a elif at the end.
ans=True
while ans:
print("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")
There are a few things you should check :
install.packages("thePackage")
(this only needs to be done once)require(thePackage)
or library(thePackage)
(this should be done every time you start a new R session)If you're not sure in which package that function is situated, you can do a few things.
help.search("some.function")
or ??some.function
to get an information box that can tell you in which package it is contained.find
and getAnywhere
can also be used to locate functions.findFn
in the sos
package as explained in this answer.RSiteSearch("some.function")
or searching with rdocumentation or rseek are alternative ways to find the function.Sometimes you need to use an older version of R, but run code created for a newer version. Newly added functions (eg hasName in R 3.4.0) won't be found then. If you use an older R version and want to use a newer function, you can use the package backports to make such functions available. You also find a list of functions that need to be backported on the git repo of backports. Keep in mind that R versions older than R3.0.0 are incompatible with packages built for R3.0.0 and later versions.
The above is fine (as I said in comment) unless your WSDL is accessible with https:// too.
Here is my workaround for this:
Set you SSLSocketFactory as default:
HttpsURLConnection.setDefaultSSLSocketFactory(...);
For Apache CXF which I use you need also add these lines to your config:
<http-conf:conduit name="*.http-conduit">
<http-conf:tlsClientParameters useHttpsURLConnectionDefaultSslSocketFactory="true" />
<http-conf:conduit>
A little bit of a more complete answer, inspired by the accepted answer:
$( '#form_id' ).submit( function( event ) {
event.preventDefault();
//validate fields
var fail = false;
var fail_log = '';
var name;
$( '#form_id' ).find( 'select, textarea, input' ).each(function(){
if( ! $( this ).prop( 'required' )){
} else {
if ( ! $( this ).val() ) {
fail = true;
name = $( this ).attr( 'name' );
fail_log += name + " is required \n";
}
}
});
//submit if fail never got set to true
if ( ! fail ) {
//process form here.
} else {
alert( fail_log );
}
});
In this case we loop all types of inputs and if they are required, we check if they have a value, and if not, a notice that they are required is added to the alert that will run.
Note that this, example assumes the form will be proceed inside the positive conditional via AJAX or similar. If you are submitting via traditional methods, move the second line, event.preventDefault();
to inside the negative conditional.
Equal height columns is the default behaviour for Bootstrap 4 grids.
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
<br>_x000D_
Line 2_x000D_
<br>_x000D_
Line 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
This one automatically excludes the trailing comma, unlike most of the other answers.
DECLARE @csv VARCHAR(1000)
SELECT @csv = COALESCE(@csv + ',', '') + ModuleValue
FROM Table_X
WHERE ModuleID = @ModuleID
(If the ModuleValue
column isn't already a string type then you might need to cast it to a VARCHAR
.)
In case you have only one controller and you want to access every action on root you can skip controller name like this
routes.MapRoute(
"Default",
"{action}/{id}",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
git checkout master
master is the tip, or the last commit. gitk will only show you up to where you are in the tree at the time. git reflog will show all the commits, but in this case, you just want the tip, so git checkout master.
I was able to test a private method inside using mockito using reflection. Here is the example, tried to name it such that it makes sense
//Service containing the mock method is injected with mockObjects
@InjectMocks
private ServiceContainingPrivateMethod serviceContainingPrivateMethod;
//Using reflection to change accessibility of the private method
Class<?>[] params = new Class<?>[]{PrivateMethodParameterOne.class, PrivateMethodParameterTwo.class};
Method m = serviceContainingPrivateMethod .getClass().getDeclaredMethod("privateMethod", params);
//making private method accessible
m.setAccessible(true);
assertNotNull(m.invoke(serviceContainingPrivateMethod, privateMethodParameterOne, privateMethodParameterTwo).equals(null));
It was easier to implement it only with one line of code:
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
What about something like this.
<div id="movie_item">
<div class="movie_item_poster">
<img src="..." style="max-width: 100%; max-height: 100%;">
</div>
<div id="movie_item_content">
<div class="movie_item_content_year">year</div>
<div class="movie_item_content_title">title</div>
<div class="movie_item_content_plot">plot</div>
</div>
<div class="movie_item_toolbar">
Lorem Ipsum...
</div>
</div>
You don't have to float both movie_item_poster
AND movie_item_content
. Just float one of them...
#movie_item {
position: relative;
margin-top: 10px;
height: 175px;
}
.movie_item_poster {
float: left;
height: 150px;
width: 100px;
}
.movie_item_content {
position: relative;
}
.movie_item_content_title {
}
.movie_item_content_year {
float: right;
}
.movie_item_content_plot {
}
.movie_item_toolbar {
clear: both;
vertical-align: bottom;
width: 100%;
height: 25px;
}
Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.
function doSomething(callback) {
// ...
// Call the callback
callback('stuff', 'goes', 'here');
}
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}
doSomething(foo);
That will call doSomething
, which will call foo
, which will alert "stuff goes here".
Note that it's very important to pass the function reference (foo
), rather than calling the function and passing its result (foo()
). In your question, you do it properly, but it's just worth pointing out because it's a common error.
Sometimes you want to call the callback so it sees a specific value for this
. You can easily do that with the JavaScript call
function:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.call(this);
}
function foo() {
alert(this.name);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Joe" via `foo`
You can also pass arguments:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
// Call our callback, but using our own instance as the context
callback.call(this, salutation);
}
function foo(salutation) {
alert(salutation + " " + this.name);
}
var t = new Thing('Joe');
t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`
Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. You can use apply
to do that:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.apply(this, ['Hi', 3, 2, 1]);
}
function foo(salutation, three, two, one) {
alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Hi Joe - 3 2 1" via `foo`
.NET does this for you. In your AssemblyInfo.cs file, set your assembly version to major.minor.* (for example: 1.0.*).
When you build your project the version is auto generated.
The build and revision numbers are generated based on the date, using the unix epoch, I believe. The build is based on the current day, and the revision is based on the number of seconds since midnight.