CSS3 introduced flexible boxes (aka. flex box) which can also achieve this behavior.
Simply define the width of the first div, and then give the second a flex-grow
value of 1
which will allow it to fill the remaining width of the parent.
.container{
display: flex;
}
.fixed{
width: 200px;
}
.flex-item{
flex-grow: 1;
}
<div class="container">
<div class="fixed"></div>
<div class="flex-item"></div>
</div>
Demo:
div {
color: #fff;
font-family: Tahoma, Verdana, Segoe, sans-serif;
padding: 10px;
}
.container {
background-color:#2E4272;
display:flex;
}
.fixed {
background-color:#4F628E;
width: 200px;
}
.flex-item {
background-color:#7887AB;
flex-grow: 1;
}
_x000D_
<div class="container">
<div class="fixed">Fixed width</div>
<div class="flex-item">Dynamically sized content</div>
</div>
_x000D_
Note that flex boxes are not backwards compatible with old browsers, but is a great option for targeting modern browsers (see also Caniuse and MDN). A great comprehensive guide on how to use flex boxes is available on CSS Tricks.
Different way:
var isEven = function(number) {
// Your code goes here!
if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};
isEven(69)
in
Python strings and listsHere are a few useful examples that speak for themselves concerning the in
method:
"foo" in "foobar"
True
"foo" in "Foobar"
False
"foo" in "Foobar".lower()
True
"foo".capitalize() in "Foobar"
True
"foo" in ["bar", "foo", "foobar"]
True
"foo" in ["fo", "o", "foobar"]
False
["foo" in a for a in ["fo", "o", "foobar"]]
[False, False, True]
Caveat. Lists are iterables, and the in
method acts on iterables, not just strings.
In Apache version 2.4.18 (Ubuntu).
Open the file /etc/apache2/apache2.conf and
search for <Directory /var/www/>
and replace to your directory.
Open file /etc/apache2/sites-available/000-default.conf, search for DocumentRoot /var/www/html
and replace it with your DocumentRoot.
If you want to test against all nil/empty objects (like empty strings or empty arrays/sets) you can use the following:
static inline BOOL IsEmpty(id object) {
return object == nil
|| ([object respondsToSelector:@selector(length)]
&& [(NSData *) object length] == 0)
|| ([object respondsToSelector:@selector(count)]
&& [(NSArray *) object count] == 0);
}
I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.
After your provided script commands, execute additional commands like below:
sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command
In your script:
#! /bin/bash
sshpass -p 'password' ssh user@host "ls; whois google.com;"
var elems = document.querySelectorAll(".widget.hover");
[].forEach.call(elems, function(el) {
el.classList.remove("hover");
});
You can patch .classList
into IE9. Otherwise, you'll need to modify the .className
.
var elems = document.querySelectorAll(".widget.hover");
[].forEach.call(elems, function(el) {
el.className = el.className.replace(/\bhover\b/, "");
});
The .forEach()
also needs a patch for IE8, but that's pretty common anyway.
EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.
Original post
The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.
More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan
You can seek until the end, then compute the difference:
std::streampos fileSize( const char* filePath ){
std::streampos fsize = 0;
std::ifstream file( filePath, std::ios::binary );
fsize = file.tellg();
file.seekg( 0, std::ios::end );
fsize = file.tellg() - fsize;
file.close();
return fsize;
}
As a native and efficient approach, you don't need to use ord
or any loop over the characters. Just encode with ascii
and ignore the errors.
The following will just remove the non-ascii characters:
new_string = old_string.encode('ascii',errors='ignore')
Now if you want to replace the deleted characters just do the following:
final_string = new_string + b' ' * (len(old_string) - len(new_string))
Right click on project, select Maven -> Update project. That should solve the issue.
You can move to desired activity on button click. just add this line.
android:onClick="sendMessage"
xml:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="@string/button" />
In your main activity just add this method:
public void sendMessage(View view) {
Intent intent = new Intent(FromActivity.this, ToActivity.class);
startActivity(intent);
}
And the most important thing: don't forget to define your activity in manifest.xml
<activity>
android:name=".ToActivity"
android:label="@string/app_name">
</activity>
If your main goal is to visualize the correlation matrix, rather than creating a plot per se, the convenient pandas
styling options is a viable built-in solution:
import pandas as pd
import numpy as np
rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
corr = df.corr()
corr.style.background_gradient(cmap='coolwarm')
# 'RdBu_r' & 'BrBG' are other good diverging colormaps
Note that this needs to be in a backend that supports rendering HTML, such as the JupyterLab Notebook. (The automatic light text on dark backgrounds is from an existing PR and not the latest released version, pandas
0.23).
You can easily limit the digit precision:
corr.style.background_gradient(cmap='coolwarm').set_precision(2)
Or get rid of the digits altogether if you prefer the matrix without annotations:
corr.style.background_gradient(cmap='coolwarm').set_properties(**{'font-size': '0pt'})
The styling documentation also includes instructions of more advanced styles, such as how to change the display of the cell the mouse pointer is hovering over. To save the output you could return the HTML by appending the render()
method and then write it to a file (or just take a screenshot for less formal purposes).
In my testing, style.background_gradient()
was 4x faster than plt.matshow()
and 120x faster than sns.heatmap()
with a 10x10 matrix. Unfortunately it doesn't scale as well as plt.matshow()
: the two take about the same time for a 100x100 matrix, and plt.matshow()
is 10x faster for a 1000x1000 matrix.
There are a few possible ways to save the stylized dataframe:
render()
method and then write the output to a file..xslx
file with conditional formatting by appending the to_excel()
method.By setting axis=None
, it is now possible to compute the colors based on the entire matrix rather than per column or per row:
corr.style.background_gradient(cmap='coolwarm', axis=None)
Use console.dir()
to output a browse-able object you can click through instead of the .toString()
version, like this:
console.dir(functor);
Prints a JavaScript representation of the specified object. If the object being logged is an HTML element, then the properties of its DOM representation are printed [1]
[1] https://developers.google.com/web/tools/chrome-devtools/debug/console/console-reference#dir
C++17 inline
variables
This awesome C++17 feature allow us to:
constexpr
: How to declare constexpr extern?main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
// Both files see the same memory address.
assert(¬main_i == notmain_func());
assert(notmain_i == 42);
}
notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
inline constexpr int notmain_i = 42;
const int* notmain_func();
#endif
notmain.cpp
#include "notmain.hpp"
const int* notmain_func() {
return ¬main_i;
}
Compile and run:
g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./main
See also: How do inline variables work?
C++ standard on inline variables
The C++ standard guarantees that the addresses will be the same. C++17 N4659 standard draft 10.1.6 "The inline specifier":
6 An inline function or variable with external linkage shall have the same address in all translation units.
cppreference https://en.cppreference.com/w/cpp/language/inline explains that if static
is not given, then it has external linkage.
Inline variable implementation
We can observe how it is implemented with:
nm main.o notmain.o
which contains:
main.o:
U _GLOBAL_OFFSET_TABLE_
U _Z12notmain_funcv
0000000000000028 r _ZZ4mainE19__PRETTY_FUNCTION__
U __assert_fail
0000000000000000 T main
0000000000000000 u notmain_i
notmain.o:
0000000000000000 T _Z12notmain_funcv
0000000000000000 u notmain_i
and man nm
says about u
:
"u" The symbol is a unique global symbol. This is a GNU extension to the standard set of ELF symbol bindings. For such a symbol the dynamic linker will make sure that in the entire process there is just one symbol with this name and type in use.
so we see that there is a dedicated ELF extension for this.
C++17 standard draft on "global" const
implies static
This is the quote for what was mentioned at: https://stackoverflow.com/a/12043198/895245
C++17 n4659 standard draft 6.5 "Program and linkage":
3 A name having namespace scope (6.3.6) has internal linkage if it is the name of
- (3.1) — a variable, function or function template that is explicitly declared static; or,
- (3.2) — a non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage; or
- (3.3) — a data member of an anonymous union.
"namespace" scope is what we colloquially often refer to as "global".
Annex C (informative) Compatibility, C.1.2 Clause 6: "basic concepts" gives the rationale why this was changed from C:
6.5 [also 10.1.7]
Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage.
Rationale: Because const objects may be used as values during translation in C++, this feature urges programmers to provide an explicit initializer for each const object. This feature allows the user to put const objects in source files that are included in more than one translation unit.
Effect on original feature: Change to semantics of well-defined feature.
Difficulty of converting: Semantic transformation.
How widely used: Seldom.
See also: Why does const imply internal linkage in C++, when it doesn't in C?
Tested in GCC 7.4.0, Ubuntu 18.04.
I just spend an hour on this, I'm new to Oracle so i was thoroughly confused..
the situation:
just installed visual studio 2012 Oracle developer tools. When i did this I lost the items in my drop down which contained my TNS entries in TOAD. I was getting this error from Visual studio AND TOAD!! WTH! so i added the environmental Variable TNS_ADMIN under "ALL USERS" with the path to my .ora file (which i now worked fine because it worked until I broke it). Toad picked up that change. Still Visual Studio wouldn't give me any love... still getting same error. THEN, i added the environmental Variable TO MY USER VARIABLES.. VIOLA!!
ENSURE THE ENVIRONMENTAL VARIABLES ARE SET FOR THE SYSTEM AND THE USER
In DJango 3.0 the default value of a BooleanField in model.py is set like this:
class model_name(models.Model):
example_name = models.BooleanField(default=False)
Johnnie, Please go through msdn guide on switch. Also, the C# language specification clearly defines the compile time error case:
• If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, bool, char, string, or an enum-type, or if it is the nullable type corresponding to one of these types, then that is the governing type of the switch statement.
• Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type corresponding to one of those types.
• Otherwise, if no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs.
Hope this helps.
Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).
>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2010-08-04T09:33:09.890000+10:00'
>>>
For me the following worked which is copied from example in /etc/apache2/apache2.conf
:
<Directory /srv/www/default>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
Require all granted
option is the solution for the first problem example in wiki.apache.org page dedicated for this issue for Apache version 2.4+.
More details about Require option can be found on official apache page for mod_authz module and on this page too. Namely:
Require all granted -> Access is allowed unconditionally.
Inject $filter to your controller
function myCtrl($scope, $filter)
{
}
Then wherever you want to use that filter, just use it like this:
$filter('filtername');
If you want to pass arguments to that filter, do it using separate parentheses:
function myCtrl($scope, $filter)
{
$filter('filtername')(arg1,arg2);
}
Where arg1
is the array you want to filter on and arg2
is the object used to filter.
Here is my approach API (i use example) - as you can see, you I don't use any file_id
(uploaded file identifier to the server) in API:
Create photo
object on server:
POST: /projects/{project_id}/photos
body: { name: "some_schema.jpg", comment: "blah"}
response: photo_id
Upload file (note that file
is in singular form because it is only one per photo):
POST: /projects/{project_id}/photos/{photo_id}/file
body: file to upload
response: -
And then for instance:
Read photos list
GET: /projects/{project_id}/photos
response: [ photo, photo, photo, ... ] (array of objects)
Read some photo details
GET: /projects/{project_id}/photos/{photo_id}
response: { id: 666, name: 'some_schema.jpg', comment:'blah'} (photo object)
Read photo file
GET: /projects/{project_id}/photos/{photo_id}/file
response: file content
So the conclusion is that, first you create an object (photo) by POST, and then you send second request with the file (again POST). To not have problems with CACHE in this approach we assume that we can only delete old photos and add new - no update binary photo files (because new binary file is in fact... NEW photo). However if you need to be able to update binary files and cache them, then in point 4
return also fileId
and change 5
to GET: /projects/{project_id}/photos/{photo_id}/files/{fileId}.
Yes. unless, there is an ambiguity.
Thank you @user1909426, I can found solution by php artisan list
it will list all command that was used on L4. It can create controller only not Model. I follow this command to generate controller.
php artisan controller:make [Name]Controller
On Laravel 5, the command has changed:
php artisan make:controller [Name]Controller
Note: [Name] name of controller
I came up with the solution and posted it on my blog
here is the htaccess code also
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]
but I posted other solutions on my blog too, it depends what you need really
As the name suggests 'untracked files' are the files which are not being tracked by git. They are not in your staging area, and were not part of any previous commits. If you want them to be versioned (or to be managed by git) you can do so by telling 'git' by using 'git add'. Check this chapter Recording Changes to the Repository in the Progit book which uses a nice visual to provide a good explanation about recording changes to git repo and also explaining the terms 'tracked' and 'untracked'.
That's more specifically a ternary operator expression than an if-then, here's the python syntax
value_when_true if condition else value_when_false
Better Example: (thanks Mr. Burns)
'Yes' if fruit == 'Apple' else 'No'
Now with assignment and contrast with if syntax
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
vs
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True
Add -q 1
to the netcat
command line:
while true; do
echo -e "HTTP/1.1 200 OK\n\n $(date)" | nc -l -p 1500 -q 1
done
clean package exec:java -P Class_Containing_Main_Method
command is also an option if you have only one Main method(PSVM) in the project, with the following Maven Setup.
Don't forget to mention the class in the <properties></properties>
section of pom.xml
:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.main.class>com.test.service.MainTester</java.main.class>
</properties>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>${java.main.class}</mainClass>
</configuration>
</plugin>
STS Run Configuration along with above Maven Setup:
If you are using the Support Library provided DrawerLayout as suggested in the Creating a navigation drawer training, you can use the newly added android.support.v7.app.ActionBarDrawerToggle (note: different from the now deprecated android.support.v4.app.ActionBarDrawerToggle):
shows a Hamburger icon when drawer is closed and an arrow when drawer is open. It animates between these two states as the drawer opens.
While the training hasn't been updated to take the deprecation/new class into account, you should be able to use it almost exactly the same code - the only difference in implementing it is the constructor.
I think you could solve this with .strip()
in gazpacho:
Input:
html = """\
<p>
<strong class="offender">YOB:</strong> 1987<br />
<strong class="offender">RACE:</strong> WHITE<br />
<strong class="offender">GENDER:</strong> FEMALE<br />
<strong class="offender">HEIGHT:</strong> 5'05''<br />
<strong class="offender">WEIGHT:</strong> 118<br />
<strong class="offender">EYE COLOR:</strong> GREEN<br />
<strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
Code:
soup = Soup(html)
text = soup.find("p").strip(whitespace=False) # to keep \n characters intact
lines = [
line.strip()
for line in text.split("\n")
if line != ""
]
data = dict([line.split(": ") for line in lines])
Output:
print(data)
# {'YOB': '1987',
# 'RACE': 'WHITE',
# 'GENDER': 'FEMALE',
# 'HEIGHT': "5'05''",
# 'WEIGHT': '118',
# 'EYE COLOR': 'GREEN',
# 'HAIR COLOR': 'BROWN'}
If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):
String uri = request.getRequestURI();
String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());
if(redirectMap.containsKey(path)) {
response.sendRedirect(redirectMap.get(path) + rest);
} else {
chain.doFilter(request, response);
}
Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.
You can either remove some of the padding above and below your logo or you can add more padding above and below links.
Adding more padding should look something like this:
nav.navbar-inverse>li>a {
padding-top: 25px;
padding-bottom: 25px;
}
So you want the next multiple of 6, is that it?
You can divide your number by 6, then ceil
it, and multiply it again:
$answer = ceil($foo / 6) * 6;
Summing the multiplication of digits with their respective power of ten:
i.e: 123 = 100+20+3 = 1*100 + 2+10 + 3*1 = 1*(10^2) + 2*(10^1) + 3*(10^0)
function atoi(array) {
// use exp as (length - i), other option would be to reverse the array.
// multiply a[i] * 10^(exp) and sum
let sum = 0;
for (let i = 0; i < array.length; i++) {
let exp = array.length-(i+1);
let value = array[i] * Math.pow(10,exp);
sum+=value;
}
return sum;
}
Downloading a file in Swift 5 with progress reporting, encapsulated into a copy-paste friendly protocol-accessed class:
protocol FileDownloadingDelegate: class {
func updateDownloadProgressWith(progress: Float)
func downloadFinished(localFilePath: URL)
func downloadFailed(withError error: Error)
}
class FilesDownloader: NSObject, URLSessionDownloadDelegate {
private weak var delegate: FileDownloadingDelegate?
func download(from url: URL, delegate: FileDownloadingDelegate) {
self.delegate = delegate
let sessionConfig = URLSessionConfiguration.background(withIdentifier: url.absoluteString) // use this identifier to resume download after app restart
let session = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTask(with: url)
task.resume()
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
DispatchQueue.main.async { self.delegate?.downloadFinished(localFilePath: location) }
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
DispatchQueue.main.async { self.delegate?.updateDownloadProgressWith(progress: Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)) }
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let theError = error else { assertionFailure("something weird happened here"); return }
DispatchQueue.main.async { self.delegate?.downloadFailed(withError: theError) }
}
}
How to use it:
class MyViewController: UIViewController {
private lazy var downloader = FilesDownloader()
func downloadFile(from url: URL) {
downloader.download(from: url, delegate: self)
}
}
extension MyViewController: FileDownloadingDelegate {
func updateDownloadProgressWith(progress: Float) {
// self.downloadProgressView.setProgress(progress, animated: true)
}
func downloadFinished(tempFilePath: URL) {
print("downloaded to \(tempFilePath)")
// resave the file into your desired place using
// let dataFromURL = NSData(contentsOf: location)
// dataFromURL?.write(to: yourDesiredFileUrl, atomically: true)
}
func downloadFailed(withError error: Error) {
// handle the error
}
}
public class MainActivity extends AppCompatActivity implements OnClickListener {
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1= (Button) findViewById(R.id.button);
b2= (Button) findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
if(v.getId()==R.id.button)
{
Intent intent=new Intent(getApplicationContext(),SignIn.class);
startActivity(intent);
}
else if (v.getId()==R.id.button2)
{
Intent in=new Intent(getApplicationContext(),SignUpactivity.class);
startActivity(in);
}
}
}
GitHub recently introduced a new feature called Projects. This provides a visual board that is typical of many Project Management tools:
A Repository as documented on GitHub:
A repository is the most basic element of GitHub. They're easiest to imagine as a project's folder. A repository contains all of the project files (including documentation), and stores each file's revision history. Repositories can have multiple collaborators and can be either public or private.
A Project as documented on GitHub:
Project boards on GitHub help you organize and prioritize your work. You can create project boards for specific feature work, comprehensive roadmaps, or even release checklists. With project boards, you have the flexibility to create customized workflows that suit your needs.
Part of the confusion is that the new feature, Projects, conflicts with the overloaded usage of the term project in the documentation above.
The +
allow 'select' only first not nested element , the >
select nested elements only - the better is to use ~
which allow to select arbitrary element which is child of parent hovered element. Using opacity/width and transition you can provide smooth appear
div { transition: all 1s }_x000D_
.ccc, .ggg { opacity: 0; color: red}_x000D_
.ccc { height: 0 }_x000D_
_x000D_
.aaa:hover ~ .bbb .ccc { opacity: 1; height: 34px }_x000D_
.aaa:hover ~ .eee .fff .ggg { opacity: 1 }
_x000D_
<div class="aaa">Hover me... to see<br><br> </div>_x000D_
_x000D_
<div class='bbb'>BBBBB_x000D_
<div class='ccc'>CCCCC_x000D_
<div class='ddd'>DDDDD</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class='eee'>EEEEE_x000D_
<div class='fff'>FFFFF_x000D_
<div class='ggg'>GGGGG</div>_x000D_
<div class='hhh'>HHHHH</div>_x000D_
</div>_x000D_
</div>
_x000D_
One way to do that is to make all your users' devices subscribe to a topic. That way when you target a message to a specific topic, all devices will get it. I think this how the Notifications section in the Firebase console does it.
Use this code to not only check if the memcache extension is enabled, but also whether the daemon is running and able to store and retrieve data successfully:
<?php
if (class_exists('Memcache')) {
$server = 'localhost';
if (!empty($_REQUEST['server'])) {
$server = $_REQUEST['server'];
}
$memcache = new Memcache;
$isMemcacheAvailable = @$memcache->connect($server);
if ($isMemcacheAvailable) {
$aData = $memcache->get('data');
echo '<pre>';
if ($aData) {
echo '<h2>Data from Cache:</h2>';
print_r($aData);
} else {
$aData = array(
'me' => 'you',
'us' => 'them',
);
echo '<h2>Fresh Data:</h2>';
print_r($aData);
$memcache->set('data', $aData, 0, 300);
}
$aData = $memcache->get('data');
if ($aData) {
echo '<h3>Memcache seem to be working fine!</h3>';
} else {
echo '<h3>Memcache DOES NOT seem to be working!</h3>';
}
echo '</pre>';
}
}
if (!$isMemcacheAvailable) {
echo 'Memcache not available';
}
?>
Old question I know, but might help someone. I've used @Adam accepted answer above, but then checked if the difference is 1 or -1 then check to see if it is a full calendar month's difference. So 21/07/55 and 20/08/55 would not be a full month, but 21/07/55 and 21/07/55 would be.
/// <summary>
/// Amended date of birth cannot be greater than or equal to one month either side of original date of birth.
/// </summary>
/// <param name="dateOfBirth">Date of birth user could have amended.</param>
/// <param name="originalDateOfBirth">Original date of birth to compare against.</param>
/// <returns></returns>
public JsonResult ValidateDateOfBirth(string dateOfBirth, string originalDateOfBirth)
{
DateTime dob, originalDob;
bool isValid = false;
if (DateTime.TryParse(dateOfBirth, out dob) && DateTime.TryParse(originalDateOfBirth, out originalDob))
{
int diff = ((dob.Month - originalDob.Month) + 12 * (dob.Year - originalDob.Year));
switch (diff)
{
case 0:
// We're on the same month, so ok.
isValid = true;
break;
case -1:
// The month is the previous month, so check if the date makes it a calendar month out.
isValid = (dob.Day > originalDob.Day);
break;
case 1:
// The month is the next month, so check if the date makes it a calendar month out.
isValid = (dob.Day < originalDob.Day);
break;
default:
// Either zero or greater than 1 month difference, so not ok.
isValid = false;
break;
}
if (!isValid)
return Json("Date of Birth cannot be greater than one month either side of the date we hold.", JsonRequestBehavior.AllowGet);
}
else
{
return Json("Date of Birth is invalid.", JsonRequestBehavior.AllowGet);
}
return Json(true, JsonRequestBehavior.AllowGet);
}
You can also:
[UIView animateWithDuration:1.0
animations:^{ self.view.alpha = 1.1; /* Some fake chages */ }
completion:^(BOOL finished)
{
NSLog(@"A second lapsed.");
}];
This case you have to fake some changes to some view to get the animation work. It is hacky indeed, but I love the block based stuff. Or wrap up @mcfedr answer below.
waitFor(1.0, ^
{
NSLog(@"A second lapsed");
});
typedef void (^WaitCompletionBlock)();
void waitFor(NSTimeInterval duration, WaitCompletionBlock completion)
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC),
dispatch_get_main_queue(), ^
{ completion(); });
}
For pointers, you need them to point to something, so pointers cost memory space.
For example a function that takes an integer pointer will not take the integer variable. So you will need to create a pointer for that first to pass on to the function.
As for a reference, it will not cost memory. You have an integer variable, and you can pass it as a reference variable. That's it. You don't need to create a reference variable specially for it.
join is not a jQuery function .Its a javascript function.
The join() method joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
Visibility is an animatable property according to the spec, but transitions on visibility do not work gradually, as one might expect. Instead transitions on visibility delay hiding an element. On the other hand making an element visible works immediately. This is as it is defined by the spec (in the case of the default timing function) and as it is implemented in the browsers.
This also is a useful behavior, since in fact one can imagine various visual effects to hide an element. Fading out an element is just one kind of visual effect that is specified using opacity. Other visual effects might move away the element using e.g. the transform property, also see http://taccgl.org/blog/css-transition-visibility.html
It is often useful to combine the opacity transition with a visibility transition! Although opacity appears to do the right thing, fully transparent elements (with opacity:0) still receive mouse events. So e.g. links on an element that was faded out with an opacity transition alone, still respond to clicks (although not visible) and links behind the faded element do not work (although being visible through the faded element). See http://taccgl.org/blog/css-transition-opacity-for-fade-effects.html.
This strange behavior can be avoided by just using both transitions, the transition on visibility and the transition on opacity. Thereby the visibility property is used to disable mouse events for the element while opacity is used for the visual effect. However care must be taken not to hide the element while the visual effect is playing, which would otherwise not be visible. Here the special semantics of the visibility transition becomes handy. When hiding an element the element stays visible while playing the visual effect and is hidden afterwards. On the other hand when revealing an element, the visibility transition makes the element visible immediately, i.e. before playing the visual effect.
You could remove the folder and update the parent directory before committing:
rm -r some_dir
svn update some_dir_parent
Generally the process will block. If the read operation is on a file descriptor marked as non-blocking or if the process is using asynchronous IO it won't block. Also if the process has other threads that aren't blocked they can continue running.
The decision as to which process runs next is up to the scheduler in the kernel.
If you need to interact directly with the DOM element, why not just use document.getElementById
since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val()
is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.
try
total.Text = DateTime.Now.ToString()
or
Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()
You declare Start
as an Integer
, while you are trying to put a DateTime
in it, which is not possible.
Height is supported to auto.
Width is not!
To do some sort of auto get the size of the div you are showing and then set the window with.
In the C# code..
TheDiv.Style["width"] = "200px";
private void setWindowSize(int width, int height)
{
string widthScript = "$('.dialogDiv').dialog('option', 'width', " + width +");";
string heightScript = "$('.dialogDiv').dialog('option', 'height', " + height + ");";
ScriptManager.RegisterStartupScript(this.Page, this.GetType(),
"scriptDOWINDOWSIZE",
"<script type='text/javascript'>"
+ widthScript
+ heightScript +
"</script>", false);
}
Open tmux configuration file with the following command:
vim ~/.tmux.conf
In the configuration file add the following line:
set -g history-limit 5000
Log out and log in again, start a new tmux windows and your limit is 5000 now.
Why would you pass a parameter to a stored procedure that doesn't use it?
It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.
Given the update to the original question, it seems like there is trouble with the context ("this") while passing event handlers. The basics are explained e.g. here http://www.w3schools.com/js/js_function_invocation.asp
A simple working version of your example could read
var doClick = function(event, additionalParameter){
// do stuff with event and this being the triggering event and caller
}
element.addEventListener('click', function(event)
{
var additionalParameter = ...;
doClick.call(this, event, additionalParameter );
}, false);
Given some C/C++ file foo.c
:
> clang -S -emit-llvm foo.c
Produces foo.ll
which is an LLVM IR file.
The -emit-llvm
option can also be passed to the compiler front-end directly, and not the driver by means of -cc1
:
> clang -cc1 foo.c -emit-llvm
Produces foo.ll
with the IR. -cc1
adds some cool options like -ast-print
. Check out -cc1 --help
for more details.
To compile LLVM IR further to assembly, use the llc
tool:
> llc foo.ll
Produces foo.s
with assembly (defaulting to the machine architecture you run it on). llc
is one of the LLVM tools - here is its documentation.
Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.
To create a new branch with a copy of your current state
git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server
Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.
You can just pass it on the command line, as
mvn -DmyVariable=someValue install
[Update] Note that the order of parameters is significant - you need to specify any options before the command(s).[/Update]
Within the POM file, you may refer to system variables (specified on the command line, or in the pom) as ${myVariable}
, and environment variables as ${env.myVariable}
. (Thanks to commenters for the correction.)
OK, so you want to pass your system variable to your tests. If - as I assume - you use the Surefire plugin for testing, the best is to specify the needed system variable(s) within the pom, in your plugins
section, e.g.
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
...
<configuration>
...
<systemPropertyVariables>
<WSNSHELL_HOME>conf</WSNSHELL_HOME>
</systemPropertyVariables>
</configuration>
</plugin>
...
</plugins>
</build>
The following code should do the trick:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="638dp" >
<TextView
android:id="@+id/textView1"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="64dp"
android:text="Email" />
<TextView
android:id="@+id/textView2"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="41dp"
android:text="Password" />
<TextView
android:id="@+id/textView3"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="47dp"
android:text="Confirm Password" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/textView4"
android:inputType="textEmailAddress" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentRight="true"
android:inputType="textPassword" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText2"
android:layout_alignParentRight="true"
android:inputType="textPassword" />
<TextView
android:id="@+id/textView4"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView3"
android:layout_marginTop="42dp"
android:text="Date of Birth" />
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView4" />
<TextView
android:id="@+id/textView5"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/datePicker1"
android:layout_marginTop="60dp"
android:layout_toLeftOf="@+id/datePicker1"
android:text="Gender" />
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView5"
android:layout_alignBottom="@+id/textView5"
android:layout_alignLeft="@+id/editText3"
android:layout_marginLeft="24dp"
android:text="Male" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioButton1"
android:layout_below="@+id/radioButton1"
android:layout_marginTop="14dp"
android:text="Female" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="23dp"
android:layout_toLeftOf="@+id/radioButton2"
android:background="@drawable/rectbutton"
android:text="Sign Up" />
Get the full Android-SDK plus the dependencies at http://developer.android.com/sdk/index.html.
Do have Java installed :)
Set either the width or height to some arbitrarily large number:
https://graph.facebook.com/username_or_id/picture?width=9999
If the width and height are the same number, the photo is cropped to a square.
or you can simply have
$('.date-pick').datePicker().val(new Date()).trigger('change')
This is normal (and has nothing to do with Python) because 8.83 cannot be represented exactly as a binary float, just as 1/3 cannot be represented exactly in decimal (0.333333... ad infinitum).
If you want to ensure absolute precision, you need the decimal
module:
>>> import decimal
>>> a = decimal.Decimal("8.833333333339")
>>> print(round(a,2))
8.83
I needed to read the results returned from a server in JSON where I couldn't guarantee the fields would be present. I'm using class org.json.simple.JSONObject which is derived from HashMap. Here are some helper functions I employed:
public static String getString( final JSONObject response,
final String key )
{ return getString( response, key, "" ); }
public static String getString( final JSONObject response,
final String key, final String defVal )
{ return response.containsKey( key ) ? (String)response.get( key ) : defVal; }
public static long getLong( final JSONObject response,
final String key )
{ return getLong( response, key, 0 ); }
public static long getLong( final JSONObject response,
final String key, final long defVal )
{ return response.containsKey( key ) ? (long)response.get( key ) : defVal; }
public static float getFloat( final JSONObject response,
final String key )
{ return getFloat( response, key, 0.0f ); }
public static float getFloat( final JSONObject response,
final String key, final float defVal )
{ return response.containsKey( key ) ? (float)response.get( key ) : defVal; }
public static List<JSONObject> getList( final JSONObject response,
final String key )
{ return getList( response, key, new ArrayList<JSONObject>() ); }
public static List<JSONObject> getList( final JSONObject response,
final String key, final List<JSONObject> defVal ) {
try { return response.containsKey( key ) ? (List<JSONObject>) response.get( key ) : defVal; }
catch( ClassCastException e ) { return defVal; }
}
Python 3 handles strings a bit different. Originally there was just one type for
strings: str
. When unicode gained traction in the '90s the new unicode
type
was added to handle Unicode without breaking pre-existing code1. This is
effectively the same as str
but with multibyte support.
In Python 3 there are two different types:
bytes
type. This is just a sequence of bytes, Python doesn't know
anything about how to interpret this as characters.str
type. This is also a sequence of bytes, but Python knows how to
interpret those bytes as characters.unicode
type was dropped. str
now supports unicode.In Python 2 implicitly assuming an encoding could cause a lot of problems; you
could end up using the wrong encoding, or the data may not have an encoding at
all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to
guess) is often a lot better and much more in line with the "Python philosophy"
of "explicit is better than implicit".
This change is incompatible with Python 2 as many return values have changed,
leading to subtle problems like this one; it's probably the main reason why
Python 3 adoption has been so slow. Since Python doesn't have static typing2
it's impossible to change this automatically with a script (such as the bundled
2to3
).
str
to bytes
with bytes('h€llo', 'utf-8')
; this should
produce b'H\xe2\x82\xacllo'
. Note how one character was converted to three
bytes.bytes
to str
with b'H\xe2\x82\xacllo'.decode('utf-8')
.Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.
In your specific piece of code, nextline
is of type bytes
, not str
,
reading stdout
and stdin
from subprocess
changed in Python 3 from str
to
bytes
. This is because Python can't be sure which encoding this uses. It
probably uses the same as sys.stdin.encoding
(the encoding of your system),
but it can't be sure.
You need to replace:
sys.stdout.write(nextline)
with:
sys.stdout.write(nextline.decode('utf-8'))
or maybe:
sys.stdout.write(nextline.decode(sys.stdout.encoding))
You will also need to modify if nextline == ''
to if nextline == b''
since:
>>> '' == b''
False
Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.
1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A'
) and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')
). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.
2 Yes, you can use function annotations, but it's a comparatively new feature and little used.
I just encountered the same issue after adding the bin folder to .gitignore, not sure if that caused the issue.
I solved it by going to Project/Properties/Build Path and I removed the scr folder and added it again.
To check configuration files for syntax errors:
# Red Hat-based (Fedora, CentOS) and OSX
httpd -t
# Debian-based (Ubuntu)
apache2ctl -t
# MacOS
apachectl -t
To list all virtual hosts, and their locations:
# Red Hat-based (Fedora, CentOS) and OSX
httpd -S
# Debian-based (Ubuntu)
apache2ctl -S
# MacOS
apachectl -S
You can also use hash-based navigation by including the following in app.module.ts
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
and by adding the following to the @NgModule({ ... })
@NgModule({
...
providers: [
ProductService, {
provide: LocationStrategy, useClass: HashLocationStrategy
}
],
...
})
“HashLocationStrategy—A hash sign (#) is added to the URL, and the URL segment after the hash uniquely identifies the route to be used as a web page fragment. This strategy works with all browsers, including the old ones.”
Excerpt From: Yakov Fain Anton Moiseev. “Angular 2 Development with TypeScript.”
This is the closest thing you can get to a "CONST Dictionary":
public static int GetValueByName(string name)
{
switch (name)
{
case "bob": return 1;
case "billy": return 2;
default: return -1;
}
}
The compiler will be smart enough to build the code as clean as possible.
ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]
sudo apt update && sudo apt upgrade
sudo apt-get install xorg lxde vnc4server lubuntu-desktop
sudo nano /etc/lightdm/lightdm.conf
[SeatDefaults]
allow-guest=false
user-session=LXDE
#user-session=Lubuntu
vncserver
sudo echo "lxpanel & /usr/bin/lxsession -s LXDE &" >> ~/.vnc/xstartup
sudo reboot
ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]
vncserver -geometry 1280x800
net stop <your service> && net start <your service>
No net restart
, unfortunately.
You can cast like this:
return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);
Or like this if you want to be compatible with tsx mode:
return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);
Just remember that this is a compile-time cast, and not a runtime cast.
By using itemStateChanged(ItemListener)
you can track selecting and deselecting checkbox (and do whatever you want based on it):
myCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
//do something...
} else {//checkbox has been deselected
//do something...
};
}
});
Java Swing itemStateChanged docu should help too. By using isSelected()
method you can just test if actual is checkbox selected:
if(myCheckBox.isSelected()){_do_something_if_selected_}
Since Oracle inserted some md5hash in their download links, one cannot automatically assemble a download link for command line.
So I tinkered some nasty bash command line to get the latest jdk download link, download it and directly install via rpm. For all who are interested:
wget -q http://www.oracle.com/technetwork/java/javase/downloads/index.html -O ./index.html && grep -Eoi ']+>' index.html | grep -Eoi '/technetwork/java/javase/downloads/jdk8-downloads-[0-9]+.html' | (head -n 1) | awk '{print "http://www.oracle.com"$1}' | xargs wget --no-cookies --header "Cookie: gpw_e24=xxx; oraclelicense=accept-securebackup-cookie;" -O index.html -q && grep -Eoi '"filepath":"[^"]+jdk-8u[0-9]+-linux-x64.rpm"' index.html | grep -Eoi 'http:[^"]+' | xargs wget --no-cookies --header "Cookie: gpw_e24=xxx; oraclelicense=accept-securebackup-cookie;" -q -O ./jdk8.rpm && sudo rpm -i ./jdk8.rpm
The bold part should be replaced by the package of your liking.
What about trying the easiest and probably most effective approach? The method normalize() removes all the rightmost trailing zeros.
from decimal import Decimal
print (Decimal('0.001000').normalize())
# Result: 0.001
Works in Python 2 and Python 3.
-- Updated --
The only problem as @BobStein-VisiBone pointed out, is that numbers like 10, 100, 1000... will be displayed in exponential representation. This can be easily fixed using the following function instead:
from decimal import Decimal
def format_float(f):
d = Decimal(str(f));
return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
If you are talking about tag stripping, it is relatively straight forward if you don't have to worry about things like <script>
tags. If all you need to do is display the text without the tags you can accomplish that with a regular expression:
<[^>]*>
If you do have to worry about <script>
tags and the like then you'll need something a bit more powerful then regular expressions because you need to track state, omething more like a Context Free Grammar (CFG). Althought you might be able to accomplish it with 'Left To Right' or non-greedy matching.
If you can use regular expressions there are many web pages out there with good info:
If you need the more complex behaviour of a CFG I would suggest using a third party tool, unfortunately I don't know of a good one to recommend.
In Python, Storing a bare python list as a numpy.array and then saving it out to file, then loading it back, and converting it back to a list takes some conversion tricks. The confusion is because python lists are not at all the same thing as numpy.arrays:
import numpy as np
foods = ['grape', 'cherry', 'mango']
filename = "./outfile.dat.npy"
np.save(filename, np.array(foods))
z = np.load(filename).tolist()
print("z is: " + str(z))
This prints:
z is: ['grape', 'cherry', 'mango']
Which is stored on disk as the filename: outfile.dat.npy
The important methods here are the tolist()
and np.array(...)
conversion functions.
Macmade's solution doesn't work for me anymore on my Jekyll instance on Github Pages anymore but I found this solution on an issue for the kramdown github repo. For OP's example it would look like this:
1. item 1
2. item 2
```
Code block
```
{:start="3"}
3. item 3
Solved my issues handily.
Another reason may be that in very old data access libraries on Windows such as RDO and ADO (COM version not ADO.NET) you had to call a special method, GetChunk, to get data from a column with more than 255 chars. If you limited a varchar column to 255, this extra code wasn't necessary.
Specifically in dotnet core 2.2 with SignalR you must change
.WithOrigins("http://localhost:3000")
or
.SetIsOriginAllowed(isOriginAllowed: _ => true) //for all origins
instead .AllowAnyOrigin()
with .AllowCredentials()
https://trailheadtechnology.com/breaking-change-in-aspnetcore-2-2-for-signalr-and-cors/
You can store favourites with no associated menu in a separate table:
CREATE TABLE FavoriteWithoutMenu
(
FavoriteWithoutMenuId uuid NOT NULL, --Primary key
UserId uuid NOT NULL,
RecipeId uuid NOT NULL,
UNIQUE KEY (UserId, RecipeId)
)
Oracle normally requires double-quotes to delimit the name of identifiers in SQL statements, e.g.
SELECT "MyColumn" AS "MyColAlias"
FROM "MyTable" "Alias"
WHERE "ThisCol" = 'That Value';
However, it graciously allows omitting the double-quotes, in which case it quietly converts the identifier to uppercase:
SELECT MyColumn AS MyColAlias
FROM MyTable Alias
WHERE ThisCol = 'That Value';
gets internally converted to something like:
SELECT "ALIAS" . "MYCOLUMN" AS "MYCOLALIAS"
FROM "THEUSER" . "MYTABLE" "ALIAS"
WHERE "ALIAS" . "THISCOL" = 'That Value';
No, it will not be evaluated. And this is very useful. For example, if you need to test whether a String is not null or empty, you can write:
if (str != null && !str.isEmpty()) {
doSomethingWith(str.charAt(0));
}
or, the other way around
if (str == null || str.isEmpty()) {
complainAboutUnusableString();
} else {
doSomethingWith(str.charAt(0));
}
If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.
You should check API
for these questions.
You can use remove methods.
a.remove(1);
OR
a.remove("acbd");
If the data in your database is POSTED from HTML form TextArea controls, different browsers use different New Line characters:
Firefox separates lines with CHR(10) only
Internet Explorer separates lines with CHR(13) + CHR(10)
Apple (pre-OSX) separates lines with CHR(13) only
So you may need something like:
set col_name = replace(replace(col_name, CHR(13), ''), CHR(10), '')
A of couple things that need to happen...
The view controller needs to extend the type UITableViewDelegate
The view controller needs to include the didSelectRowAt
function.
The table view must have the view controller assigned as its delegate.
Below is one place where assigning the delegate could take place (within the view controller).
override func loadView() {
tableView.dataSource = self
tableView.delegate = self
view = tableView
}
And a simple implementation of the didSelectRowAt
function.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("row: \(indexPath.row)")
}
I think you're looking for export
- though I could be wrong.. I've never played with tcsh before. Use the following syntax:
export VARIABLE=value
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
You can do:
setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));
At first line of the Jframe class constructor, that works fine for me
You can also see this information by going into Admin Console -> Realm Settings -> Clicking the hyperlink on the Endpoints field.
If you run the command cmd
, it will update all system variables for that command window.
std::atan2
allows calculating the arctangent of all four quadrants. std::atan
only allows calculating from quadrants 1 and 4.
Simple
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" onclick="event.preventDefault();document.getElementById('your-form').submit();">Save changes</button>
You can pass PHP arrays to JavaScript using json_encode
PHP function.
<?php
$phpArray = array(
0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri",
5 => "Sat",
6 => "Sun",
)
?>
<script type="text/javascript">
var jArray = <?php echo json_encode($phpArray); ?>;
for(var i=0; i<jArray.length; i++){
alert(jArray[i]);
}
</script>
Try This,
alter session set "_convert_set_to_join"= true;
The other alternative is to rewrite the SQL query manually [replacing the minus operator with a NOT IN subquery] evidences about 30% improvement in execution time .
select *
from A
where (col1,col2,?) not in
(select col1,col2,? from B)
union all
select * from B
where (col1,col2,?) not in
(select col1,col2,? from A);
I have referred from this post click here
For all who said that Garry Tan solution converting incorrect from RGB to HSL and back. It because he left out fraction part of number in his code. I corrected his code (javascript). Sorry for link on russian languadge, but on english absent - HSL-wiki
function toHsl(r, g, b)
{
r /= 255.0;
g /= 255.0;
b /= 255.0;
var max = Math.max(r, g, b);
var min = Math.min(r, g, b);
var h, s, l = (max + min) / 2.0;
if(max == min)
{
h = s = 0;
}
else
{
var d = max - min;
s = (l > 0.5 ? d / (2.0 - max - min) : d / (max + min));
if(max == r && g >= b)
{
h = 1.0472 * (g - b) / d ;
}
else if(max == r && g < b)
{
h = 1.0472 * (g - b) / d + 6.2832;
}
else if(max == g)
{
h = 1.0472 * (b - r) / d + 2.0944;
}
else if(max == b)
{
h = 1.0472 * (r - g) / d + 4.1888;
}
}
return {
str: 'hsl(' + parseInt(h / 6.2832 * 360.0 + 0.5) + ',' + parseInt(s * 100.0 + 0.5) + '%,' + parseInt(l * 100.0 + 0.5) + '%)',
obj: { h: parseInt(h / 6.2832 * 360.0 + 0.5), s: parseInt(s * 100.0 + 0.5), l: parseInt(l * 100.0 + 0.5) }
};
};
As mentioned in other answers, the exception is being thrown because each call to registerReceiver
is not being matched by exactly one call to unregisterReceiver
. Why not?
An Activity
does not always have a matching onDestroy
call for every onCreate
call. If the system runs out of memory, your app is evicted without calling onDestroy
.
The correct place to put a registerReceiver
call is in the onResume
call, and unregisterReceiver
in onPause
. This pair of calls is always matched. See the Activity lifecycle diagram for more details.
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Your code would change to:
SharedPreferences mPref
IntentFilter mFilter;
@Override
public void onCreate(){
super.onCreate();
mPref = PreferenceManager.getDefaultSharedPreferences(this);
mFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
}
@Override
public void onResume() {
registerReceiver(batteryNotifyReceiver,mFilter);
mPref.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause(){
unregisterReceiver(batteryNotifyReceiver, mFilter);
mPref.unregisterOnSharedPreferenceChangeListener(this);
}
Your code seems right, check if you have fopen wrappers enabled (allow_url_fopen = On
on php.ini)
Also, as mentioned by other answers, you should provide a properly encoded URI or encode it using urlencode() function. You should also check if there is any error fetching the XML string and if there is any parsing error, which you can output using libxml_get_errors() as follows:
<?php
if (($response_xml_data = file_get_contents($map_url))===false){
echo "Error fetching XML\n";
} else {
libxml_use_internal_errors(true);
$data = simplexml_load_string($response_xml_data);
if (!$data) {
echo "Error loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
} else {
print_r($data);
}
}
?>
If the problem is you can't fetch the XML code maybe it's because you need to include some custom headers in your request, check how to use stream_context_create() to create a custom stream context for use when calling file_get_contents()
on example 4 at http://php.net/manual/en/function.file-get-contents.php
This worked for me:
let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
...
The key was adding in the URLSessionDataTask
type declaration.
@Chris Doggett makes perfect sense.
Although, I found one funny trick on lvsys.com, and it actually works on firefox and chrome. Just put this comment anywhere you want the page-break to be inserted. You can also replace the <p>
tag with any block element.
<p><!-- pagebreak --></p>
I was facing the same problem and the second method proposed in the accepted answer, as noted in the comments, can be problematic when dealing with foreign keys.
My workaround is to export the database to a sql file making sure that the INSERT statements include column names. I do it using DB Browser for SQLite which has an handy feature for that. After that you just have to edit the create table statement and insert the new column where you want it and recreate the db.
In *nix like systems is just something along the lines of
cat db.sql | sqlite3 database.db
I don't know how feasible this is with very big databases, but it worked in my case.
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
<?php
$test1='2010-04-19 18:31:27';
echo date('d/m/Y',strtotime($test1));
?>
try this
Put its content in a span
which is relatively positioned, then you can control the space by the left
property of the span
.
li span {_x000D_
position: relative;_x000D_
left: -10px;_x000D_
}
_x000D_
<ul>_x000D_
<li><span>item 1</span></li>_x000D_
<li><span>item 2</span></li>_x000D_
<li><span>item 3</span></li>_x000D_
</ul>
_x000D_
You can achieve this by using cssSelector
// Use of List web elements:
String cssSelectorOfLoginButton="input[type='button'][id='login']";
//****Add cssSelector of your 1st webelement
//List<WebElement> button
=driver.findElements(By.cssSelector(cssSelectorOfLoginButton));
button.get(0).click();
I hope this work for you
http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html
This is the greatest thing ever for learning VIM.
I understand you want to download an older version via the BitBucket web interface without using a Mercurial/Git client.
Check this related question. On the comments, someone says that there is no way to do that. Fortunately, that's not entirely true.
By navigating on BitBucket project pages, I found no link to download an arbitrary version. There are links to download specific tags, in the format:
https://bitbucket.org/owner/repository/get/v0.1.2.tar.gz
But by tweaking a bit the url above, changing the tag name by the commit hash, like:
https://bitbucket.org/owner/repository/get/A0B1C2D.tar.gz
You can actually download a specific version.
As mentioned by Rakka Rage in a comment, replacing .tar.gz
by .zip
works too.
I found that in my code when I used a ration or percentage for line-height line-height;1.5;
My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px;
so that I could predict exactly how many pixels each page would take with a given number of lines.
The answer of @DanielPlaisted before generally works, but the generic method must be public or one must use BindingFlags.NonPublic | BindingFlags.Instance
! Couldn't post it as a comment for lack of reputation.
Execute this code on a good server which will provide you the complete rights for PUBLIC role. Copy the output and paste to the server with the issue. Execute. Try logging in again. It fixed our problem.
SELECT SDP.state_desc ,
SDP.permission_name ,
SSU.[name] AS "Schema" ,
SSO.[name] ,
SSO.[type]
FROM sys.sysobjects SSO
INNER JOIN sys.database_permissions SDP ON SSO.id = SDP.major_id
INNER JOIN sys.sysusers SSU ON SSO.uid = SSU.uid
ORDER BY SSU.[name] ,
SSO.[name]
In function post():
todo.author = users.get_current_user()
So, to get str(todo.author), you need str(users.get_current_user()). What is returned by get_current_user() function ?
If it is an object, check does it contain a str()" function?
I think the error lies there.
I've just done this for a project, and achieved it by using the h6 tag which I wasn't using for anything else:
in html code:
<h6><img alt="small drawing" src="../Images/image1.jpg" width="50%"/> <img alt="small drawing" src="../Images/image2.jpg" width="50%"/><br/>Optional caption text</h6>
The space between the image tags puts a vertical gap between the images. The width argument in each img tag is optional, but it neatly sizes the images to fill the width of the page. Notice that each image must be set to take up only 50% of the width. (Or 33% if you're using 3 images.) The width argument must come after the alt and src arguments or it won't work.
in css code:
/* h6: set presentation of images */
h6
{
font-family: "Franklin Gothic Demi", serif;
font-size: 1.0em;
font-weight: normal;
line-height: 1.25em;
text-align: center;
}
The text items set the look of the caption text, and the text-align property centers both the images and the caption text.
Updating the 'phones' function in Justen's answer using AngularJS 1.1.5 syntax.
Original:
phones: function($q, Phone) {
var deferred = $q.defer();
Phone.query(function(phones) {
deferred.resolve(phones);
});
return deferred.promise;
}
Updated:
phones: function(Phone) {
return Phone.query().$promise;
}
Much shorter thanks to the Angular team and contributors. :)
This is also the answer of Maximilian Hoffmann. Apparently that commit made it into 1.1.5.
Yes, I would either use the <pre>
tag or use ng-bind-html-unsafe
http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe (use ng-bind-html if you are using 1.2+) after using .replace()
to change /n
to <br />
The simplest way of installing SBT on ubuntu is the deb
package provided by Typesafe.
Run the following shell commands:
wget http://apt.typesafe.com/repo-deb-build-0002.deb
sudo dpkg -i repo-deb-build-0002.deb
sudo apt-get update
sudo apt-get install sbt
And you're done !
DBMS : Data Base Management System ..... for storage of data and efficient retrieval of data. Eg: Foxpro
1)A DBMS has to be persistent (it should be accessible when the program created the data donot exist or even the application that created the data restarted).
2) DBMS has to provide some uniform methods independent of a specific application for accessing the information that is stored.
3)DBMS does not impose any constraints or security with regard to data manipulation. It is user or the programmer responsibility to ensure the ACID PROPERTY of the database
4)In DBMS Normalization process will not be present
5)In dbms no relationship concept
6)It supports Single User only
7)It treats Data as Files internally
8)It supports 3 rules of E.F.CODD out off 12 rules
9)It requires low Software and Hardware Requirements.
FoxPro, IMS are Examples
RDBMS: Relational Data Base Management System
.....the database which is used by relations(tables) to acquire information retrieval Eg: oracle, SQL..,
1)RDBMS is based on relational model, in which data is represented in the form of relations, with enforced relationships between the tables.
2)RDBMS defines the integrity constraint for the purpose of holding ACID PROPERTY.
3)In RDBMS, normalization process will be present to check the database table cosistency
4)RDBMS helps in recovery of the database in case of loss of data
5)It is used to establish the relationship concept between two database objects, i.e, tables
6)It supports multiple users
7)It treats data as Tables internally
8)It supports minimum 6 rules of E.F.CODD
9)It requires High software and hardware
If you want to do it via javascript rather than CSS you can use:
var link = document.getElementById('nav-ask');
link.style.display = 'none'; //or
link.style.visibility = 'hidden';
depending on what you want to do.
To update entries other than appsettings
, simply use XmlDocument
.
public static void UpdateAppConfig(string tagName, string attributeName, string value)
{
var doc = new XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var tags = doc.GetElementsByTagName(tagName);
foreach (XmlNode item in tags)
{
var attribute = item.Attributes[attributeName];
if (!ReferenceEquals(null, attribute))
attribute.Value = value;
}
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
This is how you call it:
Utility.UpdateAppConfig("endpoint", "address", "http://localhost:19092/NotificationSvc/Notification.svc");
Utility.UpdateAppConfig("network", "host", "abc.com.au");
This method can be improved to cater for appSettings values as well.
If you just use rm
, you will need to follow it up with git add <fileRemoved>
. git rm
does this in one step.
You can also use git rm --cached
which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.
I use a few methods depending. In the same stylesheet i use: @media (max-width: 450px), or for separate make sure you have the link in the header correctly. I had a look at your fixmeup and you have a confusing array of links to css. It acts as you say also on HTC desire S.
The most correct answer to the question is:
String mysz2 = mysz.replaceAll("\\s","");
I just adapted this code from the other answers. I'm posting it because besides being exactly what the question requested, it also demonstrates that the result is returned as a new string, the original string is not modified as some of the answers sort of imply.
(Experienced Java developers might say "of course, you can't actually modify a String", but the target audience for this question may well not know this.)
In my case I had a file built by external dependency (xsd2code) and somehow its designer.cs files were not processed by VS correctly. Creating a new file in Visual Studio and pasting the code in it did the trick for me.
I'm providing an answer to this question, because I do not see any native, recursive implementations here that resolve the problem of DOM
elements.
The problem there is that <element>
has parent
and child
attributes, that link to other elements with parent
and child
values, which point back to the original <element>
, causing either an infinite recursive or cyclic redundancy.
If your object is something safe and simple like
{
'123':456
}
...then any other answer here will probably work.
But if you have...
{
'123':<reactJSComponent>,
'456':document.createElement('div'),
}
...then you need something like this:
// cloneVariable() : Clone variable, return null for elements or components.
var cloneVariable = function (args) {
const variable = args.variable;
if(variable === null) {
return null;
}
if(typeof(variable) === 'object') {
if(variable instanceof HTMLElement || variable.nodeType > 0) {
return null;
}
if(Array.isArray(variable)) {
var arrayclone = [];
variable.forEach((element) => {
arrayclone.push(cloneVariable({'variable':element}));
});
return arrayclone;
}
var objectclone = {};
Object.keys(variable).forEach((field) => {
objectclone[field] = cloneVariable({'variable':variable[field]});
});
return objectclone;
}
return variable;
}
Folding has been rolled out and is now implemented since Visual Studio Code version 0.10.11. There are these keyboard shortcuts available:
Fold folds the innermost uncollapsed region at the cursor:
Unfold unfolds the collapsed region at the cursor:
Fold All folds all regions in the editor:
Unfold All unfolds all regions in the editor:
References: https://code.visualstudio.com/docs/getstarted/keybindings
xsl:apply-templates
is usually (but not necessarily) used to process all or a subset of children of the current node with all applicable templates. This supports the recursiveness of XSLT application which is matching the (possible) recursiveness of the processed XML.
xsl:call-template
on the other hand is much more like a normal function call. You execute exactly one (named) template, usually with one or more parameters.
So I use xsl:apply-templates
if I want to intercept the processing of an interesting node and (usually) inject something into the output stream. A typical (simplified) example would be
<xsl:template match="foo">
<bar>
<xsl:apply-templates/>
</bar>
</xsl:template>
whereas with xsl:call-template
I typically solve problems like adding the text of some subnodes together, transforming select nodesets into text or other nodesets and the like - anything you would write a specialized, reusable function for.
As an additional remark to your specific question text:
<xsl:call-template name="nodes"/>
This calls a template which is named 'nodes':
<xsl:template name="nodes">...</xsl:template>
This is a different semantic than:
<xsl:apply-templates select="nodes"/>
...which applies all templates to all children of your current XML node whose name is 'nodes'.
you can follow BaseAdapter
and create your custome Xml
file and bind it with you BaseAdpter
and populate it with Listview
see here need to change xml
file as Require.
YOU MUST select these options
but if you want to make UITableView
not highlighted on clicking then you should make changes in UITableViewCell
properties.
Choose None option for Selection just like below
Javascript in a browser only really has a couple of effective scopes: function scope and global scope.
If a variable isn't in function scope, it's in global scope. And global variables are generally bad, so this is a construct to keep a library's variables to itself.
In CMD, type:
pip freeze
And it will show you a list of all the modules installed including the version number.
Output:
aiohttp==1.1.4
async-timeout==1.1.0
cx-Freeze==4.3.4
Django==1.9.2
django-allauth==0.24.1
django-cors-headers==1.2.2
django-crispy-forms==1.6.0
django-robots==2.0
djangorestframework==3.3.2
easygui==0.98.0
future==0.16.0
httpie==0.9.6
matplotlib==1.5.3
multidict==2.1.2
numpy==1.11.2
oauthlib==1.0.3
pandas==0.19.1
pefile==2016.3.28
pygame==1.9.2b1
Pygments==2.1.3
PyInstaller==3.2
pyparsing==2.1.10
pypiwin32==219
PyQt5==5.7
pytz==2016.7
requests==2.9.1
requests-oauthlib==0.6
six==1.10.0
sympy==1.0
virtualenv==15.0.3
xlrd==1.0.0
yarl==0.7.0
You can copy your .classpath
and .project
files to the root of the new project directory and then choose 'Import...' from the file menu, and select 'General/Existing Projects into Workspace.' In the resulting dialog, locate the root of the new project directory and finish. Make sure that you have deleted the old project from the work space before importing.
The first option is the good one - with indentation included. It is in python style - provides readability for the code.
To display it properly:
print string.lstrip()
Another potential "solution" is to use the window
object. It avoids the reference error problem when in a browser.
if (window.x) {
alert('x exists and is truthy');
} else {
alert('x does not exist, or exists and is falsy');
}
Use raw:
<%=raw @str >
But as @jmort253 correctly says, consider where the HTML really belongs.
I have a solution for this but not sure on the reason why this would be different from one environment to the other - although one big difference between the two environments is WSS svc pack 1 was installed on the environment where the error was occurring.
To fix this issue I got a good clue from this link - http://silverlight.net/forums/t/22787.aspx ie to "please check the Xml Schema of your service" and "the sequence in the schema is sorted alphabetically"
Looking at the wsdl generated I noticed that for the serialized class that was causing the error, the properties of this class were not visible in the wsdl.
The Definition of the class had private setters for most of the properties, but not for CustomFields property ie..
[Serializable]
public class FileMetaDataDto
{
.
. a constructor... etc and several other properties edited for brevity
.
public int Id { get; private set; }
public string Version { get; private set; }
public List<MetaDataValueDto> CustomFields { get; set; }
}
On removing private from the setter and redeploying the service then looking at the wsdl again, these properties were now visible, and the original error was fixed.
So the wsdl before update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
</s:sequence>
</s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
</s:sequence>
</s:complexType>
The wsdl after update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
</s:sequence>
</s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="Id" type="s:int" />
<s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Title" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="ContentType" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Icon" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="ModifiedBy" type="s:string" />
<s:element minOccurs="1" maxOccurs="1" name="ModifiedDateTime" type="s:dateTime" />
<s:element minOccurs="1" maxOccurs="1" name="FileSizeBytes" type="s:int" />
<s:element minOccurs="0" maxOccurs="1" name="Url" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="RelativeFolderPath" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="DisplayVersion" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Version" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
<s:element minOccurs="0" maxOccurs="1" name="CheckoutBy" type="s:string" />
</s:sequence>
</s:complexType>
You can use timezone.now()
for created and auto_now
for modified:
from django.utils import timezone
class User(models.Model):
created = models.DateTimeField(default=timezone.now())
modified = models.DateTimeField(auto_now=True)
If you are using a custom primary key instead of the default auto- increment int
, auto_now_add
will lead to a bug.
Here is the code of Django's default DateTimeField.pre_save withauto_now
and auto_now_add
:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = timezone.now()
setattr(model_instance, self.attname, value)
return value
else:
return super(DateTimeField, self).pre_save(model_instance, add)
I am not sure what the parameter add
is. I hope it will some thing like:
add = True if getattr(model_instance, 'id') else False
The new record will not have attr
id
, sogetattr(model_instance, 'id')
will return False will lead to not setting any value in the field.
there is really a problem in 1.8.6. and it's ok after this edition
in 1.8.6,you can add this:
requre 'jcode'
There are a bunch of reasons here: http://macresearch.org/difference-between-alloc-init-and-new
Some selected ones are:
new
doesn't support custom initializers (like initWithString
)alloc-init
is more explicit than new
General opinion seems to be that you should use whatever you're comfortable with.
You can use "<pre>(.*?)</pre>"
, (replacing pre with whatever text you want) and extract the first group (for more specific instructions specify a language) but this assumes the simplistic notion that you have very simple and valid HTML.
As other commenters have suggested, if you're doing something complex, use a HTML parser.
background
will supercede all previous background-color
, background-image
, etc. specifications. It's basically a shorthand, but a reset as well.
I will sometimes use it to overwrite previous background
specifications in template customizations, where I would want the following:
background: white url(images/image1.jpg) top left repeat;
to be the following:
background: black;
So, all parameters (background-image
, background-position
, background-repeat
) will reset to their default values.
Open the Command Prompt and type in the following:
FOR /L %i IN (1,1,254) DO ping -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt
Change 192.168.10 to match you own network.
By using -n 1 you are asking for only 1 packet to be sent to each computer instead of the usual 4 packets.
The above command will ping all IP Addresses on the 192.168.10.0 network and create a text document in the C:\ drive called ipaddresses.txt. This text document should only contain IP Addresses that replied to the ping request.
Although it will take quite a bit longer to complete, you can also resolve the IP Addresses to HOST names by simply adding -a to the ping command.
FOR /L %i IN (1,1,254) DO ping -a -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt
This is from Here
Hope this helps
There is an interesting project on github called Excel Builder (.js)
that offers a client-side way of downloading Excel xlsx files and includes options for formatting the Excel spreadsheet.
https://github.com/stephenliberty/excel-builder.js
You may encounter both browser and Excel compatibility issues using this library, but under the right conditions, it may be quite useful.
Another github project with less Excel options but less worries about Excel compatibility issues can be found here: ExcellentExport.js
https://github.com/jmaister/excellentexport
If you are using AngularJS, there is ng-csv:
a "Simple directive that turns arrays and objects into downloadable CSV files".
best solution: from jQuery v1.6 you can use prop() to add a property
$('#someid').prop('disabled', true);
to remove it, use removeProp()
$('#someid').removeProp('disabled');
Also note that the .removeProp() method should not be used to set these properties to false. Once a native property is removed, it cannot be added again. See .removeProp() for more information.
The issue with most of the other answers is that they use Distinct
, GroupBy
or ToLookup
, which creates an extra Dictionary under the hood. Equally ToUpper creates extra string.
This is what I did, which is an almost an exact copy of Microsoft's code except for one change:
public static Dictionary<TKey, TSource> ToDictionaryIgnoreDup<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer = null) =>
source.ToDictionaryIgnoreDup(keySelector, i => i, comparer);
public static Dictionary<TKey, TElement> ToDictionaryIgnoreDup<TSource, TKey, TElement>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer = null)
{
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
if (elementSelector == null)
throw new ArgumentNullException(nameof(elementSelector));
var d = new Dictionary<TKey, TElement>(comparer ?? EqualityComparer<TKey>.Default);
foreach (var element in source)
d[keySelector(element)] = elementSelector(element);
return d;
}
Because a set on the indexer causes it to add the key, it will not throw, and will also do only one key lookup. You can also give it an IEqualityComparer
, for example StringComparer.OrdinalIgnoreCase
So you want to remove dangling images? Am I correct?
systemctl enable docker-container-cleanup.timer
systemctl start docker-container-cleanup.timer
systemctl enable docker-image-cleanup.timer
systemctl start docker-image-cleanup.timer
https://github.com/larsks/docker-tools/tree/master/docker-maintenance-units
This is what I used.
$('#foo').popover({
placement : 'bottom',
title : 'Title',
content : '<div id="popOverBox"><img src="http://i.telegraph.co.uk/multimedia/archive/01515/alGore_1515233c.jpg" /></div>'
});
and for the HTML
<b id="foo" rel="popover">text goes here</b>
To fix this, I did a reinstall of xcode (This also presented user agreement). I used the following command:
xcode-select --install
There is actually another way of looking at this problem, not as a number problem, but a Unary problem, starting with the base character of Roman numbers, "I". So we represent the number with just I, and then we replace the characters in ascending value of the roman characters.
public String getRomanNumber(int number) {
return join("", nCopies(number, "I"))
.replace("IIIII", "V")
.replace("IIII", "IV")
.replace("VV", "X")
.replace("VIV", "IX")
.replace("XXXXX", "L")
.replace("XXXX", "XL")
.replace("LL", "C")
.replace("LXL", "XC")
.replace("CCCCC", "D")
.replace("CCCC", "CD")
.replace("DD", "M")
.replace("DCD", "CM");
}
I especially like this method of solving this problem rather than using a lot of ifs and while loops, or table lookups. It is also actually a quit intuitive solution when you thinking of the problem not as a number problem.
in my case this error occured if i use table without header
<thead>
<tr>
<th>example</th>
</tr>
</thead>
Float them left. In Chrome, at least, you don't need to have a wrapper, id="container"
, in LucaM's example.
This functionality just what you need. http://docs.angularjs.org/api/ng.directive:input.number
EDIT:
You can wrap the jquery plugin into directive. I created an example here: http://jsfiddle.net/anazimok/jTJCF/
HTML:
<div ng-app="myApp">
<div>
<input type="text" min="0" max="99" number-mask="" ng-model="message">
<button ng-click="handleClick()">Broadcast</button>
</div>
</div>
CSS:
.ng-invalid {
border: 1px solid red;
}
JS:
// declare a module
var app = angular.module('myApp', []);
app.directive('numberMask', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).numeric();
}
}
});
If your HTML is well-formed, you can easily employ an XML parser to do the job for you... If you're only reading, SAX would be ideal.
This is the answer if someone want to know
if (Date.now() >= exp * 1000) {
return false;
}
ON [PRIMARY] will create the structures on the "Primary" filegroup. In this case the primary key index and the table will be placed on the "Primary" filegroup within the database.
If the sent_at field is not there when its not set then:
db.emails.count({sent_at: {$exists: false}})
If its there and null, or not there at all:
db.emails.count({sent_at: null})
Use: str.capitalize()
to convert first letter of the string (contained in variable str) to a capital letter and returns the entire string.
Example: Command: "hello".capitalize() Output: Hello
The best way to do this in Angular and keep the code simple is to use this project.
https://www.npmjs.com/package/ngx-clipboard
<fa-icon icon="copy" ngbTooltip="Copy to Clipboard" aria-hidden="true"
ngxClipboard [cbContent]="target value here"
(cbOnSuccess)="copied($event)"></fa-icon>
I also faced this issue and after debugging the culprit was found. In my case it was the "space" character right before the https
This should work fine for you.
Write this code in the Page_Load
event of the page.
string ID = Request.QueryString["id"].ToString();
Response.Redirect("http://www.example.com/rendernews.php?id=" + ID);
Here's two options. I prefer the navigationAlt option since it involves less work in the end:
<html>_x000D_
_x000D_
<head>_x000D_
<style type="text/css">_x000D_
#navigation li {_x000D_
color: green;_x000D_
}_x000D_
#navigation li .navigationLevel2 {_x000D_
color: red;_x000D_
}_x000D_
#navigationAlt {_x000D_
color: green;_x000D_
}_x000D_
#navigationAlt ul {_x000D_
color: red;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<ul id="navigation">_x000D_
<li>Level 1 item_x000D_
<ul>_x000D_
<li class="navigationLevel2">Level 2 item</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
<ul id="navigationAlt">_x000D_
<li>Level 1 item_x000D_
<ul>_x000D_
<li>Level 2 item</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
In terms of bytecode, in
saves a LOAD_ATTR
and replaces a CALL_FUNCTION
with a COMPARE_OP
.
>>> dis.dis(indict)
2 0 LOAD_GLOBAL 0 (name)
3 LOAD_GLOBAL 1 (d)
6 COMPARE_OP 6 (in)
9 POP_TOP
>>> dis.dis(haskey)
2 0 LOAD_GLOBAL 0 (d)
3 LOAD_ATTR 1 (haskey)
6 LOAD_GLOBAL 2 (name)
9 CALL_FUNCTION 1
12 POP_TOP
My feelings are that in
is much more readable and is to be preferred in every case that I can think of.
In terms of performance, the timing reflects the opcode
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
10000000 loops, best of 3: 0.11 usec per loop
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
1000000 loops, best of 3: 0.205 usec per loop
in
is almost twice as fast.
Add the following 6 lines to any class to make it "Singleton".
class MySingleton
{
private constructor(){ /* ... */}
private static _instance: MySingleton;
public static getInstance(): MySingleton
{
return this._instance || (this._instance = new this());
};
}
var test = MySingleton.getInstance(); // will create the first instance
var test2 = MySingleton.getInstance(); // will return the first instance
alert(test === test2); // true
[Edit]: Use Alex answer if you prefer to get the instance through a property rather a method.
An easy way to write it is with if_na
from hablar
:
library(dplyr)
library(hablar)
df <- tibble(a = c(1, 2, 3, NA, 5, 6, 8))
df %>%
mutate(a = if_na(a, 0))
which returns:
a
<dbl>
1 1
2 2
3 3
4 0
5 5
6 6
7 8
Andrew had a great response but I wanted to tweek it a little. The way this is different is that I like my ModelViews to not have overhead data in them. Just the data for the object. It seem that ViewData fits the bill for over head data, but of course I'm new at this. I suggest doing something like this.
Controller
virtual public ActionResult DisplaySomeWidget(int id)
{
SomeModelView returnData = someDataMapper.getbyid(1);
var serializer = new JavaScriptSerializer();
ViewData["JSON"] = serializer.Serialize(returnData);
return View(myview, returnData);
}
View
//create base js object;
var myWidget= new Widget(); //Widget is a class with a public member variable called data.
myWidget.data= <%= ViewData["JSON"] %>;
What This does for you is it gives you the same data in your JSON as in your ModelView so you can potentially return the JSON back to your controller and it would have all the parts. This is similar to just requesting it via a JSONRequest however it requires one less call so it saves you that overhead. BTW this is funky for Dates but that seems like another thread.
Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.
a = {}
k = 0
while k < 10:
<dynamically create key>
key = ...
<calculate value>
value = ...
a[key] = value
k += 1
There are also some interesting data structures in the new 'collections' module that might be applicable:
The issue for me was that I did not have an account added to Sourcetree.
Adding an account allowed me to push to my repo:
Tools > Options > Authentication > Add > Refresh OAuth Token
There is no reason to do that. In fact, I would choose to combine declaration and initialization as in
final Boolean isMatch = email1.equals (email2);
using the final
keyword so you can't change it (accidentally) afterwards anymore either.
include() needs a full file path, relative to the file system's root directory.
This should work:
include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");
I had this issue due to a network change after I opened the emulator. If you change your WiFi after you start the emulator, you only need to restart the emulator to get internet access
First you must test the query list size; here a example:
long count;
if (query.list().size() > 0)
count=(long) criteria.list().get(0);
else
count=0;
return count;
If you want to execute a function when something is done. One of a good solution is to listen to events.
For example, I'll implement a Dispatcher
, a DispatcherEvent
class with ES6,then:
let Notification = new Dispatcher()
Notification.on('Load data success', loadSuccessCallback)
const loadSuccessCallback = (data) =>{
...
}
//trigger a event whenever you got data by
Notification.dispatch('Load data success')
Dispatcher:
class Dispatcher{
constructor(){
this.events = {}
}
dispatch(eventName, data){
const event = this.events[eventName]
if(event){
event.fire(data)
}
}
//start listen event
on(eventName, callback){
let event = this.events[eventName]
if(!event){
event = new DispatcherEvent(eventName)
this.events[eventName] = event
}
event.registerCallback(callback)
}
//stop listen event
off(eventName, callback){
const event = this.events[eventName]
if(event){
delete this.events[eventName]
}
}
}
DispatcherEvent:
class DispatcherEvent{
constructor(eventName){
this.eventName = eventName
this.callbacks = []
}
registerCallback(callback){
this.callbacks.push(callback)
}
fire(data){
this.callbacks.forEach((callback=>{
callback(data)
}))
}
}
Happy coding!
p/s: My code is missing handle some error exceptions
Same applies for guard statements. The same error message lead me to this post and answer (thanks @nhgrif).
The code: Print the last name of the person only if the middle name is less than four characters.
func greetByMiddleName(name: (first: String, middle: String?, last: String?)) {
guard let Name = name.last where name.middle?.characters.count < 4 else {
print("Hi there)")
return
}
print("Hey \(Name)!")
}
Until I declared last as an optional parameter I was seeing the same error.
Enter
git log .
from the specific directory, it also gives commits in that directory.
You can use addEventListener
to pass this
to a JavaScript function.
HTML
<button id="button">Year</button>
JavaScript
(function () {
var btn = document.getElementById('button');
btn.addEventListener('click', function () {
Date('#year');
}, false);
})();
function Data(string)
{
$('.filter').removeClass('active');
$(this).parent().addClass('active') ;
}
Here is a more generic solution based on @rindeal solution which does not work on MacOS/BSD (/r
expects a file):
cat << DOC > input.txt
abc
cdef
line
DOC
$ cat << EOF | sed '/^cdef$/ r /dev/stdin' input.txt
line 1
line 2
EOF
# outputs:
abc
cdef
line 1
line 2
line
This can be used to pipe anything into the file at the given position:
$ date | sed '/^cdef$/ r /dev/stdin' input.txt
# outputs
abc
cdef
Tue Mar 17 10:50:15 CET 2020
line
Also, you could add multiple commands which allows deleting the marker line cdef
:
$ date | sed '/^cdef$/ {
r /dev/stdin
d
}' input.txt
# outputs
abc
Tue Mar 17 10:53:53 CET 2020
line
The following code works fine with me:
brew install zbar
pip install pyqrcode
pip install pyzbar
For QR code image creation:
import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)
For QR code decoding:
from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)
that prints the result:
[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]
All answers here did not work for me. Instead, to add a space at the end of a string in XML
i did this
<string name="more_store">more store<b> </b> </string>
This may help someone,
You can get the row output from this and format the row_date object as you want.
var from_date = '2016-01-01';
var to_date = '2016-02-20';
var dates = getDates(from_date, to_date);
console.log(dates);
function getDates(from_date, to_date) {
var current_date = new Date(from_date);
var end_date = new Date(to_date);
var getTimeDiff = Math.abs(current_date.getTime() - end_date.getTime());
var date_range = Math.ceil(getTimeDiff / (1000 * 3600 * 24)) + 1 ;
var weekday = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var dates = new Array();
for (var i = 0; i <= date_range; i++) {
var getDate, getMonth = '';
if(current_date.getDate() < 10) { getDate = ('0'+ current_date.getDate());}
else{getDate = current_date.getDate();}
if(current_date.getMonth() < 9) { getMonth = ('0'+ (current_date.getMonth()+1));}
else{getMonth = current_date.getMonth();}
var row_date = {day: getDate, month: getMonth, year: current_date.getFullYear()};
var fmt_date = {weekDay: weekday[current_date.getDay()], date: getDate, month: months[current_date.getMonth()]};
var is_weekend = false;
if (current_date.getDay() == 0 || current_date.getDay() == 6) {
is_weekend = true;
}
dates.push({row_date: row_date, fmt_date: fmt_date, is_weekend: is_weekend});
current_date.setDate(current_date.getDate() + 1);
}
return dates;
}
https://gist.github.com/pranid/3c78f36253cbbc6a41a859c5d718f362.js
something like import sys; sys.exit(0)
?
This can be done by using unlist
before as.vector
.
The result is the same as using the parameter use.names=FALSE
.
as.vector(unlist(myList))
<input type="text" name="field" maxlength="8"
onkeypress="return onlyAlphabets(event,this);" />
function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
As of Excel 2019 you could do this. The "Error" at the end is the default.
SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")
Using Jeka https://jeka.dev JkPathTree, it's quite straightforward.
Path wholeDirToZip = Paths.get("dir/to/zip");
Path zipFile = Paths.get("file.zip");
JkPathTree.of(wholeDirToZip).zipTo(zipFile);
In my case, MySQL's parameter; lower_case_table_names
was configured = 0
.
It causes queries related with using upper cases will not work.
ASCII defines 128 characters, which map to the numbers 0–127. Unicode defines (less than) 221 characters, which, similarly, map to numbers 0–221 (though not all numbers are currently assigned, and some are reserved).
Unicode is a superset of ASCII, and the numbers 0–127 have the same meaning in ASCII as they have in Unicode. For example, the number 65 means "Latin capital 'A'".
Because Unicode characters don't generally fit into one 8-bit byte, there are numerous ways of storing Unicode characters in byte sequences, such as UTF-32 and UTF-8.
Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
(Not cross-browser tested), but this is my answer:
.btn-circle {
width: 40px;
height: 40px;
line-height: 40px; /* adjust line height to align vertically*/
padding:0;
border-radius: 50%;
}
I'm guessing that you want something like
SELECT tab1.a, tab2.b, tab3.c, tab4.d
FROM table1 tab1
JOIN table2 tab2 ON (tab1.fg = tab2.fg)
LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
tab3.dd = tab5.dd)
At the time of writing, there was a bug in chrome which required an xmlns
attribute in order to trigger rendering:
<xsl:stylesheet xmlns="http://www.w3.org/1999/xhtml" ... >
This was the problem I was running into when serving the xml file from a server.
If unlike me, you are viewing the xml file from a file:///
url, then the solutions mentioning --allow-file-access-from-files
are the ones you want
I use openssl, but if you prefer not to, or are on a system (particularly Windows) that doesn't have it, since java 7 in 2011 keytool
can do the whole job:
keytool -printcert -sslserver host[:port] -rfc >tempfile
keytool -import [-noprompt] -alias nm -keystore file [-storepass pw] [-storetype ty] <tempfile
# or with noprompt and storepass (so nothing on stdin besides the cert) piping works:
keytool -printcert -sslserver host[:port] -rfc | keytool -import -noprompt -alias nm -keystore file -storepass pw [-storetype ty]
Conversely, for java 9 up always, and for earlier versions in many cases, Java can use a PKCS12 file for a keystore instead of the traditional JKS file, and OpenSSL can create a PKCS12 without any assistance from keytool:
openssl s_client -connect host:port </dev/null | openssl pkcs12 -export -nokeys [-name nm] [-passout option] -out p12file
# <NUL on Windows
# default is to prompt for password, but -passout supports several options
# including actual value, envvar, or file; see the openssl(1ssl) man page
Quick solution in NetBeans 6.8.
In the Projects window right-click on the name of the project that lacks library -> Properties -> The Project Properties window opens. In Categories tree select "Libraries" node -> On the right side of the Project Properties window press button "Add JAR/Folder" -> Select jars you need.
You also can see my short Video How-To.
Here is a little code to accomplish it:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);
The beauty of the React Native is that it supports lots of JS libraries like Moment.js. Using moment.js would be a better/easier way to handle date/time instead coding from scratch
just run this in the terminal (yarn add moment
also works if using React's built-in package manager):
npm install moment --save
And in your React Native js page:
import Moment from 'moment';
render(){
Moment.locale('en');
var dt = '2016-05-02T00:00:00';
return(<View> {Moment(dt).format('d MMM')} </View>) //basically you can do all sorts of the formatting and others
}
You may check the moment.js official docs here https://momentjs.com/docs/
I tested this and it kinda works out :
exec(open('filename').read()) # Don't forget to put the filename between ' '
Follow the steps given below:
Stop your MySQL server completely. This can be done by accessing the Services window inside Windows XP and Windows Server 2003, where you can stop the MySQL service.
Open your MS-DOS command prompt using "cmd" inside the Run window. Inside it navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.
Execute the following command in the command prompt: mysqld.exe -u root --skip-grant-tables
Leave the current MS-DOS command prompt as it is, and open a new MS-DOS command prompt window.
Navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.
Enter mysql
and press enter.
You should now have the MySQL command prompt working. Type use mysql;
so that we switch to the "mysql" database.
Execute the following command to update the password:
UPDATE user SET Password = PASSWORD('NEW_PASSWORD') WHERE User = 'root';
However, you can now run any SQL command that you wish.
After you are finished close the first command prompt and type exit;
in the second command prompt windows to disconnect successfully. You can now start the MySQL service.
Use set.update()
or |=
>>> a = set('abc')
>>> l = ['d', 'e']
>>> a.update(l)
>>> a
{'e', 'b', 'c', 'd', 'a'}
>>> l = ['f', 'g']
>>> a |= set(l)
>>> a
{'e', 'b', 'f', 'c', 'd', 'g', 'a'}
edit: If you want to add the list itself and not its members, then you must use a tuple, unfortunately. Set members must be hashable.
From your question all I can understand is that you already have some hover effect on your button which you want remove. For that either remove that css which causes the hover effect or override it.
For overriding, do this
.buttonDisabled:hover
{
//overriding css goes here
}
For example if your button's background color changes on hover from red to blue. In the overriding css you will make it as red so that it doesnt change.
Also go through all the rules of writing and overriding css. Get familiar with what css will have what priority.
Best of luck.