Add Runtime Color attribute named "tintColor" from StoryBoard. This is working(for Xcode 8 and above).
if you want unselected color.. you can add unselectedItemTintColor
too.
you can set tintColor of UIBarItem :
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.magentaColor()], forState:.Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState:.Selected)
According to the Apple Human Interface Guidelines:
@1x : about 25 x 25 (max: 48 x 32)
@2x : about 50 x 50 (max: 96 x 64)
@3x : about 75 x 75 (max: 144 x 96)
Another solution (which is a hack) is to set the alpha on the tabBarController to 0.01 so that it is virtually invisible yet still clickable. Then set a an ImageView control on the bottom of the MainWindow nib with your custom tabbar image underneath the alpha'ed tabBarCOntroller. Then swap the images, change colors or hightlight when the tabbarcontroller switches views.
However, you lose the '...more' and customize functionality.
HTML Code
<html>
<body>
<head>
<title></title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
//============================= DATABASE CONNECTIVITY d ====================
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
//============================= DATABASE CONNECTIVITY u ====================
//============================= Retrieve data from DB d ====================
$sql = "SELECT name, size, type FROM videos";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
$path = "uploaded/" . $row["name"];
echo $path . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
//============================= Retrieve data from DB d ====================
?>
</body>
</html>
The following worked for me without floating (I modified your example a little for visual effect):
.container_x000D_
{_x000D_
white-space: nowrap; /*Prevents Wrapping*/_x000D_
_x000D_
width: 300px;_x000D_
height: 120px;_x000D_
overflow-x: scroll;_x000D_
overflow-y: hidden;_x000D_
}_x000D_
.slide_x000D_
{_x000D_
display: inline-block; /*Display inline and maintain block characteristics.*/_x000D_
vertical-align: top; /*Makes sure all the divs are correctly aligned.*/_x000D_
white-space: normal; /*Prevents child elements from inheriting nowrap.*/_x000D_
_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: red;_x000D_
margin: 5px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="slide">something something something</div>_x000D_
<div class="slide">something something something</div>_x000D_
<div class="slide">something something something</div>_x000D_
<div class="slide">something something something</div>_x000D_
</div>
_x000D_
The divs may be separated by spaces. If you don't want this, use margin-right: -4px;
instead of margin: 5px;
for .slide
(it's ugly but it's a tricky problem to deal with).
To activate a Python virtual environment:
$cd ~/python-venv/
$./bin/activate
To deactivate:
$deactivate
The above commands are unsafe because you might break your module when switching versions. Instead I recommend the following
npm shrinkwrap
command.npm install -g next-update // from your package next-update
Dates in VBA are just floating point numbers, where the integer part represents the date and the fraction part represents the time. So in addition to using the Date
function as tlayton says (to get the current date) you can also cast a date value to a integer to get the date-part from an arbitrary date: Int(myDateValue)
.
zitao xiong's answer is pretty close to what I use; I also include the file name (by stripping off the path of FILE).
#ifdef DEBUG
#define NSLogDebug(format, ...) \
NSLog(@"<%s:%d> %s, " format, \
strrchr("/" __FILE__, '/') + 1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__)
#else
#define NSLogDebug(format, ...)
#endif
Yes, you can use what's known as :nth-child
selectors.
In this case you would use:
li:nth-child(3n) {
// Styling for every third element here.
}
:nth-child(3n):
3(0) = 0
3(1) = 3
3(2) = 6
3(3) = 9
3(4) = 12
:nth-child()
is compatible in Chrome, Firefox, and IE9+.
For a work around to use :nth-child()
amongst other pseudo-classes/attribute selectors in IE6 through to IE8, see this link.
It is simple as you don't even expect.
If the value is positive it loaded when the container starts
If the value is not positive than the servelet is loaded when the request is made.
All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:
var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US"));
// (or 1,2345 with your local culture, for instance)
(obviously, you should replace the "en-US" with the culture of your number local culture)
the same way, if you want to do ToString()
d.ToString(new CultureInfo("en-US"));
ymin, ymax = axes.get_ylim()
If you are using the plt
api directly, you can avoid calls to axes
altogether:
def myplotfunction(title, values, errors, plot_file_name):
# plot errorbars
indices = range(0, len(values))
fig = plt.figure()
plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')
plt.ylim([-0.5, len(values) - 0.5])
plt.xlabel('My x-axis title')
plt.ylabel('My y-axis title')
# title
plt.title(title)
# save as file
plt.savefig(plot_file_name)
# close figure
plt.close(fig)
For me, there are some changes to make(ver. 2.20)
moment.locale('de')
, and you create a new object representing the date of now by moment()
(note the parenthesis) and then format('LLL')
it. The parenthesis is important.So that means:
moment.locale('de');
var now = moment();
now.format('LLL');
moment-with-locale.js
. The file contains all locale info and has a larger file size. Download the locale
folder is not enough. If necessary, change the name to be moment.js
. Django just refuses to load moment-with-locale.js
in my case.EDIT: It turned out that renaming the file is not necessary. I just forgot to invoke it in the page so Django does not think loading it is necessary, so my fault.
Using zip function we can get both element and index.
countries = ['Pakistan','India','China','Russia','USA']
for index, element zip(range(0,countries),countries):
print('Index : ',index)
print(' Element : ', element,'\n')
output : Index : 0 Element : Pakistan ...
See also :
Late answer...
Composer 1.10.1 2020-03-13 20:34:27 laravel --version Laravel Installer 3.0.1
Put export PATH=$PATH:~/.config/composer/vendor/bin:$PATH in your ~/.zshrc or ~/.bashrc source ~/.zshrc or ~/.bashrc This works
There is no build-in variable for this purpose, but you can always find out the playbook's absolute path with "pwd" command, and register its output to a variable.
- name: Find out playbook's path
shell: pwd
register: playbook_path_output
- debug: var=playbook_path_output.stdout
Now the path is available in variable playbook_path_output.stdout
If you are using zsh do the following.
Open .zshrc file nano $HOME/.zshrc
You will see the commented $PATH variable here
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/...
Remove the comment symbol(#) and append your new path using a separator(:) like this.
export PATH=$HOME/bin:/usr/local/bin:/Users/ebin/Documents/Softwares/mongoDB/bin:$PATH
source $HOME/.zshrc
You're done !!!
They both take a function from the type of the optional to something.
map()
applies the function "as is" on the optional you have:
if (optional.isEmpty()) return Optional.empty();
else return Optional.of(f(optional.get()));
What happens if your function is a function from T -> Optional<U>
?
Your result is now an Optional<Optional<U>>
!
That's what flatMap()
is about: if your function already returns an Optional
, flatMap()
is a bit smarter and doesn't double wrap it, returning Optional<U>
.
It's the composition of two functional idioms: map
and flatten
.
% sudo port selfupdate;
% sudo port upgrade outdated;
% sudo port install maven3;
% sudo port select --set maven maven3;
— add following to .zshenv -- start using zsh if you dont —
set -a
[[ -d /opt/local/share/java/maven3 ]] &&
M3_HOME=/opt/local/share/java/maven3 &&
M2_HOME=/opt/local/share/java/maven3 &&
MAVEN_OPTS="-Xmx1024m" &&
M2=${M2_HOME}/bin
set +a
As Peter already pointed out:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com/events')
In [3]: type(r)
Out[3]: requests.models.Response
In [4]: type(r.content)
Out[4]: str
You may also want to check r.text
.
Also: https://2.python-requests.org/en/latest/user/quickstart/
Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:
std::string c = "hello" + "world";
This doesn’t work because for C++ this seems like you’re trying to add two char
pointers. Instead, you need to convert at least one of the char*
literals to a std::string
. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:
std::string c = std::string("hello") + "world";
Almost every page you visit uses both. The static content (eg, images, videos) is served by the web server, and the rest (the parts that are different between you and other users) are generated by the application server.
This is what you need ...
public boolean indexExists(final List list, final int index) {
return index >= 0 && index < list.size();
}
Why not use an plain old array? Indexed access to a List is a code smell I think.
In Python, you can use urllib2
(http://docs.python.org/2/library/urllib2.html) to do all of that work for you.
Simply enough:
import urllib2
f = urllib2.urlopen(url)
print f.read()
Will print the received HTTP response.
To pass GET/POST parameters the urllib.urlencode()
function can be used. For more information, you can refer to the Official Urllib2 Tutorial
I fixed the issue (temporarily) by going to Edit Scheme, then in the Build section, removing my unit test target from being invoked in "Run".
More readable way of achieving this (not a fan of single line ansible tasks)
- local_action:
module: copy
content: "{{ foo_result }}"
dest: /path/to/destination/file
I had the same issue when my server free disk space available was 0
You can use the command (there must be ample space for the mysql files)
REPAIR TABLE `<table name>`;
for repairing individual tables
For future readers I'd like to advise the DPack extension for Visual Studio 2010.
It's got a load of utilities built in including a line counter which says how many lines are blank, code, and etc.
A good practice is write text inside String.xml
example:
String.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="yellow">Yellow</string>
</resources>
and inside layout:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/yellow" />
You can try this one
$('#content').on('change keyup keydown paste cut', 'textarea', function () {_x000D_
$(this).height(0).height(this.scrollHeight);_x000D_
}).find('textarea').change();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="content">_x000D_
<textarea>How about it</textarea><br />_x000D_
<textarea rows="5">111111_x000D_
222222_x000D_
333333_x000D_
444444_x000D_
555555_x000D_
666666</textarea>_x000D_
</div>
_x000D_
I know its about a year late, but you can also create a 9 path image There's a tool that comes with android SDK which helps in creating such image See this link: http://developer.android.com/tools/help/draw9patch.html
PS: the image can be infinitely scaled as well
As an example of the difference -- if you have a task the does something with the UI thread (e.g. a task that represents an animation in a Storyboard) if you Task.WaitAll()
then the UI thread is blocked and the UI is never updated. if you use await Task.WhenAll()
then the UI thread is not blocked, and the UI will be updated.
Just use
If @searchType is null means 'return the whole table' then use
WHERE p.[Type] = @SearchType OR @SearchType is NULL
If @searchType is an empty string means 'return the whole table' then use
WHERE p.[Type] = @SearchType OR @SearchType = ''
If @searchType is null or an empty string means 'return the whole table' then use
WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''
I have used NuSOAP in the past. I liked it because it is just a set of PHP files that you can include. There is nothing to install on the web server and no config options to change. It has WSDL support as well which is a bonus.
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?
this question might have your answer, it worked for me.
For 2014, I edited in this new version, based on the ultra-handy comment by Norbert below! This does everything. Cheers
// yourLabel is your UILabel.
float widthIs =
[self.yourLabel.text
boundingRectWithSize:self.yourLabel.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName:self.yourLabel.font }
context:nil]
.size.width;
NSLog(@"the width of yourLabel is %f", widthIs);
How about
$('#county').append(
$('<option />')
.text('Select a city / town in Sweden')
.val(''),
$('<option />')
.text('Melbourne')
.val('Melbourne')
);
You can use Ra-Ajax and have an iframe wrapped inside e.g. a Window control. Though in general terms I don't encourage people to use iframes (for anything)
Another alternative is to load the HTML on the server and send it directly into the Window as the content of a Label or something. Check out how this Ajax RSS parser is loading the RSS items in the source which can be downloaded here (Open Source - LGPL)
(Disclaimer; I work with Ra-Ajax...)
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
You can also see this error when selecting for a union where corresponding columns can be null.
select * from (select D.dept_no, D.nullable_comment
from dept D
union
select R.dept_no, NULL
from redundant_dept R
)
This apparently confuses the parser, a solution is to assign a column alias to the always null column.
select * from (select D.dept_no, D.comment
from dept D
union
select R.dept_no, NULL "nullable_comment"
from redundant_dept R
)
The alias does not have to be the same as the corresponding column, but the column heading in the result is driven by the first query from among the union members, so it's probably a good practice.
If you also want to get the name of the foreign key column:
SELECT i.TABLE_SCHEMA, i.TABLE_NAME,
i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME,
k.COLUMN_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME
FROM information_schema.TABLE_CONSTRAINTS i
LEFT JOIN information_schema.KEY_COLUMN_USAGE k
ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME
WHERE i.TABLE_SCHEMA = '<TABLE_NAME>' AND i.CONSTRAINT_TYPE = 'FOREIGN KEY'
ORDER BY i.TABLE_NAME;
I know it has been answered good few times already, but I like below way of doing this. I hope it will help someone.
//attach object (search for row)
TableName tn = _context.TableNames.Attach(new TableName { PK_COLUMN = YOUR_VALUE});
// set new value
tn.COLUMN_NAME_TO_UPDATE = NEW_COLUMN_VALUE;
// set column as modified
_context.Entry<TableName>(tn).Property(tnp => tnp.COLUMN_NAME_TO_UPDATE).IsModified = true;
// save change
_context.SaveChanges();
here's how you can do it with a cool shell trick:
mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'
'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.
use the -t flag to enable table-format output
Don't like any of those solutions.
this is how i do it:
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='"
. sqlEsc($somename) . "' ;";
then i use my own sqlEsc function:
function sqlEsc($val)
{
global $mysqli;
return mysqli_real_escape_string($mysqli, $val);
}
Spring's Web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that you can choose an appropriate base class: if you don't have a form, you don't need a form controller. This is a major difference to Struts
I was looking for an integer value in named column, so I did the below:
int index = dgv_myDataGridView.CurrentCell.RowIndex;
int id = Convert.ToInt32(dgv_myDataGridView["ID", index].Value)
The good thing about this is that the column can be in any position in the grid view and you will still get the value.
Cheers
Linux kernel coding style Chapter 5 gives great pros and cons (mostly cons) of using typedef
.
Please don't use things like "vps_t".
It's a mistake to use typedef for structures and pointers. When you see a
vps_t a;
in the source, what does it mean?
In contrast, if it says
struct virtual_container *a;
you can actually tell what "a" is.
Lots of people think that typedefs "help readability". Not so. They are useful only for:
(a) totally opaque objects (where the typedef is actively used to hide what the object is).
Example: "pte_t" etc. opaque objects that you can only access using the proper accessor functions.
NOTE! Opaqueness and "accessor functions" are not good in themselves. The reason we have them for things like pte_t etc. is that there really is absolutely zero portably accessible information there.
(b) Clear integer types, where the abstraction helps avoid confusion whether it is "int" or "long".
u8/u16/u32 are perfectly fine typedefs, although they fit into category (d) better than here.
NOTE! Again - there needs to be a reason for this. If something is "unsigned long", then there's no reason to do
typedef unsigned long myflags_t;
but if there is a clear reason for why it under certain circumstances might be an "unsigned int" and under other configurations might be "unsigned long", then by all means go ahead and use a typedef.
(c) when you use sparse to literally create a new type for type-checking.
(d) New types which are identical to standard C99 types, in certain exceptional circumstances.
Although it would only take a short amount of time for the eyes and brain to become accustomed to the standard types like 'uint32_t', some people object to their use anyway.
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their signed equivalents which are identical to standard types are permitted -- although they are not mandatory in new code of your own.
When editing existing code which already uses one or the other set of types, you should conform to the existing choices in that code.
(e) Types safe for use in userspace.
In certain structures which are visible to userspace, we cannot require C99 types and cannot use the 'u32' form above. Thus, we use __u32 and similar types in all structures which are shared with userspace.
Maybe there are other cases too, but the rule should basically be to NEVER EVER use a typedef unless you can clearly match one of those rules.
In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.
Cookies are your best bet. Look for the jquery cookie plugin.
Cookies are designed for this sort of situation -- you want to keep some information about this client on client side. Just be aware that cookies are passed back and forth on every web request so you can't store large amounts of data in there. But just a simple answer to a question should be fine.
If you're running cPanel/WHM, make sure that IP is whitelisted in the firewall. You will als need to add that IP to the remote SQL IP list in the cPanel account you're trying to connect to.
To remove the special characters, try
var name = name.replace(/[!@#$%^&*]/g, "");
You can try this cool app available in play store called Html Page Source https://play.google.com/store/apps/details?id=com.scintillar.hps
Personnally, I prefer:
var result = from entry in table
where (entry.something??0)==(value??0)
select entry;
over
var result = from entry in table
where (value == null ? entry.something == null : entry.something == value)
select entry;
because it prevents repetition -- though that's not mathematically exact, but it fits well most cases.
Try the following enum :
enum Color {
//Color end string, color reset
RESET("\033[0m"),
// Regular Colors. Normal color, no bold, background color etc.
BLACK("\033[0;30m"), // BLACK
RED("\033[0;31m"), // RED
GREEN("\033[0;32m"), // GREEN
YELLOW("\033[0;33m"), // YELLOW
BLUE("\033[0;34m"), // BLUE
MAGENTA("\033[0;35m"), // MAGENTA
CYAN("\033[0;36m"), // CYAN
WHITE("\033[0;37m"), // WHITE
// Bold
BLACK_BOLD("\033[1;30m"), // BLACK
RED_BOLD("\033[1;31m"), // RED
GREEN_BOLD("\033[1;32m"), // GREEN
YELLOW_BOLD("\033[1;33m"), // YELLOW
BLUE_BOLD("\033[1;34m"), // BLUE
MAGENTA_BOLD("\033[1;35m"), // MAGENTA
CYAN_BOLD("\033[1;36m"), // CYAN
WHITE_BOLD("\033[1;37m"), // WHITE
// Underline
BLACK_UNDERLINED("\033[4;30m"), // BLACK
RED_UNDERLINED("\033[4;31m"), // RED
GREEN_UNDERLINED("\033[4;32m"), // GREEN
YELLOW_UNDERLINED("\033[4;33m"), // YELLOW
BLUE_UNDERLINED("\033[4;34m"), // BLUE
MAGENTA_UNDERLINED("\033[4;35m"), // MAGENTA
CYAN_UNDERLINED("\033[4;36m"), // CYAN
WHITE_UNDERLINED("\033[4;37m"), // WHITE
// Background
BLACK_BACKGROUND("\033[40m"), // BLACK
RED_BACKGROUND("\033[41m"), // RED
GREEN_BACKGROUND("\033[42m"), // GREEN
YELLOW_BACKGROUND("\033[43m"), // YELLOW
BLUE_BACKGROUND("\033[44m"), // BLUE
MAGENTA_BACKGROUND("\033[45m"), // MAGENTA
CYAN_BACKGROUND("\033[46m"), // CYAN
WHITE_BACKGROUND("\033[47m"), // WHITE
// High Intensity
BLACK_BRIGHT("\033[0;90m"), // BLACK
RED_BRIGHT("\033[0;91m"), // RED
GREEN_BRIGHT("\033[0;92m"), // GREEN
YELLOW_BRIGHT("\033[0;93m"), // YELLOW
BLUE_BRIGHT("\033[0;94m"), // BLUE
MAGENTA_BRIGHT("\033[0;95m"), // MAGENTA
CYAN_BRIGHT("\033[0;96m"), // CYAN
WHITE_BRIGHT("\033[0;97m"), // WHITE
// Bold High Intensity
BLACK_BOLD_BRIGHT("\033[1;90m"), // BLACK
RED_BOLD_BRIGHT("\033[1;91m"), // RED
GREEN_BOLD_BRIGHT("\033[1;92m"), // GREEN
YELLOW_BOLD_BRIGHT("\033[1;93m"), // YELLOW
BLUE_BOLD_BRIGHT("\033[1;94m"), // BLUE
MAGENTA_BOLD_BRIGHT("\033[1;95m"), // MAGENTA
CYAN_BOLD_BRIGHT("\033[1;96m"), // CYAN
WHITE_BOLD_BRIGHT("\033[1;97m"), // WHITE
// High Intensity backgrounds
BLACK_BACKGROUND_BRIGHT("\033[0;100m"), // BLACK
RED_BACKGROUND_BRIGHT("\033[0;101m"), // RED
GREEN_BACKGROUND_BRIGHT("\033[0;102m"), // GREEN
YELLOW_BACKGROUND_BRIGHT("\033[0;103m"), // YELLOW
BLUE_BACKGROUND_BRIGHT("\033[0;104m"), // BLUE
MAGENTA_BACKGROUND_BRIGHT("\033[0;105m"), // MAGENTA
CYAN_BACKGROUND_BRIGHT("\033[0;106m"), // CYAN
WHITE_BACKGROUND_BRIGHT("\033[0;107m"); // WHITE
private final String code;
Color(String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
}
And now we will make a small example:
class RunApp {
public static void main(String[] args) {
System.out.print(Color.BLACK_BOLD);
System.out.println("Black_Bold");
System.out.print(Color.RESET);
System.out.print(Color.YELLOW);
System.out.print(Color.BLUE_BACKGROUND);
System.out.println("YELLOW & BLUE");
System.out.print(Color.RESET);
System.out.print(Color.YELLOW);
System.out.println("YELLOW");
System.out.print(Color.RESET);
}
}
See What is the maximum length of a URL in different browsers?
The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.
Initialise here..
SharedPreferences msharedpref = getSharedPreferences("msh",
MODE_PRIVATE);
Editor editor = msharedpref.edit();
store data...
editor.putString("id",uida); //uida is your string to be stored
editor.commit();
finish();
fetch...
SharedPreferences prefs = this.getSharedPreferences("msh", Context.MODE_PRIVATE);
uida = prefs.getString("id", "");
Try PySoundCard which uses PortAudio for playback which is available on many platforms. In addition, it recognizes "professional" sound devices with lots of channels.
Here a small example from the Readme:
from pysoundcard import Stream
"""Loop back five seconds of audio data."""
fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs*5/blocksize)):
s.write(s.read(blocksize))
s.stop()
Alternatively referred to as a fixed space or hard space, non-breaking space (NBSP) is used in programming and word processing to create a space in a line that cannot be broken by word wrap.
With HTML,
allows you to create multiple spaces that are visible on a web page and not only in the source code.
You should really use the pip tool.
Use pip install -e .
to install your package in development mode. This is a very good practice, recommended by pytest (see their good practices documentation, where you can also find two project layouts to follow).
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
You can also add the toolbar in Visual Studio to have the buttons available.
View > Toolbars > Text Editor
The Starter Trade-offs sheet of my comparison spreadsheet has comprehensive one-on-one comparisons between each generator. So no more need to distortedly cherry-pick great things to say about your favorite.
Here is the one between generator-angular-fullstack and MEAN.js. The percentages are values for each benefit based on my personal weightings, where a perfect generator would be 100%
generator- angular- fullstack offers 8% that MEANJS.org doesn't
MeanJS.org. offers 9% that generator-angular-fullstack doesn't
Here is the one between MEAN.io and MEAN.js in a more readable format
<table border="1" cellpadding="10"><tbody><tr><td valign="top" width="33%"><br><br><h1>MeanJS.org. provides these benefits that MEAN.io. doesn't</h1><br><br><b>Help</b>:<br> * Dedicated/searchable user group for questions, using github issues<br> * There's a book about it<br><b>File Organization</b>:<br> * Basic sourcecode organization, module(->submodule)->side<br> * Module directories hold directives<br><b>Code Modularization</b>:<br> * Approach to AngularJS modules, Only one module definition per file<br> * Approach to AngularJS modules, Don’t alter a module other than where it is defined<br><b>Model</b>:<br> * Object-relational mapping<br> * Server-side validation, server-side example<br> * Client side validation, using Angular 1.3<br><b>View</b>:<br> * Approach to AngularJS views, Directives start with "data-"<br> * Approach to data readiness, Use ng-init<br><b>Control</b>:<br> * Approach to frontend routing or state changing, URLs start with '#!'<br> * Approach to frontend routing or state changing, Use query parameters to store route state<br><b>Support for things</b>:<br> * Languages, LESS<br> * Languages, SASS<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Don't use "new"<br><b>Testing</b>:<br> * Testing, using Mocha<br> * End-to-end tests<br> * End-to-end tests, using Protractor<br> * Continuous integration (CI), using Travis<br><b>Development and debugging</b>:<br> * Command line interface (CLI), using Yeoman<br><b>Build</b>:<br> * Build configurations file(s)<br> * Deployment automation, using Azure<br> * Deployment automation, using Digital Ocean, screencast of it<br> * Deployment automation, using Heroku, screencast of it<br><b>Code Generation</b>:<br> * Input application profile<br> * Quick install?<br> * Options for making subcomponents<br> * config generator<br> * controller (client side) generator<br> * directive generator<br> * filter generator<br> * route (client side) generator<br> * service (client side) generator<br> * test - client side<br> * view or view partial generator<br> * controller (server side) generator<br> * model (server side) generator<br> * route (server side) generator<br> * test (server side) generator<br><b>Implemented Functionality</b>:<br> * Account Management, Forgotten Password with Resetting<br> * Chat<br> * CSV processing<br> * E-mail sending system<br> * E-mail sending system, using Nodemailer<br> * E-mail sending system, using its own e-mail implementation<br> * Menus system, state-based<br> * Paypal integration<br> * Responsive design<br> * Social connections management page<br><b>Performance</b>:<br> * Creates a favicon<br><b>Security</b>:<br> * Safe from IP Spoofing<br> * Authorization, Access Contol List (ACL)<br> * Authentication, Cookie<br> * Websocket and RESTful http share security policies<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. provides these benefits that MeanJS.org. doesn't</h1><br><br><b>Quality</b>:<br> * Sponsoring company<br><b>Help</b>:<br> * Docs with flatdoc<br><b>Code Modularization</b>:<br> * Share code between projects<br> * Module manager<br><b>View</b>:<br> * Approach to data readiness, Use state.resolve()<br><b>Control</b>:<br> * Approach to frontend code loading, Use AMD with Require.js<br> * Approach to frontend code loading, using wiredep<br> * Approach to error handling, Server-side logging<br><b>Client/Server Communication</b>:<br> * Centralized event handling<br> * Approach to XHR calls, using $http and $q<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Wrap code in an IIFE (SEAF, SIAF)<br><b>Development and debugging</b>:<br> * API introspection report and testing interface, using Swagger<br> * Command line interface (CLI), using Independent command line interface<br><b>Build</b>:<br> * Development build, add IIFEs (SEAF, SIAF) to executable copies of code<br> * Deployment automation<br> * Deployment automation, using Heroku<br><b>Code Generation</b>:<br> * Scaffolding undo (mean package -d <name>)<br> * FEATURE (a.k.a. module, entity) generator, Menu items added for new features<br><b>Implemented Functionality</b>:<br> * Admin page for users and roles<br> * Content Management System (Use special data-bound directives in your templates.<br>Switch to edit mode and you can edit the values right where you see them)<br> * File Upload<br> * i18n, localization<br> * Menus system, submenus<br> * Search<br> * Search, actually works with backend API<br> * Search, using Elastic Search<br> * Styles, using Bootstrap, using UI Bootstrap AngularJS directives<br> * Text (WYSIWYG) Editor<br> * Text (WYSIWYG) Editor, using medium-editor<br><b>Performance</b>:<br> * Instrumentation, server-side<br><b>Security</b>:<br> * Serverside authenticated route restriction<br> * Authentication, using Oauth, Link multiple Oauth strategies to one account<br> * Authentication, JSON Web Token (JWT)<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. and MeanJS.org. both provide these benefits</h1><br><br><b>Quality</b>:<br> * Version Control, using git<br><b>Platforms</b>:<br> * Client-side JS Framework, using AngularJS<br> * Frontend Server/ Framework, using Node.JS<br> * Frontend Server/ Framework, using Node.JS, using Express<br> * API Server/ Framework, using NodeJS<br> * API Server/ Framework, using NodeJS, using Express<br><b>Help</b>:<br> * Dedicated/searchable user group for questions<br> * Dedicated/searchable user group for questions, using Google Groups<br> * Dedicated/searchable user group for questions, using Facebook<br> * Dedicated/searchable user group for questions, response time mostly under a day<br> * Example application<br> * Tutorial screencast in English<br> * Tutorial screencast in English, using Youtube<br> * Dedicated chatroom<br><b>File Organization</b>:<br> * Basic sourcecode organization, module(->submodule)->side, with type subfolders<br> * Module directories hold controllers<br> * Module directories hold services<br> * Module directories hold templates<br> * Module directories hold unit tests<br> * Separate route configuration files for each module<br><b>Code Modularization</b>:<br> * Modularized Functionality<br> * Approach to AngularJS modules, No global 'app' module variable<br> * Approach to AngularJS modules, No global 'app' module variable without an IIFE<br><b>Model</b>:<br> * Setup of persistent storage<br> * Setup of persistent storage, using NoSQL db<br> * Setup of persistent storage, using NoSQL db, using MongoDB<br><b>View</b>:<br> * No XHR calls in controllers<br> * Templates, using Angular directives<br> * Approach to data readiness, prevents Flash of Unstyled/compiled Content (FOUC)<br><b>Control</b>:<br> * Approach to frontend routing or state changing, example of it<br> * Approach to frontend routing or state changing, State-based routing<br> * Approach to frontend routing or state changing, State-based routing, using ui-router<br> * Approach to frontend routing or state changing, HTML5 Mode<br> * Approach to frontend code loading, using angular.bootstrap()<br><b>Client/Server Communication</b>:<br> * Serve status codes only as responses<br> * Accept nested, JSON parameters<br> * Add timer header to requests<br> * Support for signed and encrypted cookies<br> * Serve URLs based on the route definitions<br> * Can serve headers only<br> * Approach to XHR calls, using JSON<br> * Approach to XHR calls, using $resource (angular-resource)<br><b>Support for things</b>:<br> * Languages, JavaScript (server side)<br> * Languages, Swig<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Use 'use strict'<br><b>Tool Configuration/customization</b>:<br> * Separate runtime configuration profiles<br><b>Testing</b>:<br> * Testing, using Jasmine<br> * Testing, using Karma<br> * Client-side unit tests<br> * Continuous integration (CI)<br> * Automated device testing, using Live Reload<br> * Server-side integration & unit tests<br> * Server-side integration & unit tests, using Mocha<br><b>Development and debugging</b>:<br> * Command line interface (CLI)<br><b>Build</b>:<br> * Build-time Dependency Management, using npm<br> * Build-time Dependency Management, using bower<br> * Build tool / Task runner, using Grunt<br> * Build tool / Task runner, using gulp<br> * Development build, script<br> * Development build, reload build script file upon change<br> * Development build, copy assets to build or dist or target folder<br> * Development build, html page processing<br> * Development build, html page processing, inject references by searching directories<br> * Development build, html page processing, inject references by searching directories, injects js references<br> * Development build, html page processing, inject references by searching directories, injects css references<br> * Development build, LESS/SASS/etc files are linted, compiled<br> * Development build, JavaScript style checking<br> * Development build, JavaScript style checking, using jshint or jslint<br> * Development build, run unit tests<br> * Production build, script<br> * Production build, concatenation (aggregation, globbing, bundling) (If you add debug:true to your config/env/development.js the will not be <br>uglified)<br> * Production build, minification<br> * Production build, safe pre-minification, using ng-annotate<br> * Production build, uglification<br> * Production build, make static pages for SEO<br><b>Code Generation</b>:<br> * FEATURE (a.k.a. module, entity) generator (README.md<br>feature css<br>routes<br>controller<br>view<br>additional menu item)<br><b>Implemented Functionality</b>:<br> * 404 Page<br> * 500 Page<br> * Account Management<br> * Account Management, register/login/logout<br> * Account Management, is password manager friendly<br> * Front-end CRUD<br> * Full-stack CRUD<br> * Full-stack CRUD, with Read<br> * Full-stack CRUD, with Create, Update and Delete<br> * Google Analytics<br> * Menus system<br> * Realtime data sync<br> * Realtime data sync, using socket.io<br> * Styles, using Bootstrap<br><b>Performance</b>:<br> * Javascript performance thing<br> * Javascript performance thing, using lodash<br> * One event-loop thread handles all requests<br> * Configurable response caching (Express plugin<br><b>https</b>://www.npmjs.org/package/apicache)<br> * Clustered HTTP sessions<br><b>Security</b>:<br> * JavaScript obfuscation<br> * https<br> * Authentication, using Oauth<br> * Authentication, Basic (With Passport or others)<br> * Authentication, Digest (With Passport or others)<br> * Authentication, Token (With Passport or others)<br></td></tr></tbody></table>
_x000D_
The best way is to use your code and then store the image in OG tags in the page you are linking to, then Facebook will pick them up.
<meta property="og:title" content="Facebook Open Graph Demo">
<meta property="og:image" content="http://example.com/main-image.png">
<meta property="og:site_name" content="Example Website">
<meta property="og:description" content="Here is a nice description">
You can find documentation to OG tags and how to use them with share buttons here
tl;dr
All maven POMs inherit from a base Super POM.
The snippet below is part of the Super POM for Maven 3.5.4.
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
Try this
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
or user_category_subscriptions.user_id is null
My solution was just simple as: have you tried turning it off and on again? So I restarted the computer and the issue was gone.
Just add another join:
SELECT dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id,
images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
I've tried all the possibilities. Nothing worked for me except the following. var element = document.querySelectorAll("input[id=btn1]"); element[0].setAttribute("disabled",true);
The DPI of the screen of the Nexus 10 is ±300, which is in the unofficial xhdpi
range of 280-400.
Usually, devices use resources designed for their density. But there are exceptions, and exceptions might be added in the future.
The Nexus 10 uses xxhdpi
resources when it comes to launcher icons.
The standard quantised DPI for xxhdpi is 480 (which means screens with a DPI somewhere in the range of 400-560 are probably xxhdpi).
It needs to go directly under the root <configuration>
node and you need to set a path like this:
<?xml version="1.0"?>
<configuration>
<location path="." inheritInChildApplications="false">
<!-- Stuff that shouldn't be inherited goes in here -->
</location>
</configuration>
A better way to handle configuration inheritance is to use a <clear/>
in the child config wherever you don't want to inherit. So if you didn't want to inherit the parent config's connection strings you would do something like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<clear/>
<!-- Child config's connection strings -->
</connectionStrings>
</configuration>
I wrote an Open Source Library called MgntUtils that has a utility that works with String versions. It correctly compares them, works with version ranges and so forth. Here is this library javadoc See methods TextUtils.comapreVersions(...)
. It has been heavily used and well tested. Here is the article that describes the library and where to get it. It is available as Maven artifact and on the github (with sources and JavaDoc)
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
Using SaSS
change the brand color
$brand-primary:#some-color;
this will change the primary color accross all UI.
Using css-
suppose you want to change button primary color.So
btn.primary{
background:#some-color;
}
search the element and add a new css/sass rule in a new file and attach it after u load the bootstrap css.
You can try this:
$mytimestamp = 1465298940;
echo gmdate("m-d-Y", $mytimestamp);
Output :
06-07-2016
fs.exists(path, callback)
and fs.existsSync(path)
are deprecated now, see https://nodejs.org/api/fs.html#fs_fs_exists_path_callback and https://nodejs.org/api/fs.html#fs_fs_existssync_path.
To test the existence of a file synchronously one can use ie. fs.statSync(path)
. An fs.Stats
object will be returned if the file exists, see https://nodejs.org/api/fs.html#fs_class_fs_stats, otherwise an error is thrown which will be catched by the try / catch statement.
var fs = require('fs'),
path = '/path/to/my/file',
stats;
try {
stats = fs.statSync(path);
console.log("File exists.");
}
catch (e) {
console.log("File does not exist.");
}
just remove this because constructor don't have a return type like void it will be like this :
private Flow()
{
X = x;
Y = y;
}
mysql_query("SHOW TABLES FROM yourDB");
//> loop thru results and see if it exists
//> in this way with only one query one can check easly more table
or mysql_query("SHOW TABLES LIKE 'tblname'");
Don't use mysql_list_tables();
because it's deprecated
Add builtin COPY in project.csproj file:
<Project>
...
<Target Name="AfterBuild">
<Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Debug\bin" SkipUnchangedFiles="false" />
<Copy SourceFiles="$(ProjectDir)..\..\Lib\*.dll" DestinationFolder="$(OutDir)Release\bin" SkipUnchangedFiles="false" />
</Target>
</Project>
You can use .length
with just a descendant selector, like this:
var count = $("#selected li").length;
If you have to use .children()
, then it's like this:
var count = $("#selected ul").children().length;
SELECT COUNT(*) FROM (SELECT * FROM tbl WHERE id=1 UNION SELECT * FROM tbl WHERE id=2) a
If you got two rows, they different, if one - the same.
This worked for me:
svn add `svn status . | grep "^?" | awk '{print $2}'`
(Source)
As you already solved your problem for Windows, this is a UNIX solution (following Sam). I added here as I think it is still useful for those who reach this question asking for the same thing (as the title does not include the keyword "WINDOWS").
Note (Feb, 2015): As commented by "bdrx", the above command could be further simplified in this way:
svn add `svn status . | awk '/^[?]/{print $2}'`
add by user root this command : ssh user_to_acces@hostName -X
user_to_acces = user hostName = hostname machine
okay, thx a lot now i use sth like this:
public static String[] removeElements(String[] input, String deleteMe) {
if (input != null) {
List<String> list = new ArrayList<String>(Arrays.asList(input));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(deleteMe)) {
list.remove(i);
}
}
return list.toArray(new String[0]);
} else {
return new String[0];
}
}
Siddharth's answer is terrific.
However, this technique can hit trouble when working with a large set of data (my computer froze up on 50,000 rows). Some less processor-intensive methods:
Single uniqueness check
Use a formula that looks at less data
=IF(SUMPRODUCT(($A2:$A3=A2)*($B2:$B3=B2))>1,0,1)
Multiple uniqueness checks
If you need to check uniqueness in different columns, you can't rely on two sorts.
Instead,
Add formula covering the maximum number of records for each grouping. If ABC might have 50 rows, the formula will be
=IF(SUMPRODUCT(($A2:$A49=A2)*($B2:$B49=B2))>1,0,1)
If there are too many files to delete, which is actually a case for me. You can also try the following solution:
1) fetch
2) merge with a strategy. For instance this one works for me:
git.exe merge --strategy=ours master
Just wanted to add: If you create a database in mySQL on a live site, then go into PHPMyAdmin and the database isn't showing up - logout of cPanel then log back in, open PHPMyAdmin, and it should be there now.
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
_x000D_
var keys=Object.keys(a).sort();_x000D_
for(var i=0,key=keys[0];i<keys.length;key=keys[++i]){_x000D_
document.write(key+' : '+a[key]+'<br>');_x000D_
}
_x000D_
Here is the solution in raw code (put together thanks to stjohnroe and Shamik):
Endpoint ep = Endpoint.create(new WebserviceImpl());
List<Handler> handlerChain = ep.getBinding().getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
ep.getBinding().setHandlerChain(handlerChain);
ep.publish(publishURL);
Where SOAPLoggingHandler is (ripped from linked examples):
package com.myfirm.util.logging.ws;
import java.io.PrintStream;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
/*
* This simple SOAPHandler will output the contents of incoming
* and outgoing messages.
*/
public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {
// change this to redirect output if desired
private static PrintStream out = System.out;
public Set<QName> getHeaders() {
return null;
}
public boolean handleMessage(SOAPMessageContext smc) {
logToSystemOut(smc);
return true;
}
public boolean handleFault(SOAPMessageContext smc) {
logToSystemOut(smc);
return true;
}
// nothing to clean up
public void close(MessageContext messageContext) {
}
/*
* Check the MESSAGE_OUTBOUND_PROPERTY in the context
* to see if this is an outgoing or incoming message.
* Write a brief message to the print stream and
* output the message. The writeTo() method can throw
* SOAPException or IOException
*/
private void logToSystemOut(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean)
smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
out.println("\nOutbound message:");
} else {
out.println("\nInbound message:");
}
SOAPMessage message = smc.getMessage();
try {
message.writeTo(out);
out.println(""); // just to add a newline
} catch (Exception e) {
out.println("Exception in handler: " + e);
}
}
}
You can also use below code:
int ss = nDur%60;
nDur = nDur/60;
int mm = nDur%60;
int hh = nDur/60;
<pre>
<input type="text" #titleInput>
<button type="submit" (click) = 'addTodo(titleInput.value)'>Add</button>
</pre>
{
addTodo(title:string) {
console.log(title);
}
}
From MSDN:
Set Keyword: In VBA, the Set keyword is necessary to distinguish between assignment of an object and assignment of the default property of the object. Since default properties are not supported in Visual Basic .NET, the Set keyword is not needed and is no longer supported.
The problem there is the /bin/.
command. That's really weird, since . should always be a link to the directory it's in. (Honestly, unless .
is a strange alias or function, I don't even see how it's possible.) It's also a little unusual that your shell doesn't have a .
builtin for source
.
One quick fix would be to just run the virtualenv in a different shell. (An obvious second advantage being that instead of having to deactivate
you can just exit
.)
/bin/bash --rcfile bin/activate
If your shell supports it, you may also have the nonstandard source
command, which should do the same thing as .
, but may not exist. (All said, you should try to figure out why your environment is strange or it will cause you pain again in the future.)
By the way, you didn't need to chmod +x
those files. Files only need to be executable if you want to execute them directly. In this case you're trying to launch them from .
, so they don't need it.
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
As of Python 3.2+, you can also accomplish this using the to_bytes
native int method:
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
newFile.write(byte.to_bytes(1, byteorder='big'))
I.e., each single call to to_bytes
in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte
. You can also shorten the last two lines into a single one:
newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))
Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.
var updater = {};
function geoCodeCity(goocoord) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': goocoord
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
updater.currentLocation = results[1].formatted_address;
} else {
if (status == "ERROR") {
console.log(status);
}
}
});
};
There are many methods :
CSS
<div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div>
2 . Center horizontally and vertically a single line of text
CSS
<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>
3 . Center horizontal and vertical align of an element with no specific measure
CSS
<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>
You can also use WriteConsole method to print on console.
AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);
Python 3.10 (use |
): Example for a function which takes a single argument that is either an int
or str
and returns either an int
or str
:
def func(arg: int | str) -> int | str:
^^^^^^^^^ ^^^^^^^^^
type of arg return type
Python 3.5 - 3.9 (use typing.Union
):
from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
type of arg return type
For the special case of X | None
you can use Optional[X]
.
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
For Windows:
You may find the need to check the status of your domains DNS records, or check the Name Servers to see which records the servers are pulling.
Launch Windows Command Prompt by navigating to Start > Command Prompt or via Run > CMD.
Type NSLOOKUP and hit Enter. The default Server is set to your local DNS, the Address will be your local IP.
Set the DNS Record type you wish to lookup by typing set type=##
where ## is the record type, then hit Enter. You may use ANY, A, AAAA, A+AAAA, CNAME, MX, NS, PTR, SOA, or SRV as the record type.
Now enter the domain name you wish to query then hit Enter.. In this example, we will use Managed.com.
NSLOOKUP will now return the record entries for the domain you entered.
You can also change the Name Servers which you are querying. This is useful if you are checking the records before DNS has fully propagated. To change the Name Server type server [name server]. Replace [name server] with the Name Servers you wish to use. In this example, we will set these as NSA.managed.com.
Once changed, change the query type (Step 3) if needed then enter new a new domain (Step 4.)
For Linux:
1) Check DNS Records Using Dig Command Dig stands for domain information groper is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers that are returned from the name server(s) that were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its flexibility, ease of use and clarity of output. Other lookup tools tend to have less functionality than dig.
2) Check DNS Records Using NSlookup Command Nslookup is a program to query Internet domain name servers. Nslookup has two modes interactive and non-interactive.
Interactive mode allows the user to query name servers for information about various hosts and domains or to print a list of hosts in a domain.
Non-interactive mode is used to print just the name and requested information for a host or domain. It’s network administration tool which will help them to check and troubleshoot DNS related issues.
3) Check DNS Records Using Host Command host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. When no arguments or options are given, host prints a short summary of its command line arguments and options.
I will say before all that this will not always works, i have tested this with sans-serif
font and external fonts like open sans
Sometimes, when you use huge fonts, try to approximate to font-size:49px
and upper
This is a header text with a size of 48px (font-size:48px;
in the element that contains the text).
But, if you up the 48px to font-size:49px;
(and 50px, 60px, 80px, etc...), something interesting happens
The text automatically get smooth, and seems really good
If you are looking for small fonts, you can try this, but isn't very effective.
To the parent of the text, just apply the next css property: -webkit-backface-visibility: hidden;
You can transform something like this:
To this:
(the font is Kreon
)
Consider that when you are not putting that property, -webkit-backface-visibility: visible;
is inherit
But be careful, that practice will not give always good results, if you see carefully, Chrome just make the text look a little bit blurry.
-webkit-backface-visibility: hidden;
will works too when you transform a text in Chrome (with the -webkit-transform
property, that includes rotations, skews, etc)
Without -webkit-backface-visibility: hidden;
With -webkit-backface-visibility: hidden;
Well, I don't know why that practices works, but it does for me. Sorry for my weird english.
Actually one can always create an ordinary list of numpy arrays and convert it later.
In [1]: import numpy as np
In [2]: a = np.array([[1,2],[3,4]])
In [3]: b = np.array([[1,2],[3,4]])
In [4]: l = [a]
In [5]: l.append(b)
In [6]: l = np.array(l)
In [7]: l.shape
Out[7]: (2, 2, 2)
In [8]: l
Out[8]:
array([[[1, 2],
[3, 4]],
[[1, 2],
[3, 4]]])
If you have a js file that references the jquery, it could be because the js file is in the body and not in the head section (that was my problem). You should move your js file to the head section AFTER the jquery.js reference.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script src="myfile.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
Two options for runtime type checking with generics:
Option 1 - Corrupt your constructor
Let's assume you are overriding indexOf(...), and you want to check the type just for performance, to save yourself iterating the entire collection.
Make a filthy constructor like this:
public MyCollection<T>(Class<T> t) {
this.t = t;
}
Then you can use isAssignableFrom to check the type.
public int indexOf(Object o) {
if (
o != null &&
!t.isAssignableFrom(o.getClass())
) return -1;
//...
Each time you instantiate your object you would have to repeat yourself:
new MyCollection<Apples>(Apples.class);
You might decide it isn't worth it. In the implementation of ArrayList.indexOf(...), they do not check that the type matches.
Option 2 - Let it fail
If you need to use an abstract method that requires your unknown type, then all you really want is for the compiler to stop crying about instanceof. If you have a method like this:
protected abstract void abstractMethod(T element);
You can use it like this:
public int indexOf(Object o) {
try {
abstractMethod((T) o);
} catch (ClassCastException e) {
//...
You are casting the object to T (your generic type), just to fool the compiler. Your cast does nothing at runtime, but you will still get a ClassCastException when you try to pass the wrong type of object into your abstract method.
NOTE 1: If you are doing additional unchecked casts in your abstract method, your ClassCastExceptions will get caught here. That could be good or bad, so think it through.
NOTE 2: You get a free null check when you use instanceof. Since you can't use it, you may need to check for null with your bare hands.
Couldn't that just be done by only using a positive button?
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Look at this dialog!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
[x for x in myList if x.n == 30] # list of all matches
[x.n_squared for x in myList if x.n == 30] # property of matches
any(x.n == 30 for x in myList) # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30] # indices of all matches
def first(iterable, default=None):
for item in iterable:
return item
return default
first(x for x in myList if x.n == 30) # the first match, if any
I think this would work...
create table atable
(
atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
Modified datetime DEFAULT ((0))
)
Edit: This is wrong...The minimum SQL DateTime Value is 1/1/1753. My solution provides a datetime = 1/1/1900 00:00:00. Other answers have the correct minimum date...
I've found a post here on Stackoverflow and implemented your design:
Here's the original post: https://stackoverflow.com/a/5768262/1368423
Is that what you're looking for?
HTML:
<div class="container-fluid wrapper">
<div class="row-fluid columns content">
<div class="span2 article-tree">
navigation column
</div>
<div class="span10 content-area">
content column
</div>
</div>
<div class="footer">
footer content
</div>
</div>
CSS:
html, body {
height: 100%;
}
.container-fluid {
margin: 0 auto;
height: 100%;
padding: 20px 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.columns {
background-color: #C9E6FF;
height: 100%;
}
.content-area, .article-tree{
background: #bada55;
overflow:auto;
height: 100%;
}
.footer {
background: red;
height: 20px;
}
Though this question is rather old, here's a answer :)
What you are asking for can be achieved by using jQuery's .click() event method and .on() event method
So this could be the code:
// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");
$(document).ready(function() {
// When the document is ready/loaded, execute function
// Hide hangoutButton
hangoutButton.hide();
// Assign "click"-event-method to userImage
userImage.on("click", function() {
console.log("in onclick");
hangoutButton.click();
});
});
Yes... I am using Hue 3.7.0 - The Hadoop UI and to get current date/time information we can use below commands in Hive:
SELECT from_unixtime(unix_timestamp()); --/Selecting Current Time stamp/
SELECT CURRENT_DATE; --/Selecting Current Date/
SELECT CURRENT_TIMESTAMP; --/Selecting Current Time stamp/
However, in Impala you will find that only below command is working to get date/time details:
SELECT from_unixtime(unix_timestamp()); --/Selecting Current Timestamp /
Hope it resolves your query :)
My version using variables in a bash script:
Find any backslashes and replace with forward slashes:
input="This has a backslash \\"
output=$(echo "$input" | sed 's,\\,/,g')
echo "$output"
An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files.
AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.
Use TextSwitcher
(for nice text transition animation) and timer instead.
Just remove/comment the following line from your httpd.conf file (etc/httpd/conf)
Require all granted
This is needed till Apache Version 2.2 and is not required from thereon.
PHP's implode
function can be used to convert an array into a string --- it is similar to join
in other languages.
You can use it like so:
$string_product = implode(',', $array);
With an array like [1, 2, 3]
, this would result in a string like "1,2,3"
.
I recently found and modified this snippet from an existing SO post that I have not been able to find again but I've found it very useful
// specify any elements you've attached listeners to here
const nodes = [document]
// https://developer.mozilla.org/en-US/docs/Web/Events
const logBrowserEvents = () => {
const AllEvents = {
AnimationEvent: ['animationend', 'animationiteration', 'animationstart'],
AudioProcessingEvent: ['audioprocess'],
BeforeUnloadEvent: ['beforeunload'],
CompositionEvent: [
'compositionend',
'compositionstart',
'compositionupdate',
],
ClipboardEvent: ['copy', 'cut', 'paste'],
DeviceLightEvent: ['devicelight'],
DeviceMotionEvent: ['devicemotion'],
DeviceOrientationEvent: ['deviceorientation'],
DeviceProximityEvent: ['deviceproximity'],
DragEvent: [
'drag',
'dragend',
'dragenter',
'dragleave',
'dragover',
'dragstart',
'drop',
],
Event: [
'DOMContentLoaded',
'abort',
'afterprint',
'beforeprint',
'cached',
'canplay',
'canplaythrough',
'change',
'chargingchange',
'chargingtimechange',
'checking',
'close',
'dischargingtimechange',
'downloading',
'durationchange',
'emptied',
'ended',
'error',
'fullscreenchange',
'fullscreenerror',
'input',
'invalid',
'languagechange',
'levelchange',
'loadeddata',
'loadedmetadata',
'noupdate',
'obsolete',
'offline',
'online',
'open',
'open',
'orientationchange',
'pause',
'play',
'playing',
'pointerlockchange',
'pointerlockerror',
'ratechange',
'readystatechange',
'reset',
'seeked',
'seeking',
'stalled',
'submit',
'success',
'suspend',
'timeupdate',
'updateready',
'visibilitychange',
'volumechange',
'waiting',
],
FocusEvent: [
'DOMFocusIn',
'DOMFocusOut',
'Unimplemented',
'blur',
'focus',
'focusin',
'focusout',
],
GamepadEvent: ['gamepadconnected', 'gamepaddisconnected'],
HashChangeEvent: ['hashchange'],
KeyboardEvent: ['keydown', 'keypress', 'keyup'],
MessageEvent: ['message'],
MouseEvent: [
'click',
'contextmenu',
'dblclick',
'mousedown',
'mouseenter',
'mouseleave',
'mousemove',
'mouseout',
'mouseover',
'mouseup',
'show',
],
// https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
MutationNameEvent: ['DOMAttributeNameChanged', 'DOMElementNameChanged'],
MutationEvent: [
'DOMAttrModified',
'DOMCharacterDataModified',
'DOMNodeInserted',
'DOMNodeInsertedIntoDocument',
'DOMNodeRemoved',
'DOMNodeRemovedFromDocument',
'DOMSubtreeModified',
],
OfflineAudioCompletionEvent: ['complete'],
OtherEvent: ['blocked', 'complete', 'upgradeneeded', 'versionchange'],
UIEvent: [
'DOMActivate',
'abort',
'error',
'load',
'resize',
'scroll',
'select',
'unload',
],
PageTransitionEvent: ['pagehide', 'pageshow'],
PopStateEvent: ['popstate'],
ProgressEvent: [
'abort',
'error',
'load',
'loadend',
'loadstart',
'progress',
],
SensorEvent: ['compassneedscalibration', 'Unimplemented', 'userproximity'],
StorageEvent: ['storage'],
SVGEvent: [
'SVGAbort',
'SVGError',
'SVGLoad',
'SVGResize',
'SVGScroll',
'SVGUnload',
],
SVGZoomEvent: ['SVGZoom'],
TimeEvent: ['beginEvent', 'endEvent', 'repeatEvent'],
TouchEvent: [
'touchcancel',
'touchend',
'touchenter',
'touchleave',
'touchmove',
'touchstart',
],
TransitionEvent: ['transitionend'],
WheelEvent: ['wheel'],
}
const RecentlyLoggedDOMEventTypes = {}
Object.keys(AllEvents).forEach((DOMEvent) => {
const DOMEventTypes = AllEvents[DOMEvent]
if (Object.prototype.hasOwnProperty.call(AllEvents, DOMEvent)) {
DOMEventTypes.forEach((DOMEventType) => {
const DOMEventCategory = `${DOMEvent} ${DOMEventType}`
nodes.forEach((node) => {
node.addEventListener(
DOMEventType,
(e) => {
if (RecentlyLoggedDOMEventTypes[DOMEventCategory]) return
RecentlyLoggedDOMEventTypes[DOMEventCategory] = true
// NOTE: throttle continuous events
setTimeout(() => {
RecentlyLoggedDOMEventTypes[DOMEventCategory] = false
}, 1000)
const isActive = e.target === document.activeElement
// https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
const hasActiveElement = document.activeElement !== document.body
const msg = [
DOMEventCategory,
'target:',
e.target,
...(hasActiveElement
? ['active:', document.activeElement]
: []),
]
if (isActive) {
console.info(...msg)
}
},
true,
)
})
})
}
})
}
logBrowserEvents()
// export default logBrowserEvents
Unique key allows max 2 NULL values. Explaination:
create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)
insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')
select * from teppp
null string , address1
NULL,address2
NULL,address3
If you try inserting same values as below:
insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')
Every time you will get error like:
Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.
Another way of doing this is that first you remove the class modal-open, which closes the modal. Then you remove the class modal-backdrop that removes the grayish cover of the modal.
Following code can be used:
$('body').removeClass('modal-open')
$('.modal-backdrop').remove()
R.id.button
is not part of R.layout.activity_main
. How should the activity find it in the content view?
The layout that contains the button is displayed by the Fragment, so you have to get the Button there, in the Fragment.
One thing you need to realize is in Ruby everything is an object. Given that, if you don't define your methods within Module
or Class
, Ruby will put it within the Object
class. So, your code will be local to the Object
scope.
A typical approach on Object Oriented Programming is encapsulate all logic within a class:
class Point
attr_accessor :x, :y
# If we don't specify coordinates, we start at 0.
def initialize(x = 0, y = 0)
# Notice that `@` indicates instance variables.
@x = x
@y = y
end
# Here we override the `+' operator.
def +(point)
Point.new(self.x + point.x, self.y + point.y)
end
# Here we draw the point.
def draw(offset = nil)
if offset.nil?
new_point = self
else
new_point = self + offset
end
new_point.draw_absolute
end
def draw_absolute
puts "x: #{self.x}, y: #{self.y}"
end
end
first_point = Point.new(100, 200)
second_point = Point.new(3, 4)
second_point.draw(first_point)
Hope this clarifies a bit.
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
Here is one of the way in mongodb you can achieve this.
db.usercollection.find({ $where: 'this.name.length < 4' })
The definition of asarray
is:
def asarray(a, dtype=None, order=None):
return array(a, dtype, copy=False, order=order)
So it is like array
, except it has fewer options, and copy=False
. array
has copy=True
by default.
The main difference is that array
(by default) will make a copy of the object, while asarray
will not unless necessary.
You can do docker-compose exec SERVICE_NAME sh
on the command line. The SERVICE_NAME
is defined in your docker-compose.yml
. For example,
services:
zookeeper:
image: wurstmeister/zookeeper
ports:
- "2181:2181"
The SERVICE_NAME
would be "zookeeper".
It's a simple question, with no simple answer.
More over, all of the existing answers here are whether out of date or unreliable.
So if you're searching for a solution in 2020.
Here are a few things to take in mind:
All the hardware based identifiers (SSAID, IMEI, MAC, etc) are unreliable for non-google's devices (Everything except Pixels and Nexuses), which are more than 50% of active devices worldwide. Therefore official Android identifiers best practices clearly states:
Avoid using hardware identifiers, such as SSAID (Android ID), IMEI, MAC address, etc...
That makes most of the answers above invalid. Also due to different android security updates, some of them require newer and stricter runtime permissions, which can be simply denied by user.
As example CVE-2018-9489
which affects all the WIFI based techniques mentioned above.
That makes those identifiers not only unreliable, but also unaccessible in many cases.
So in simpler words: don't use those techniques.
Many other answers here are suggesting to use the AdvertisingIdClient
, which is also incompatible, as its by design should be used only for ads profiling. It's also stated in the official reference
Only use an Advertising ID for user profiling or ads use cases
It's not only unreliable for device identification, but you also must follow the user privacy regarding ad tracking policy, which states clearly that user can reset or block it at any moment.
So don't use it either.
Since you cannot have the desired static globally unique and reliable device identifier. Android's official reference suggest:
Use a FirebaseInstanceId or a privately stored GUID whenever possible for all other use cases, except for payment fraud prevention and telephony.
It's unique for the application installation on the device, so when the user uninstall the app - it's wiped out, so it's not 100% reliable, but it's the next best thing.
To use FirebaseInstanceId
add the latest firebase-messaging dependency into your gradle
implementation 'com.google.firebase:firebase-messaging:20.2.4'
And use the code below in a background thread:
String reliableIdentifier = FirebaseInstanceId.getInstance().getId();
If you need to store the device identification on your remote server, then don't store it as is (plain text), but a hash with salt.
Today it's not only a best practice, you actually must to do it by law according to GDPR - identifiers and similar regulations.
As Paula, I had the same problem, my modal was not showing, and I realized that my button was in a '< form >' tag ... :
<button class="btn btn-danger" data-toggle="modal" data-target="#deleteItemModal">Delete</button>
I just replaced < button > by < a >, and my modal worked well
<a class="btn btn-danger" data-toggle="modal" data-target="#deleteItemModal">Delete</a>
Also had this problem occurring on the web application surface. Eventually found out that the same error message comes from the SQL update statement in the specific table.
Finally then figured out that the column definition in the relating history table(s) did not map the original table column length of nvarchar
types in some specific cases.
There is no DATEDIFF()
function in Oracle. On Oracle, it is an arithmetic issue
select DATE1-DATE2 from table
You want to use %d
or %i
for integers. %@
is used for objects.
It's worth noting, though, that the following code will accomplish the same task and is much clearer.
label.intValue = count;
Without any libraries, you could do this instead:
def to_frequency_table(data):
frequencytable = {}
for key in data:
if key in frequencytable:
frequencytable[key] += 1
else:
frequencytable[key] = 1
return frequencytable
Example:
to_frequency_table([1,1,1,1,2,3,4,4])
>>> {1: 4, 2: 1, 3: 1, 4: 2}
Select the code you want to comment, then use Ctr + / to comment and Ctrl + / also to uncomment. It may not work for all types of source files, but it works great for Java code.
You probably need quotes around those string fields, but, you should be using parameterized queries!
cmd.CommandText = "INSERT INTO Data ([Name],PhoneNo,Address) VALUES (@name, @phone, @address)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Connection = connection;
Incidentally, your original query could have been fixed like this (note the single quotes):
"VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";
but this would have made it vulnerable to SQL Injection attacks since a user could type in
'; drop table users; --
into one of your textboxes. Or, more mundanely, poor Daniel O'Reilly would break your query every time.
Try to use the WEEKDAY()
function.
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
Try this Code :
public class FirebaseMessagingServices extends com.google.firebase.messaging.FirebaseMessagingService {_x000D_
private static final String TAG = "MY Channel";_x000D_
Bitmap bitmap;_x000D_
_x000D_
@Override_x000D_
public void onMessageReceived(RemoteMessage remoteMessage) {_x000D_
super.onMessageReceived(remoteMessage);_x000D_
Utility.printMessage(remoteMessage.getNotification().getBody());_x000D_
_x000D_
// Check if message contains a data payload._x000D_
if (remoteMessage.getData().size() > 0) {_x000D_
Log.d(TAG, "Message data payload: " + remoteMessage.getData());_x000D_
_x000D_
String title = remoteMessage.getData().get("title");_x000D_
String body = remoteMessage.getData().get("body");_x000D_
String message = remoteMessage.getData().get("message");_x000D_
String imageUri = remoteMessage.getData().get("image");_x000D_
String msg_id = remoteMessage.getData().get("msg-id");_x000D_
_x000D_
_x000D_
Log.d(TAG, "1: " + title);_x000D_
Log.d(TAG, "2: " + body);_x000D_
Log.d(TAG, "3: " + message);_x000D_
Log.d(TAG, "4: " + imageUri);_x000D_
_x000D_
_x000D_
if (imageUri != null)_x000D_
bitmap = getBitmapfromUrl(imageUri);_x000D_
_x000D_
}_x000D_
_x000D_
sendNotification(message, bitmap, title, msg_id);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
private void sendNotification(String message, Bitmap image, String title,String msg_id) {_x000D_
int notifyID = 0;_x000D_
try {_x000D_
notifyID = Integer.parseInt(msg_id);_x000D_
} catch (NumberFormatException e) {_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
String CHANNEL_ID = "my_channel_01"; // The id of the channel._x000D_
Intent intent = new Intent(this, HomeActivity.class);_x000D_
intent.putExtra("title", title);_x000D_
intent.putExtra("message", message);_x000D_
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);_x000D_
_x000D_
_x000D_
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,_x000D_
PendingIntent.FLAG_ONE_SHOT);_x000D_
_x000D_
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);_x000D_
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "01")_x000D_
.setContentTitle(title)_x000D_
.setSmallIcon(R.mipmap.ic_notification)_x000D_
.setStyle(new NotificationCompat.BigTextStyle()_x000D_
.bigText(message))_x000D_
.setContentText(message)_x000D_
.setAutoCancel(true)_x000D_
.setSound(defaultSoundUri)_x000D_
.setChannelId(CHANNEL_ID)_x000D_
.setContentIntent(pendingIntent);_x000D_
_x000D_
if (image != null) {_x000D_
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle() //Set the Image in Big picture Style with text._x000D_
.bigPicture(image)_x000D_
.setSummaryText(message)_x000D_
.bigLargeIcon(null));_x000D_
}_x000D_
_x000D_
_x000D_
NotificationManager notificationManager =_x000D_
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);_x000D_
_x000D_
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // For Oreo and greater than it, we required Notification Channel._x000D_
CharSequence name = "My New Channel"; // The user-visible name of the channel._x000D_
int importance = NotificationManager.IMPORTANCE_HIGH;_x000D_
_x000D_
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,name, importance); //Create Notification Channel_x000D_
notificationManager.createNotificationChannel(channel);_x000D_
}_x000D_
_x000D_
notificationManager.notify(notifyID /* ID of notification */, notificationBuilder.build());_x000D_
}_x000D_
_x000D_
public Bitmap getBitmapfromUrl(String imageUrl) { //This method returns the Bitmap from Url;_x000D_
try {_x000D_
URL url = new URL(imageUrl);_x000D_
HttpURLConnection connection = (HttpURLConnection) url.openConnection();_x000D_
connection.setDoInput(true);_x000D_
connection.connect();_x000D_
InputStream input = connection.getInputStream();_x000D_
Bitmap bitmap = BitmapFactory.decodeStream(input);_x000D_
return bitmap;_x000D_
_x000D_
} catch (Exception e) {_x000D_
// TODO Auto-generated catch block_x000D_
e.printStackTrace();_x000D_
return null;_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}
_x000D_
I used starikovs' solution. I started with a bash window and gave the commands
cd ~
touch .bashrc
Then I found the .bashrc file in windows explorer, opened it with notepad++ and added
PATH=$PATH:"C:\Program Files (x86)\Notepad++"
so that bash knows where to find Notepad++. (Having Notepad++ in the bash PATH is a useful thing on its own!) Then I pasted his line
git config --global core.editor "notepad++.exe -multiInst"
into a bash window. I started a new bash window for a git repository to test things with the command
git rebase -i HEAD~10
and the file opened in Notepad++ as hoped.
It depends on how you define better. If you want the code to look cleaner, you can use .Sum() as mentioned in other answers. If you want the operation to run quickly and you have a large array, you can make it parallel by breaking it into sub sums and then sum the results.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>com</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
<key>net</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
<key>org</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
This will allow to connect to .com .net .org
I tried "validating" de *.jsp and *.xml files in eclipse with the validate tool.
"right click on directory/file ->- validate" and it worked!
Using eclipse juno.
Hope it helps!
I found the solution for it by analyzing the data packets using wireshark. What I found is that while making a secure connection, android was falling back to SSLv3 from TLSv1 . It is a bug in android versions < 4.4 , and it can be solved by removing the SSLv3 protocol from Enabled Protocols list. I made a custom socketFactory class called NoSSLv3SocketFactory.java. Use this to make a socketfactory.
/*Copyright 2015 Bhavit Singh Sengar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class NoSSLv3SocketFactory extends SSLSocketFactory{
private final SSLSocketFactory delegate;
public NoSSLv3SocketFactory() {
this.delegate = HttpsURLConnection.getDefaultSSLSocketFactory();
}
public NoSSLv3SocketFactory(SSLSocketFactory delegate) {
this.delegate = delegate;
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
private Socket makeSocketSafe(Socket socket) {
if (socket instanceof SSLSocket) {
socket = new NoSSLv3SSLSocket((SSLSocket) socket);
}
return socket;
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return makeSocketSafe(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException {
return makeSocketSafe(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
return makeSocketSafe(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return makeSocketSafe(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return makeSocketSafe(delegate.createSocket(address, port, localAddress, localPort));
}
private class NoSSLv3SSLSocket extends DelegateSSLSocket {
private NoSSLv3SSLSocket(SSLSocket delegate) {
super(delegate);
}
@Override
public void setEnabledProtocols(String[] protocols) {
if (protocols != null && protocols.length == 1 && "SSLv3".equals(protocols[0])) {
List<String> enabledProtocols = new ArrayList<String>(Arrays.asList(delegate.getEnabledProtocols()));
if (enabledProtocols.size() > 1) {
enabledProtocols.remove("SSLv3");
System.out.println("Removed SSLv3 from enabled protocols");
} else {
System.out.println("SSL stuck with protocol available for " + String.valueOf(enabledProtocols));
}
protocols = enabledProtocols.toArray(new String[enabledProtocols.size()]);
}
super.setEnabledProtocols(protocols);
}
}
public class DelegateSSLSocket extends SSLSocket {
protected final SSLSocket delegate;
DelegateSSLSocket(SSLSocket delegate) {
this.delegate = delegate;
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public String[] getEnabledCipherSuites() {
return delegate.getEnabledCipherSuites();
}
@Override
public void setEnabledCipherSuites(String[] suites) {
delegate.setEnabledCipherSuites(suites);
}
@Override
public String[] getSupportedProtocols() {
return delegate.getSupportedProtocols();
}
@Override
public String[] getEnabledProtocols() {
return delegate.getEnabledProtocols();
}
@Override
public void setEnabledProtocols(String[] protocols) {
delegate.setEnabledProtocols(protocols);
}
@Override
public SSLSession getSession() {
return delegate.getSession();
}
@Override
public void addHandshakeCompletedListener(HandshakeCompletedListener listener) {
delegate.addHandshakeCompletedListener(listener);
}
@Override
public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) {
delegate.removeHandshakeCompletedListener(listener);
}
@Override
public void startHandshake() throws IOException {
delegate.startHandshake();
}
@Override
public void setUseClientMode(boolean mode) {
delegate.setUseClientMode(mode);
}
@Override
public boolean getUseClientMode() {
return delegate.getUseClientMode();
}
@Override
public void setNeedClientAuth(boolean need) {
delegate.setNeedClientAuth(need);
}
@Override
public void setWantClientAuth(boolean want) {
delegate.setWantClientAuth(want);
}
@Override
public boolean getNeedClientAuth() {
return delegate.getNeedClientAuth();
}
@Override
public boolean getWantClientAuth() {
return delegate.getWantClientAuth();
}
@Override
public void setEnableSessionCreation(boolean flag) {
delegate.setEnableSessionCreation(flag);
}
@Override
public boolean getEnableSessionCreation() {
return delegate.getEnableSessionCreation();
}
@Override
public void bind(SocketAddress localAddr) throws IOException {
delegate.bind(localAddr);
}
@Override
public synchronized void close() throws IOException {
delegate.close();
}
@Override
public void connect(SocketAddress remoteAddr) throws IOException {
delegate.connect(remoteAddr);
}
@Override
public void connect(SocketAddress remoteAddr, int timeout) throws IOException {
delegate.connect(remoteAddr, timeout);
}
@Override
public SocketChannel getChannel() {
return delegate.getChannel();
}
@Override
public InetAddress getInetAddress() {
return delegate.getInetAddress();
}
@Override
public InputStream getInputStream() throws IOException {
return delegate.getInputStream();
}
@Override
public boolean getKeepAlive() throws SocketException {
return delegate.getKeepAlive();
}
@Override
public InetAddress getLocalAddress() {
return delegate.getLocalAddress();
}
@Override
public int getLocalPort() {
return delegate.getLocalPort();
}
@Override
public SocketAddress getLocalSocketAddress() {
return delegate.getLocalSocketAddress();
}
@Override
public boolean getOOBInline() throws SocketException {
return delegate.getOOBInline();
}
@Override
public OutputStream getOutputStream() throws IOException {
return delegate.getOutputStream();
}
@Override
public int getPort() {
return delegate.getPort();
}
@Override
public synchronized int getReceiveBufferSize() throws SocketException {
return delegate.getReceiveBufferSize();
}
@Override
public SocketAddress getRemoteSocketAddress() {
return delegate.getRemoteSocketAddress();
}
@Override
public boolean getReuseAddress() throws SocketException {
return delegate.getReuseAddress();
}
@Override
public synchronized int getSendBufferSize() throws SocketException {
return delegate.getSendBufferSize();
}
@Override
public int getSoLinger() throws SocketException {
return delegate.getSoLinger();
}
@Override
public synchronized int getSoTimeout() throws SocketException {
return delegate.getSoTimeout();
}
@Override
public boolean getTcpNoDelay() throws SocketException {
return delegate.getTcpNoDelay();
}
@Override
public int getTrafficClass() throws SocketException {
return delegate.getTrafficClass();
}
@Override
public boolean isBound() {
return delegate.isBound();
}
@Override
public boolean isClosed() {
return delegate.isClosed();
}
@Override
public boolean isConnected() {
return delegate.isConnected();
}
@Override
public boolean isInputShutdown() {
return delegate.isInputShutdown();
}
@Override
public boolean isOutputShutdown() {
return delegate.isOutputShutdown();
}
@Override
public void sendUrgentData(int value) throws IOException {
delegate.sendUrgentData(value);
}
@Override
public void setKeepAlive(boolean keepAlive) throws SocketException {
delegate.setKeepAlive(keepAlive);
}
@Override
public void setOOBInline(boolean oobinline) throws SocketException {
delegate.setOOBInline(oobinline);
}
@Override
public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
delegate.setPerformancePreferences(connectionTime, latency, bandwidth);
}
@Override
public synchronized void setReceiveBufferSize(int size) throws SocketException {
delegate.setReceiveBufferSize(size);
}
@Override
public void setReuseAddress(boolean reuse) throws SocketException {
delegate.setReuseAddress(reuse);
}
@Override
public synchronized void setSendBufferSize(int size) throws SocketException {
delegate.setSendBufferSize(size);
}
@Override
public void setSoLinger(boolean on, int timeout) throws SocketException {
delegate.setSoLinger(on, timeout);
}
@Override
public synchronized void setSoTimeout(int timeout) throws SocketException {
delegate.setSoTimeout(timeout);
}
@Override
public void setTcpNoDelay(boolean on) throws SocketException {
delegate.setTcpNoDelay(on);
}
@Override
public void setTrafficClass(int value) throws SocketException {
delegate.setTrafficClass(value);
}
@Override
public void shutdownInput() throws IOException {
delegate.shutdownInput();
}
@Override
public void shutdownOutput() throws IOException {
delegate.shutdownOutput();
}
@Override
public String toString() {
return delegate.toString();
}
@Override
public boolean equals(Object o) {
return delegate.equals(o);
}
}
}
Use this class like this while connecting :
SSLContext sslcontext = SSLContext.getInstance("TLSv1");
sslcontext.init(null, null, null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());
HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);
l_connection = (HttpsURLConnection) l_url.openConnection();
l_connection.connect();
UPDATE :
Now, correct solution would be to install a newer security provider using Google Play Services:
ProviderInstaller.installIfNeeded(getApplicationContext());
This effectively gives your app access to a newer version of OpenSSL and Java Security Provider, which includes support for TLSv1.2 in SSLEngine. Once the new provider is installed, you can create an SSLEngine which supports SSLv3, TLSv1, TLSv1.1 and TLSv1.2 the usual way:
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
SSLEngine engine = sslContext.createSSLEngine();
Or you can restrict the enabled protocols using engine.setEnabledProtocols
.
Don't forget to add the following dependency (check the latest version here):
implementation 'com.google.android.gms:play-services-auth:17.0.0'
For more info, checkout this link.
Though this might be too late to comment but here's the working code for problems such as yours.
<div id="player">
<audio autoplay hidden>
<source src="link/to/file/file.mp3" type="audio/mpeg">
If you're reading this, audio isn't supported.
</audio>
</div>
The ONLY right way to do it with XPath :
//div[contains(concat(" ", normalize-space(@class), " "), " Test ")]
The function normalize-space
strips leading and trailing whitespace, and also replaces sequences of whitespace characters by a single space.
If not need many of these Xpath queries, you might want to use a library that converts CSS selectors to XPath, as CSS selectors are usually a lot easier to both read and write than XPath queries. For example, in this case, you could use both div[class~="Test"]
and div.Test
to get the same result.
Some libraries I've been able to find :
ogdate
is itself a string, why are you trying to access it's value
property that it doesn't have ?
console.log(og_date.split('-'));
Create a new WebSite, after error go to folder where you created a project, in a txt app open the .csproj file, find this tag "<UseIIS>
" and change "false" to "true", in lines bellow find the tag "<IISUrl>
" then put the iis url(find url in iis), your tags must be like this:
<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>0</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost/yourIISAppAlias
</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
Consider 2 dataFrames:
>>> aDF.show()
+---+----+
| id|datA|
+---+----+
| 1| a1|
| 2| a2|
| 3| a3|
+---+----+
and
>>> bDF.show()
+---+----+
| id|datB|
+---+----+
| 2| b2|
| 3| b3|
| 4| b4|
+---+----+
To accomplish what you are looking for, there are 2 ways:
1. Different joining condition. Instead of saying aDF.id == bDF.id
aDF.join(bDF, aDF.id == bDF.id, "outer")
Write this:
aDF.join(bDF, "id", "outer").show()
+---+----+----+
| id|datA|datB|
+---+----+----+
| 1| a1|null|
| 3| a3| b3|
| 2| a2| b2|
| 4|null| b4|
+---+----+----+
This will automatically get rid of the extra the dropping process.
2. Use Aliasing: You will lose data related to B Specific Id's in this.
>>> from pyspark.sql.functions import col
>>> aDF.alias("a").join(bDF.alias("b"), aDF.id == bDF.id, "outer").drop(col("b.id")).show()
+----+----+----+
| id|datA|datB|
+----+----+----+
| 1| a1|null|
| 3| a3| b3|
| 2| a2| b2|
|null|null| b4|
+----+----+----+
isEmpty()
is included in the S4Vectors base package. No need to load any other packages.
a <- which(1:3 == 5)
isEmpty(a)
# [1] TRUE
As you can probably see from the multitude of different (and often mutually exclusive) answers, it depends on who you ask. In some arenas, the terms are synonymous. Or they might each refer to two similar concepts:
In either case, the intention is to allow the program to not be blocked waiting for a slow process to complete - how the program is expected to respond is the only real difference. Which term refers to which also changes from programmer to programmer, language to language, or platform to platform. Or the terms may refer to completely different concepts (such as the use of synchronous/asynchronous in relation to thread programming).
Sorry, but I don't believe there is a single right answer that is globally true.
While React.js is a parent Javascript library for developing web applications.
While you use tags like <View>
, <Text>
very frequently in React-Native, React.js uses web html tags like <div>
<h1>
<h2>
, which are only synonyms in dictionary of web/mobile developments.
For React.js you need DOM for path rendering of html tags, while for mobile application: React-Native uses AppRegistry to register your app.
I hope this is an easy explanation for quick differences/similarities in React.js and React-Native.
It can be because you have jpa dependendencies and plugins...
just comment it if not use(build.gradle or pom file)
e. g.
// kotlin("plugin.jpa") version "1.3.61"
// implementation("org.springframework.boot:spring-boot-starter-data-jpa")
There's a couple of other tricks that Postgres offers for string matching (if that happens to be your DB):
ILIKE, which is a case insensitive LIKE match:
select * from people where name ilike 'JOHN'
Matches:
And if you want to get really mad you can use regular expressions:
select * from people where name ~ 'John.*'
Matches:
As noted in several blogs, strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.
$dt = date("Y-m-d");
echo date( "Y-m-d", strtotime( "$dt +1 day" ) ); // PHP: 2009-03-04
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP: 2009-03-31
why you need a for-loop for this? the solution is very obvious:
answers.add(answer1);
answers.add(answer2);
answers.add(answer3);
that's it. no for-loop needed.
Although Marcelo's solution seems to be working great, you may not need to download the font at all! Just link to it remotely.
E.g the font is hosted on example.com, do
@font-face {
font-family: "Font Name";
font-style: normal;
src: url(http://example.com/webfonts/font-name.woff);
}
You may easily figure out the direct url to the font by looking into css code from example.com and see how they linked the file.
Got the same error, CHECK THIS : MINOR SILLY MISTAKE
check findviewbyid(R.id.yourID); If you have put the id correct or not.
This also happens when your password contains some special characters like @,$,etc. To avoid this situation you can wrap password in single quotes:
$ mysql -usomeuser -p's0mep@$$w0Rd'
Or instead don't use password while entering. Leave it blank and then type it when terminal asks. This is the recommended way.
$ mysql -usomeuser -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 191
Server version: 5.5.46-0ubuntu0.14.04.2 (Ubuntu)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Maybe you could make the field readonly and on submit disable all readonly fields
$(".myform").submit(function(e) {
$("input[readonly]").prop("disabled", true);
});
and the input (+ script) should be
<input type="text" readonly="readonly" name="test" value="test" />
$('input[readonly]').click(function () {
$(this).removeAttr('readonly');
});
$(".myform").submit(function(e) {
$("input[readonly]").prop("disabled", true);
e.preventDefault();
});
$('.reset').click(function () {
$("input[readonly]").prop("disabled", false);
})
$('input[readonly]').click(function () {
$(this).removeAttr('readonly');
})
_x000D_
input[readonly] {
color: gray;
border-color: currentColor;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="myform">
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<input readonly="readonly" value="test" />
<button>Submit</button>
<button class="reset" type="button">Reset</button>
</form>
_x000D_
In case you want to see what this all means, here is a blow-by-blow of everything:
CREATE TABLE `users_partners` (
`uid` int(11) NOT NULL DEFAULT '0',
`pid` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`uid`,`pid`),
KEY `partner_user` (`pid`,`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
Primary key is based on both columns of this quick reference table. A Primary key requires unique values.
Let's begin:
INSERT INTO users_partners (uid,pid) VALUES (1,1);
...1 row(s) affected
INSERT INTO users_partners (uid,pid) VALUES (1,1);
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'
INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1);
...0 row(s) affected
INSERT INTO users_partners (uid,pid) VALUES (1,1) ON DUPLICATE KEY UPDATE uid=uid
...0 row(s) affected
note, the above saved too much extra work by setting the column equal to itself, no update actually needed
REPLACE INTO users_partners (uid,pid) VALUES (1,1)
...2 row(s) affected
and now some multiple row tests:
INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'
INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...3 row(s) affected
no other messages were generated in console, and it now has those 4 values in the table data. I deleted everything except (1,1) so I could test from the same playing field
INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4) ON DUPLICATE KEY UPDATE uid=uid
...3 row(s) affected
REPLACE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...5 row(s) affected
So there you have it. Since this was all performed on a fresh table with nearly no data and not in production, the times for execution were microscopic and irrelevant. Anyone with real-world data would be more than welcome to contribute it.
If you have a partial page form for both editing and adding, then the trick I use to default value to 0
is to do the following:
@Html.TextBox("Age", Model.Age ?? 0)
That way it will be 0
if unset or the actual age if it exists.
I had this issue. A repo was requiring me to input credentials every time. All my other repos were not asking for my credentials. They were even set up to track GitLab using HTTPS under the same account credentials, so it was weird that they all worked fine except one.
Comparing the .git/config files, I found that there were 2 key differences in the URLs which was causing the issue:
Does ask for credentials:
https://gitlab.com/myaccount/myproject
Does not ask for credentials:
https://[email protected]/myaccount/myproject.git
So adding the "myaccount@" and ".git" resolved the issue in my case.
Partially based on Mohsen's answer (the added first condition covers the case where the child is hidden before the parent):
jQuery.fn.isChildOverflowing = function (child) {
var p = jQuery(this).get(0);
var el = jQuery(child).get(0);
return (el.offsetTop < p.offsetTop || el.offsetLeft < p.offsetLeft) ||
(el.offsetTop + el.offsetHeight > p.offsetTop + p.offsetHeight || el.offsetLeft + el.offsetWidth > p.offsetLeft + p.offsetWidth);
};
Then just do:
jQuery('#parent').isChildOverflowing('#child');
If the file does not exists, open(name,'r+')
will fail.
You can use open(name, 'w')
, which creates the file if the file does not exist, but it will truncate the existing file.
Alternatively, you can use open(name, 'a')
; this will create the file if the file does not exist, but will not truncate the existing file.
@media (max-width: 767px) {
img {
display: table;
margin: 0 auto;
}
}
After reading Java 7 Update 21 Security Improvements in Detail mention..
With the introduced changes it is most likely that no end-user is able to run your application when they are either self-signed or unsigned.
..I was wondering how this would go for loose class files - the 'simplest' applets of all.
Your security settings have blocked a local application from running
That is the dialog seen for an applet consisting of loose class files being loaded off the local file system when the JRE is set to the default 'High' security setting.
Note that a slight quirk of the JRE only produced that on point 3 of.
If you load the simple applet (loose class file) seen at this resizable applet demo off the internet - which boasts an applet
element of:
<applet
code="PlafChanger.class"
codebase="."
alt="Pluggable Look'n'Feel Changer appears here if Java is enabled"
width='100%'
height='250'>
<p>Pluggable Look'n'Feel Changer appears here in a Java capable browser.</p>
</applet>
It also seems to load successfully. Implying that:-
Applets loaded from the local file system are now subject to a stricter security sandbox than those loaded from the internet or a local server.
As of Java 7 update 51.
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
This happens to me every time I add a pod to the podfile.
I constantly try and find the problem but I just go round in circles again and again!
The error messages range, however the way to fix it is the same every time!
Comment out(#) ALL of the pods in the podfile and run pod install in terminal.
Then...
Uncomment out all of the pods in the podfile and run pod install again.
This has worked for me every single time!
Another way:
print "test1.py"
import subprocess
subprocess.call("test1.py", shell=True)
The advantage to this method is that you don't have to edit an existing Python script to put all its code into a subroutine.
Here's a short one-liner using regular expressions:
print [re.compile(r"8").sub("", m) for m in mylist]
If we separate the regex operations and improve the namings:
pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res
For what its worth, installing a system app to the /system/app
directory will be:
adb push appname.apk /system/app/
Just ensure you're in the right directory where the target .apk file to be installed is, or you could just copy the .apk file to the platform-tools
directory of the Android SDK and adb
would definitely find it.
You could opt for a pure CSS solution:
#hfont1 {
transition: color 1s ease-in-out;
-moz-transition: color 1s ease-in-out; /* FF 4 */
-webkit-transition: color 1s ease-in-out; /* Safari & Chrome */
-o-transition: color 1s ease-in-out; /* Opera */
}
The I
attribute only exists on matrix
objects, not ndarray
s. You can use numpy.linalg.inv
to invert arrays:
inverse = numpy.linalg.inv(x)
Note that the way you're generating matrices, not all of them will be invertible. You will either need to change the way you're generating matrices, or skip the ones that aren't invertible.
try:
inverse = numpy.linalg.inv(x)
except numpy.linalg.LinAlgError:
# Not invertible. Skip this one.
pass
else:
# continue with what you were doing
Also, if you want to go through all 3x3 matrices with elements drawn from [0, 10), you want the following:
for comb in itertools.product(range(10), repeat=9):
rather than combinations_with_replacement
, or you'll skip matrices like
numpy.array([[0, 1, 0],
[0, 0, 0],
[0, 0, 0]])
'UserId' is wholly the wrong approach. The Verb (HTTP Methods) and Noun approach is what Roy Fielding meant for The REST architecture. The Nouns are either:
One good naming convention is:
[POST or Create](To the *collection*)
sub.domain.tld/class_name.{media_type}
[GET or Read](of *one* thing)
sub.domain.tld/class_name/id_value.{media_type}
[PUT or Update](of *one* thing)
sub.domain.tld/class_name/id_value.{media_type}
[DELETE](of *one* thing)
sub.domain.tld/class_name/id_value.{media_type}
[GET or Search](of a *collection*, FRIENDLY URL)
sub.domain.tld/class_name.{media_type}/{var}/{value}/{more-var-value-pairs}
[GET or Search](of a *collection*, Normal URL)
sub.domain.tld/class_name.{media_type}?var=value&more-var-value-pairs
Where {media_type} is one of: json, xml, rss, pdf, png, even html.
It is possible to distinguish the collection by adding an 's' at the end, like:
'users.json' *collection of things*
'user/id_value.json' *single thing*
But this means you have to keep track of where you have put the 's' and where you haven't. Plus half the planet (Asians for starters) speaks languages without explicit plurals so the URL is less friendly to them.
I think the reason it doesn't work has something to do with the fact that you have the right
position set, but not the left
.
If you manually set the left
to the current position, it seems to go:
Live example: http://jsfiddle.net/XqqtN/
var left = $('#coolDiv').offset().left; // Get the calculated left position
$("#coolDiv").css({left:left}) // Set the left to its calculated position
.animate({"left":"0px"}, "slow");
EDIT:
Appears as though Firefox behaves as expected because its calculated left
position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto
for the left position.
Because auto
is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o)
Setting the left position manually before the animate as above fixes the issue.
If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable:
$("#coolDiv").css('left', function(){ return $(this).offset().left; })
.animate({"left":"0px"}, "slow"); ?
Here's some pure-Python code you can use to calculate the mean and standard deviation.
All code below is based on the statistics
module in Python 3.4+.
def mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/n # in Python 2 use sum(data)/float(n)
def _ss(data):
"""Return sum of square deviations of sequence data."""
c = mean(data)
ss = sum((x-c)**2 for x in data)
return ss
def stddev(data, ddof=0):
"""Calculates the population standard deviation
by default; specify ddof=1 to compute the sample
standard deviation."""
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/(n-ddof)
return pvar**0.5
Note: for improved accuracy when summing floats, the statistics
module uses a custom function _sum
rather than the built-in sum
which I've used in its place.
Now we have for example:
>>> mean([1, 2, 3])
2.0
>>> stddev([1, 2, 3]) # population standard deviation
0.816496580927726
>>> stddev([1, 2, 3], ddof=1) # sample standard deviation
0.1
If a different library is fine for you, you could try org.json:
JSONObject object = new JSONObject(myJSONString);
String[] keys = JSONObject.getNames(object);
for (String key : keys)
{
Object value = object.get(key);
// Determine type of value and do something with it...
}
Your issue here is that you're not understanding the scope that you're setting.
You are passing the ready
function a function itself. Within this function, you're creating another function called codeAddress
. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).
For example:
var myfunction = function(){
var myVar = 12345;
};
console.log(myVar); // 'undefined' - since it is within
// the scope of the function only.
Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress
method available to all:
$(function(){
$("#imgid").click(function(){
var address = $("#formatedAddress").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
});
});
(You should remove the existing onclick
and add an ID to the image element that you want to handle)
Note that I've replaced $(document).ready()
with its shortcut of just $()
(http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById
with the jQuery object.
For the official CLI client "psql" see here. And "pgAdmin3" 1.10 (still in beta) has "pgScript".
Ruby FTW:
ls | ruby -e 'puts STDIN.readlines.shuffle'
this may help
Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");
I do it for beamer presentations,
provide tmp-0.png through tmp-34.png
\usepackage{animate}
\begin{frame}{Torque Generating Mechanism}
\animategraphics[loop,controls,width=\linewidth]{12}{output/tmp-}{0}{34}
\end{frame}
Another way of doing it is by using isdigit function. Below is the code for it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
char input[MAXINPUT] = "";
int length,i;
scanf ("%s", input);
length = strlen (input);
for (i=0;i<length; i++)
if (!isdigit(input[i]))
{
printf ("Entered input is not a number\n");
exit(1);
}
printf ("Given input is a number\n");
}
You can use YQL to do the request without needing to host your own proxy. I have made a simple function to make it easier to run commands:
function RunYQL(command, callback){
callback_name = "__YQL_callback_"+(new Date()).getTime();
window[callback_name] = callback;
a = document.createElement('script');
a.src = "http://query.yahooapis.com/v1/public/yql?q="
+escape(command)+"&format=json&callback="+callback_name;
a.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(a);
}
If you have jQuery, you may use $.getJSON instead.
A sample may be this:
RunYQL('select * from html where url="http://www.google.com/"',
function(data){/* actions */}
);
In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".
this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/"
+ Assembly.GetExecutingAssembly().GetName().Name
+ ";component/"
+ "Icons/Freq.png", UriKind.Absolute));
I also made a function if anybody would like it...
/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
if (pathInApplication[0] == '/')
{
pathInApplication = pathInApplication.Substring(1);
}
return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute));
}
Usage:
this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");
One way is:
select table.*
from table
join
(
select ID, max(Date) as max_dt
from table
group by ID
) t
on table.ID= t.ID and table.Date = t.max_dt
Note that if you have multiple equally higher dates for same ID, then you will get all those rows in result
Most of the options are problematic for multi-select. Place Title attribute, and make first option as data-hidden="true"
<select class="selectpicker" title="Some placeholder text...">
<option data-hidden="true"></option>
<option>First</option>
<option>Second</option>
</select>
Yes you right and I just want to make it understandable for complete beginners.
<link rel="shortcut icon" href="images/favicon.ico" />
and past it without any changes in between <head>
opening and </head>
closing tag.The article Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError
error explains the behavior in great details.
The problem with you setup is that ngAfterViewInit
lifecycle hook is executed after change detection processed DOM updates. And you're effectively changing the property that is used in the template in this hook which means that DOM needs to be re-rendered:
ngAfterViewInit() {
this.message = 'all done loading :)'; // needs to be rendered the DOM
}
and this will require another change detection cycle and Angular by design only runs one digest cycle.
You basically have two alternatives how to fix it:
update the property asynchronously either using setTimeout
, Promise.then
or asynchronous observable referenced in the template
perform the property update in a hook before the DOM update - ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked.
I have encountered this error during unit testing of a component (only during testing, within application it worked normally). The solution is to import ReactiveFormsModule
in .spec.ts
file:
// Import module
import { ReactiveFormsModule } from '@angular/forms';
describe('MyComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [ReactiveFormsModule], // Also add it to 'imports' array
})
.compileComponents();
}));
});
I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.
package local.test.servlet;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;
@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
// /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
System.out.println(templateFileUrl.getPath());
String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
String outputFileDir = "MasatoExcelHorizontalOutput";
ReportProcessor reportProcessor = new ReportProcessor();
ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);
ReportSheet outputSheet = new ReportSheet("MySheet");
outputBook.addReportSheet(outputSheet);
reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
System.out.println("wtf???");
reportProcessor.process(outputBook);
System.out.println("done!!");
}
catch(Exception e) {
System.out.println(e);
}
} //end doGet()
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}//end class
class OutputStreamExporter extends ReportBookExporter {
private HttpServletResponse response;
public OutputStreamExporter(HttpServletResponse response) {
this.response = response;
}
@Override
public String getExtention() {
return null;
}
@Override
public String getFormatType() {
return ExcelExporter.FORMAT_TYPE;
}
@Override
public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {
System.out.println(book.getFirstVisibleTab());
System.out.println(book.getSheetName(0));
//TODO write to stream
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
book.write(response.getOutputStream());
response.getOutputStream().close();
System.out.println("booya!!");
}
catch(Exception e) {
System.out.println(e);
}
}
}//end class
Switch the order of the code: You're calling the click event before it is attached.
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
[self.navigationController setDelegate:self];
Set the delegate to the root view controller.
I had the same problem when I upgraded jquery UI to 1.8.1 without upgrading the corresponding theme. Only is needed to upgrade the theme too and "auto" works again.
I realize this is an old thread, but @alex 's answer needs to be marked as the correct answer
element.getBoundingClientRect()
is an exact match to jQuery's $(element).offset()
And it's compatible with IE4+ ... https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
along the lines of bayer's answer:
''.join(i for i in s if i.isdigit())
Here is an interesting solution: it uses the browsers CSS engine to to add a dummy property to elements matching the selector and then evaluates the computed style to find matched elements:
It does dynamically create a style rule [...] It then scans the whole document (using the much decried and IE-specific but very fast document.all) and gets the computed style for each of the elements. We then look for the foo property on the resulting object and check whether it evaluates as “bar”. For each element that matches, we add to an array.
You need to specify the path where your chromedriver is located.
Place chromedriver on your system path, or where your code is.
If not using a system path, link your chromedriver.exe
(For non-Windows users, it's just called chromedriver
):
browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
(Set executable_path
to the location where your chromedriver is located.)
If you've placed chromedriver on your System Path, you can shortcut by just doing the following:
browser = webdriver.Chrome()
If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:
chmod +x chromedriver
That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium
I've ported c# code used to work against smtp.google.com:587 to work via office365 without success. Tried all combinations of Credential before/after using Ssl and almost every recommendation made on the Internet - w/o success (got 5.7.1 .... error).
Finally got this line from somewhere as last resort, just before .Send(message)
smtpClient.TargetName = "STARTTLS/smtp.office365.com";
Since then - every send() is big success.
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
There is such possibility even if they are not Parent - Child relationship - and that's Flux. There is pretty good (for me personally) implementation for that called Alt.JS (with Alt-Container).
For example you can have Sidebar that is dependent on what is set in component Details. Component Sidebar is connected with SidebarActions and SidebarStore, while Details is DetailsActions and DetailsStore.
You could use then AltContainer like that
<AltContainer stores={{
SidebarStore: SidebarStore
}}>
<Sidebar/>
</AltContainer>
{this.props.content}
Which would keep stores (well I could use "store" instead of "stores" prop). Now, {this.props.content} CAN BE Details depending on the route. Lets say that /Details redirect us to that view. Details would have for example a checkbox that would change Sidebar element from X to Y if it would be checked.
Technically there is no relationship between them and it would be hard to do without flux. BUT WITH THAT it is rather easy.
Now let's get to DetailsActions. We will create there
class SiteActions {
constructor() {
this.generateActions(
'setSiteComponentStore'
);
}
setSiteComponent(value) {
this.dispatch({value: value});
}
}
and DetailsStore
class SiteStore {
constructor() {
this.siteComponents = {
Prop: true
};
this.bindListeners({
setSiteComponent: SidebarActions.COMPONENT_STATUS_CHANGED
})
}
setSiteComponent(data) {
this.siteComponents.Prop = data.value;
}
}
And now, this is the place where magic begin.
As You can see there is bindListener to SidebarActions.ComponentStatusChanged which will be used IF setSiteComponent will be used.
now in SidebarActions
componentStatusChanged(value){
this.dispatch({value: value});
}
We have such thing. It will dispatch that object on call. And it will be called if setSiteComponent in store will be used (that you can use in component for example during onChange on Button ot whatever)
Now in SidebarStore we will have
constructor() {
this.structures = [];
this.bindListeners({
componentStatusChanged: SidebarActions.COMPONENT_STATUS_CHANGED
})
}
componentStatusChanged(data) {
this.waitFor(DetailsStore);
_.findWhere(this.structures[0].elem, {title: 'Example'}).enabled = data.value;
}
Now here you can see, that it will wait for DetailsStore. What does it mean? more or less it means that this method need to wait for DetailsStoreto update before it can update itself.
tl;dr One Store is listening on methods in a store, and will trigger an action from component action, which will update its own store.
I hope it can help you somehow.
Concept Solution:br.read() returns particular character's int value so loop continue's until we won't get -1 as int value and Hence up to there it prints br.readLine() which returns a line into String form.
//Way 1:
while(br.read()!=-1)
{
//continues loop until we won't get int value as a -1
System.out.println(br.readLine());
}
//Way 2:
while((line=br.readLine())!=null)
{
System.out.println(line);
}
//Way 3:
for(String line=br.readLine();line!=null;line=br.readLine())
{
System.out.println(line);
}
Way 4: It's an advance way to read file using collection and arrays concept How we iterate using for each loop. check it here http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html
Using PowerShell, you can use the following
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name
This will show a list off all services which displayname starts with "NATION-".
You can also directly stop or start the services;
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service
or simply
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service
A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:
(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) =
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) =
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38
for n,line in enumerate(open("file")):
if "pattern" in line: print n+1
The fact is that libstdc++ actually supported std::to_string
in *-w64-mingw32 targets since 4.8.0. However, this does not include support for MinGW.org, Cygwin and variants (e.g. *-pc-msys from MSYS2). See also https://cygwin.com/ml/cygwin/2015-01/msg00245.html.
I have implemented a workaround before the bug resolved for MinGW-w64. Being different to code in other answers, this is a mimic to libstdc++ (as possible). It does not require string stream construction but depends on libstdc++ extensions. Even now I am using mingw-w64 targets on Windows, it still works well for multiple other targets (as long as long double
functions not being used).