Default in Debian 8.1 and PostgreSQL 9.4 after the installation with the package manager apt-get
ps auxw | grep postgres | grep -- -D
postgres 17340 0.0 0.5 226700 21756 ? S 09:50 0:00 /usr/lib/postgresql/9.4/bin/postgres -D /var/lib/postgresql/9.4/main -c config_file=/etc/postgresql/9.4/main/postgresql.conf
so apparently /var/lib/postgresql/9.4/main
.
Try this:
<div class="row">
<div class="alert alert-info" style="min-height:100px;">
<div class="col-xs-9">
<a href="#" class="alert-link">Summary:Its some
description.......testtesttest</a>
</div>
<div class="col-xs-3">
<button type="button" class="btn btn-primary btn-lg">Large button</button>
</div>
</div>
</div>
Demo:
If time_created is a unix timestamp (int), you should be able to use something like this:
DELETE FROM locks WHERE time_created < (UNIX_TIMESTAMP() - 600);
(600 seconds = 10 minutes - obviously)
Otherwise (if time_created is mysql timestamp), you could try this:
DELETE FROM locks WHERE time_created < (NOW() - INTERVAL 10 MINUTE)
There is also a nice web app to see the dependencies in a weighted map kind of view.
For example:
Since 0.14.1, you can now do nlargest
and nsmallest
on a groupby
object:
In [23]: df.groupby('id')['value'].nlargest(2)
Out[23]:
id
1 2 3
1 2
2 6 4
5 3
3 7 1
4 8 1
dtype: int64
There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index was.
If you're not interested in it, you can do .reset_index(level=1, drop=True)
to get rid of it altogether.
(Note: From 0.17.1 you'll be able to do this on a DataFrameGroupBy too but for now it only works with Series
and SeriesGroupBy
.)
As of June 2019, if your user's are on iOS 13 the cellular download limit has been lifted. User's just get a warning now. Read here
In case the article is removed here are screen shots of it below
For that, you need to update the redis configuration file.By default, there is no any password for redis.
01) open redis configuration file
sudo vi /etc/redis/redis.conf
find requirepass field under SECURITY section and uncomment that field.Then set your password instead of "foobared"
# requirepass foobared
It should be like,
requirepass YOUR_PASSWORD
Then restart redis and start redis-cli.
If you need to check whether you have set the password correctly, you can run below commads in redis-cli.
sithara@sithara-X555UJ ~ $ redis-cli
127.0.0.1:6379> set key1 18
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth admin
OK
127.0.0.1:6379> get key1
(nil)
127.0.0.1:6379> exit
sithara@sithara-X555UJ ~ $ redis-cli
127.0.0.1:6379> set key1 18
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth admin
OK
127.0.0.1:6379> set key2 check
OK
127.0.0.1:6379> get key2
"check"
127.0.0.1:6379> get key1
(nil)
127.0.0.1:6379> set key1 20
OK
127.0.0.1:6379> get key1
"20"
127.0.0.1:6379> exit
`
For Abbreviated Month Names : "Aug"
DateTimeFormatInfo.GetAbbreviatedMonthName Method (Int32)
Returns the culture-specific abbreviated name of the specified month based on the culture associated with the current DateTimeFormatInfo object.
string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(8)
For Full Month Names : "August"
DateTimeFormatInfo.GetMonthName Method (Int32)
Returns the culture-specific full name of the specified month based on the culture associated with the current DateTimeFormatInfo object.
string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(8);
You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial: http://docs.python-guide.org/en/latest/starting/install3/osx/.
To run the program you can then copy and paste in this code:
python /Users/luca/Documents/python/gameover.py
Or you can go to the directory of the file with cd
followed by the folder. When you are in the folder you can then python YourFile.py
.
if you are overriding onMeasure
, don't forget to update the new sizes
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(newWidth, newHeight);
}
How about using numpy.vectorize
.
import numpy as np
x = np.array([1, 2, 3, 4, 5])
squarer = lambda t: t ** 2
vfunc = np.vectorize(squarer)
vfunc(x)
# Output : array([ 1, 4, 9, 16, 25])
Range("A:B,D:E,G:H").Select
can help
Edit note: I just saw you have used different column sequence, I have updated my answer
The simplest way to create a manifest is:
Project Properties -> Security -> Click "enable ClickOnce security settings"
(it will generate default manifest in your project Properties) -> then Click
it again in order to uncheck that Checkbox -> open your app.maifest and edit
it as you wish.
Clarification:
Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.
Original answer:
Incredibly, this is now possible purely in CSS3.
/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
width: 100%;
}
/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
width: 50%;
}
/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
width: 33.3333%;
}
/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
width: 25%;
}
The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.
Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).
Don't you just love CSS3?
CodePen Example:
Sources:
R doesn't have these operations because (most) objects in R are immutable. They do not change. Typically, when it looks like you're modifying an object, you're actually modifying a copy.
git push public :master
This would delete the remote branch named master
as Kent Fredric has pointed out.
To list remote-tracking branches:
git branch -r
To delete a remote-tracking branch:
git branch -rd public/master
The W3C has a good introduction.
In short:
HTML is a text markup language. Text means any characters, not just ones in ASCII.
You can also represent any unicode character with ASCII
<div class="container">
<img src="http://i.stack.imgur.com/2OrtT.jpg"/>
</div>
<style>
.container {
width: 150px;
height: 100px;
overflow: hidden;
}
</style>
Just add position: fixed;
in your div style.
I have checked and Its working fine in my code.
You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.
Pick an encoding and stick with it:
f.write(printinfo.encode('utf8') + '\n')
or use io.open()
to create a file object that'll encode for you as you write to the file:
import io
f = io.open(filename, 'w', encoding='utf8')
You may want to read:
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky
before continuing.
Not really an answer to the specific question, but if there are others, like me, who are getting this error in fastAPI and end up here:
It is probably because your route response has a value that can't be JSON serialised by jsonable_encoder
. For me it was WKBElement: https://github.com/tiangolo/fastapi/issues/2366
Like in the issue, I ended up just removing the value from the output.
Instead of getApplicationContext()
, just use ActivityName.this
.
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...
Import the jQuery library in your page mark-up:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Then create another *.js script file (I call mine ExecutePageMethod
, since that is the only method it is going to expose) and import it:
<script type="text/javascript" src="/ExecutePageMethod.js" ></script>
Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):
function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
You will then need to augment your .NET page method with the appropriate attributes, as such:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
return "Yay!";
}
Now, within your page mark-up, within a script
block or from another script file, you can call the method, like so:
ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);
Obviously you will need to implement the OnSuccess
and OnFailure
methods.
To consume the results, say in the OnSuccess
method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:
function OnSuccess(result) {
var parsedResult = jQuery.parseJSON(result.d);
}
This ExecutePageMethod
code is particularly useful since it it reusable, so rather than having to manage an $.ajax
call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.
In sdk Manager download android 5.1.1, it worked for me
If the column data type is datetime then you can do this following to eliminate time from datetime and compare between date range only.
where cast(getdate() as date) between cast(loginTime as date) and cast(logoutTime as date)
Just my 2 cents regarding the divs option.
Famous/Infamous and SamsaraJS (and possibly others) use absolutely positioned non-nested divs (with non-trivial HTML/CSS content), combined with matrix2d/matrix3d for positioning and 2D/3D transformations, and achieve a stable 60FPS on moderate mobile hardware, so I'd argue against divs being a slow option.
There are plenty of screen recordings on Youtube and elsewhere, of high-performance 2D/3D stuff running in the browser with everything being an DOM element which you can Inspect Element on, at 60FPS (mixed with WebGL for certain effects, but not for the main part of the rendering).
This worked for me:
var xdoc = new XmlDocument { XmlResolver = null };
xdoc.LoadXml(xmlFragment);
You can use animated background-position property and sprite image.
In my case I had a directory with 800+ files ending with .StoredProcedure.sql
(they were scripted with SSMS).
The solutions posted above didn't work. But I came up with this:
(Based on answers to batch programming - get relative path of file)
@echo off
setlocal enabledelayedexpansion
for %%f in (*) do (
set B=%%f
set B=!B:%CD%\=!
ren "!B!" "!B:.StoredProcedure=!"
)
The above script removes the substring .StoredProcedure
from the filename. I'm sure it can be adapted to cover more cases, ask for input and be overall more generic.
Open Command Prompt as Administrator.
To Install any Python Package use this command including --user
.
pip install --ignore-installed --upgrade --user <packagename>
You may use PopupController for the same one the SDK which shows UIViewController as subview You may check PopupController
Here is sample code for the same
popup = PopupController
.create(self.navigationController!)
.customize(
[
.layout(.center),
.animation(.fadeIn),
.backgroundStyle(.blackFilter(alpha: 0.8)),
.dismissWhenTaps(true),
.scrollable(true)
]
)
.didShowHandler { popup in
}
.didCloseHandler { popup in
}
let container = MTMPlayerAndCardSelectionVC.instance()
container.closeHandler = {() in
self.popup.dismiss()
}
popup.show(container)
I know this is a old question but here is another solution that works for me
SET @dtDate = "your date"
DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))
And if some one is looking for different examples here is a link http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
I hope this helps some one else. stackoverflow Rocks!!!!
This can be done with an input element of a type "submit". This will appear as a button to the user and clicking the button will send the form.
<form action="" method="post">
<input type="submit" name="upvote" value="Upvote" />
</form>
Scenario:
Your domain: mydomain.com
Domain you wish to send to: theirdomain.com
1. Determine the mail server you're sending to. Open a CMD prompt Type
NSLOOKUP
set q=mx
theirdomain.com
Response:
Non-authoritative answer:
theirdomain.com MX preference = 50, mail exchanger = mail.theirdomain.com
Nslookup_big
EDIT Be sure to type exit to terminate NSLOOKUP.
2. Connect to their mail server
SMTP communicates over port 25. We will now try to use TELNET to connect to their mail server "mail.theirdomain.com"
Open a CMD prompt
TELNET MAIL.THEIRDOMAIN.COM 25
You should see something like this as a response:
220 mx.google.com ESMTP 6si6253627yxg.6
Be aware that different servers will come up with different greetings but you should get SOMETHING. If nothing comes up at this point there are 2 possible problems. Port 25 is being blocked at your firewall, or their server is not responding. Try a different domain, if that works then it's not you.
3. Send an Email
Now, use simple SMTP commands to send a test email. This is very important, you CANNOT use the backspace key, it will work onscreen but not be interpreted correctly. You have to type these commands perfectly.
ehlo mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
This is a test, please do not respond
.
quit
So, what does that all mean? EHLO - introduce yourself to the mail server HELO can also be used but EHLO tells the server to use the extended command set (not that we're using that).
MAIL FROM - who's sending the email. Make sure to place this is the greater than/less than brackets as many email servers will require this (Postini).
RCPT TO - who you're sending it to. Again you need to use the brackets. See Step #4 on how to test relaying mail!
DATA - tells the SMTP server that what follows is the body of your email. Make sure to hit "Enter" at the end.
. - the period alone on the line tells the SMTP server you're all done with the data portion and it's clear to send the email.
quit - exits the TELNET session.
4. Test SMTP relay Testing SMTP relay is very easy, and simply requires a small change to the above commands. See below:
ehlo mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
This is a test, please do not respond
.
quit
See the difference? On the RCPT TO line, we're sending to a domain that is not controlled by the SMTP server we're sending to. You will get an immediate error is SMTP relay is turned off. If you're able to continue and send an email, then relay is allowed by that server.
In Swift 4.2 and many earlier versions, instead of setting the first header's height to 0 like in the other answers, you can just set the other headers to nil
. Say you have two sections and only want the second one (i.e., 1
) to have a header. That header will have the text Foobar:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 1 ? "Foobar" : nil
}
First of all, stay away from Arraylist
or Hashtable
. Those classes are to be considered deprecated, in favor of generics. They are still in the language for legacy purposes.
Now, what you are looking for is the List<T>
class. Note that if T is a value type you will have contiguos memory, but not if T is a reference type, for obvious reasons.
you don't need a map
necessarily
that is the closest lambda to the LINQ example:
int[] idx = new int[] { 0 };
Stream.of( names ).filter( name -> name.length() <= idx[0]++ ).collect( Collectors.toList() );
As far as I understand, it is going to drop your database and re-create it based on your db/schema.rb
file. That is why you need to make sure that your schema.rb
file is always up to date and under version control.
paxdiablo's answer is great, but there are a lot of common resolutions that have just a few more or less pixels in a given direction, and the greatest common divisor approach gives horrible results to them.
Take for example the well behaved resolution of 1360x765 which gives a nice 16:9 ratio using the gcd approach. According to Steam, this resolution is only used by 0.01% of it's users, while 1366x768 is used by a whoping 18.9%. Let's see what we get using the gcd approach:
1360x765 - 16:9 (0.01%)
1360x768 - 85:48 (2.41%)
1366x768 - 683:384 (18.9%)
We'd want to round up that 683:384 ratio to the closest, 16:9 ratio.
I wrote a python script that parses a text file with pasted numbers from the Steam Hardware survey page, and prints all resolutions and closest known ratios, as well as the prevalence of each ratio (which was my goal when I started this):
# Contents pasted from store.steampowered.com/hwsurvey, section 'Primary Display Resolution'
steam_file = './steam.txt'
# Taken from http://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Vector_Video_Standards4.svg/750px-Vector_Video_Standards4.svg.png
accepted_ratios = ['5:4', '4:3', '3:2', '8:5', '5:3', '16:9', '17:9']
#-------------------------------------------------------
def gcd(a, b):
if b == 0: return a
return gcd (b, a % b)
#-------------------------------------------------------
class ResData:
#-------------------------------------------------------
# Expected format: 1024 x 768 4.37% -0.21% (w x h prevalence% change%)
def __init__(self, steam_line):
tokens = steam_line.split(' ')
self.width = int(tokens[0])
self.height = int(tokens[2])
self.prevalence = float(tokens[3].replace('%', ''))
# This part based on pixdiablo's gcd answer - http://stackoverflow.com/a/1186465/828681
common = gcd(self.width, self.height)
self.ratio = str(self.width / common) + ':' + str(self.height / common)
self.ratio_error = 0
# Special case: ratio is not well behaved
if not self.ratio in accepted_ratios:
lesser_error = 999
lesser_index = -1
my_ratio_normalized = float(self.width) / float(self.height)
# Check how far from each known aspect this resolution is, and take one with the smaller error
for i in range(len(accepted_ratios)):
ratio = accepted_ratios[i].split(':')
w = float(ratio[0])
h = float(ratio[1])
known_ratio_normalized = w / h
distance = abs(my_ratio_normalized - known_ratio_normalized)
if (distance < lesser_error):
lesser_index = i
lesser_error = distance
self.ratio_error = distance
self.ratio = accepted_ratios[lesser_index]
#-------------------------------------------------------
def __str__(self):
descr = str(self.width) + 'x' + str(self.height) + ' - ' + self.ratio + ' - ' + str(self.prevalence) + '%'
if self.ratio_error > 0:
descr += ' error: %.2f' % (self.ratio_error * 100) + '%'
return descr
#-------------------------------------------------------
# Returns a list of ResData
def parse_steam_file(steam_file):
result = []
for line in file(steam_file):
result.append(ResData(line))
return result
#-------------------------------------------------------
ratios_prevalence = {}
data = parse_steam_file(steam_file)
print('Known Steam resolutions:')
for res in data:
print(res)
acc_prevalence = ratios_prevalence[res.ratio] if (res.ratio in ratios_prevalence) else 0
ratios_prevalence[res.ratio] = acc_prevalence + res.prevalence
# Hack to fix 8:5, more known as 16:10
ratios_prevalence['16:10'] = ratios_prevalence['8:5']
del ratios_prevalence['8:5']
print('\nSteam screen ratio prevalences:')
sorted_ratios = sorted(ratios_prevalence.items(), key=lambda x: x[1], reverse=True)
for value in sorted_ratios:
print(value[0] + ' -> ' + str(value[1]) + '%')
For the curious, these are the prevalence of screen ratios amongst Steam users (as of October 2012):
16:9 -> 58.9%
16:10 -> 24.0%
5:4 -> 9.57%
4:3 -> 6.38%
5:3 -> 0.84%
17:9 -> 0.11%
As MadScientist pointed out, you can export individual variables with:
export MY_VAR = foo # Available for all targets
Or export variables for a specific target (target-specific variables):
my-target: export MY_VAR_1 = foo
my-target: export MY_VAR_2 = bar
my-target: export MY_VAR_3 = baz
my-target: dependency_1 dependency_2
echo do something
You can also specify the .EXPORT_ALL_VARIABLES
target to—you guessed it!—EXPORT ALL THE THINGS!!!:
.EXPORT_ALL_VARIABLES:
MY_VAR_1 = foo
MY_VAR_2 = bar
MY_VAR_3 = baz
test:
@echo $$MY_VAR_1 $$MY_VAR_2 $$MY_VAR_3
Why switch between PHP versions when you can use multiple PHP version at a same time with a single xampp installation? With a single xampp installation, you have 2 options:
Run an older PHP version for only the directory of your old project: This will serve the purpose most of the time, you may have one or two old projects that you intend to run with older PHP version. Just configure xampp to run older PHP version only for those project directories.
Run an older PHP version on a separate port of xampp: Sometimes you may
be upgrading and old project to latest PHP version when you need to run the
same project on new and older PHP version back and forth.
Then you can set an older PHP version on a different port (say 8056)
so when you go to http://localhost/any_project/
xampp runs PHP 7
and when you go to http://localhost:8056/any_project/
xampp runs PHP
5.6.
Run an older PHP version on a virtualhost: You can create a virtualhost like localhost56 to run PHP 5.6 while you can use PHP 7 on localhost.
Lets set it up.
Step 1: Download PHP
So you have PHP 7 running under xampp, you want to add an older PHP version to it, say PHP 5.6. Download the nts (Non Thread Safe) version of PHP zip archive from php.net (see archive for older versions) and extract the files under c:\xampp\php56
. The thread safe version does not include php-cgi.exe.
Step 2: Configure php.ini
Open c:\xampp\php56\php.ini
file in notepad. If the file does not exist copy php.ini-development
to php.ini
and open it in notepad. Then uncomment the following line:
extension_dir = "ext"
Step 3: Configure apache
Open xampp control panel, click config button for apache, and click Apache (httpd-xampp.conf)
. A text file will open up put the following settings at the bottom of the file:
ScriptAlias /php56 "C:/xampp/php56"
Action application/x-httpd-php56-cgi /php56/php-cgi.exe
<Directory "C:/xampp/php56">
AllowOverride None
Options None
Require all denied
<Files "php-cgi.exe">
Require all granted
</Files>
</Directory>
Note: You can add more versions of PHP to your xampp installation following step 1 to 3 if you want.
Step 4 (option 1): [Add Directories to run specific PHP version]
Now you can set directories that will run in PHP 5.6. Just add the following at the bottom of the config file (httpd-xampp.conf
from Step 3) to set directories.
<Directory "C:\xampp\htdocs\my_old_project1">
<FilesMatch "\.php$">
SetHandler application/x-httpd-php56-cgi
</FilesMatch>
</Directory>
<Directory "C:\xampp\htdocs\my_old_project2">
<FilesMatch "\.php$">
SetHandler application/x-httpd-php56-cgi
</FilesMatch>
</Directory>
Step 4 (option 2): [Run older PHP version on a separate port]
Now to to set PHP v5.6 to port 8056 add the following code to the bottom of the config file (httpd-xampp.conf
from Step 3).
Listen 8056
<VirtualHost *:8056>
<FilesMatch "\.php$">
SetHandler application/x-httpd-php56-cgi
</FilesMatch>
</VirtualHost>
Step 4 (option 3): [Run an older PHP version on a virtualhost]
To create a virtualhost (localhost56) on a directory (htdocs56) to use PHP v5.6 on http://localhost56, create directory htdocs56 at your desired location and
add localhost56 to your hosts file (see how),
then add the following code to the bottom of the config file (httpd-xampp.conf
from Step 3).
<VirtualHost localhost56:80>
DocumentRoot "C:\xampp\htdocs56"
ServerName localhost56
<Directory "C:\xampp\htdocs56">
Require all granted
</Directory>
<FilesMatch "\.php$">
SetHandler application/x-httpd-php56-cgi
</FilesMatch>
</VirtualHost>
Finish: Save and Restart Apache
Save and close the config file, Restart apache from xampp control panel. If you went for option 2 you can see the additional port(8056) listed in your xampp control panel.
Update for Error:
malformed header from script 'php-cgi.exe': Bad header
If you encounter the above error, open httpd-xampp.conf
again and comment out the following line with a leading # (hash character).
SetEnv PHPRC "\\path\\to\\xampp\\php"
This fixed version of code above remember the last element of CVS row ;-)
(tested with a CSV file with 5400 rows and 26 elements by row)
public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"') {
bool bolQuote = false;
StringBuilder bld = new StringBuilder();
List<string> retAry = new List<string>();
foreach (char c in r.ToCharArray())
if ((c == fieldSep && !bolQuote))
{
retAry.Add(bld.ToString());
bld.Clear();
}
else
if (c == stringSep)
bolQuote = !bolQuote;
else
bld.Append(c);
/* to solve the last element problem */
retAry.Add(bld.ToString()); /* added this line */
return retAry.ToArray();
}
You can either add or replace fragment in your activity. Create a FrameLayout
in activity layout xml
file.
Then do this in your activity to add fragment:
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();
And to replace fragment do this:
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();
See Android documentation on adding a fragment to an activity or following related questions on SO:
Difference between add(), replace(), and addToBackStack()
Basic difference between add() and replace() method of Fragment
Difference between add() & replace() with Fragment's lifecycle
SQL> grant create any procedure to testdb;
This is a command when we want to give create privilege to "testdb" user.
I also had this problem. it was weird that it worked on my lollipop emulator, but not on my actual kitkat device.
Android Studio will now force you to write the permission upper case, and that's the problem.
Add
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Above the application tab and it will work.
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.button1:
//do ur code
Toast.makeText(this,"This is button 1",Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Intent intent = new Intent(this,SecondActivity.class);
Intent.putExtra("key",value);
startActivity(intent);
break;
case R.id.button3:
//do ur code
break;
case R.id.button4:
//do ur code;
break;
default:
//do ur code;
}
}
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
I found that following these instructions helped with finding what the problem was. For me, that was the killer, not knowing what was broken.
Quoting from the link
In Tomcat 6 or above, the default logger is the”java.util.logging” logger and not Log4J. So if you are trying to add a “log4j.properties” file – this will NOT work. The Java utils logger looks for a file called “logging.properties” as stated here: http://tomcat.apache.org/tomcat-6.0-doc/logging.html
So to get to the debugging details create a “logging.properties” file under your”/WEB-INF/classes” folder of your WAR and you’re all set.
And now when you restart your Tomcat, you will see all of your debugging in it’s full glory!!!
Sample logging.properties file:
org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler
Kotlin DSL: add to your build.gradle.kts
tasks.withType<Test> {
useJUnitPlatform()
}
Gradle DSL: add to your build.gradle
test {
useJUnitPlatform()
}
Well, first off, the ^
operator in C/C++ is the bit-wise XOR. It has nothing to do with powers.
Now, regarding your problem with using the pow()
function, some googling shows that casting one of the arguments to double helps:
result = (int) pow((double) a,i);
Note that I also cast the result to int
as all pow()
overloads return double, not int
. I don't have a MS compiler available so I couldn't check the code above, though.
Since C99, there are also float
and long double
functions called powf
and powl
respectively, if that is of any help.
Note: Traditionally the use of the label tag is for menus. eg:
<menu>
<label>Option 1</label>
<input type="radio" id="opt1">
<label>Option 2</label>
<input type="radio" id="opt2">
<label>Option 3</label>
<input type="radio" id="opt3">
</menu>
setTimeout(func, 5000);
-- it will call the function named func() after the time specified. here, 5000 milli seconds , i.e) after 5 seconds
I believe you should escape the dot. Try:
String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split("\\.")[0];
Otherwise dot is interpreted as any character in regular expressions.
[I mentioned this in response to the selected answer, but it was suggested to make it more prominent as an answer of its own]
It should be noted that
ENV PATH="/opt/gtk/bin:${PATH}"
may not be the same as
ENV PATH="/opt/gtk/bin:$PATH"
The former, with curly brackets, might provide you with the host's PATH. The documentation doesn't suggest this would be the case, but I have observed that it is. This is simple to check just do RUN echo $PATH
and compare it to RUN echo ${PATH}
It might be a little late but for future referent there is a CSS ONLY solution as Olly Hodgons shows here http://lostmonocle.com/post/1479126030/fixing-the-chrome-autocomplete-background-colour
All you have to do is to add a further selector to overwrite the default input fields setting So use instead of
input:-webkit-autofill {
background-color: #FAFFBD !important;
}
Somthing like
#login input:-webkit-autofill {
background-color: #ff00ff;
}
or
form input:-webkit-autofill {
background-color: #f0f;
}
which seems to work fine with me.
lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx Credit to "Tuna Toksoz"
Usage first:
TConverter.ChangeType<T>(StringValue);
The class is below.
public static class TConverter
{
public static T ChangeType<T>(object value)
{
return (T)ChangeType(typeof(T), value);
}
public static object ChangeType(Type t, object value)
{
TypeConverter tc = TypeDescriptor.GetConverter(t);
return tc.ConvertFrom(value);
}
public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
{
TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
}
}
You can use registry to set IE version for webbrowser control. Go to: HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION and add "yourApplicationName.exe" with value of browser_emulation To see value of browser_emulation, refer link: http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation
To create the regex from a string, you have to use JavaScript's RegExp
object.
If you also want to match/replace more than one time, then you must add the g
(global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
Not every string is a valid regex, though: there are some speciall characters, like (
or [
. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
Note: the regex in the question uses the s
modifier, which didn't exist at the time of the question, but does exist -- a s
(dotall) flag/modifier in JavaScript -- today.
The expression -z string
is true if the length of string is zero
.
Maybe an example would help.
Your app wants to download a file from some remote computer and then write to to a local disk. The remote computer is the other side of a dial-up modem and a satellite link. The latency and transfer time will be huge and you have other things to do. So, you have a function/method that will write a buffer to disk. You pass a pointer to this method to your network API, together with the remote URI and other stuff. This network call returns 'immediately' and you can do your other stuff. 30 seconds later, the first buffer from the remote computer arrives at the network layer. The network layer then calls the function that you passed during the setup and so the buffer gets written to disk - the network layer has 'called back'. Note that, in this example, the callback would happen on a network layer thread than the originating thread, but that does not matter - the buffer still gets written to the disk.
Old post I know. In order to run your app always in portrait mode even when orientation may be or is swapped etc (for example on tablets) I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.
private void initActivityScreenOrientPortrait()
{
// Avoid screen rotations (use the manifests android:screenOrientation setting)
// Set this to nosensor or potrait
// Set window fullscreen
this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
DisplayMetrics metrics = new DisplayMetrics();
this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Test if it is VISUAL in portrait mode by simply checking it's size
boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels );
if( !bIsVisualPortrait )
{
// Swap the orientation to match the VISUAL portrait mode
if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
{ this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
}
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }
}
Works like a charm!
NOTICE:
Change this.activity
by your activity or add it to the main activity and remove this.activity
;-)
Visual Studio requires that DDEX Providers (Data Designer Extensibility) be registered by adding certain entries in the Windows Registry during installation (HKLM\SOFTWARE\Microsoft\VisualStudio\{version}\DataProviders
) . See DDEX Provider Registration in MSDN for more details.
Note that from MS SQL 2012 onwards you can use FORMAT(value,'format')
e.g. WHERE FORMAT(YourDatetime,'HH:mm') = '17:00'
Support for peer to peer WiFi networking is available since API level 14.
I think it's a good idea to keep avoiding modules unless you stick them into separate namespaces. Because in Intellisense methods in modules will be visible from everywhere in that namespace.
So instead of ModuleName.MyMethod()
you end up with MyMethod()
popups in anywhere and this kind of invalidates the encapsulation. (at least in the programming level).
That's why I always try to create Class with shared methods, seems so much better.
Using the AWS SDK use the getObjectMetadata method. The method will throw an AmazonServiceException if the key doesn't exist.
private AmazonS3 s3;
...
public boolean exists(String path, String name) {
try {
s3.getObjectMetadata(bucket, getS3Path(path) + name);
} catch(AmazonServiceException e) {
return false;
}
return true;
}
If you happen to be using CMake, you can use ExternalProject_Add
as described here.
This avoids you having to keep gtest source code in your repository, or installing it anywhere. It is downloaded and built in your build tree automatically.
Configure application context and all will be ok.
In iOS 10, and on newer iPhones, you can also use haptic API. This haptic feedback is softer than the AudioToolbox API.
For your GAME OVER scenario, a heavy UI impact feedback should be suitable.
UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
You could use the other haptic feedback styles.
Use LinkedHashMap and use this function.
private LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
Define like this and.
private Entry getEntry(int id){
Iterator iterator = map.entrySet().iterator();
int n = 0;
while(iterator.hasNext()){
Entry entry = (Entry) iterator.next();
if(n == id){
return entry;
}
n ++;
}
return null;
}
The function can return the selected entry.
You can only access overridden methods in the overriding methods (or in other methods of the overriding class).
So: either don't override method2()
or call super.method2()
inside the overridden version.
I had the same issue on Windows. It was resolved by setting the environment variable as follow:
Variable name: OPENSSL_CONF Variable value: C:(OpenSSl Directory)\bin\openssl.cnf
Pass a selector to the jQuery parents function:
d.parents('.a').attr('id')
EDIT Hmm, actually Slaks's answer is superior if you only want the closest ancestor that matches your selector.
Probably you need to set library reference as "Copy Local = True" on properties dialog. On visual studio click on "references" then right-click on the missing reference, from the context menu click properties, you should see copy local setting.
Typically for dynamic lists of items, you use a std::vector
.
Generally I use memset or a loop for raw memory dynamic allocation, depending on how variable I anticipate that area of code to be in the future.
called_from
must be null
. Add a test against that condition like
if (called_from != null && called_from.equalsIgnoreCase("add")) {
or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null
behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)
if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null
Almost 5 years later, I think my answer can reduce a little bit the hard work of many people.
Update an element in the DOM with the HTML from the one from the ajax call can be achieved that way
$('#submitform').click(function() {
$.ajax({
url: "getinfo.asp",
data: {
txtsearch: $('#appendedInputButton').val()
},
type: "GET",
dataType : "html",
success: function (data){
$('#showresults').html($('#showresults',data).html());
// similar to $(data).find('#showresults')
},
});
or with replaceWith()
// codes
success: function (data){
$('#showresults').replaceWith($('#showresults',data));
},
Have you tried
git add .
This recurses into sub-directories, whereas I don't think * does.
See here
Back up a completely empty database. Instead of dropping all the objects, just restore the backup.
Yes, you can program Android apps in C++ (for the most part), using the Native Development Kit (NDK), although Java is the primary/preferred language for programming Android, and your C++ code will likely have to interface with Java components, and you'll likely need to read and understand the documentation for Java components, as well. Therefore, I'd advise you to use Java unless you have some existing C++ code base that you need to port and that isn't practical to rewrite in Java.
Java is very similar to C++, I don't think you will have any problems picking it up... going from C++ to Java is incredibly easy; going from Java to C++ is a little more difficult, though not terrible. Java for C++ Programmers does a pretty good job at explaining the differences. Writing your Android code in Java will be more idiomatic and will also make the development process easier for you (as the tooling for the Java Android SDK is significantly better than the corresponding NDK tooling)
In terms of setup, Google provides the Android Studio IDE for both Java and C++ Android development (with Gradle as the build system), but you are free to use whatever IDE or build system you want so long as, under the hood, you are using the Android SDK / NDK to produce the final outputs.
Notepad++ will forget your macros unless you map them to hotkeys via Settings - Shortcut mapper - Macros before exiting Notepad++ (as per https://superuser.com/questions/332481/how-can-i-add-a-macro-in-notepad. Tested with Notepad v6.8.3 on Windows7.)
SELECT
p.spid, p.status, p.hostname, p.loginame, p.cpu, r.start_time, r.command,
p.program_name, text
FROM
sys.dm_exec_requests AS r,
master.dbo.sysprocesses AS p
CROSS APPLY sys.dm_exec_sql_text(p.sql_handle)
WHERE
p.status NOT IN ('sleeping', 'background')
AND r.session_id = p.spid
send requtest and get response with kibana,kibana is can autocomplete elastic query builder and have more tools
GET /_cat/indices
kibana dev tools
http://localhost:5601/app/kibana#/dev_tools/console
Guava also has Base64 (among other encodings and incredibly useful stuff)
Give this a try :P
s = '#'.repeat(10)_x000D_
_x000D_
document.body.innerHTML = s
_x000D_
Your question is hard to understand, but if I'm getting the gist, you simply have some value in your main view that you want to access in a partial being rendered in that view.
If you just render a partial with just the partial name:
@Html.Partial("_SomePartial")
It will actually pass your model as an implicit parameter, the same as if you were to call:
@Html.Partial("_SomePartial", Model)
Now, in order for your partial to actually be able to use this, though, it too needs to have a defined model, for example:
@model Namespace.To.Your.Model
@Html.Action("MemberProfile", "Member", new { id = Model.Id })
Alternatively, if you're dealing with a value that's not on your view's model (it's in the ViewBag or a value generated in the view itself somehow, then you can pass a ViewDataDictionary
@Html.Partial("_SomePartial", new ViewDataDictionary { { "id", someInteger } });
And then:
@Html.Action("MemberProfile", "Member", new { id = ViewData["id"] })
As with the model, Razor will implicitly pass your partial the view's ViewData
by default, so if you had ViewBag.Id
in your view, then you can reference the same thing in your partial.
getch()
can also be used which is defined in conio.h.
The sample program would look like this :
#include <stdio.h>
#include <conio.h>
int main()
{
//your code
getch();
return 0;
}
getch()
waits for any character input from the keyboard (not necessarily enter key).
I ended up using the bootstrap 3 dropdown button, I'm posting my solution here in case it helps someone in future. Adding the bootstrap 3 list-inline to the class for the ul causes it to display in a nicely compact format as well.
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Select icon <span class="caret"></span>
</button>
<ul class="dropdown-menu list-inline" role="menu">
<li><span class="glyphicon glyphicon-cutlery"></span></li>
<li><span class="glyphicon glyphicon-fire"></span></li>
<li><span class="glyphicon glyphicon-glass"></span></li>
<li><span class="glyphicon glyphicon-heart"></span></li>
</ul>
</div>
I'm using Angular.js so this is the actual code I used:
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Avatar <span class="caret"></span>
</button>
<ul class="dropdown-menu list-inline" role="menu">
<li ng-repeat="avatar in avatars" ng-click="avatarSelected(avatar)">
<span ng-class="getAvatar(avatar)"></span>
</li>
</ul>
</div>
And in my controller:
$scope.avatars=['cutlery','eye-open','flag','flash','glass','fire','hand-right','heart','heart-empty','leaf','music','send','star','star-empty','tint','tower','tree-conifer','tree-deciduous','usd','user','wrench','time','road','cloud'];
$scope.getAvatar=function(avatar){
return 'glyphicon glyphicon-'+avatar;
};
One approach is to add a pure virtual GetNodeType() method to NodeDTO and override it in the descendants so that each descendant returns actual type.
Use the gca
("get current axes") helper function:
ax = plt.gca()
Example:
import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()
There looks to be an issue when the time of the phone/emulator is different to the one of the server (where react-native packager is running). In my case there was a 1 minute difference between the time of the phone and the computer. After synchronizing them (didn't do anything fancy, the phone was set on manual time, and I just set it to use the network(sim) provided time), everything worked fine. This github issue helped me find the problem.
I am using git-bash in windows.The simplest way is to change the path address to have the forward slashes:
git clone C:/Dev/proposed
P.S: Start the git-bash on the destination folder.
Path used in clone ---> c:/Dev/proposed
Original path in windows ---> c:\Dev\proposed
In my case it was Bootstrap popup in opened state.
Text input was in another calendar popup on top of Bootstrap one, input got its focus back after removing tabindex="-1"
attribute from Bootstrap modal.
The java.util.Collections class has a sort method that takes a list and a custom Comparator. You can define your own Comparator to sort your Person object however you like.
Sometimes while installing JDK, you may get a dll is missing error. Because of this, it won't copy the tools.jar file to the java folder. So please reinstall the JDK in a different location and if it is successful then you will see the tools.jar file.
The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. Consequently this exception can be thrown when there are many transactions in progress even when most of the individual transactions are of moderate size.
refer this link
I needed to do the same and had to query a query to get the result
I set my first query up to bring in all IDs from the table and all other information needed to filter:
SELECT tMAIN.tLOTS.NoContract, tMAIN.ID
FROM tMAIN INNER JOIN tLOTS ON tMAIN.ID = tLOTS.id
WHERE (((tLOTS.NoContract)=False));
Save this as Q04_1 -0 this returned 1229 results (there are 63 unique records to query - soime with multiple LOTs)
SELECT DISTINCT ID
FROM q04_1;
Saved that as q04_2
I then wrote another query which brought in the required information linked to the ID
SELECT q04_2.ID, tMAIN.Customer, tMAIN.Category
FROM q04_2 INNER JOIN tMAIN ON q04_2.ID = tMAIN.ID;
Worked a treat and got me exactly what I needed - 63 unique records returned with customer and category details.
This is how I worked around it as I couldn't get the Group By working at all - although I am rather "wet behind the ears" weith SQL (so please be gentle and constructive with feedback)
The number of binary trees can be calculated using the catalan number.
The number of binary search trees can be seen as a recursive solution. i.e., Number of binary search trees = (Number of Left binary search sub-trees) * (Number of Right binary search sub-trees) * (Ways to choose the root)
In a BST, only the relative ordering between the elements matter. So, without any loss on generality, we can assume the distinct elements in the tree are 1, 2, 3, 4, ...., n. Also, let the number of BST be represented by f(n) for n elements.
Now we have the multiple cases for choosing the root.
...... Similarly, for i-th element as the root, i-1 elements can be on the left and n-i on the right.
These sub-trees are itself BST, thus, we can summarize the formula as:
f(n) = f(0)f(n-1) + f(1)f(n-2) + .......... + f(n-1)f(0)
Base cases, f(0) = 1, as there is exactly 1 way to make a BST with 0 nodes. f(1) = 1, as there is exactly 1 way to make a BST with 1 node.
Try this one
public static void main(String[] args)
{
int x=11;
int y=x/2; // spaces
int z=1; // *`s
for(int i=0;i<5;i++)
{
for(int j=0;j<y;j++)
{
System.out.print(" ");
}
for(int k=0;k<z;k++)
{
System.out.print("*");
}
y=y-1;
z=z+2;
System.out.println();
}
}
If you have Ruby for Windows,
C:\>more file
bath Abath Bbath XYZbathABC
C:\>ruby -pne "$_.gsub!(/bath/,\"hello\")" file
hello Ahello Bhello XYZhelloABC
Yeah I had an issue where my querystring would overflow and duplicate, but this was due to my own sluggishness. so I played a bit and worked up some js jquery(actualy sizzle) and C# magick.
So i just realized that after the server has done with the passed values, the values doesn't matter anymore, there is no reuse, if the client wanted to do the same thing evidently it will always be a new request, even if its the same parameters being passed. And thats all clientside, so some caching/cookies etc could be cool in that regards.
JS:
$(document).ready(function () {
$('#ser').click(function () {
SerializeIT();
});
function SerializeIT() {
var baseUrl = "";
baseUrl = getBaseUrlFromBrowserUrl(window.location.toString());
var myQueryString = "";
funkyMethodChangingStuff(); //whatever else before serializing and creating the querystring
myQueryString = $('#fr2').serialize();
window.location.replace(baseUrl + "?" + myQueryString);
}
function getBaseUrlFromBrowserUrl(szurl) {
return szurl.split("?")[0];
}
function funkyMethodChangingStuff(){
//do stuff to whatever is in fr2
}
});
HTML:
<div id="fr2">
<input type="text" name="qURL" value="http://somewhere.com" />
<input type="text" name="qSPart" value="someSearchPattern" />
</div>
<button id="ser">Serialize! and go play with the server.</button>
C#:
using System.Web;
using System.Text;
using System.Collections.Specialized;
public partial class SomeCoolWebApp : System.Web.UI.Page
{
string weburl = string.Empty;
string partName = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
string loadurl = HttpContext.Current.Request.RawUrl;
string querySZ = null;
int isQuery = loadurl.IndexOf('?');
if (isQuery == -1) {
//If There Was no Query
}
else if (isQuery >= 1) {
querySZ = (isQuery < loadurl.Length - 1) ? loadurl.Substring(isQuery + 1) : string.Empty;
string[] getSingleQuery = querySZ.Split('?');
querySZ = getSingleQuery[0];
NameValueCollection qs = null;
qs = HttpUtility.ParseQueryString(querySZ);
weburl = qs["qURL"];
partName = qs["qSPart"];
//call some great method thisPageRocks(weburl,partName); or whatever.
}
}
}
Okay criticism is welcome (this was a nightly concoction so feel free to note adjustments). If this helped at all, thumb it up, Happy Coding.
No duplicates, each request as unique as you modified it, and due to how this is structured,easy to add more queries dynamicaly from wthin the dom.
Are you talking about getchar
function?
Removing all the events on document
:
One liner:
for (key in getEventListeners(document)) { getEventListeners(document)[key].forEach(function(c) { c.remove() }) }
Pretty version:
for (key in getEventListeners(document)) {
getEventListeners(document)[key].forEach(function(c) {
c.remove()
})
}
I agree with @pkozlowski.opensource answer, but ng-clock class did't work for me for using with ng-repeat. so I would like to recommend you to use class for simple delimiter expression like {{name}} and ngCloak directive for ng-repeat.
<div class="ng-cloak">{{name}}<div>
and
<li ng-repeat="item in items" ng-cloak>{{item.name}}<li>
The presence of this data-attribute tells Bootstrap to switch between visual or a logical states of another element on user interaction.
It is used to show modals, tab content, tooltips and popover menus as well as setting a pressed-state for a toggle-button. It is used in multiple ways without a clear documentation.
If your email address is '[email protected]', try changing the createDirectoryEntry() as below.
XYZ is an optional parameter if it exists in mydomain directory
static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = new DirectoryEntry("myname.mydomain.com");
ldapConnection.Path = "LDAP://OU=Users, OU=XYZ,DC=mydomain,DC=com";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
return ldapConnection;
}
This will basically check for com -> mydomain -> XYZ -> Users -> abcd
The main function looks as below:
try
{
username = "Firstname LastName"
DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(cn=" + username + ")";
....
Here is a solution that worked for me running on a MacBook Pro (desktop).
I was getting the same error and it turns out it's because I had the USB connected to a peripheral device (my monitor) rather than a USB on the PC itself. It stopped any errors right away and is a simple solution.
Multilingual Version, tested on Japanese OS
Batch File
set getdesk=REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop
FOR /f "delims=(=" %%G IN ('%getdesk% ^|find "_SZ"') DO set desktop=%%G
set desktop1=%desktop:*USERPROFILE%\=%
cd "%userprofile%\%desktop1%"
set getdesk=
set desktop1=
set desktop=
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
#a {_x000D_
display:flex;_x000D_
_x000D_
align-items:flex-start;_x000D_
align-content:flex-start;_x000D_
}_x000D_
_x000D_
#a > div {_x000D_
_x000D_
background-color:red;_x000D_
padding:5px;_x000D_
margin:2px;_x000D_
}_x000D_
#a > #c {_x000D_
align-self:stretch;_x000D_
}
_x000D_
<div id="a">_x000D_
_x000D_
<div id="b">left</div>_x000D_
<div id="c">middle</div>_x000D_
<div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
_x000D_
</div>
_x000D_
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
Simply add spaces for { 2 3 4 5 6 } like these:
cout<<"{";
for(){
cout<<" "<<n; //n is the element to print !
}
cout<<" }";
GetHashCode()
is used to help support using the object as a key for hash tables. (A similar thing exists in Java etc). The goal is for every object to return a distinct hash code, but this often can't be absolutely guaranteed. It is required though that two logically equal objects return the same hash code.
A typical hash table implementation starts with the hashCode value, takes a modulus (thus constraining the value within a range) and uses it as an index to an array of "buckets".
First install a pod :-
pod 'SwiftGifOrigin'
and import in your class
import SwiftGifOrigin
then write this code in viewDidiload method
yourImageView.image = UIImage.gif(name: "imageName")
Note:- plz do not include the file extension in the gif file name. Ex:-
//Don't Do this
yourImageView.image = UIImage.gif(name: "imageName.gif")
See source: https://github.com/swiftgif/SwiftGif
Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use subprocess.call
.
#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])
If you want to do things while it is executing or feed things into stdin
, you can use communicate
after the popen
call.
#start and process things, then wait
p = subprocess.Popen([data["om_points"], ">", diz['d']+"/points.xml"])
print "Happens while running"
p.communicate() #now wait plus that you can send commands to process
As stated in the documentation, wait
can deadlock, so communicate is advisable.
string result = await resp.Content.ReadAsStringAsync(); List _Resp = JsonConvert.DeserializeObject<List>(result); //List _objList = new List((IEnumerable)_Resp);
IList usll = _Resp.Select(a => a.lttsdata).ToList();
// List<ListViewClass> _objList = new List<ListViewClass>((IEnumerable<ListViewClass>)_Resp);
//IList usll = _objList.OrderBy(a=> a.ReqID).ToList();
Lv.ItemsSource = usll;
Simply call InetAddress.getByName(String host)
passing in your textual IP address.
From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.
You forgot the table
in your syntax:
drop table [table_name]
which drops a table.
Using
drop table if exists [table_name]
checks if the table exists before dropping it.
If it exists, it gets dropped.
If not, no error will be thrown and no action be taken.
This project on github looks promising:
https://github.com/eligrey/FileSaver.js
FileSaver.js implements the W3C saveAs() FileSaver interface in browsers that do not natively support it.
Also have a look at the demo here:
Iterate less the second time (just when first letter of substring matches) but still uses 2 for loops:
function findSubstringOccurrences(str, word) {
let occurrences = 0;
for(let i=0; i<str.length; i++){
if(word[0] === str[i]){ // to make it faster and iterate less
for(let j=0; j<word.length; j++){
if(str[i+j] !== word[j]) break;
if(j === word.length - 1) occurrences++;
}
}
}
return occurrences;
}
console.log(findSubstringOccurrences("jdlfkfomgkdjfomglo", "omg"));
It would be best to have a TIMESTAMP
column that defaults to CURRENT_TIMESTAMP
.. it is the only true predictive behavior you can find here.
The second-best thing you can do is ORDER BY ID DESC LIMIT 1
and hope the newest ID is the largest value.
After an hour or two of trying every combination of ui-view autoscroll=true
, $stateChangeStart
, $locationChangeStart
, $uiViewScrollProvider.useAnchorScroll()
, $provide('$uiViewScroll', ...)
, and many others, I couldn't get scroll-to-top-on-new-page to work as expected.
This was ultimately what worked for me. It captures pushState and replaceState and only updates scroll position when new pages are navigated to (back/forward button retain their scroll positions):
.run(function($anchorScroll, $window) {
// hack to scroll to top when navigating to new URLS but not back/forward
var wrap = function(method) {
var orig = $window.window.history[method];
$window.window.history[method] = function() {
var retval = orig.apply(this, Array.prototype.slice.call(arguments));
$anchorScroll();
return retval;
};
};
wrap('pushState');
wrap('replaceState');
})
SELECT f.name AS ForeignKey, OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
well looking for a simpler variation I found this:
it's truly smart, and I guess you might want to add other browsers variations too although it worked for me both on Chrome and Firefox.
demo and credit => http://codepen.io/Ahrengot/pen/bKdLC
@keyframes fadeIn { _x000D_
from { opacity: 0; } _x000D_
}_x000D_
_x000D_
.animate-flicker {_x000D_
animation: fadeIn 1s infinite alternate;_x000D_
}
_x000D_
<h2 class="animate-flicker">Jump in the hole!</h2>
_x000D_
File name should match the layout id which in this example is : items_list_item.xml in the layout folder of your application
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView android:id="@+id/R.id.list_item_image"
android:layout_width="100dip"
android:layout_height="wrap_content" />
</LinearLayout>
The code should instead be something like this:
TextView text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("test");
Take a look at this solution using Linq. His example is similar in that he needed different markup for every 3rd item.
foreach( var myItem in Model.Members.Select(x,i) => new {Member = x, Index = i){
...
}
These are the three most straight forward methods:
1) Initialize from an initializer list:
std::vector<int> TestVector = {2,5,8,11,14};
2) Assign from an initializer list:
std::vector<int> TestVector;
TestVector.assign( {2,5,8,11,14} ); // overwrites TestVector
3) Insert an initializer list at a given point:
std::vector<int> TestVector;
...
TestVector.insert(end(TestVector), {2,5,8,11,14} ); // preserves previous elements
When reading through a member function, knowing who "owns" each variable is absolutely essential to understanding the meaning of the variable. In a function like this:
void Foo::bar( int apples )
{
int bananas = apples + grapes;
melons = grapes * bananas;
spuds += melons;
}
...it's easy enough to see where apples and bananas are coming from, but what about grapes, melons, and spuds? Should we look in the global namespace? In the class declaration? Is the variable a member of this object or a member of this object's class? Without knowing the answer to these questions, you can't understand the code. And in a longer function, even the declarations of local variables like apples and bananas can get lost in the shuffle.
Prepending a consistent label for globals, member variables, and static member variables (perhaps g_, m_, and s_ respectively) instantly clarifies the situation.
void Foo::bar( int apples )
{
int bananas = apples + g_grapes;
m_melons = g_grapes * bananas;
s_spuds += m_melons;
}
These may take some getting used to at first—but then, what in programming doesn't? There was a day when even { and } looked weird to you. And once you get used to them, they help you understand the code much more quickly.
(Using "this->" in place of m_ makes sense, but is even more long-winded and visually disruptive. I don't see it as a good alternative for marking up all uses of member variables.)
A possible objection to the above argument would be to extend the argument to types. It might also be true that knowing the type of a variable "is absolutely essential to understanding the meaning of the variable." If that is so, why not add a prefix to each variable name that identifies its type? With that logic, you end up with Hungarian notation. But many people find Hungarian notation laborious, ugly, and unhelpful.
void Foo::bar( int iApples )
{
int iBananas = iApples + g_fGrapes;
m_fMelons = g_fGrapes * iBananas;
s_dSpuds += m_fMelons;
}
Hungarian does tell us something new about the code. We now understand that there are several implicit casts in the Foo::bar() function. The problem with the code now is that the value of the information added by Hungarian prefixes is small relative to the visual cost. The C++ type system includes many features to help types either work well together or to raise a compiler warning or error. The compiler helps us deal with types—we don't need notation to do so. We can infer easily enough that the variables in Foo::bar() are probably numeric, and if that's all we know, that's good enough for gaining a general understanding of the function. Therefore the value of knowing the precise type of each variable is relatively low. Yet the ugliness of a variable like "s_dSpuds" (or even just "dSpuds") is great. So, a cost-benefit analysis rejects Hungarian notation, whereas the benefit of g_, s_, and m_ overwhelms the cost in the eyes of many programmers.
Just change your controller to the following:
public function create()
{
$items = Subject::all(['id', 'name']);
return View::make('your view', compact('items',$items));
}
And your view to:
<div class="form-group">
{!! Form::Label('item', 'Item:') !!}
<select class="form-control" name="item_id">
@foreach($items as $item)
<option value="{{$item->item_id}}">{{$item->id}}</option>
@endforeach
</select>
</div>
Hope this will solve your problem
For me, other answers didn't work. I had to go to open Files
and do Invalidate caches and restart
on Intellij. After that, everything worked fine again.
Assuming you want to float the elements, you would also have to float the label
elements too.
Something like this would work:
label {
/* Other styling... */
text-align: right;
clear: both;
float:left;
margin-right:15px;
}
#form {_x000D_
background-color: #FFF;_x000D_
height: 600px;_x000D_
width: 600px;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
margin-top: 0px;_x000D_
border-top-left-radius: 10px;_x000D_
border-top-right-radius: 10px;_x000D_
padding: 0px;_x000D_
text-align:center;_x000D_
}_x000D_
label {_x000D_
font-family: Georgia, "Times New Roman", Times, serif;_x000D_
font-size: 18px;_x000D_
color: #333;_x000D_
height: 20px;_x000D_
width: 200px;_x000D_
margin-top: 10px;_x000D_
margin-left: 10px;_x000D_
text-align: right;_x000D_
clear: both;_x000D_
float:left;_x000D_
margin-right:15px;_x000D_
}_x000D_
input {_x000D_
height: 20px;_x000D_
width: 300px;_x000D_
border: 1px solid #000;_x000D_
margin-top: 10px;_x000D_
float: left;_x000D_
}_x000D_
input[type=button] {_x000D_
float:none;_x000D_
}
_x000D_
<div id="form">_x000D_
<form action="" method="post" name="registration" class="register">_x000D_
<fieldset>_x000D_
<label for="Student">Name:</label>_x000D_
<input name="Student" id="Student" />_x000D_
<label for="Matric_no">Matric number:</label>_x000D_
<input name="Matric_no" id="Matric_no" />_x000D_
<label for="Email">Email:</label>_x000D_
<input name="Email" id="Email" />_x000D_
<label for="Username">Username:</label>_x000D_
<input name="Username" id="Username" />_x000D_
<label for="Password">Password:</label>_x000D_
<input name="Password" id="Password" type="password" />_x000D_
<input name="regbutton" type="button" class="button" value="Register" />_x000D_
</fieldset>_x000D_
</form>_x000D_
</div>
_x000D_
Alternatively, a more common approach would be to wrap the input
/label
elements in groups:
<div class="form-group">
<label for="Student">Name:</label>
<input name="Student" id="Student" />
</div>
#form {_x000D_
background-color: #FFF;_x000D_
height: 600px;_x000D_
width: 600px;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
margin-top: 0px;_x000D_
border-top-left-radius: 10px;_x000D_
border-top-right-radius: 10px;_x000D_
padding: 0px;_x000D_
text-align:center;_x000D_
}_x000D_
label {_x000D_
font-family: Georgia, "Times New Roman", Times, serif;_x000D_
font-size: 18px;_x000D_
color: #333;_x000D_
height: 20px;_x000D_
width: 200px;_x000D_
margin-top: 10px;_x000D_
margin-left: 10px;_x000D_
text-align: right;_x000D_
margin-right:15px;_x000D_
float:left;_x000D_
}_x000D_
input {_x000D_
height: 20px;_x000D_
width: 300px;_x000D_
border: 1px solid #000;_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div id="form">_x000D_
<form action="" method="post" name="registration" class="register">_x000D_
<fieldset>_x000D_
<div class="form-group">_x000D_
<label for="Student">Name:</label>_x000D_
<input name="Student" id="Student" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Matric_no">Matric number:</label>_x000D_
<input name="Matric_no" id="Matric_no" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Email">Email:</label>_x000D_
<input name="Email" id="Email" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Username">Username:</label>_x000D_
<input name="Username" id="Username" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Password">Password:</label>_x000D_
<input name="Password" id="Password" type="password" />_x000D_
</div>_x000D_
<input name="regbutton" type="button" class="button" value="Register" />_x000D_
</fieldset>_x000D_
</form>_x000D_
</div>
_x000D_
Note that the for
attribute should correspond to the id
of a labelable element, not its name
. This will allow users to click the label
to give focus to the corresponding form element.
@Greg is correct that one must write explicit comparison functions in the general case.
It is possible to use memcmp
if:
NaN
.-Wpadded
with clang to check this) OR the structs are explicitly initialized with memset
at initialization.BOOL
) that have distinct but equivalent values.Unless you are programming for embedded systems (or writing a library that might be used on them), I would not worry about some of the corner cases in the C standard. The near vs. far pointer distinction does not exist on any 32- or 64- bit device. No non-embedded system that I know of has multiple NULL
pointers.
Another option is to auto-generate the equality functions. If you lay your struct definitions out in a simple way, it is possible to use simple text processing to handle simple struct definitions. You can use libclang for the general case – since it uses the same frontend as Clang, it handles all corner cases correctly (barring bugs).
I have not seen such a code generation library. However, it appears relatively simple.
However, it is also the case that such generated equality functions would often do the wrong thing at application level. For example, should two UNICODE_STRING
structs in Windows be compared shallowly or deeply?
This one might be good
function addDayswithdate($date,$days){
$date = strtotime("+".$days." days", strtotime($date));
return date("Y-m-d", $date);
}
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
As Thrasgod correctly showed in his answer, the best way is to use the paintComponent, but also if the case is to have a semi transparent JPanel (or any other component, really) and have something not transparent inside. You have to also override the paintChildren method and set the alfa value to 1. In my case I extended the JPanel like that:
public class TransparentJPanel extends JPanel {
private float panelAlfa;
private float childrenAlfa;
public TransparentJPanel(float panelAlfa, float childrenAlfa) {
this.panelAlfa = panelAlfa;
this.childrenAlfa = childrenAlfa;
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(getBackground());
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, panelAlfa));
super.paintComponent(g2d);
}
@Override
protected void paintChildren(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(getBackground());
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_ATOP, childrenAlfa));
super.paintChildren(g);
}
//getter and setter
}
And in my project I only need to instantiate Jpanel jp = new TransparentJPanel(0.3f, 1.0f);
, if I want only the Jpanel transparent.
You could, also, mess with the JPanel shape using g2d.fillRoundRect
and g2d.drawRoundRect
, but it's not in the scope of this question.
I guess that you have some value that uniquely identifies a person on which you can base your checks.
This is a tricky one. Assuming you want to keep the structure a tree, I suggest this:
Assume this: A
has kids with his own daughter.
A
adds himself to the program as A
and as B
. Once in the role of father, let's call it boyfriend.
Add a is_same_for_out()
function which tells the output generating part of your program that all links going to B
internally should be going to A
on presentation of data.
This will make some extra work for the user, but I guess IT would be relatively easy to implement and maintain.
Building from that, you could work on code synching A
and B
to avoid inconsistencies.
This solution is surely not perfect, but is a first approach.
Indeed, thanks to the comments to my post here, it looks like sparse directories are the way to go. I believe the following should do it:
svn checkout --depth empty http://svnserver/trunk/proj
svn update --set-depth infinity proj/foo
svn update --set-depth infinity proj/bar
svn update --set-depth infinity proj/baz
Alternatively, --depth immediates
instead of empty
checks out files and directories in trunk/proj
without their contents. That way you can see which directories exist in the repository.
As mentioned in @zigdon's answer, you can also do a non-recursive checkout. This is an older and less flexible way to achieve a similar effect:
svn checkout --non-recursive http://svnserver/trunk/proj
svn update trunk/foo
svn update trunk/bar
svn update trunk/baz
For some, this could be as easy as setting the system path for dynamic libraries. On OS X, this is as simple as setting the DYLD_LIBRARY_PATH
environment variable. See:
I agree partly with Ed Staub. Gradle definitely is more powerful compared to maven and provides more flexibility long term.
After performing an evaluation to move from maven to gradle, we decided to stick to maven itself for two issues we encountered with gradle ( speed is slower than maven, proxy was not working ) .
Another solution would be to open the 'run configuration' and then in the 'Environment' tab, set the couple {Path,Value}.
For instance to add a 'lib' directory located at the root of the project,
Path <- ${workspace_loc:name_of_the_project}\lib
setAutoSize method must come before setWidth:
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setWidth('10');
We may use user defined function. At first initialize sum variable equal to zero. Then traverse the array and add element with sum . Then update the sum variable.
Code Snippet :
import java.util.*;
import java.lang.*;
import java.io.*;
class Sum
{
public static int sum(int arr[])
{
int sum=0;
for(int i=0; i<arr.length; i++)
{
sum += arr[i];
}
return sum;
}
public static void main (String[] args)
{
int arr[] = {1, 2, 3, 4, 5};
int total = sum(arr);
System.out.printf("%d", total);
}
}
The error message is fairly self-explanatory
(a,b,c,d,e) = line.split()
expects line.split()
to yield 5 elements, but in your case, it is only yielding 1 element. This could be because the data is not in the format you expect, a rogue malformed line, or maybe an empty line - there's no way to know.
To see what line is causing the issue, you could add some debug statements like this:
if len(line.split()) != 11:
print line
As Martin suggests, you might also be splitting on the wrong delimiter.
I took the answer above in C#/.Net, and rewrote it for Qt/C++, not to much changed, but I wanted to leave it here for anyone in the future looking for a C++'ish' answer.
bool MainWindow::isColumnExisting(QString &table, QString &columnName){
QSqlQuery q;
try {
if(q.exec("PRAGMA table_info("+ table +")"))
while (q.next()) {
QString name = q.value("name").toString();
if (columnName.toLower() == name.toLower())
return true;
}
} catch(exception){
return false;
}
return false;
}
There is no native version of Visual Studio for Mac OS X.
Almost all versions of Visual Studio have a Garbage rating on Wine's application database, so Wine isn't an option either, sadly.
Use a backslash as such
"From time to \"time\"";
Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this
'From time to "time"';
The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such
$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"
As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:
$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;
I just came across this question and thought on contributing with a solution that does not use regex.
In my case I use a helper method:
public boolean notNumber(String input){
boolean notNumber = false;
try {
// must not start with a number
@SuppressWarnings("unused")
double checker = Double.valueOf(input.substring(0,1));
}
catch (Exception e) {
notNumber = true;
}
return notNumber;
}
Probably an overkill, but I try to avoid regex whenever I can.
Assuming you want to get the value if the key does exist, use Dictionary<TKey, TValue>.TryGetValue
:
int value;
if (dictionary.TryGetValue(key, out value))
{
// Key was in dictionary; "value" contains corresponding value
}
else
{
// Key wasn't in dictionary; "value" is now 0
}
(Using ContainsKey
and then the the indexer makes it look the key up twice, which is pretty pointless.)
Note that even if you were using reference types, checking for null wouldn't work - the indexer for Dictionary<,>
will throw an exception if you request a missing key, rather than returning null. (This is a big difference between Dictionary<,>
and Hashtable
.)
The always @* would never trigger as no Right hand arguments change. Why not use a wire with assign?
module top (
input wire clk,
output wire [7:0] led
);
wire [7:0] data_reg ;
assign data_reg = 8'b10101011;
assign led = data_reg;
endmodule
If you actually want a flop where you can change the value, the default would be in the reset clause.
module top
(
input clk,
input rst_n,
input [7:0] data,
output [7:0] led
);
reg [7:0] data_reg ;
always @(posedge clk or negedge rst_n) begin
if (!rst_n)
data_reg <= 8'b10101011;
else
data_reg <= data ;
end
assign led = data_reg;
endmodule
Hope this helps
The reason why most use HashSet
is that the operations are (on average) O(1) instead of O(log n). If the set contains standard items you will not be "messing around with hash functions" as that has been done for you. If the set contains custom classes, you have to implement hashCode
to use HashSet
(although Effective Java shows how), but if you use a TreeSet
you have to make it Comparable
or supply a Comparator
. This can be a problem if the class does not have a particular order.
I have sometimes used TreeSet
(or actually TreeMap
) for very small sets/maps (< 10 items) although I have not checked to see if there is any real gain in doing so. For large sets the difference can be considerable.
Now if you need the sorted, then TreeSet
is appropriate, although even then if updates are frequent and the need for a sorted result is infrequent, sometimes copying the contents to a list or an array and sorting them can be faster.
This library is our standard for uuid generation and parsing:
Theory for convert GPS(WGS84)
to Cartesian coordinates
https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_geodetic_to_ECEF_coordinates
The following is what I am using:
I attached a VB code I wrote:
Imports System.Math
'Input GPSLatitude is WGS84 Latitude,h is altitude above the WGS 84 ellipsoid
Public Function GetSphericalLatitude(ByVal GPSLatitude As Double, ByVal h As Double) As Double
Dim A As Double = 6378137 'semi-major axis
Dim f As Double = 1 / 298.257223563 '1/f Reciprocal of flattening
Dim e2 As Double = f * (2 - f)
Dim Rc As Double = A / (Sqrt(1 - e2 * (Sin(GPSLatitude * PI / 180) ^ 2)))
Dim p As Double = (Rc + h) * Cos(GPSLatitude * PI / 180)
Dim z As Double = (Rc * (1 - e2) + h) * Sin(GPSLatitude * PI / 180)
Dim r As Double = Sqrt(p ^ 2 + z ^ 2)
Dim SphericalLatitude As Double = Asin(z / r) * 180 / PI
Return SphericalLatitude
End Function
Please notice that the h
is altitude above the WGS 84 ellipsoid
.
Usually GPS
will give us H
of above MSL
height.
The MSL
height has to be converted to height h
above the WGS 84 ellipsoid
by using the geopotential model EGM96
(Lemoine et al, 1998).
This is done by interpolating a grid of the geoid height file with a spatial resolution of 15 arc-minutes.
Or if you have some level professional GPS
has Altitude H
(msl,heigh above mean sea level) and UNDULATION
,the relationship between the geoid
and the ellipsoid (m)
of the chosen datum output from internal table. you can get h = H(msl) + undulation
To XYZ by Cartesian coordinates:
x = R * cos(lat) * cos(lon)
y = R * cos(lat) * sin(lon)
z = R *sin(lat)
I am afraid there isn't any easy solution with regards to font resizing. You can change the font size using a media query, but technically it will not resize smoothly. For an example, if you use:
@media only screen and (max-width: 320px){font-size: 3em;}
your font-size
will be 3em both for a 300 pixels and 200 pixels width. But you need lower font-size
for 200px width to make perfect responsive.
So, what is the real solution? There is only one way. You have to create a PNG image (with a transparent background) containing your text. After that you can easily make your image responsive (for example: width:35%; height:28px). By this way your text will be fully responsive with all devices.
I answer my own question reporting what therefore seems to be the most comprehensive overall procedure to Access IP Camera in Python OpenCV.
Given an IP camera:
IP
address port
where the IP address is accessed protocol
(HTTP/RTSP etc.) specified by the camera provider Then, if your camera is protected go ahead and find out:
username
password
Then use your data to run the following script:
"""Access IP Camera in Python OpenCV"""
import cv2
stream = cv2.VideoCapture('protocol://IP:port/1')
# Use the next line if your camera has a username and password
# stream = cv2.VideoCapture('protocol://username:password@IP:port/1')
while True:
r, f = stream.read()
cv2.imshow('IP Camera stream',f)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
NOTE: In my original question I specify to being working with Teledyne Dalsa Genie Nano XL Camera. Unfortunately for this kind of cameras this normal way of accessing the IP Camera video stream does not work and the Sapera SDK must be employed in order to grab frames from the device.
For substracting in moment.js:
moment().subtract(1, 'months').format('MMM YYYY');
Documentation:
http://momentjs.com/docs/#/manipulating/subtract/
Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).
moment().subtract('seconds', 1); // Deprecated in 2.8.0
moment().subtract(1, 'seconds');
As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.
moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8
When you are working with a Gitlab or Github you can run in trouble in this way. You squash your commits with one of the above method. My preferite one is:
git rebase -i HEAD~4
or
git rebase -i origin/master
select squash or fixup for yours commit. At this point you would check with git status. And the message could be:
On branch ABC-1916-remote
Your branch and 'origin/ABC-1916' have diverged,
and have 1 and 7 different commits each, respectively.
(use "git pull" to merge the remote branch into yours)
And you can be tempted to pull it. DO NOT DO THAT or you will be in the same situation as before.
Instead push to your origin with:
git push origin +ABC-1916-remote:ABC-1916
The + allow to force push only to one branch.
If someone is still having trouble with it ... I solved it by correcting it this way:
Inside the site conf file (example: /etc/nginx/conf.d/SITEEXAMPLE.conf
) I have the following line:
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
The error occurs because my site is NOT in the "/usr/share/nginx/html
" folder but in the folder: /var/www/html/SITE/
So, change that part, leaving the code as below. Note: For those who use the site standard in /var/www/html/YOUR_SITE/
fastcgi_param SCRIPT_FILENAME /var/www/html/YOUR_SITE/$fastcgi_script_name;
There is a new instance method called String::formatted(Object... args)
as of Java 15.
The internal implementation is same to String::format(String format, Object... args)
.
Formats using this string as the format string, and the supplied arguments.
String step1 = "one";
String step2 = "two";
// results in "Step one of two"
String string = "Step %s of %s".formatted(step1, step2);
Advantage: The difference is that the method is not static
and the formatting pattern is a string itself from which a new one is created based on the args
. This allows chaining to build the format itself first.
Disadvantage: There is no overloaded method with Locale
, therefore uses the default one. If you need to use a custom Locale
, you have to stick with String::format(Locale l,String format,Object... args)
.
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
Doing it as a stored procedure does have lot of advantages. You can get the sequence that is inserted into the table using syntax insert into table_name values returning
.
Like:
declare
some_seq_val number;
lv_seq number;
begin
some_seq_val := your_seq.nextval;
insert into your_tab (col1, col2, col3)
values (some_seq_val, val2, val3) returning some_seq_val into lv_seq;
dbms_output.put_line('The inserted sequence is: '||to_char(lv_seq));
end;
/
Or just return some_seq_val
. In case you are not making use of SEQUENCE, and arriving the sequence on some calculation, you can make use of returning into
effectively.
# detach head and move to D commit
git checkout <SHA1-for-D>
# move HEAD to A, but leave the index and working tree as for D
git reset --soft <SHA1-for-A>
# Redo the D commit re-using the commit message, but now on top of A
git commit -C <SHA1-for-D>
# Re-apply everything from the old D onwards onto this new place
git rebase --onto HEAD <SHA1-for-D> master
I think you need to include only these options in build.gradle:
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
}
p.s same answer from my post in : Error :: duplicate files during packaging of APK
Most of the previous answers do a good job explaining how, why, and when to use onResume()
but I would like to add something about re-creating your Activity
.
I want to know if I want to restart the activity at the end of exectuion of an other what method is executed onCreate() or onResume()
The answer is onCreate()
However, when deciding to actually re-create it, you should ask yourself how much of the Activity
needs to be re-created. If it is data in an adapter, say for a list, then you can call notifyDataChanged()
on the adapter
to repopulate the adapter
and not have to redraw everything.
Also, if you just need to update certain views
but not all then it may be more efficient to call invalidate()
on the view
(s) that need updated. This will only redraw those views
and possibly allow your application to run more smoothly. I hope this can help you.
var data=[];
var $el=$("#my-select");
$el.find('option:selected').each(function(){
data.push({value:$(this).val(),text:$(this).text()});
});
console.log(data)
-XX:PermSize
specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize
.
The default border-style
is none
, so you must specify that as well as the width and the colour.
You can use the border
shorthand property to set all three values in one go.
Also, the border attribute describes the border for the table and the cells. CSS is much more flexible so it only describes the border of the elements you are selecting. You need to select the cells too in order to get the same effect.
table, th, td {
border: solid black 1px;
}
See also border properties and tables in CSS.
Installing ASP.NET MVC3 from here should help.
You are logging sup
directly which is a string
console.log('sup')
Also you are using the wrong id
The template says #main_search
but you are using #searchBar
I suppose you are trying this out
$(function() {
var sup = $('#main_search').val('hi')
console.log(sup); // sup is a variable here
});
The registry is a no-go. You're not sure whether the user which uses your application, has sufficient rights to write to the registry.
You can use the app.config
file to save application-level settings (that are the same for each user who uses your application).
I would store user-specific settings in an XML file, which would be saved in Isolated Storage or in the SpecialFolder.ApplicationData directory.
Next to that, as from .NET 2.0, it is possible to store values back to the app.config
file.
Here:
def random_color():
rgbl=[255,0,0]
random.shuffle(rgbl)
return tuple(rgbl)
The result is either red, green or blue. The method is not applicable to other sets of colors though, where you'd have to build a list of all the colors you want to choose from and then use random.choice to pick one at random.
Add the following lines to the [alias] section of your .gitconfig file
ignore = update-index --assume-unchanged
unignore = update-index --no-assume-unchanged
ignored = !git ls-files -v | grep "^[[:lower:]]"
Now you can use git ignore my_file
to ignore changes to the local file, and git unignore my_file
to stop ignoring the changes. git ignored
lists the ignored files.
This answer was gleaned from http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html.
This feature is now supported, since Visual Studio Code 1.17. To fold/collapse your code block, just add the region tags, such as //#region my block name
and //#endregion
if coding in TypeScript/JavaScript.
Example:
If you want the second highest number you can use
=LARGE(E4:E9;2)
although that doesn't account for duplicates so you could get the same result as the Max
If you want the largest number that is smaller than the maximum number you can use this version
=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)
You can use this if you want to assign a background image on the backend:
divContent.Attributes.Add("style"," background-image:
url('images/icon_stock.gif');");
using System.Diagnostics;
class Program
{
static void Test1()
{
for (int i = 1; i <= 100; i++)
{
Console.WriteLine("Test1 " + i);
}
}
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Test1();
sw.Stop();
Console.WriteLine("Time Taken-->{0}",sw.ElapsedMilliseconds);
}
}
There is some incorrect information in this thread. I copied and pasted the incorrect information:
LEFT OUTER JOIN
SELECT * FROM A, B WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT * FROM A, B WHERE B.column(+) = A.column
The above is WRONG!!!!! It's reversed. How I determined it's incorrect is from the following book:
Oracle OCP Introduction to Oracle 9i: SQL Exam Guide. Page 115 Table 3-1 has a good summary on this. I could not figure why my converted SQL was not working properly until I went old school and looked in a printed book!
Here is the summary from this book, copied line by line:
Oracle outer Join Syntax:
from tab_a a, tab_b b,
where a.col_1 + = b.col_1
ANSI/ISO Equivalent:
from tab_a a left outer join
tab_b b on a.col_1 = b.col_1
Notice here that it's the reverse of what is posted above. I suppose it's possible for this book to have errata, however I trust this book more so than what is in this thread. It's an exam guide for crying out loud...
As Mike stated, the best way is to use information_schema
. As long as you're not in the master database, system stored procedures won't be returned.
SELECT *
FROM DatabaseName.INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
If for some reason you had non-system stored procedures in the master database, you could use the query (this will filter out MOST system stored procedures):
SELECT *
FROM [master].INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
AND LEFT(ROUTINE_NAME, 3) NOT IN ('sp_', 'xp_', 'ms_')
For those folks who like to measure speed in IPS ;)
require 'benchmark/ips'
ary = []
1000.times {
ary << {:bar => rand(1000)}
}
Benchmark.ips do |x|
x.report("sort") { ary.sort{ |a,b| b[:bar] <=> a[:bar] } }
x.report("sort reverse") { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse }
x.report("sort_by -a[:bar]") { ary.sort_by{ |a| -a[:bar] } }
x.report("sort_by a[:bar]*-1") { ary.sort_by{ |a| a[:bar]*-1 } }
x.report("sort_by.reverse!") { ary.sort_by{ |a| a[:bar] }.reverse }
x.compare!
end
And results:
Warming up --------------------------------------
sort 93.000 i/100ms
sort reverse 91.000 i/100ms
sort_by -a[:bar] 382.000 i/100ms
sort_by a[:bar]*-1 398.000 i/100ms
sort_by.reverse! 397.000 i/100ms
Calculating -------------------------------------
sort 938.530 (± 1.8%) i/s - 4.743k in 5.055290s
sort reverse 901.157 (± 6.1%) i/s - 4.550k in 5.075351s
sort_by -a[:bar] 3.814k (± 4.4%) i/s - 19.100k in 5.019260s
sort_by a[:bar]*-1 3.732k (± 4.3%) i/s - 18.706k in 5.021720s
sort_by.reverse! 3.928k (± 3.6%) i/s - 19.850k in 5.060202s
Comparison:
sort_by.reverse!: 3927.8 i/s
sort_by -a[:bar]: 3813.9 i/s - same-ish: difference falls within error
sort_by a[:bar]*-1: 3732.3 i/s - same-ish: difference falls within error
sort: 938.5 i/s - 4.19x slower
sort reverse: 901.2 i/s - 4.36x slower
Add the @JsonIgnoreProperties("fieldname")
annotation to your POJO.
Or you can use @JsonIgnore
before the name of the field you want to ignore while deserializing JSON. Example:
@JsonIgnore
@JsonProperty(value = "user_password")
public String getUserPassword() {
return userPassword;
}
For posterity / completeness's sake… Here are two FULL examples of how to implement this ridiculously versatile "way of doing things". @Robert's answer is blissfully concise and correct, but here I want to also show ways to actually "define" the blocks.
@interface ReusableClass : NSObject
@property (nonatomic,copy) CALayer*(^layerFromArray)(NSArray*);
@end
@implementation ResusableClass
static NSString const * privateScope = @"Touch my monkey.";
- (CALayer*(^)(NSArray*)) layerFromArray {
return ^CALayer*(NSArray* array){
CALayer *returnLayer = CALayer.layer
for (id thing in array) {
[returnLayer doSomethingCrazy];
[returnLayer setValue:privateScope
forKey:@"anticsAndShenanigans"];
}
return list;
};
}
@end
Silly? Yes. Useful? Hells yeah. Here is a different, "more atomic" way of setting the property.. and a class that is ridiculously useful…
@interface CALayoutDelegator : NSObject
@property (nonatomic,strong) void(^layoutBlock)(CALayer*);
@end
@implementation CALayoutDelegator
- (id) init {
return self = super.init ?
[self setLayoutBlock: ^(CALayer*layer){
for (CALayer* sub in layer.sublayers)
[sub someDefaultLayoutRoutine];
}], self : nil;
}
- (void) layoutSublayersOfLayer:(CALayer*)layer {
self.layoutBlock ? self.layoutBlock(layer) : nil;
}
@end
This illustrates setting the block property via the accessor (albeit inside init, a debatably dicey practice..) vs the first example's "nonatomic" "getter" mechanism. In either case… the "hardcoded" implementations can always be overwritten, per instance.. a lá..
CALayoutDelegator *littleHelper = CALayoutDelegator.new;
littleHelper.layoutBlock = ^(CALayer*layer){
[layer.sublayers do:^(id sub){ [sub somethingElseEntirely]; }];
};
someLayer.layoutManager = littleHelper;
Also.. if you want to add a block property in a category... say you want to use a Block instead of some old-school target / action "action"... You can just use associated values to, well.. associate the blocks.
typedef void(^NSControlActionBlock)(NSControl*);
@interface NSControl (ActionBlocks)
@property (copy) NSControlActionBlock actionBlock; @end
@implementation NSControl (ActionBlocks)
- (NSControlActionBlock) actionBlock {
// use the "getter" method's selector to store/retrieve the block!
return objc_getAssociatedObject(self, _cmd);
}
- (void) setActionBlock:(NSControlActionBlock)ab {
objc_setAssociatedObject( // save (copy) the block associatively, as categories can't synthesize Ivars.
self, @selector(actionBlock),ab ,OBJC_ASSOCIATION_COPY);
self.target = self; // set self as target (where you call the block)
self.action = @selector(doItYourself); // this is where it's called.
}
- (void) doItYourself {
if (self.actionBlock && self.target == self) self.actionBlock(self);
}
@end
Now, when you make a button, you don't have to set up some IBAction
drama.. Just associate the work to be done at creation...
_button.actionBlock = ^(NSControl*thisButton){
[doc open]; [thisButton setEnabled:NO];
};
This pattern can be applied OVER and OVER to Cocoa API's. Use properties to bring the relevant parts of your code closer together, eliminate convoluted delegation paradigms, and leverage the power of objects beyond that of just acting as dumb "containers".
The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag.
<script type="text/javascript">
$(document).ready(function() {
document.title = 'blah';
});
</script>
One more solution which is easy to understand :)
var newstring = mystring.split('.').join(' ');
from nltk.corpus import stopwords
# ...
filtered_words = [word for word in word_list if word not in stopwords.words('english')]
To disable close button you should add the following code to your Window class (the code was taken from here, edited and reformatted a bit):
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
if (hwndSource != null)
{
hwndSource.AddHook(HwndSourceHook);
}
}
private bool allowClosing = false;
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
private const uint MF_BYCOMMAND = 0x00000000;
private const uint MF_GRAYED = 0x00000001;
private const uint SC_CLOSE = 0xF060;
private const int WM_SHOWWINDOW = 0x00000018;
private const int WM_CLOSE = 0x10;
private IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case WM_SHOWWINDOW:
{
IntPtr hMenu = GetSystemMenu(hwnd, false);
if (hMenu != IntPtr.Zero)
{
EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
}
}
break;
case WM_CLOSE:
if (!allowClosing)
{
handled = true;
}
break;
}
return IntPtr.Zero;
}
This code also disables close item in System menu and disallows closing the dialog using Alt+F4.
You will probably want to close the window programmatically. Just calling Close()
will not work. Do something like this:
allowClosing = true;
Close();
As Wingman said, Google App Engine is a great solution for your scenario.
You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android
And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4
If you actually want this code to run at load, not at domready (ie you need the images to be loaded as well), then unfortunately the ready function doesn't do it for you. I generally just do something like this:
Include in document javascript (ie always called before onload fired):
var pageisloaded=0;
window.addEvent('load',function(){
pageisloaded=1;
});
Then your code:
if (pageisloaded) {
DoStuffFunction();
} else {
window.addEvent('load',DoStuffFunction);
}
(Or the equivalent in your framework of preference.) I use this code to do precaching of javascript and images for future pages. Since the stuff I'm getting isn't used for this page at all, I don't want it to take precedence over the speedy download of images.
There may be a better way, but I've yet to find it.
Use Form
, not form
. The capitalization counts.
As NT3RP told us that:
... we (Yahoo!) don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service...
So I just thought of sharing this site with you:
http://josscrowcroft.github.com/open-exchange-rates/
[update: site has moved to - http://openexchangerates.org]
This site says:
No access fees, no rate limits, no ugly XML - just free, hourly updated exchange rates in JSON format
[update: Free for personal use, a bargain for your business.]
I hope I've helped and this is of some use to you (and others too). : )
The error is indeed fixed by inserting this
with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
It should've been this:
foo.on('error', function(this: Foo, err: any) {
or this:
foo.on('error', function(this: typeof foo, err: any) {
A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this
and arrow-functions.
check this Twig Reference.
You can do it that simple:
{% if (a or b) %}
...
{% endif %}
This is the first and the easiest method
new ArrayList<T>(Arrays.asList(myArray));
Another method
//declare myarray
ArrayList <String> ar = new ArrayList<String> ();
for(String s : myArray){
ar.add(s);
}
This is iterating through the array and adding each element separately
The kind of for loop used here is called enhanced for loop
Run the following command on the terminal:
sudo apt-get autoremove ruby