You are binding properties to nothing. :required
in
<select class="form-control" v-model="selected" :required @change="changeLocation">
and :selected
in
<option :selected>Choose Province</option>
If you set the code like so, your errors should be gone:
<template>
<select class="form-control" v-model="selected" :required @change="changeLocation">
<option>Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
you would now need to have a data
property called selected
so that v-model works. So,
{
data () {
return {
selected: "Choose Province"
}
}
}
If that seems like too much work, you can also do it like:
<template>
<select class="form-control" :required="true" @change="changeLocation">
<option :selected="true">Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
You can use the v-model
approach if your default value depends on some data property.
You can go for the second method if your default selected value happens to be the first option
.
You can also handle it programmatically by doing so:
<select class="form-control" :required="true">
<option
v-for="option in options"
v-bind:value="option.id"
:selected="option == '<the default value you want>'"
>{{ option }}</option>
</select>
sudo update-alternatives --config php
sudo update-alternatives --config phar
sudo update-alternatives --config phar.phar
Default PHP 5.6 is set on your system and you need to switch to PHP 7.1.
Apache:
$ sudo a2dismod php5.6
$ sudo a2enmod php7.1
$ sudo service apache2 restart
Command Line:
$ sudo update-alternatives --set php /usr/bin/php7.1
$ sudo update-alternatives --set phar /usr/bin/phar7.1
$ sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.1
Default PHP 7.1 is set on your system and you need to switch to PHP 5.6.
Apache:
$ sudo a2dismod php7.1
$ sudo a2enmod php5.6
$ sudo service apache2 restart
Command Line:
$ sudo update-alternatives --set php /usr/bin/php5.6
The difference is subtle.
In JavaScript an undefined
variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a;
for instance, then a
will be undefined
, because it was never assigned any value.
But if you then assign a = null;
then a
will now be null
. In JavaScript null
is an object (try typeof null
in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined
is a value).
Example:
var a;
typeof a; # => "undefined"
a = null;
typeof null; # => "object"
This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:
function doSomething(first, second, optional) {
if (typeof optional === "undefined") {
optional = "three";
}
// do something
}
If you omit the optional
parameter doSomething(1, 2) then
optional will be the "three"
string but if you pass doSomething(1, 2, null)
then optional will be null
.
As for the equal ==
and strictly equal ===
comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0"
will return true; while 0 === "0"
will return false, because a number is not a string.
You may use those operators to check between undefined
an null
. For example:
null === null # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true
The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:
function test(val) {
return val == null;
}
test(null); # => true
test(undefined); # => true
export VAR=value
will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR='my val'
. If you want the variable to be interpolated, use double quotes, like export VAR="$MY_OTHER_VAR"
.
Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).
Without using a visual selection, gU<motion>
will make the characters in motion
uppercase, or use gu<motion>
for lowercase.
For more of these, see Section 3 in Vim's change.txt help file.
remove partition by
and add group by
clause,
SELECT BrandId
,SUM(ICount) totalSum
FROM Table
WHERE DateId = 20130618
GROUP BY BrandId
Try this Macro. Anywhere you want the "true" or false to show up just replace it with PRINTBOOL(var) where var is the bool you want the text for.
#define PRINTBOOL(x) x?"true":"false"
#id {
position: relative;
opacity: 0.99;
}
#id::before {
content: "";
position: absolute;
width: 100%;
height: 100%;
z-index: -1;
background: url('image.png');
opacity: 0.3;
}
Hack with opacity 0.99 (less than 1) creates z-index context so you can not worry about global z-index values. (Try to remove it and see what happens in the next demo where parent wrapper has positive z-index.)
If your element already has z-index, then you don't need this hack.
Demo.
Most possible cause of such issues can be some invisible view is on the top of view being clicked, which prevents the click event to trigger. So recheck your xml layout properly before searching anything vigorously online.
PS :- In my case, a recyclerView was totally covering the layout and hence clicking on imageView was restricted.
If you are running Windows 7 onward, you can try the new 'robocopy' command:
robocopy "$(SolutionDir)Solution Items\References\*.dll" "$(TargetDir)"
More information about robocopy can be found here.
I ran into a similar situation with code that WAS working , then was not.
Turned while dragging / dropping code within a file, I moved an object into another set of braces. Took longer to figure out than I care to admit.
Bit once I move the code back into its proper place, the error resolved.
Here is the typical structure of new Codeigniter project:
- application/
- system/
- user_guide/
- index.php <- this is the file you need to change
I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.
With this code you can deploy your site to your production server without changing index.php each time.
// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
if (defined('ENVIRONMENT')) {
switch (ENVIRONMENT) {
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
ini_set('display_errors', 0);
break;
default:
exit('The application environment is not set correctly.');
}
}
You can declare array as readonly
, but keep in mind that you can change element of readonly
array.
public readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
...
Titles[0] = "bla";
Consider using enum, as Cody suggested, or IList.
public readonly IList<string> ITitles = new List<string> {"German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();
If you guys are having this problem in sails.js just set your cors.js to include Authorization as the allowed header
/***************************************************************************_x000D_
* *_x000D_
* Which headers should be allowed for CORS requests? This is only used in *_x000D_
* response to preflight requests. *_x000D_
* *_x000D_
***************************************************************************/_x000D_
_x000D_
headers: 'Authorization' // this line here
_x000D_
This answer will do what you need, although usually you don't add specific usernames to sudoers
. Instead, you have a group of sudoers and just add your user to that group when needed. This way you don't need to use visudo
more than once when giving sudo
permission to users.
If you're on Ubuntu, the group is most probably already set up and called admin
:
$ sudo cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
...
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
# See sudoers(5) for more information on "#include" directives:
#includedir /etc/sudoers.d
On other distributions, like Arch and some others, it's usually called wheel
and you may need to set it up: Arch Wiki
To give users in the wheel group full root privileges when they precede a command with "sudo", uncomment the following line: %wheel ALL=(ALL) ALL
Also note that on most systems visudo
will read the EDITOR
environment variable or default to using vi
. So you can try to do EDITOR=vim visudo
to use vim
as the editor.
To add a user to the group you should run (as root):
# usermod -a -G groupname username
where groupname
is your group (say, admin
or wheel
) and username
is the username (say, john
).
The answer to my comment above on the Original Question makes me think this is all he wants:
loopnum = 0
word = 'afrykanerskojezyczny'
wordlist = ['afrykanerskojezycznym','afrykanerskojezyczni','nieafrykanerskojezyczni']
for i in wordlist:
wordlist[loopnum] = word
loopnum += 1
This will do the following:
For every value in wordlist, set that value of the wordlist to the origional code.
All you have to do is put this piece of code where you need to change wordlist, making sure you store the words you need to change in wordlist, and that the original word is correct.
Hope this helps!
Adding this maven dependency with JUnit Jupiter (v.5.5.1) solves the issue.
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
You can also do
console.log("a = %o, b = %o", a, b);
where a and b are objects.
React Router v4 and React Router v5, generic
React Router v4 does not parse the query for you any more, but you can only access it via this.props.location.search
(or useLocation, see below). For reasons see nbeuchat's answer.
E.g. with qs library imported as qs
you could do
qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key
Another library would be query-string. See this answer for some more ideas on parsing the search string. If you do not need IE-compatibility you can also use
new URLSearchParams(this.props.location.search).get("__firebase_request_key")
For functional components you would replace this.props.location
with the hook useLocation. Note, you could use window.location.search
, but this won't allow to trigger React rendering on changes.
If your (non-functional) component is not a direct child of a Switch
you need to use withRouter to access any of the router provided props.
React Router v3
React Router already parses the location for you and passes it to your RouteComponent as props. You can access the query (after ? in the url) part via
this.props.location.query.__firebase_request_key
If you are looking for the path parameter values, separated with a colon (:) inside the router, these are accessible via
this.props.match.params.redirectParam
This applies to late React Router v3 versions (not sure which). Older router versions were reported to use this.props.params.redirectParam
.
General
nizam.sp's suggestion to do
console.log(this.props)
will be helpful in any case.
Not for entire application or particular class.
CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture
at all.
Sample code to change cultures for current thread:
CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:
(3.3).ToString(new CultureInfo("fr-FR"))
Rather than breaking half-way through, you should simply shorten your loop.
size_t length = strlen(str);
size_t i;
for (i = 0; i < (length / 2); i++)
{
char temp = str[length - i - 1];
str[length - i - 1] = str[i];
str[i] = temp;
}
data = [4, 5, 6] # Your global variable
def print_data(data): # <-- Pass in a parameter called "data"
print data # <-- Note: You can access global variable inside your function, BUT for now, which is which? the parameter or the global variable? Confused, huh?
print_data(data)
This is roughly how I'd do it: the line is created by setting a border-bottom
on the containing h2
then giving the h2
a smaller line-height
. The text is then put in a nested span
with a non-transparent background.
h2 {_x000D_
width: 100%; _x000D_
text-align: center; _x000D_
border-bottom: 1px solid #000; _x000D_
line-height: 0.1em;_x000D_
margin: 10px 0 20px; _x000D_
} _x000D_
_x000D_
h2 span { _x000D_
background:#fff; _x000D_
padding:0 10px; _x000D_
}
_x000D_
<h2><span>THIS IS A TEST</span></h2>_x000D_
<p>this is some content other</p>
_x000D_
I tested in Chrome only, but there's no reason it shouldn't work in other browsers.
JSFiddle: http://jsfiddle.net/7jGHS/
Most of simple problems get complicated because simple functionality like order() in R that gives a statistical result in both and descending order is missing in various python libraries. But if we devise our thinking that all such statistical ordering and parameters in python are easily found in pandas, we can can result sooner than looking in 100 different places. Also, development of R and pandas go hand-in-hand because they were created for same purpose. To solve this problem I use following code that gets me by anywhere:
unique, counts = np.unique(x, return_counts=True)
d = {'unique':unique, 'counts':count} # pass the list to a dictionary
df = pd.DataFrame(d) #dictionary object can be easily passed to make a dataframe
df.sort_values(by = 'count', ascending=False, inplace = True)
df = df.reset_index(drop=True) #optional only if you want to use it further
Finally I found answer myself. To add new icons in 2.3.2 bootstrap we have to add Font Awsome css in you file. After doing this we can override the styles with css to change the color and size.
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
CSS
.brown{color:#9b846b}
If we want change the color of icon then just add brown class and icon will turn in brown color. It also provide icon of various size.
HTML
<p><i class="icon-camera-retro icon-large brown"></i> icon-camera-retro</p> <!--brown class added-->
<p><i class="icon-camera-retro icon-2x"></i> icon-camera-retro</p>
<p><i class="icon-camera-retro icon-3x"></i> icon-camera-retro</p>
<p><i class="icon-camera-retro icon-4x"></i> icon-camera-retro</p>
Or rather than to declare a function, simply:
setTimeout(() => {
console.log('hello');
}, 1000);
The clean
, install
and deploy
phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.
mvn clean install
This command invokes the clean
phase and then the install
phase sequentially:
clean
: removes files generated at build-time in a project's directory (target
by default)install
: installs the package into the local repository, for use as a dependency in other projects locally.mvn deploy
This command invokes the deploy
phase:
deploy
: copies the final package to the remote repository for sharing with other developers and projects.mvn release
This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare
and perform
. As documented:
Preparing a release goes through the following release phases:
- Check that there are no uncommitted changes in the sources
- Check that there are no SNAPSHOT dependencies
- Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
- Transform the SCM information in the POM to include the final destination of the tag
- Run the project tests against the modified POMs to confirm everything is in working order
- Commit the modified POMs
- Tag the code in the SCM with a version name (this will be prompted for)
- Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
- Commit the modified POMs
And then:
Performing a release runs the following release phases:
- Checkout from an SCM URL with optional tag
- Run the predefined Maven goals to release the project (by default, deploy site-deploy)
Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter
statement exactly the way you originally had it works perfectly:
ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);
You only need to add parenthesis if you need to alter more than one column at once, such as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));
Make sure that there are no typos in your .env file. This was the cause of a blank screen with me.
Nothing got logged to screen nor logfiles or nginx logs. Just a blank screen.
I have no idea how it can work automatically, but you can copy "], " together with new line and then use replace function.
Try this
$("body").css({"background-color":"blue"});
if(!my_string){
// stuff
}
and
if(my_string !== "")
if you want to accept null but reject empty
EDIT: woops, forgot your condition is if it IS empty
I experienced the same problem on my repository. I'm the master of the repository, but I had such an error.
I've unprotected my project and then re-protected again, and the error is gone.
We had upgraded the gitlab version between my previous push and the problematic one. I suppose that this upgrade has created the bug.
Here's a version closely resembling Apache's StringUtils version:
public int indexOfIgnoreCase(String str, String searchStr) {
return indexOfIgnoreCase(str, searchStr, 0);
}
public int indexOfIgnoreCase(String str, String searchStr, int fromIndex) {
// https://stackoverflow.com/questions/14018478/string-contains-ignore-case/14018511
if(str == null || searchStr == null) return -1;
if (searchStr.length() == 0) return fromIndex; // empty string found; use same behavior as Apache StringUtils
final int endLimit = str.length() - searchStr.length() + 1;
for (int i = fromIndex; i < endLimit; i++) {
if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) return i;
}
return -1;
}
Best solution is to use
DELETE FROM table WHERE id NOT IN ( 2 )
From http://ora-01438.ora-code.com/ (the definitive resource outside of Oracle Support):
ORA-01438: value larger than specified precision allowed for this column
Cause: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.
Action: Enter a value that complies with the numeric column's precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.
http://ora-06512.ora-code.com/:
ORA-06512: at stringline string
Cause: Backtrace message as the stack is unwound by unhandled exceptions.
Action: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.
You could try this. It doesn't read all of f into memory at once (using the file object's iterator) and it closes the file when the code leaves the with block.
if data.find('!masters') != -1:
with open('masters.txt', 'r') as f:
for line in f:
print line
sck.send('PRIVMSG ' + chan + " " + line + '\r\n')
If you're using an older version of python (pre 2.6) you'll have to have
from __future__ import with_statement
There are two solutions for it.
Solution number one: 1.Recreate the project. While creating a project ensure that precompiled header is checked(Application settings... *** Do not check empty project)
Solution Number two: 1.Create stdafx.h and stdafx.cpp in your project 2 Right click on project -> properties -> C/C++ -> Precompiled Headers 3.select precompiled header to create(/Yc) 4.Rebuild the solution
Drop me a message if you encounter any issue.
You have written like
@Html.RadioButtonFor(model => model.gender, "Male", new { @checked = true }) and
@Html.RadioButtonFor(model => model.gender, "Female", new { @checked = true })
Here you have taken gender as a Enum
type and you have written the value for the radio button as a string
type- change "Male" to 0 and "Female" to 1.
It worked for me, In eclipse: Window > Preference > Team > SVN: select SVNKit (Pure Java) instead JavaHL(JNI)
To do this, you can use Microsoft's more advanced command-line shell called "Windows PowerShell." It should come standard on the latest versions of Windows, but you can download it from Microsoft if you don't already have it installed.
To get the last five lines in the text file simply read the file using Get-Content
, then have Select-Object
pick out the last five items/lines for you:
Get-Content c:\scripts\test.txt | Select-Object -last 5
Source: Using the Get-Content Cmdlet
This is "By Design". The parseFloat
function will only consider the parts of the string up until in reaches a non +, -, number, exponent or decimal point. Once it sees the comma it stops looking and only considers the "75" portion.
To fix this convert the commas to decimal points.
var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 = ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()
Well Lorenz Lo Sauer already have a good question for this. but if you want to resolve this problem through the Pycharm Tuning (without turning off Pycharm code inspection). you can tuning the heap size as you need. since I prefer to use increasing Heap Size solution for slow running Pycharm Application.
You can tune up Heap Size by editing pycharm.exe.vmoptions file. and pycharm64.exe.vmoptions for 64bit application. and then edit -Xmx and -Xms value on it.
So I allocate 2048m for xmx and xms value (which is 2GB) for my Pycharm Heap Size. Here it is My Configuration. I have 8GB memory so I had set it up with this setting:
-server
-Xms2048m
-Xmx2048m
-XX:MaxPermSize=2048m
-XX:ReservedCodeCacheSize=2048m
save the setting, and restart IDE. And I enable "Show memory indicator" in settings->Appearance & Behavior->Appearance. to see it in action :
and Pycharm is quick and running fine now.
Reference : https://www.jetbrains.com/help/pycharm/2017.1/tuning-pycharm.html#d176794e266
I think the following helper method could also solve the problem.
private TResult InvokeAsyncFuncSynchronously<TResult>(Func< Task<TResult>> func)
{
TResult result = default(TResult);
var autoResetEvent = new AutoResetEvent(false);
Task.Run(async () =>
{
try
{
result = await func();
}
catch (Exception exc)
{
mErrorLogger.LogError(exc.ToString());
}
finally
{
autoResetEvent.Set();
}
});
autoResetEvent.WaitOne();
return result;
}
Can be used the following way:
InvokeAsyncFuncSynchronously(Service.GetCustomersAsync);
Since you tagged the question with javascript
and html
...
For a purely HTML solution, you can use a meta
tag in the header
to "refresh" the page, specifying a different URL:
<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">
If you can/want to use JavaScript, you can set the location.href
of the window
:
<script type="text/javascript">
window.location.href = "http://www.yourdomain.com/somepage.html";
</script>
For others come to here:
If you happen to put your docker command in a file, say run.sh
, check your line separator. In Linux, it should be LR
, otherwise you would get the same error.
EXPECTED for 302: redirect uses same request method POST on NEW_URL
CLIENT POST OLD_URL -> SERVER 302 NEW_URL -> CLIENT POST NEW_URL
ACTUAL for 302, 303: redirect changes request method from POST to GET on NEW_URL
CLIENT POST OLD_URL -> SERVER 302 NEW_URL -> CLIENT GET NEW_URL (redirect uses GET)
CLIENT POST OLD_URL -> SERVER 303 NEW_URL -> CLIENT GET NEW_URL (redirect uses GET)
ACTUAL for 307: redirect uses same request method POST on NEW_URL
CLIENT POST OLD_URL -> SERVER 307 NEW_URL -> CLIENT POST NEW_URL
You can also try this which lists the commits that has changed a specific part of a file (Implemented in Git 1.8.4).
Result returned would be the list of commits that modified this particular part. Command :
git log --pretty=short -u -L <upperLimit>,<lowerLimit>:<path_to_filename>
where upperLimit is the start_line_number and lowerLimit is the ending_line_number of the file.
More details at https://www.techpurohit.com/list-some-useful-git-commands
I had the same problem and the best solution I found is to first create the table defining primary key and then to use insert into statement.
CREATE TABLE mytable (
field1 INTEGER PRIMARY KEY,
field2 TEXT
);
INSERT INTO mytable
SELECT field1, field2
FROM anothertable;
Convert the array into a hash. Then look for the key.
array = ['a', 'b', 'c']
hash = Hash[array.map.with_index.to_a] # => {"a"=>0, "b"=>1, "c"=>2}
hash['b'] # => 1
select *
into #TempTable
from SomeTale
select *
from #TempTable
Have you tried the following:
SELECT ID, COUNT(*), max(date)
FROM table
GROUP BY ID;
There are multiple ways to do so, but Oracle and IBM say that using +
, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder
or StringBuffer
is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer
.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
You can have as many branches you want, just as a regular git repository, but according to heroku docs, any branch other than master
will be ignored.
http://devcenter.heroku.com/articles/git
Branches pushed to Heroku other than master will be ignored. If you’re working out of another branch locally, you can either merge to master before pushing, or specify that you want to push your local branch to a remote master.
This means that you can push anything you want, but you app at heroku will always point to the master branch.
But, if you question regards how to create branches and to work with git you should check this other question
The solution with the /etc/docker/daemon.json
file didn't work for me on Ubuntu.
I was able to configure Docker insecure registries on Ubuntu by providing command line options to the Docker daemon in /etc/default/docker
file, e.g.:
# /etc/default/docker
DOCKER_OPTS="--insecure-registry=a.example.com --insecure-registry=b.example.com"
The same way can be used to configure custom directory for docker images and volumes storage, default DNS servers, etc..
Now, after the Docker daemon has restarted (after executing sudo service docker restart
), running docker info
will show:
Insecure Registries:
a.example.com
b.example.com
127.0.0.0/8
Firstly, in a development mode, you should use JDK instead of the JRE. Secondly, the JAVA_HOME is where you install Java and where all the others frameworks will search for what they need (JRE,javac,...)
So if you set
JAVA_HOME=/usr/lib/jvm/java-7-oracle/jre/bin/java
when you run a "mvn" command, Maven will try to access to the java by adding /bin/java, thinking that the JAVA_HOME is in the root directory of Java installation.
But setting
JAVA_HOME=/usr/lib/jvm/java-7-oracle/
Maven will access add bin/java then it will work just fine.
Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:
s == 'True'
Or to checks against a whole bunch of values:
s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
Be cautious when using the following:
>>> bool("foo")
True
>>> bool("")
False
Empty strings evaluate to False
, but everything else evaluates to True
. So this should not be used for any kind of parsing purposes.
Getter and setter are sometimes too heavy to implement just to observe proper value changes. Usually this needs extra temporary variable handling and extra checks, and you will want to avoid even those tiny labour if you write hundreds of getters and setters. These stuffs are for the situation.
private void cbShowHide_CheckedChanged(object sender, EventArgs e)
{
if (cbShowHide.Checked)
{
txtPin.UseSystemPasswordChar = PasswordPropertyTextAttribute.No.Password;
}
else
{
//Hides Textbox password
txtPin.UseSystemPasswordChar = PasswordPropertyTextAttribute.Yes.Password;
}
}
Copy this code to show and hide your textbox using a checkbox
<script type="text/javascript" runat="server">
public void Page_Load(object Sender, System.EventArgs e)
{
double rad=0.0;
TextBox1.Attributes.Add("Visible", "False");
if (TextBox1.Text != "")
rad = Convert.ToDouble(TextBox1.Text);
Button1.Attributes.Add("OnClick","alert("+ rad +")");
}
</script>
<asp:Button ID="Button1" runat="server" Text="Diameter"
style="z-index: 1; left: 133px; top: 181px; position: absolute" />
<asp:TextBox ID="TextBox1" Visible="True" Text="" runat="server"
AutoPostBack="true"
style="z-index: 1; left: 134px; top: 133px; position: absolute" ></asp:TextBox>
use the help of this, hope it will be usefull
I use block-mode visual selection:
I
(Shift + I) to enter insert mode.This is not a uni-tasker. It works:
c
instead of I
).The Python standard library comes with an e-mail parsing function: email.utils.parseaddr()
.
It returns a two-tuple containing the real name and the actual address parts of the e-mail:
>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')
>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')
>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')
And if the parsing is unsuccessful, it returns a two-tuple of empty strings:
>>> parseaddr('[invalid!email]')
('', '')
An issue with this parser is that it's accepting of anything that is considered as a valid e-mail address for RFC-822 and friends, including many things that are clearly not addressable on the wide Internet:
>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')
>>> parseaddr('invalid-email')
('', 'invalid-email')
So, as @TokenMacGuy put it, the only definitive way of checking an e-mail address is to send an e-mail to the expected address and wait for the user to act on the information inside the message.
However, you might want to check for, at least, the presence of an @-sign on the second tuple element, as @bvukelic suggests:
>>> '@' in parseaddr("invalid-email")[1]
False
If you want to go a step further, you can install the dnspython project and resolve the mail servers for the e-mail domain (the part after the '@'), only trying to send an e-mail if there are actual MX
servers:
>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
[...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
[...]
dns.resolver.NXDOMAIN
You can catch both NoAnswer
and NXDOMAIN
by catching dns.exception.DNSException
.
And Yes, foo@[email protected]
is a syntactically valid address. Only the last @
should be considered for detecting where the domain part starts.
Wikipedia tells what comma operator does:
"In the C and C++ programming languages, the comma operator (represented by the token ,
) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type)."
The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.
On my machine in a repo I regularly use it looks like this:
KidA% cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
autocflg = true
[remote "origin"]
url = ssh://localhost:8888/opt/local/var/git/project.git
#url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git
fetch = +refs/heads/*:refs/remotes/origin/*
The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.
This is the file that is getting manipulated under-the-hood when you run something like git remote rm
or git remote add
but in this case since its only a typo you made it might make sense to correct it this way.
1) For me that's the most simple way passing parameters to async task is like this
// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);
Declare and use the async task like here
private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean...pParams)
{
Boolean param1, param2, param3;
//
param1=pParams[0];
param2=pParams[1];
param3=pParams[2];
....
}
2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.
/* Generic Async Task */
interface MyGenericMethod {
int execute(String param);
}
protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
public String mParam; // member variable to parameterize the function
@Override
protected Void doInBackground(MyGenericMethod... params) {
// do something here
params[0].execute("Myparameter");
return null;
}
}
// to start the asynctask do something like that
public void startAsyncTask()
{
//
AsyncTask<MyGenericMethod, Void, Void> mytest = new testtask().execute(new MyGenericMethod() {
public int execute(String param) {
//body
return 1;
}
});
}
I know the question is for a pandas
df but in the case the shuffle occurs by row (column order changed, row order unchanged), then the columns names do not matter anymore and it could be interesting to use an np.array
instead, then np.apply_along_axis()
will be what you are looking for.
If that is acceptable then this would be helpful, note it is easy to switch the axis along which the data is shuffled.
If you panda data frame is named df
, maybe you can:
values = df.values
, np.array
from values
np.array
by row or columnnp.array
a = np.array([[10, 11, 12], [20, 21, 22], [30, 31, 32],[40, 41, 42]])
print(a)
[[10 11 12]
[20 21 22]
[30 31 32]
[40 41 42]]
print(np.apply_along_axis(np.random.permutation, 1, a))
[[11 12 10]
[22 21 20]
[31 30 32]
[40 41 42]]
print(np.apply_along_axis(np.random.permutation, 0, a))
[[40 41 32]
[20 31 42]
[10 11 12]
[30 21 22]]
print(a)
[[10 11 12]
[20 21 22]
[30 31 32]
[40 41 42]]
This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.
Use CSS, it makes for much easier management of the style itself.
Only change the line str1:=''; to str1:=' ';
Matplotlib does this by default.
E.g.:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()
And, as you may already know, you can easily add a legend:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')
plt.show()
If you want to control the colors that will be cycled through:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])
plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')
plt.show()
If you're unfamiliar with matplotlib, the tutorial is a good place to start.
Edit:
First off, if you have a lot (>5) of things you want to plot on one figure, either:
Otherwise, you're going to wind up with a very messy plot! Be nice to who ever is going to read whatever you're doing and don't try to cram 15 different things onto one figure!!
Beyond that, many people are colorblind to varying degrees, and distinguishing between numerous subtly different colors is difficult for more people than you may realize.
That having been said, if you really want to put 20 lines on one axis with 20 relatively distinct colors, here's one way to do it:
import matplotlib.pyplot as plt
import numpy as np
num_plots = 20
# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))
# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
plt.plot(x, i * x + 5 * i)
labels.append(r'$y = %ix + %i$' % (i, 5*i))
# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center',
bbox_to_anchor=[0.5, 1.1],
columnspacing=1.0, labelspacing=0.0,
handletextpad=0.0, handlelength=1.5,
fancybox=True, shadow=True)
plt.show()
By deleting all emulator, sometime memory will not be reduce to our expectation. So open below mention path in you c drive
C:\Users{Username}.android\avd
In this avd folder, you can able to see all the avd's which you created earlier. So you need to delete all avd's that will remove all the unused spaces grab by your emulator's. Than create the fresh emulator for you works.
1) The most simple way would be using WMPLib
WMPLib.WindowsMediaPlayer Player;
private void PlayFile(String url)
{
Player = new WMPLib.WindowsMediaPlayer();
Player.PlayStateChange += Player_PlayStateChange;
Player.URL = url;
Player.controls.play();
}
private void Player_PlayStateChange(int NewState)
{
if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
{
//Actions on stop
}
}
2) Alternatively you can use the open source library NAudio. It can play mp3 files using different methods and actually offers much more than just playing a file.
This is as simple as
using NAudio;
using NAudio.Wave;
IWavePlayer waveOutDevice = new WaveOut();
AudioFileReader audioFileReader = new AudioFileReader("Hadouken! - Ugly.mp3");
waveOutDevice.Init(audioFileReader);
waveOutDevice.Play();
Don't forget to dispose after the stop
waveOutDevice.Stop();
audioFileReader.Dispose();
waveOutDevice.Dispose();
You are adding the formControlName
to the label and not the input.
You have this:
<div >
<div class="input-field col s12">
<input id="email" type="email">
<label class="center-align" for="email" formControlName="email">Email</label>
</div>
</div>
Try using this:
<div >
<div class="input-field col s12">
<input id="email" type="email" formControlName="email">
<label class="center-align" for="email">Email</label>
</div>
</div>
Update the other input fields as well.
Close NetBeans.
Stop MySQL Server.
Update MySQL (if available)
Start MySQL Server.
Open NetBeans.
If still doesn't connect, download MySQL Connector/J and add mysql-connector-java-[version].jar to your
classpath and also to your Webserver's lib directory. For instance, Tomcat lib path
in XAMPP is
C:\xampp\tomcat\lib.
Then repeat the steps again.
Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-
cd C:\xampp\apache\bin
(the default installation path for Xampp)httpd -k restart
I hope that this is of use to others just starting out with running a local Apache server.
Check that you closed your class.
For example, if you have controller class with methods, and by accident you delete the final bracket, which close whole class, you will get this error.
class someControler{
private $varr;
public $varu;
..
public function method {
..
}
..
}// if you forget to close the controller, you will get the error
Even this works.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:drawable="@android:color/white" />
</selector>
I added the android:drawable
attribute to each item, and their values are colors.
By the way, why do they say that color
is one of the attributes of selector
? They don't write that android:drawable
is required.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="hex_color"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
</selector>
There is no problem to do sudo python setup.py install, if you're sure it's what you want to do.
The difference is that it will use the site-packages directory of your OS as a destination for .py files to be copied.
so, if you want pip to be accessible os wide, that's probably the way to go. I do not say that others way are bad, but this is probably fair enough.
Solutions:
Solution A:
com.oreilly.servlet.MultipartRequest
Solution B:
org.apache.commons.fileupload.MultipartStream
Solution C:
Solution D:
Use Struts. Struts 1.1 handles this automatically.
@media print{_x000D_
body{_x000D_
visibility: hidden; /* no print*/_x000D_
}_x000D_
.print{_x000D_
_x000D_
visibility:visible; /*print*/_x000D_
}_x000D_
}
_x000D_
<body>_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="print"> <!---print--->_x000D_
<div class="print"> <!---print--->_x000D_
_x000D_
_x000D_
</body>
_x000D_
Click Developer Tools to inspect element. You may also use keyboard shortcuts, such as CtrlL+Shift+I, F12 (or Fn+F12), etc.
You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:
http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA
To simply append to a file in powershell,you can use add-content.
So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.
$NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
$NewLine | add-content -path $file
Or,
"{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file
This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.
If you simply do NOT want any status bar at all, you need to update your plist with this data: To do this, in the plist, add those 2 settings:
<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
In iOS 7 you are expected to design your app with an overlaid transparent status bar in mind. See the new iOS 7 Weather app for example.
I provide another answer that I found by api-client-library
by Google
try {
DateTime dateTime = DateTime.parseRfc3339(date);
dateTime = new DateTime(new Date(dateTime.getValue()), TimeZone.getDefault());
long timestamp = dateTime.getValue(); // get date in timestamp
int timeZone = dateTime.getTimeZoneShift(); // get timezone offset
} catch (NumberFormatException e) {
e.printStackTrace();
}
Installation guide,
https://developers.google.com/api-client-library/java/google-api-java-client/setup#download
Here is API reference,
https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/util/DateTime
Source code of DateTime
Class,
https://github.com/google/google-http-java-client/blob/master/google-http-client/src/main/java/com/google/api/client/util/DateTime.java
DateTime
unit tests,
https://github.com/google/google-http-java-client/blob/master/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java#L121
You can use strptime(3)
to parse the time, and then mktime(3)
to convert it to a time_t
:
const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm); // t is now your desired time_t
You can use the vassal package, which is exactly designed for this.
All you need is to install vassal and do
from vassal.terminal import Terminal
shell = Terminal(["scp username@host:/home/foo.txt foo_local.txt"])
shell.run()
Also, it will save you authenticate credential and don't need to type them again and again.
Using the post-update file below:
On your local copy, modify your .git/config file and add your web server as a remote:
[remote "production"]
url = username@webserver:/path/to/htdocs/.git
On the server, replace .git/hooks/post-update with file below
Add execute access to the file (again, on the server):
chmod +x .git/hooks/post-update
Now, just locally push to your web server and it should automatically update the working copy:
git push production
#!/bin/sh
#
# This hook does two things:
#
# 1. update the "info" files that allow the list of references to be
# queries over dumb transports such as http
#
# 2. if this repository looks like it is a non-bare repository, and
# the checked-out branch is pushed to, then update the working copy.
# This makes "push" function somewhat similarly to darcs and bzr.
#
# To enable this hook, make this file executable by "chmod +x post-update".
git-update-server-info
is_bare=$(git-config --get --bool core.bare)
if [ -z "$is_bare" ]
then
# for compatibility's sake, guess
git_dir_full=$(cd $GIT_DIR; pwd)
case $git_dir_full in */.git) is_bare=false;; *) is_bare=true;; esac
fi
update_wc() {
ref=$1
echo "Push to checked out branch $ref" >&2
if [ ! -f $GIT_DIR/logs/HEAD ]
then
echo "E:push to non-bare repository requires a HEAD reflog" >&2
exit 1
fi
if (cd $GIT_WORK_TREE; git-diff-files -q --exit-code >/dev/null)
then
wc_dirty=0
else
echo "W:unstaged changes found in working copy" >&2
wc_dirty=1
desc="working copy"
fi
if git diff-index --cached HEAD@{1} >/dev/null
then
index_dirty=0
else
echo "W:uncommitted, staged changes found" >&2
index_dirty=1
if [ -n "$desc" ]
then
desc="$desc and index"
else
desc="index"
fi
fi
if [ "$wc_dirty" -ne 0 -o "$index_dirty" -ne 0 ]
then
new=$(git rev-parse HEAD)
echo "W:stashing dirty $desc - see git-stash(1)" >&2
( trap 'echo trapped $$; git symbolic-ref HEAD "'"$ref"'"' 2 3 13 15 ERR EXIT
git-update-ref --no-deref HEAD HEAD@{1}
cd $GIT_WORK_TREE
git stash save "dirty $desc before update to $new";
git-symbolic-ref HEAD "$ref"
)
fi
# eye candy - show the WC updates :)
echo "Updating working copy" >&2
(cd $GIT_WORK_TREE
git-diff-index -R --name-status HEAD >&2
git-reset --hard HEAD)
}
if [ "$is_bare" = "false" ]
then
active_branch=`git-symbolic-ref HEAD`
export GIT_DIR=$(cd $GIT_DIR; pwd)
GIT_WORK_TREE=${GIT_WORK_TREE-..}
for ref
do
if [ "$ref" = "$active_branch" ]
then
update_wc $ref
fi
done
fi
ArrayList.clear(From Java Doc):
Removes all of the elements from this list. The list will be empty after this call returns
convert_objects is deprecated.
For pandas >= 0.17.0, use pd.to_numeric
df["2nd"] = pd.to_numeric(df["2nd"])
The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...
...create an NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
...iterate over it
for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
...make it mutable
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
Note: historic version before 2010: [[dictionary mutableCopy] autorelease]
...and alter it
[mutableDict setObject:@"value3" forKey:@"key3"];
...then store it to a file
[mutableDict writeToFile:@"path/to/file" atomically:YES];
...and read it back again
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];
...read a value
NSString *x = [anotherDict objectForKey:@"key1"];
...check if a key exists
if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");
...use scary futuristic syntax
From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]
I think you are editing something in the windows registry but that has no effect on the path.
Try this:
How to Add, Remove or Edit Environment variables in Windows 7
the variable of interest is the PATH
also you can type on the command line:
Set PATH=%PATH%;(your new path);
m:n
is used to denote a many-to-many relationship (m
objects on the other side related to n
on the other) while 1:n
refers to a one-to-many relationship (1
object on the other side related to n
on the other).
So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.
All I did was simply remove Jupyter
and then alias python=python2.7
and install all packages on Python 2.7 again.
Arguably, I can install virtualenv
but me and my colleagues are only using 2.7. I am just going to be lazy in this case :)
Try this:
jQuery('#main').css('opacity', '0.6');
or
jQuery('#main').css({'filter':'alpha(opacity=60)', 'zoom':'1', 'opacity':'0.6'});
if you want to support IE7, IE8 and so on.
copied from polyfill Array.prototype.find code of Array.find, and added the array as first parameter.
you can pass the search term as predicate function
// Example_x000D_
var listOfObjects = [{key: "1", value: "one"}, {key: "2", value: "two"}]_x000D_
var result = findInArray(listOfObjects, function(element) {_x000D_
return element.key == "1";_x000D_
});_x000D_
console.log(result);_x000D_
_x000D_
// the function you want_x000D_
function findInArray(listOfObjects, predicate) {_x000D_
if (listOfObjects == null) {_x000D_
throw new TypeError('listOfObjects is null or not defined');_x000D_
}_x000D_
_x000D_
var o = Object(listOfObjects);_x000D_
_x000D_
var len = o.length >>> 0;_x000D_
_x000D_
if (typeof predicate !== 'function') {_x000D_
throw new TypeError('predicate must be a function');_x000D_
}_x000D_
_x000D_
var thisArg = arguments[1];_x000D_
_x000D_
var k = 0;_x000D_
_x000D_
while (k < len) {_x000D_
var kValue = o[k];_x000D_
if (predicate.call(thisArg, kValue, k, o)) {_x000D_
return kValue;_x000D_
}_x000D_
k++;_x000D_
}_x000D_
_x000D_
return undefined;_x000D_
}
_x000D_
SelectedText = this.combobox.SelectionBoxItem.ToString();
Array initializer support for type inference were changed in Visual Basic 10 vs Visual Basic 9.
In previous version of VB it was required to put empty parens to signify an array. Also, it would define the array as object array unless otherwise was stated:
' Integer array
Dim i as Integer() = {1, 2, 3, 4}
' Object array
Dim o() = {1, 2, 3}
Check more info:
AWS EFS, EBS and S3. From Functional Standpoint, here is the difference
EFS:
Network filesystem :can be shared across several Servers; even between regions. The same is not available for EBS case. This can be used esp for storing the ETL programs without the risk of security
Highly available, scalable service.
Running any application that has a high workload, requires scalable storage, and must produce output quickly.
It can provide higher throughput. It match sudden file system growth, even for workloads up to 500,000 IOPS or 10 GB per second.
Lift-and-shift application support: EFS is elastic, available, and scalable, and enables you to move enterprise applications easily and quickly without needing to re-architect them.
Analytics for big data: It has the ability to run big data applications, which demand significant node throughput, low-latency file access, and read-after-write operations.
EBS:
S3:
Robust performance, scalability, and availability: Amazon S3 scales storage resources free from resource procurement cycles or investments upfront.
2)Data lake and big data analytics: Create a data lake to hold raw data in its native format, then using machine learning tools, analytics to draw insights.
keytool
is a tool to manage (public/private) security keys and certificates and store them in a Java KeyStore
file (stored_file_name.jks).
It is provided with any standard JDK
/JRE
distributions.
You can find it under the following folder %JAVA_HOME%\bin
.
As Sayse mentioned, exit code 259 (0x103)
has special meaning, in this case the process being debugged is still running.
I saw this a lot with debugging web services, because the thread continues to run after executing each web service call (as it is still listening for further calls).
Yippe - an update to AWS CLI allows you to recursively ls through buckets...
aws s3 ls s3://<bucketname> --recursive | grep -v -E "(Bucket: |Prefix: |LastWriteTime|^$|--)" | awk 'BEGIN {total=0}{total+=$3}END{print total/1024/1024" MB"}'
First use git remote update
, to bring your remote refs up to date. Then you can do one of several things, such as:
git status -uno
will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.
git show-branch *master
will show you the commits in all of the branches whose names end in 'master' (eg master and origin/master).
If you use -v
with git remote update
(git remote -v update
) you can see which branches got updated, so you don't really need any further commands.
However, it looks like you want to do this in a script or program and end up with a true/false value. If so, there are ways to check the relationship between your current HEAD commit and the head of the branch you're tracking, although since there are four possible outcomes you can't reduce it to a yes/no answer. However, if you're prepared to do a pull --rebase
then you can treat "local is behind" and "local has diverged" as "need to pull", and the other two as "don't need to pull".
You can get the commit id of any ref using git rev-parse <ref>
, so you can do this for master and origin/master and compare them. If they're equal, the branches are the same. If they're unequal, you want to know which is ahead of the other. Using git merge-base master origin/master
will tell you the common ancestor of both branches, and if they haven't diverged this will be the same as one or the other. If you get three different ids, the branches have diverged.
To do this properly, eg in a script, you need to be able to refer to the current branch, and the remote branch it's tracking. The bash prompt-setting function in /etc/bash_completion.d
has some useful code for getting branch names. However, you probably don't actually need to get the names. Git has some neat shorthands for referring to branches and commits (as documented in git rev-parse --help
). In particular, you can use @
for the current branch (assuming you're not in a detached-head state) and @{u}
for its upstream branch (eg origin/master
). So git merge-base @ @{u}
will return the (hash of the) commit at which the current branch and its upstream diverge and git rev-parse @
and git rev-parse @{u}
will give you the hashes of the two tips. This can be summarized in the following script:
#!/bin/sh
UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
if [ $LOCAL = $REMOTE ]; then
echo "Up-to-date"
elif [ $LOCAL = $BASE ]; then
echo "Need to pull"
elif [ $REMOTE = $BASE ]; then
echo "Need to push"
else
echo "Diverged"
fi
Note: older versions of git didn't allow @
on its own, so you may have to use @{0}
instead.
The line UPSTREAM=${1:-'@{u}'}
allows you optionally to pass an upstream branch explicitly, in case you want to check against a different remote branch than the one configured for the current branch. This would typically be of the form remotename/branchname. If no parameter is given, the value defaults to @{u}
.
The script assumes that you've done a git fetch
or git remote update
first, to bring the tracking branches up to date. I didn't build this into the script because it's more flexible to be able to do the fetching and the comparing as separate operations, for example if you want to compare without fetching because you already fetched recently.
\r\n
for Windows will do just fine.
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
serves two purposes.
IE=edge
: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.chrome=1
: specifies that Google Chrome frame should start if the user has it installedThe IE=edge
flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.
As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1
will do nothing more than consume a few bytes of bandwidth.
I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.
Note, the W3C validator will flag chrome=1
as an error:
Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.
Just to add on top of other answers:
Windows Users: You can give the PATH to JRE in eclipse.ini separated by '/' or '\'. It doesn't matter. Eclipse will pick it anyway. For example, in my windows system, either of the paths is fine (after -vm of course):
C:/Program Files/Java/jre1.8.0_181/bin or C:\Program Files\Java\jre1.8.0_181\bin
I tried killall -9 node
command in terminal
then again i run my project using npm start
and it's working fine
We'd like to think that "net stop " will stop the service. Sadly, reality isn't that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won't know, though, unless you check errorlevel.
The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.
But then again...
I'm seeing the first service take a long time to stop, then the "net stop" for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still "Started" - no change to "Stopping". Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
This solution worked very nicely for me using jquery, thought I'd cross reference it here as I found this page before the other one. Someone else might do the same.
$("#id").html($("#id option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
Keep quitting Xcode until the damn thing works.
solution :
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}
data = []
with codecs.open('d:\output.txt','rU','utf-8') as f:
for line in f:
data.append(json.loads(line))
Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str()
.
min(as.numeric(data[,2]))
You can use the following little trick:
set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%
The call
there causes another layer of variable expansion, making it necessary to quote the original %
signs but it all works out in the end.
If you want to use the destructuring assignment, you'll need the same number of floats as you have variables:
grade_1, grade_2, grade_3, average = 0.0, 0.0, 0.0, 0.0
One solution is with JQuery:
$(document).ready(
function () {
$('#mycheckboxId').click(function () {
// here the action or function to call
});
}
);
There is a browser-based implementation of VSC that allows you to run it on a browser on your Android (or any other) device. Check it out here:
Users of the fish shell can use this script to do the same thing.
# content has to be in .config/fish/config.fish
# if it does not exist, create the file
setenv SSH_ENV $HOME/.ssh/environment
function start_agent
echo "Initializing new SSH agent ..."
ssh-agent -c | sed 's/^echo/#echo/' > $SSH_ENV
echo "succeeded"
chmod 600 $SSH_ENV
. $SSH_ENV > /dev/null
ssh-add
end
function test_identities
ssh-add -l | grep "The agent has no identities" > /dev/null
if [ $status -eq 0 ]
ssh-add
if [ $status -eq 2 ]
start_agent
end
end
end
if [ -n "$SSH_AGENT_PID" ]
ps -ef | grep $SSH_AGENT_PID | grep ssh-agent > /dev/null
if [ $status -eq 0 ]
test_identities
end
else
if [ -f $SSH_ENV ]
. $SSH_ENV > /dev/null
end
ps -ef | grep $SSH_AGENT_PID | grep -v grep | grep ssh-agent > /dev/null
if [ $status -eq 0 ]
test_identities
else
start_agent
end
end
Depends on what you want to do:
to read the value as an ascii code, you can write
char a = 'a';
int ia = (int)a;
/* note that the int cast is not necessary -- int ia = a would suffice */
to convert the character '0' -> 0
, '1' -> 1
, etc, you can write
char a = '4';
int ia = a - '0';
/* check here if ia is bounded by 0 and 9 */
Explanation:
a - '0'
is equivalent to ((int)a) - ((int)'0')
, which means the ascii values of the characters are subtracted from each other. Since 0
comes directly before 1
in the ascii table (and so on until 9
), the difference between the two gives the number that the character a
represents.
In case you would like to find the area between 2 values of x mean = 1; standard deviation = 2; the probability of x between [0.5,2]
import scipy.stats
scipy.stats.norm(1, 2).cdf(2) - scipy.stats.norm(1,2).cdf(0.5)
Programmatically (Swift 4 & 5)
self.passwordTextField.isSecureTextEntry = true
The ngRoute module is no longer part of the core angular.js
file. If you are continuing to use $routeProvider then you will now need to include angular-route.js
in your HTML:
<script src="angular.js">
<script src="angular-route.js">
You also have to add ngRoute
as a dependency for your application:
var app = angular.module('MyApp', ['ngRoute', ...]);
If instead you are planning on using angular-ui-router
or the like then just remove the $routeProvider
dependency from your module .config()
and substitute it with the relevant provider of choice (e.g. $stateProvider
). You would then use the ui.router
dependency:
var app = angular.module('MyApp', ['ui.router', ...]);
Postgres has an inbuilt mechanism for the same, which in the same query returns the id or whatever you want the query to return. here is an example. Consider you have a table created which has 2 columns column1 and column2 and you want column1 to be returned after every insert.
# create table users_table(id serial not null primary key, name character varying);
CREATE TABLE
#insert into users_table(name) VALUES ('Jon Snow') RETURNING id;?
id
----
1
(1 row)
# insert into users_table(name) VALUES ('Arya Stark') RETURNING id;?
id
----
2
(1 row)
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
[Closure and strong reference cycles]
As you know Swift's closure can capture the instance. It means that you are able to use self
inside a closure. Especially escaping closure
[About] can create a strong reference cycle
[About]. By the way you have to explicitly use self
inside escaping closure
.
Swift closure has Capture List
feature which allows you to avoid such situation and break a reference cycle because do not have a strong reference to captured instance. Capture List element is a pair of weak
/unowned
and a reference to class or variable.
For example
class A {
private var completionHandler: (() -> Void)!
private var completionHandler2: ((String) -> Bool)!
func nonescapingClosure(completionHandler: () -> Void) {
print("Hello World")
}
func escapingClosure(completionHandler: @escaping () -> Void) {
self.completionHandler = completionHandler
}
func escapingClosureWithPArameter(completionHandler: @escaping (String) -> Bool) {
self.completionHandler2 = completionHandler
}
}
class B {
var variable = "Var"
func foo() {
let a = A()
//nonescapingClosure
a.nonescapingClosure {
variable = "nonescapingClosure"
}
//escapingClosure
//strong reference cycle
a.escapingClosure {
self.variable = "escapingClosure"
}
//Capture List - [weak self]
a.escapingClosure {[weak self] in
self?.variable = "escapingClosure"
}
//Capture List - [unowned self]
a.escapingClosure {[unowned self] in
self.variable = "escapingClosure"
}
//escapingClosureWithPArameter
a.escapingClosureWithPArameter { [weak self] (str) -> Bool in
self?.variable = "escapingClosureWithPArameter"
return true
}
}
}
weak
- more preferable, use it when it is possibleunowned
- use it when you are sure that lifetime of instance owner is bigger than closure" Make double-<Esc> clear search highlights
nnoremap <silent> <Esc><Esc> <Esc>:nohlsearch<CR><Esc>
This behaviour is terminal-specific and specified by the terminal emulator you use (e.g. xterm
) and the semantics of terminal that it provides. The terminal behaviour has been very stable for the last 20 years, and you can reasonably rely on the semantics of \b
.
It works in Chrome 19.0.1084.41 beta!
So at some point in the future, keyframes could really be... frames!
You are living in the future ;)
if (x.equals(y))
This looks like an expensive operation. Are there any hash codes calculated this way?
It is not an expensive operation and no hash codes are calculated. Java does not magically calculate hash codes, equals(...)
is just a method call, not different from any other method call.
The JVM will most likely even optimize the method call away (inlining the comparison that takes place inside the method), so this call is not much more expensive than using ==
on two primitive int
values.
Note: Don't prematurely apply micro-optimizations; your assumptions like "this must be slow" are most likely wrong or don't matter, because the code isn't a performance bottleneck.
I have a Windows 7 desktop with a Google Nexus 7 connected to that. I also had the 'offline' problem. Mine is resolved by revoking any previous authorization on Nexus. So now I get the prompt to authorize on Nexus--I am not saving the authorization for now at least--and I allow the authorization--and voila!--Android SDK correctly shows the device as 'asus-nexus_7-xxxx'. HTH
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
You can use something like ini_set('session.gc_maxlifetime', 28800); // 8 * 60 * 60
too.
Totally useless database naming conventions. Every table name has to start with a number. The numbers show which kind of data is in the table.
This makes it hard to find a table if you only know the first letter of its name. Also - as this is a mssql database - we have to surround tablenames with square brackets everywhere.
-- doesn't work
select * from 0examples;
-- does work
select * from [0examples];
I use and may advise the following solution (python3.6):
y = int(x + (x % (1 if x >= 0 else -1)))
It works fine for half-numbers (positives and negatives) and works even faster than int(round(x)):
round_methods = [lambda x: int(round(x)),
lambda x: int(x + (x % (1 if x >= 0 else -1))),
lambda x: np.rint(x).astype(int),
lambda x: int(proper_round(x))]
for rm in round_methods:
%timeit rm(112.5)
Out:
201 ns ± 3.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
159 ns ± 0.646 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
925 ns ± 7.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.18 µs ± 8.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
for rm in round_methods:
print(rm(112.4), rm(112.5), rm(112.6))
print(rm(-12.4), rm(-12.5), rm(-12.6))
print('=' * 11)
Out:
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
For the focus() function to work on the element the div needs to have a tabindex attribute. This is probably not done by default on this type of element as it is not an input field. You can add a tabindex for example at -1 to prevent users who use tab to focus on it. If you use a positive tabindex users will be able to use tab to focus on the div element.
Here an example: http://jsfiddle.net/klodder/gFPQL/
However tabindex is not supported in Safari.
For SQL Server use exec sp_help
USE db_name;
exec sp_help 'dbo.table_name'
For MySQL, use describe
DESCRIBE table_name;
Wrote a tutorial so that you can animate your activity's in and out,
Enjoy:
l = dict.keys()
l2 = l
l2.append(0)
l3 = []
for repeater in range(0, len(l)):
smallnum = float("inf")
for listitem in l2:
if listitem < smallnum:
smallnum = listitem
l2.remove(smallnum)
l3.append(smallnum)
l3.remove(0)
l = l3
for listitem in l:
print(listitem)
Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.
>>> books = {}
>>> books['book'] = 3
>>> books['book'] -= 1
>>> books
{'book': 2}
In your case:
book_shop[ch1] -= 1
In current version of debian you have pyclean
script which is in python-minimal
package.
Usage is simple:
pyclean .
If you have even the relative pathname (in this case it appears to be ./
) you can open files relative to your script file(s). I use Perl, but the same general solution can apply: I split the directory into an array of folders, then pop
off the last element (the script), then push
(or for you, append
) on whatever I want, and then join them together again, and BAM! I have a working pathname that points to exactly where I expect it to point, relative or absolute.
Of course, there are better solutions, as posted. I just kind of like mine.
In [28]: df = DataFrame(np.random.randn(1000000,10))
In [29]: df
Out[29]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000000 entries, 0 to 999999
Data columns (total 10 columns):
0 1000000 non-null values
1 1000000 non-null values
2 1000000 non-null values
3 1000000 non-null values
4 1000000 non-null values
5 1000000 non-null values
6 1000000 non-null values
7 1000000 non-null values
8 1000000 non-null values
9 1000000 non-null values
dtypes: float64(10)
In [30]: frames = [ df.iloc[i*60:min((i+1)*60,len(df))] for i in xrange(int(len(df)/60.) + 1) ]
In [31]: %timeit [ df.iloc[i*60:min((i+1)*60,len(df))] for i in xrange(int(len(df)/60.) + 1) ]
1 loops, best of 3: 849 ms per loop
In [32]: len(frames)
Out[32]: 16667
Here's a groupby way (and you could do an arbitrary apply rather than sum)
In [9]: g = df.groupby(lambda x: x/60)
In [8]: g.sum()
Out[8]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 16667 entries, 0 to 16666
Data columns (total 10 columns):
0 16667 non-null values
1 16667 non-null values
2 16667 non-null values
3 16667 non-null values
4 16667 non-null values
5 16667 non-null values
6 16667 non-null values
7 16667 non-null values
8 16667 non-null values
9 16667 non-null values
dtypes: float64(10)
Sum is cythonized that's why this is so fast
In [10]: %timeit g.sum()
10 loops, best of 3: 27.5 ms per loop
In [11]: %timeit df.groupby(lambda x: x/60)
1 loops, best of 3: 231 ms per loop
Had the same problem . Fixed it by installing Microsoft Foundation Classes for C++.
A new version for the scenario where the callback will be called by some other function, not your own code, and you want to add additional parameters.
For example, let's pretend that you have a lot of nested calls with success and error callbacks. I will use angular promises for this example but any javascript code with callbacks would be the same for the purpose.
someObject.doSomething(param1, function(result1) {
console.log("Got result from doSomething: " + result1);
result.doSomethingElse(param2, function(result2) {
console.log("Got result from doSomethingElse: " + result2);
}, function(error2) {
console.log("Got error from doSomethingElse: " + error2);
});
}, function(error1) {
console.log("Got error from doSomething: " + error1);
});
Now you may want to unclutter your code by defining a function to log errors, keeping the origin of the error for debugging purposes. This is how you would proceed to refactor your code:
someObject.doSomething(param1, function (result1) {
console.log("Got result from doSomething: " + result1);
result.doSomethingElse(param2, function (result2) {
console.log("Got result from doSomethingElse: " + result2);
}, handleError.bind(null, "doSomethingElse"));
}, handleError.bind(null, "doSomething"));
/*
* Log errors, capturing the error of a callback and prepending an id
*/
var handleError = function (id, error) {
var id = id || "";
console.log("Got error from " + id + ": " + error);
};
The calling function will still add the error parameter after your callback function parameters.
Don't put the @ before the id
new { id = "1" }
The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Visit https://play.golang.org/p/dx6PTtuBXQW
package main
import (
"fmt"
"sort"
)
func main() {
mapEg := map[string]string{"c":"a","a":"c","b":"b"}
keys := make([]string, 0, len(mapEg))
for k := range mapEg {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(keys)
}
Major difference:
String is immutable. It means that you can't modify a string at all; the result of modification is a new string. This is not effective if you plan to append to a string.
StringBuilder is mutable. It can be modified in any way and it doesn't require creation of a new instance. When the work is done, ToString() can be called to get the string.
Strings can participate in interning. It means that strings with same contents may have same addresses. StringBuilder can't be interned.
String is the only class that can have a reference literal.
In your HTML, try and put the text that you want to come up in the title part of the code:
<a href="buzz.html" title="buzz hover text">
You can also do the same for the alt text of your image.
Using ObjectAnimator
private fun slideDown(view: View) {
val height = view.height
ObjectAnimator.ofFloat(view, "translationY", 0.toFloat(), height.toFloat()).apply {
duration = 1000
start()
}
}
private fun slideUp(view: View) {
val height = view.height
ObjectAnimator.ofFloat(view, "translationY", height.toFloat(),0.toFloat()).apply {
duration = 1000
start()
}
}
Make the value a list, e.g.
a["abc"] = [1, 2, "bob"]
UPDATE:
There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.
key = "somekey"
a.setdefault(key, [])
a[key].append(1)
Results:
>>> a
{'somekey': [1]}
Next, try:
key = "somekey"
a.setdefault(key, [])
a[key].append(2)
Results:
>>> a
{'somekey': [1, 2]}
The magic of setdefault
is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault
returns the key you can combine these into a single line:
a.setdefault("somekey",[]).append("bob")
Results:
>>> a
{'somekey': [1, 2, 'bob']}
You should look at the dict
methods, in particular the get()
method, and do some experiments to get comfortable with this.
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();
pick one, for example
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Something", new ArrayList<Integer>());
for (int i=0;i<numarulDeCopii; i++) {
map.get("Something").add(coeficientUzura[i]);
}
or just
HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);
You typically restore purchases with this code:
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
It will reinvoke -paymentQueue:updatedTransactions
on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.
Not all types of In-App purchases can be restored.
That should be:
java -Dtest="true" -jar myApplication.jar
Then the following will return the value:
System.getProperty("test");
The value could be null
, though, so guard against an exception using a Boolean
:
boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );
Note that the getBoolean
method delegates the system property value, simplifying the code to:
if( Boolean.getBoolean( "test" ) ) {
// ...
}
Ion_auth! Looks very promising and small footprint! I like..
Setting the CurrentCell
and then calling BeginEdit(true)
works well for me.
The following code shows an eventHandler for the KeyDown
event that sets a cell to be editable.
My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
{
e.Handled = true;
DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
dataGridView1.CurrentCell = cell;
dataGridView1.BeginEdit(true);
}
}
If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.
Is Arr
a base type of Obj
? Does the Obj class exist? Your code would work only if Arr is a base type of Obj. You can try this instead:
Obj[] myArray = objects.Select(o =>
{
var someLocalVar = o.someVar;
return new Obj()
{
Var1 = someLocalVar,
Var2 = o.var2
};
}).ToArray();
Generic classes are a type of class that takes in a data type as a parameter when it's created. This type parameter is specified using angle brackets and the type can change each time a new instance of the class is instantiated. For instance, let's create an ArrayList for Employee objects and another for Company objects
ArrayList<Employee> employees = new ArrayList<Employee>();
ArrayList<Company> companies = new ArrayList<Company>();
You'll notice that we're using the same ArrayList class to create both lists and we pass in the Employee or Company type using angle brackets. Having one generic class be able to handle multiple types of data cuts down on having a lot of classes that perform similar tasks. Generics also help to cut down on bugs by giving everything a strong type which helps the compiler point out errors. By specifying a type for ArrayList, the compiler will throw an error if you try to add an Employee to the Company list or vice versa.
The vector you are creating is neither row nor column. It actually has 1 dimension only. You can verify that by
myvector.ndim
which is 1
myvector.shape
, which is (3,)
(a tuple with one element only). For a row vector is should be (1, 3)
, and for a column (3, 1)
Two ways to handle this
reshape
your current oneYou can explicitly create a row or column
row = np.array([ # one row with 3 elements
[1, 2, 3]
]
column = np.array([ # 3 rows, with 1 element each
[1],
[2],
[3]
])
or, with a shortcut
row = np.r_['r', [1,2,3]] # shape: (1, 3)
column = np.r_['c', [1,2,3]] # shape: (3,1)
Alternatively, you can reshape it to (1, n)
for row, or (n, 1)
for column
row = my_vector.reshape(1, -1)
column = my_vector.reshape(-1, 1)
where the -1
automatically finds the value of n
.
There is a builtin environment: browser
that includes window
.
Example .eslintrc.json
:
"env": {
"browser": true,
"node": true,
"jasmine": true
},
More information: http://eslint.org/docs/user-guide/configuring.html#specifying-environments
Also see the package.json
answer by chevin99 below.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
[edit on 2009-04-21]
As Micah pointed out, this only works when you have named that
particular range (hence .Name anyone?) Yeah, oops!
[/edit]
A little late to the party, I know, but in case anyone else catches this in a google search (as I just did), you could also try the following:
Dim cell as Range
Dim address as String
Set cell = Sheet1.Range("A1")
address = cell.Name
This should return the full address, something like "=Sheet1!$A$1".
Assuming you don't want the equal sign, you can strip it off with a Replace function:
address = Replace(address, "=", "")
The following should prefix 'www' to any request that doesn't have one, and redirect the edited request to the new URI.
RewriteCond "%{HTTP_HOST}" "!^www\." [NC]
RewriteCond "%{HTTP_HOST}" "(.*)"
RewriteRule "(.*)" "http://www.%1$1" [R=301,L]
I ran into the same issue, but it was an issue with the actual site settings in IIS
.
Select Advanced Settings...
for your site/application and then look at the Enabled Protocols
value. For whatever reson the value was blank for my site and caused the following error:
HTTP Error 503. The service is unavailable.
The fix was to add in http
and select OK
. The site was then functional again.
I encountered this problem while upgrading from CXF 2.7.0 to 3.0.2. Here is what I did to resolve it:
Included the following in my pom.xml
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.0</version>
</dependency>
and added the following provider
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />
</jaxrs:providers>
SQL Loader helps load csv files into tables: SQL*Loader
If you want sqlplus only, then it gets a bit complicated. You need to locate your sqlloader script and csv file, then run the sqlldr command.
There are a number of properties on the StringComparer
static class that return comparers for any type of case-sensitivity you might want:
For instance, you can call
StringComparer.CurrentCultureIgnoreCase.Equals(string1, string2)
or
StringComparer.CurrentCultureIgnoreCase.Compare(string1, string2)
It's a bit cleaner than the string.Equals
or string.Compare
overloads that take a StringComparison
argument.
First navigate to your Java/jre/bin folder in cmd cd c:\Program Files (x86)\Java\jre7\bin
Then use : [change debug.keystore path to the correct location on your system] install openssl (for windows 32 or 64 as per your needs at c:\openssl )
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\vibhor\.android\debug.keystore" | "c:\openssl\bin\openssl.exe" sha1 -binary | "c:\openssl\bin\openssl.exe" base64
So the whole command goes like this : [prompts to enter keystore password on execution ]
c:\Program Files (x86)\Java\jre7\bin>keytool -exportcert -alias androiddebugkey
-keystore "C:\Users\vibhor\.android\debug.keystore" | "c:\openssl\bin\openssl.ex
e" sha1 -binary | "c:\openssl\bin\openssl.exe" base64
Enter keystore password:
Update by Arkadiy: I've observed more correct behavior of System.currentTimeMillis()
on Windows 7 in Oracle Java 8. The time was returned with 1 millisecond precision. The source code in OpenJDK has not changed, so I do not know what causes the better behavior.
David Holmes of Sun posted a blog article a couple years ago that has a very detailed look at the Java timing APIs (in particular System.currentTimeMillis()
and System.nanoTime()
), when you would want to use which, and how they work internally.
Inside the Hotspot VM: Clocks, Timers and Scheduling Events - Part I - Windows
One very interesting aspect of the timer used by Java on Windows for APIs that have a timed wait parameter is that the resolution of the timer can change depending on what other API calls may have been made - system wide (not just in the particular process). He shows an example where using Thread.sleep()
will cause this resolution change.
Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException
this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original).
Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}
There are a simple way to make it work. The element and all childs you set a same class name, then:
element.onmouseover = function(event){
if (event.target.className == "name"){
/*code*/
}
}
As of now, the Go compiler generates identical code in both cases, so it is a matter of taste. GCCGo does generate different code, but barely anyone uses it so I wouldn't worry about that.
Here's some more good practices around Timer use:
http://tech.puredanger.com/2008/09/22/timer-rules/
In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.
Option 1: In SSMS go to View > Object Explorer Details
or press F7. Use the Search
box. Finally in the displayed list right click and select Synchronize
to find the object in the Object Explorer
tree.
Option 2: Install an Add-On like dbForge Search
. Right click on the displayed list and select Find in Object Explorer
.
Each method of mysqli can fail. You should test each return value. If one fails, think about whether it makes sense to continue with an object that is not in the state you expect it to be. (Potentially not in a "safe" state, but I think that's not an issue here.)
Since only the error message for the last operation is stored per connection/statement you might lose information about what caused the error if you continue after something went wrong. You might want to use that information to let the script decide whether to try again (only a temporary issue), change something or to bail out completely (and report a bug). And it makes debugging a lot easier.
$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
// and since all the following operations need a valid/ready statement object
// it doesn't make sense to go on
// you might want to use a more sophisticated mechanism than die()
// but's it's only an example
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
// again execute() is useless if you can't bind the parameters. Bail out somehow.
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->close();
The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....
I open the Play Store from my App with the following code:
val uri: Uri = Uri.parse("market://details?id=$packageName")
val goToMarket = Intent(Intent.ACTION_VIEW, uri)
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY or
Intent.FLAG_ACTIVITY_NEW_DOCUMENT or
Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
try {
startActivity(goToMarket)
} catch (e: ActivityNotFoundException) {
startActivity(Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=$packageName")))
}
Add the -v
option to your grep
command to invert the results.
I had the same problem with webapi in ASP.NET core, in my case it was because my application needs authentication, then it assigns the annotation [AllowAnonymous]
and it worked.
[AllowAnonymous]
public async Task <IList <IServic >> GetServices () {
}
You can update your python version to 3.8 in conda using the command
conda install -c anaconda python=3.8
as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running
conda update --all
may resolve some dependency failures. You can also create a new environment called py38 using this command
conda create -n py38 python=3.8
Edit - note that the conda install
option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).
I think using try/catch pattern is not very well for performance. I advice to use this:
public static boolean appInstalledOrNot(Context context, String uri) {
PackageManager pm = context.getPackageManager();
List<PackageInfo> packageInfoList = pm.getInstalledPackages(PackageManager.GET_ACTIVITIES);
if (packageInfoList != null) {
for (PackageInfo packageInfo : packageInfoList) {
String packageName = packageInfo.packageName;
if (packageName != null && packageName.equals(uri)) {
return true;
}
}
}
return false;
}
For iPhone 5.5" display you need to change the simulator to "Physical Size" on iPhone 8 Plus
In case of plotting time series, the command ts.plot
requires a different argument than xaxt="n"
require(graphics)
ts.plot(ldeaths, mdeaths, xlab="year", ylab="deaths", lty=c(1:2), gpars=list(xaxt="n"))
axis(1, at = seq(1974, 1980, by = 2))
To augment PYTHONPATH, run regedit and navigate to KEY_LOCAL_MACHINE \SOFTWARE\Python\PythonCore and then select the folder for the python version you wish to use. Inside this is a folder labelled PythonPath, with one entry that specifies the paths where the default install stores modules. Right-click on PythonPath and choose to create a new key. You may want to name the key after the project whose module locations it will specify; this way, you can easily compartmentalize and track your path modifications.
thanks
useState is a Hook that allows you to have state variables in functional components.
There are two types of components in React: class and functional components.
Class components are ES6 classes that extend from React.Component and can have state and lifecycle methods:
class Message extends React.Component {
constructor(props) {
super(props);
this.state = {
message: ‘’
};
}
componentDidMount() {
/* ... */
}
render() {
return <div>{this.state.message}</div>;
}
}
Functional components are functions that just accept arguments as the properties of the component and return valid JSX:
function Message(props) {
return <div>{props.message}</div>
}
// Or as an arrow function
const Message = (props) => <div>{props.message}</div>
As you can see, there are no state or lifecycle methods.
There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.
Update:
As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile
to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile
on OS X now requires the output to be a socket and the code won't work!
The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.
#include <fcntl.h>
#include <unistd.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <copyfile.h>
#else
#include <sys/sendfile.h>
#endif
int OSCopyFile(const char* source, const char* destination)
{
int input, output;
if ((input = open(source, O_RDONLY)) == -1)
{
return -1;
}
if ((output = creat(destination, 0660)) == -1)
{
close(input);
return -1;
}
//Here we use kernel-space copying for performance reasons
#if defined(__APPLE__) || defined(__FreeBSD__)
//fcopyfile works on FreeBSD and OS X 10.5+
int result = fcopyfile(input, output, 0, COPYFILE_ALL);
#else
//sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
off_t bytesCopied = 0;
struct stat fileinfo = {0};
fstat(input, &fileinfo);
int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
#endif
close(input);
close(output);
return result;
}
EDIT: Replaced the opening of the destination with the call to creat()
as we want the flag O_TRUNC
to be specified. See comment below.
in the terminal window on your mac, press control+c
In my case,I was getting error while refreshing gradle ('View'->Tool Windows->Gradle) tab and hit "refresh" and getting this error no such property gradleversion for class jetgradleplugin.
Had to install latest intellij compatible with gradle 5+
Easy Solution. You can use the following function to convert your Enum to an array of objects.
buildGoalProgressMeasurementsArray(): Object[] {
return Object.keys(GoalProgressMeasurements)
.map(key => ({ id: GoalProgressMeasurements[key], name: key }))
}
If you needed to strip that underscore off, we could use regex as follows:
buildGoalProgressMeasurementsArray(): Object[] {
return Object.keys(GoalProgressMeasurements)
.map(key => ({ id: GoalProgressMeasurements[key], name: key.replace(/_/g, ' ') }))
}
Here, W and H are width and height of input, F are filter dimensions, P is padding size (i.e., number of rows or columns to be padded)
For SAME padding:
For VALID padding:
This should be fine, since you haven't pushed your commits anywhere else yet, and you're free to rewrite the history of your branch after origin/master
. First I would run a git fetch origin
to make sure that origin/master
is up to date. Assuming that you're currently on master
, you should be able to do:
git rebase origin/master
... which will replay all of your commits that aren't in origin/master
onto origin/master
. The default action of rebase is to ignore merge commits (e.g. those that your git pull
s probably introduced) and it'll just try to apply the patch introduced by each of your commits onto origin/master
. (You may have to resolve some conflicts along the way.) Then you can create your new branch based on the result:
git branch new-work
... and then reset your master
back to origin/master
:
# Use with care - make sure "git status" is clean and you're still on master:
git reset --hard origin/master
When doing this kind of manipulating branches with git branch
, git reset
, etc. I find it useful to frequently look at the commit graph with gitk --all
or a similar tool, just to check that I understand where all the different refs are pointing.
Alternatively, you could have just created a topic branch based on where your master is at in the first place (git branch new-work-including-merges
) and then reset master
as above. However, since your topic branch will include merges from origin/master
and you've not pushed your changes yet, I'd suggest doing a rebase so that the history is tidier. (Also, when you eventually merge your topic branch back to master, the changes will be more obvious.)
If you have a large index, you should use a default value
<field ... default="EMPTY" />
and then query for this default value. This is much more efficient than q=-id:["" TO *]
If you want to use for <input>
it will not work, for <input>
or text area you need to use Javascript
<script language="javascript" type="text/javascript">
function capitaliseName()
{
var str = document.getElementById("name").value;
document.getElementById("name").value = str.charAt(0).toUpperCase() + str.slice(1);
}
</script>
<textarea name="NAME" id="name" onkeydown = "capitaliseName()"></textarea>
that is supposed to work well for <input>
or <textarea>
Go to Help -> About Eclipse Sdk
This may also add to understanding of the difference between those two operators:
df <- data.frame(
a = rnorm(10),
b <- rnorm(10)
)
For the first element R has assigned values and proper name, while the name of the second element looks a bit strange.
str(df)
# 'data.frame': 10 obs. of 2 variables:
# $ a : num 0.6393 1.125 -1.2514 0.0729 -1.3292 ...
# $ b....rnorm.10.: num 0.2485 0.0391 -1.6532 -0.3366 1.1951 ...
R version 3.3.2 (2016-10-31); macOS Sierra 10.12.1