You can get numpy array of rgb image easily by using numpy
and Image from PIL
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
im = Image.open('*image_name*') #These two lines
im_arr = np.array(im) #are all you need
plt.imshow(im_arr) #Just to verify that image array has been constructed properly
This considers any padding, border or margin the element has as well as elements larger than the viewport itself.
function inViewport($ele) {
var lBound = $(window).scrollTop(),
uBound = lBound + $(window).height(),
top = $ele.offset().top,
bottom = top + $ele.outerHeight(true);
return (top > lBound && top < uBound)
|| (bottom > lBound && bottom < uBound)
|| (lBound >= top && lBound <= bottom)
|| (uBound >= top && uBound <= bottom);
}
To call it use something like this:
var $myElement = $('#my-element'),
canUserSeeIt = inViewport($myElement);
console.log(canUserSeeIt); // true, if element is visible; false otherwise
Check to see if there are any triggers on the table you are trying to execute queries against. They can sometimes throw this error as they are trying to run the update/select/insert trigger that is on the table.
You can modify your query to disable then enable the trigger if the trigger DOES NOT need to be executed for whatever query you are trying to run.
ALTER TABLE your_table DISABLE TRIGGER [the_trigger_name]
UPDATE your_table
SET Gender = 'Female'
WHERE (Gender = 'Male')
ALTER TABLE your_table ENABLE TRIGGER [the_trigger_name]
len(repr(float(x)/3))
However I must say that this isn't as reliable as you think.
Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:
>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001
The explanation on why this happens is in this chapter of the python tutorial.
A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal
:
>>> print len(str(decimal.Decimal('0.1')))
3
I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.
Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.
In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.
I'll make some notes and corrections to your code:
def main():
# doc to define the function
# proper Python indentation
# document significant variables, especially inputs and outputs
# grade_1, grade_2, grade_3, average - id these
# year - id this
# fName, lName, ID, converted_ID
infile = open("studentinfo.txt", "r")
# you didn't 'intialize' this variable
data = infile.read()
# nor this
fName, lName, ID, year = data.split(",")
# this will produce an error if the file does not have the right number of strings
# 'year' is now a string, even though you 'initialized' it as 0
year = int(year)
# now 'year' is an integer
# a language that requires initialization would have raised an error
# over this switch in type of this variable.
# Prompt the user for three test scores
grades = eval(input("Enter the three test scores separated by a comma: "))
# 'eval' ouch!
# you could have handled the input just like you did the file input.
grade_1, grade_2, grade_3 = grades
# this would work only if the user gave you an 'iterable' with 3 values
# eval() doesn't ensure that it is an iterable
# and it does not ensure that the values are numbers.
# What would happen with this user input: "'one','two','three',4"?
# Create a username
uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
# earlier you 'initialized' converted_ID
# initialization in a static typed language would have caught this typo
# pseudo-initialization in Python does not catch typos
....
Very good option is update to Internet Explorer 10. You will find very useful developers tools including compatibility with from IE5 to IE 10 including quirks mode. If switch the IE version i menu, the page rendering of the page is changing immediately.
Very good feature of this mode is javascript and HTML (firebug like) debugger, which works in compatibility mode. It means, you can debug javascript in very old IE with the newest debugger, which is very cool feature. You cannot do that with virtual machine. Yes, you can have virtual machine for checking the final result.
From find manual:
NON-BUGS
Operator precedence surprises
The command find . -name afile -o -name bfile -print will never print
afile because this is actually equivalent to find . -name afile -o \(
-name bfile -a -print \). Remember that the precedence of -a is
higher than that of -o and when there is no operator specified
between tests, -a is assumed.
“paths must precede expression” error message
$ find . -name *.c -print
find: paths must precede expression
Usage: find [-H] [-L] [-P] [-Olevel] [-D ... [path...] [expression]
This happens because *.c has been expanded by the shell resulting in
find actually receiving a command line like this:
find . -name frcode.c locate.c word_io.c -print
That command is of course not going to work. Instead of doing things
this way, you should enclose the pattern in quotes or escape the
wildcard:
$ find . -name '*.c' -print
$ find . -name \*.c -print
the documentation has this blurb https://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history
import requests
r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for
I believe the CSS-only solution text-overflow: ellipsis
applies to one line only, so you won't be able to go this route:
.yourdiv {
line-height: 1.5em; /* Sets line height to 1.5 times text size */
height: 3em; /* Sets the div height to 2x line-height (3 times text size) */
width: 100%; /* Use whatever width you want */
white-space: normal; /* Wrap lines of text */
overflow: hidden; /* Hide text that goes beyond the boundaries of the div */
text-overflow: ellipsis; /* Ellipses (cross-browser) */
-o-text-overflow: ellipsis; /* Ellipses (cross-browser) */
}
Have you tried http://tpgblog.com/threedots/ for jQuery?
In a case where you are using a custom cell type, say ArticleCell, you might get an error that says :
Initializer for conditional binding must have Optional type, not 'ArticleCell'
You will get this error if your line of code looks something like this:
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as! ArticleCell
You can fix this error by doing the following :
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as ArticleCell?
If you check the above, you will see that the latter is using optional casting for a cell of type ArticleCell.
Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());
and then use the methods period.getYears()
, period.getMonths()
, period.getDays()
, duration.toHoursPart()
, duration.toMinutesPart()
, duration.toSecondsPart()
.
I'll answer the original question, i.e. how to get the time difference between two LocalDateTimes
in years, months, days, hours & minutes, such that the "sum" (see note below) of all the values for the different units equals the total temporal difference, and such that the value in each unit is smaller than the next bigger unit—i.e. minutes < 60
, hours < 24
, and so on.
Given two LocalDateTimes
start
and end
, e.g.
LocalDateTime start = LocalDateTime.of(2019, 11, 29, 17, 15);
LocalDateTime end = LocalDateTime.of(2020, 11, 30, 18, 44);
we can represent the absolute timespan between the two with a Duration
—perhaps using Duration.between(start, end)
. But the biggest unit we can extract out of a Duration
is days (as a temporal unit equivalent to 24h)—see the note below for an explanation. To use larger units (months, years) we can represent this Duration
with a pair of (Period
, Duration
), where the Period
measures the difference up to a precision of days and the Duration
represents the remainder:
Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());
Now we can simply use the methods defined on Period
and Duration
to extract the individual units:
System.out.printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds",
period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(),
duration.toMinutesPart(), duration.toSecondsPart());
1 years, 0 months, 1 days, 1 hours, 29 minutes, 0 seconds
or, using the default format:
System.out.println(period + " + " + duration);
P1Y1D + PT1H29M
Note that, in java.time
's conception, "units" like "month" or "year" don't represent a fixed, absolute temporal value—they're date- and calendar-dependent, as the following example illustrates:
LocalDateTime
start1 = LocalDateTime.of(2020, 1, 1, 0, 0),
end1 = LocalDateTime.of(2021, 1, 1, 0, 0),
start2 = LocalDateTime.of(2021, 1, 1, 0, 0),
end2 = LocalDateTime.of(2022, 1, 1, 0, 0);
System.out.println(Period.between(start1.toLocalDate(), end1.toLocalDate()));
System.out.println(Duration.between(start1, end1).toDays());
System.out.println(Period.between(start2.toLocalDate(), end2.toLocalDate()));
System.out.println(Duration.between(start2, end2).toDays());
P1Y
366
P1Y
365
What I do is create a vertical block for the shadow, and place it next to where my block element should be. The two blocks are then wrapped into another block:
<div id="wrapper">
<div id="shadow"></div>
<div id="content">CONTENT</div>
</div>
<style>
div#wrapper {
width:200px;
height:258px;
}
div#wrapper > div#shadow {
display:inline-block;
width:1px;
height:100%;
box-shadow: -3px 0px 5px 0px rgba(0,0,0,0.8)
}
div#wrapper > div#content {
display:inline-block;
height:100%;
vertical-align:top;
}
</style>
jsFiddle example here.
The transmission delay is the amount of time required for the router to push out the packet.
The propagation delay, is the time it takes a bit to propagate from one router to the next.
the transmission and propagation delay are completely different! if denote the length of the packet by L bits, and denote the transmission rate of the link from first router to second router by R bits/sec. then transmission delay will be L/R. and this is depended to transmission rate of link and the length of packet.
then if denote the distance between two routers d and denote the propagation speed s, the propagation delay will be d/s. it is a function of the Distance between the two routers, but has no dependence to the packet's length or the transmission rate of the link.
Works for me:
select DATE( FROM_UNIXTIME( columnname ) ) from tablename;
Use htmlparser2, its way faster and pretty straightforward. Consult this usage example:
https://www.npmjs.org/package/htmlparser2#usage
And the live demo here:
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
Bugginess* in the new Drupal 8 capabilities here inspired us to write our own:
<a href="{{ view_node }}">{% if title|length > 32 %}{% set title_array = title|split(' ') %}{% set title_word_count = 0 %}{% for ta in title_array %}{% set word_count = ta|length %}{% if title_word_count < 32 %}{% set title_word_count = title_word_count + word_count %}{{ ta }} {% endif %}{% endfor %}...{% else %}{{ title }}{% endif %}</a>
This takes into consideration both words and characters (*the "word boundary" setting in D8 was displaying nothing).
If enabled in your version of Vim, a terminal can be started with the :term
command.
Terminal window support was added to Vim 8. It is an optional feature that can be enabled when compiling Vim with the +terminal feature. If your version of Vim has terminal support, :echo has('terminal')
will output "1".
Entering :term
will place you in Terminal-Job mode, where you can use the terminal as expected.
Within Terminal-Job mode, pressing Ctrl-W N
or Ctrl-\ Ctrl-N
switches the mode to Terminal-Normal, which allows the cursor to be moved and commands to be ran similarly to Vim's Normal mode. To switch back to Terminal-Job mode, press i
.
Other answers mention similar functionality in Neovim.
Should be:
SELECT registrationDate,
(SELECT CASE
WHEN COUNT(*)< 2 THEN 'Ama'
WHEN COUNT(*)< 5 THEN 'SemiAma'
WHEN COUNT(*)< 7 THEN 'Good'
WHEN COUNT(*)< 9 THEN 'Better'
WHEN COUNT(*)< 12 THEN 'Best'
ELSE 'Outstanding'
END as a FROM Articles
WHERE Articles.userId = Users.userId) as ranking,
(SELECT COUNT(*)
FROM Articles
WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS
IntPtr GetIntPtr(Byte[] byteBuf)
{
IntPtr ptr = Marshal.AllocHGlobal(byteBuf.Length);
for (int i = 0; i < byteBuf.Length; i++)
{
Marshal.WriteByte(ptr, i, byteBuf[i]);
}
return ptr;
}
Try deleting index.lock
file in your .git
directory.
rm -f .git/index.lock
Such problems generally occur when you execute two git
commands simultaneously; maybe one from the command prompt and one from an IDE.
I've played around with select items before and without overriding the functionality with JavaScript, I don't think it's possible in Chrome. Whether you use a plugin or write your own code, CSS only is a no go for Chrome/Safari and as you said, Firefox is better at dealing with it.
When running PHP on windows with ISS there are some configuration settings in ISS that need to be set to prevent generic default pages from being shown.
1) Double click on FastCGISettings, click on PHP then Edit. Set StandardErrorMode to ReturnStdErrLn500.
2) Go the the site, double click on the Error Pages, click on the 500 status, click Edit Feature Settings, Change Error Responses to Detailed Errors, click ok
You can call a function from within a class with:
A().method1()
You need to put arguments before my_script.R
and use -
on the arguments, e.g.
R CMD BATCH -blabla my_script.R
commandArgs()
will receive -blabla
as a character string in this case. See the help for details:
$ R CMD BATCH --help
Usage: R CMD BATCH [options] infile [outfile]
Run R non-interactively with input from infile and place output (stdout
and stderr) to another file. If not given, the name of the output file
is the one of the input file, with a possible '.R' extension stripped,
and '.Rout' appended.
Options:
-h, --help print short help message and exit
-v, --version print version info and exit
--no-timing do not report the timings
-- end processing of options
Further arguments starting with a '-' are considered as options as long
as '--' was not encountered, and are passed on to the R process, which
by default is started with '--restore --save --no-readline'.
See also help('BATCH') inside R.
Fuel UX combobox has all the features you would expect.
Creating colnames with iterating
df = pd.DataFrame(columns=['colname_' + str(i) for i in range(5)])
print(df)
# Empty DataFrame
# Columns: [colname_0, colname_1, colname_2, colname_3, colname_4]
# Index: []
to_html()
operations
print(df.to_html())
# <table border="1" class="dataframe">
# <thead>
# <tr style="text-align: right;">
# <th></th>
# <th>colname_0</th>
# <th>colname_1</th>
# <th>colname_2</th>
# <th>colname_3</th>
# <th>colname_4</th>
# </tr>
# </thead>
# <tbody>
# </tbody>
# </table>
this seems working
print(type(df.to_html()))
# <class 'str'>
when you create df like this
df = pd.DataFrame(columns=COLUMN_NAMES)
it has 0 rows × n columns
, you need to create at least one row index by
df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])
now it has 1 rows × n columns
. You are be able to add data. Otherwise its df that only consist colnames object(like a string list).
Assuming we are talking about web applications and building APIs:
One approach is to categorize files by feature, much like what a micro service architecture would look like. The biggest win in my opinion is that it is super easy to see which files relate to a feature of the application.
The best way to illustrate is through an example:
We are developing a library application. In the first version of the application, a user can:
In a second version, users can also:
In a third version, users can also:
First we have the following structure:
books
+- controllers
¦ +- booksController.js
¦ +- authorsController.js
¦
+- entities
+- book.js
+- author.js
We then add on the user and loan features:
user
+- controllers
¦ +- userController.js
+- entities
¦ +- user.js
+- middleware
+- authentication.js
loan
+- controllers
¦ +- loanController.js
+- entities
+- loan.js
And then the favorites functionality:
favorites
+- controllers
¦ +- favoritesController.js
+- entities
+- favorite.js
For any new developer that gets handed the task to add on that the books search should also return information if any book have been marked as favorite, it's really easy to see where in the code he/she should look.
Then when the product owner sweeps in and exclaims that the favorites feature should be removed completely, it's easy to remove it.
More info about why it wasn't working for me in case it helps future people:
The reason why it wasn't working is that {% include %} in django doesn't like special characters like fancy apostrophe. The template data I was trying to include was pasted from word. I had to manually remove all of these special characters and then it included successfully.
select
username,
osuser,
terminal,
utl_inaddr.get_host_address(terminal) IP_ADDRESS
from
v$session
where
username is not null
order by
username,
osuser;
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
I also faced this problem when making a new project in eclipse.
Modify
Dosgi.requiredJavaVersion=1.6
to
Dosgi.requiredJavaVersion=1.7
Hope this helps
In pandas 0.20.2
you can do:
from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype
is_string_dtype(df['A'])
>>>> True
is_numeric_dtype(df['B'])
>>>> True
So your code becomes:
for y in agg.columns:
if (is_string_dtype(agg[y])):
treat_str(agg[y])
elif (is_numeric_dtype(agg[y])):
treat_numeric(agg[y])
There is an Extension Manager extension, that may help. It seems to allow to install a set of extensions specified in the settings.json
.
I had the same problem
I fixed that by using two options
contentType: false
processData: false
Actually I Added these two command to my $.ajax({}) function
var video = document.querySelector('video');
video.muted = true;
video.play()
Only this solution helped me, <video autoplay muted ...>...</video>
didn't work...
If you're at the top level - or able to cleanly get to the top level - of the thread, then just returning is nice. Throwing an exception isn't as clean, as you need to be able to check that nothing's going to catch the exception and ignore it.
The reason you need to use Thread.currentThread()
in order to call interrupt()
is that interrupt()
is an instance method - you need to call it on the thread you want to interrupt, which in your case happens to be the current thread. Note that the interruption will only be noticed the next time the thread would block (e.g. for IO or for a monitor) anyway - it doesn't mean the exception is thrown immediately.
Change this (CURRENT_TIMESTAMP-30)
To This: DateADD(mi, -30, Current_TimeStamp)
To get the current date use GetDate().
MSDN Link to DateAdd Function
MSDN Link to Get Date Function
Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable
For radio button:
<md-radio-button disabled>Select color</md-radio-button>
For dropdown:
<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>
I have resolved the said
MqttException (0) - javax.net.ssl.SSLHandshakeException: No subjectAltNames on the certificate match
error by adding one (can add multiple) alternative subject name in the server certificate (having CN=example.com) which after prints the part of certificate as below:
Subject Alternative Name:
DNS: example.com
I used KeyExplorer on windows for generating my server certificate. You can follow this link for adding alternative subject names (follow the only part for adding it).
Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases. However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):
RouterModule.forRoot([{ path: "", component: LoginComponent}])
This example might be seem a bit lengthy, but its intention should be quite clear.
It uses 3 Boolean properties in the ViewModel called, FlagForValue1
, FlagForValue2
and FlagForValue3
.
Each of these 3 properties is backed by a single private field called _intValue
.
The 3 Radio buttons of the view (xaml) are each bound to its corresponding Flag property in the view model. This means the radio button displaying "Value 1" is bound to the FlagForValue1
bool property in the view model and the other two accordingly.
When setting one of the properties in the view model (e.g. FlagForValue1
), its important to also raise property changed events for the other two properties (e.g. FlagForValue2
, and FlagForValue3
) so the UI (WPF INotifyPropertyChanged
infrastructure) can selected / deselect each radio button correctly.
private int _intValue;
public bool FlagForValue1
{
get
{
return (_intValue == 1) ? true : false;
}
set
{
_intValue = 1;
RaisePropertyChanged("FlagForValue1");
RaisePropertyChanged("FlagForValue2");
RaisePropertyChanged("FlagForValue3");
}
}
public bool FlagForValue2
{
get
{
return (_intValue == 2) ? true : false;
}
set
{
_intValue = 2;
RaisePropertyChanged("FlagForValue1");
RaisePropertyChanged("FlagForValue2");
RaisePropertyChanged("FlagForValue3");
}
}
public bool FlagForValue3
{
get
{
return (_intValue == 3) ? true : false;
}
set
{
_intValue = 3;
RaisePropertyChanged("FlagForValue1");
RaisePropertyChanged("FlagForValue2");
RaisePropertyChanged("FlagForValue3");
}
}
The xaml looks like this:
<RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue1, Mode=TwoWay}"
>Value 1</RadioButton>
<RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue2, Mode=TwoWay}"
>Value 2</RadioButton>
<RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue3, Mode=TwoWay}"
>Value 3</RadioButton>
How do you find this one?
function Foobar(foobar) {
this.foobar = foobar;
}
Foobar.prototype = {
foobar: null
};
Foobar.fromComponents = function(foo, bar) {
var foobar = foo + bar;
return new Foobar(foobar);
};
//usage: the following two lines give the same result
var x = Foobar.fromComponents('Abc', 'Cde');
var y = new Foobar('AbcDef')
Your code doesn't work (parse) because you have an extra )
at the end that causes a Parse Error. Count, you have 2 (
and 3 )
. It would work fine if you fix that, but strtotime()
returns a timestamp, so to get a human readable time use date()
.
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the )
is the main issue here.
dict((k, v) for k, v in points.items() if all(x < 5 for x in v))
You could choose to call .iteritems()
instead of .items()
if you're in Python 2 and points
may have a lot of entries.
all(x < 5 for x in v)
may be overkill if you know for sure each point will always be 2D only (in that case you might express the same constraint with an and
) but it will work fine;-).
Try this:
package example.spin.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
</RelativeLayout>
It's a really old topic but as it still comes up top in search results:
Nowadays you can add additional class fa-fw
to set it fixed width.
Example:
<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>
The latest docker supports setting ulimits through the command line and the API. For instance, docker run
takes --ulimit <type>=<soft>:<hard>
and there can be as many of these as you like. So, for your nofile, an example would be --ulimit nofile=262144:262144
Perl approach:
perl -ne 'if($i<1000) { print; } else { print STDERR;}; $i++;' in 1> in.new 2> out && mv in.new in
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
int main()
{
char string[200];
int g,a,i,G[20],A[20],met;
gets(string);
g=convert_input(G,string);
for(i=0;i<=g;i++)
printf("\n%d>>%d",i,G[i]);
return 0;
}
int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
temp=0;
while(string[i]!=' ' && string[i]!='\0')
temp=temp*10 + (string[i++]-'0') ;
if(string[i]==' ')
i++;
K[j++]=temp;
}
return j-1;
}
I had the requirement to retrieve all properties whose key starts with a distinct prefix (e.g. all properties starting with "log4j.appender.") and wrote following Code (using streams and lamdas of Java 8).
public static Map<String,Object> getPropertiesStartingWith( ConfigurableEnvironment aEnv,
String aKeyPrefix )
{
Map<String,Object> result = new HashMap<>();
Map<String,Object> map = getAllProperties( aEnv );
for (Entry<String, Object> entry : map.entrySet())
{
String key = entry.getKey();
if ( key.startsWith( aKeyPrefix ) )
{
result.put( key, entry.getValue() );
}
}
return result;
}
public static Map<String,Object> getAllProperties( ConfigurableEnvironment aEnv )
{
Map<String,Object> result = new HashMap<>();
aEnv.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
return result;
}
public static Map<String,Object> getAllProperties( PropertySource<?> aPropSource )
{
Map<String,Object> result = new HashMap<>();
if ( aPropSource instanceof CompositePropertySource)
{
CompositePropertySource cps = (CompositePropertySource) aPropSource;
cps.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
return result;
}
if ( aPropSource instanceof EnumerablePropertySource<?> )
{
EnumerablePropertySource<?> ps = (EnumerablePropertySource<?>) aPropSource;
Arrays.asList( ps.getPropertyNames() ).forEach( key -> result.put( key, ps.getProperty( key ) ) );
return result;
}
// note: Most descendants of PropertySource are EnumerablePropertySource. There are some
// few others like JndiPropertySource or StubPropertySource
myLog.debug( "Given PropertySource is instanceof " + aPropSource.getClass().getName()
+ " and cannot be iterated" );
return result;
}
private static void addAll( Map<String, Object> aBase, Map<String, Object> aToBeAdded )
{
for (Entry<String, Object> entry : aToBeAdded.entrySet())
{
if ( aBase.containsKey( entry.getKey() ) )
{
continue;
}
aBase.put( entry.getKey(), entry.getValue() );
}
}
Note that the starting point is the ConfigurableEnvironment which is able to return the embedded PropertySources (the ConfigurableEnvironment is a direct descendant of Environment). You can autowire it by:
@Autowired
private ConfigurableEnvironment myEnv;
If you not using very special kinds of property sources (like JndiPropertySource, which is usually not used in spring autoconfiguration) you can retrieve all properties held in the environment.
The implementation relies on the iteration order which spring itself provides and takes the first found property, all later found properties with the same name are discarded. This should ensure the same behaviour as if the environment were asked directly for a property (returning the first found one).
Note also that the returned properties are not yet resolved if they contain aliases with the ${...} operator. If you want to have a particular key resolved you have to ask the Environment directly again:
myEnv.getProperty( key );
There are 2 ways to call-
setInterval(function (){ functionName();}, 60000);
setInterval(functionName, 60000);
above function will call on every 60 seconds.
If you want to use substr()
, you can easily add the dashes or slashes like this..
$datetime = "20130409163705";
$yyyy = substr($datetime,0,4);
$mm = substr($datetime,4,6);
$dd = substr($datetime,6,8);
$hh = substr($datetime,8,10);
$MM = substr($datetime,10,12);
$ss = substr($datetime,12,14);
$dt_formatted = $mm."/".$dd."/".$yyyy." ".$hh.":".$MM.":".$ss;
You can figure out any further formatting from that point.
git config --local receive.denyCurrentBranch updateInstead
https://github.com/git/git/blob/v2.3.0/Documentation/config.txt#L2155
Use that on the server repository, and it also updates the working tree if no untracked overwrite would happen.
It was added in Git 2.3 as mentioned by VonC in the comments.
I've compiled Git 2.3 and gave it a try. Sample usage:
git init server
cd server
touch a
git add .
git commit -m 0
git config --local receive.denyCurrentBranch updateInstead
cd ..
git clone server local
cd local
touch b
git add .
git commit -m 1
git push origin master:master
cd ../server
ls
Output:
a
b
Yay, b
got pushed!
You have your arguments to the remote add
command reversed:
git remote add <NAME> <PATH>
So:
git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git
See git remote --help
for more information.
import subprocess
python_path = subprocess.check_output("which python", shell=True).strip()
python_path = python_path.decode('utf-8')
Compiler will complain only if you are going to use that class in such a way that the compiler needs to know its implementation.
Ex:
It will not complain if you are just going to use it as a pointer. Of course, you will have to #import it in the implementation file (if you are instantiating an object of that class) since it needs to know the class contents to instantiate an object.
NOTE: #import is not same as #include. This means there is nothing called circular import. import is kind of a request for the compiler to look into a particular file for some information. If that information is already available, compiler ignores it.
Just try this, import A.h in B.h and B.h in A.h. There will be no problems or complaints and it will work fine too.
When to use @class
You use @class only if you don't even want to import a header in your header. This could be a case where you don't even care to know what that class will be. Cases where you may not even have a header for that class yet.
An example of this could be that you are writing two libraries. One class, lets call it A, exists in one library. This library includes a header from the second library. That header might have a pointer of A but again might not need to use it. If library 1 is not yet available, library B will not be blocked if you use @class. But if you are looking to import A.h, then library 2's progress is blocked.
Bad news I'm afraid (or maybe great news?) : it isn't C code, it's an example of "Processing" - an open source language aimed at programming images. Take a look here
Looks very cool.
Here is simple example of how you can do this.
Just replace the image file and you are done.
HTML Code
<input type="radio" id="r1" name="rr" />
<label for="r1"><span></span>Radio Button 1</label>
<p>
<input type="radio" id="r2" name="rr" />
<label for="r2"><span></span>Radio Button 2</label>
CSS
input[type="radio"] {
display:none;
}
input[type="radio"] + label {
color:#f2f2f2;
font-family:Arial, sans-serif;
font-size:14px;
}
input[type="radio"] + label span {
display:inline-block;
width:19px;
height:19px;
margin:-1px 4px 0 0;
vertical-align:middle;
background:url(check_radio_sheet.png) -38px top no-repeat;
cursor:pointer;
}
input[type="radio"]:checked + label span {
background:url(check_radio_sheet.png) -57px top no-repeat;
}
Another option is to use the package require-dir which let's you do the following. It supports recursion as well.
var requireDir = require('require-dir');
var dir = requireDir('./path/to/dir');
Have a look at the respective sitepoint reference pages for background-image and URIs
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.
I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.
I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.
Experiment 1
Parallel.For(0, 1000000000, x => Method1());
Experiment 2
for (int i = 0; i < 1000000000; i++)
{
Task o = new Task(Method1);
o.Start();
}
The ArrayList uses the equals method implemented in the class (your case Thing class) to do the equals comparison.
Box shadows can use commas to have multiple effects, just like with background images (in CSS3).
If you're looking for a recursive directory listing solutions. Use below code I hope it should help you.
<?php
/**
* Function for recursive directory file list search as an array.
*
* @param mixed $dir Main Directory Path.
*
* @return array
*/
function listFolderFiles($dir)
{
$fileInfo = scandir($dir);
$allFileLists = [];
foreach ($fileInfo as $folder) {
if ($folder !== '.' && $folder !== '..') {
if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
$allFileLists[$folder . '/'] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
} else {
$allFileLists[$folder] = $folder;
}
}
}
return $allFileLists;
}//end listFolderFiles()
$dir = listFolderFiles('your searching directory path ex:-F:\xampp\htdocs\abc');
echo '<pre>';
print_r($dir);
echo '</pre>'
?>
UPDATE
Just a quick note, as I can see this looks really stupid, and it has no good use with pure PHP because the array_merge
just works there. BUT try it with the PHP MongoDB driver before you rush to downvote. That dude WILL add indexes for whatever reason, and WILL ruin the merged object. With my naïve little function, the merge comes out exactly the way it was supposed to with a traditional array_merge
.
I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge
, array_replace
nor array_push
worked. I had a bit complex structure of objects wrapped as arrays in array:
$a = [
["a" => [1, "a2"]],
["b" => ["b1", 2]]
];
$t = [
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
And I needed to merge them keeping the same structure like this:
$merged = [
["a" => [1, "a2"]],
["b" => ["b1", 2]],
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
The best solution I came up with was this:
public static function glueArrays($arr1, $arr2) {
// merges TWO (2) arrays without adding indexing.
$myArr = $arr1;
foreach ($arr2 as $arrayItem) {
$myArr[] = $arrayItem;
}
return $myArr;
}
Short answer:
$ git remote show -n origin
or, an alternative for pure quick scripts:
$ git config --get remote.origin.url
Some info:
$ git remote -v
will print all remotes (not what you want). You want origin right?$ git remote show origin
much better, shows only origin
but takes too long (tested on git version 1.8.1.msysgit.1).I ended up with: $ git remote show -n origin
, which seems to be fastest. With -n
it will not fetch remote heads (AKA branches). You don't need that type of info, right?
http://www.kernel.org/pub//software/scm/git/docs/git-remote.html
You can apply | grep -i fetch
to all three versions to show only the fetch URL.
If you require pure speed, then use:
$ git config --get remote.origin.url
Thanks to @Jefromi for pointing that out.
First of all print
isn't a function in Python 2, it is a statement.
To suppress the automatic newline add a trailing ,
(comma). Now a space will be used instead of a newline.
Demo:
print 1,
print 2
output:
1 2
Or use Python 3's print()
function:
from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)
As you can clearly see print()
function is much more powerful as we can specify any string to be used as end
rather a fixed space.
Thi is your code :
Driver.findElement(By.xpath(//a[@href ='/docs/configuration']")).click();
You missed the Quotation mark
it should be as below
Driver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();
Hope this helps!
Answer updated for 2020:
Both <object>
and <embed>
are included in the WHAT-WG HTML Living Standard (Sept 2020).
<object>
The object element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a child browsing context, or as an external resource to be processed by a plugin.
<embed>
The embed element provides an integration point for an external (typically non-HTML) application or interactive content.
Are there advantages/disadvantages to using one tag vs. the other?
The opinion of Mozilla Developer Network (MDN) appears (albeit fairly subtly) to very marginally favour <object>
over <embed>
but overwhelmingly, MDN, wants to recommend that wherever you can, you avoid embedding external content entirely.
[...] you are unlikely to use these elements very much — Applets haven't been used for years, Flash is no longer very popular, due to a number of reasons (see The case against plugins, below), PDFs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. Plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects.
Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For virtually all applications, it's time to stop delivering content that depends on plugins and start taking advantage of Web technologies instead.
If you want to overwrite only one file:
git fetch
git checkout origin/master <filepath>
If you want to overwrite all changed files:
git fetch
git reset --hard origin/master
(This assumes that you're working on master
locally and you want the changes on the origin's master
- if you're on a branch, substitute that in instead.)
There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])
) or using an empty array (like c.toArray(new String[0])
).
In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.
You can follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).
If you are using Babel or such transpilers and using async/await you could do :
function onDrop() {
console.log("dropped");
}
async function dropAll( collections ) {
const drops = collections.map(col => conn.collection(col).drop(onDrop) );
await drops;
console.log("all dropped");
}
The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.
Here's a short snippet to keep SO reviewers happy:
Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.
And read the section which follows it:
This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.
Copy a value from one row to any other qualified rows within the same table (or different tables):
UPDATE `your_table` t1, `your_table` t2
SET t1.your_field = t2.your_field
WHERE t1.other_field = some_condition
AND t1.another_field = another_condition
AND t2.source_id = 'explicit_value'
Start off by aliasing the table into 2 unique references so the SQL server can tell them apart
Next, specify the field(s) to copy.
Last, specify the conditions governing the selection of the rows
Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.
One issue is that reindex
will fail if there are duplicate values. Say we're working with timestamped data, which we want to index by date:
df = pd.DataFrame({
'timestamps': pd.to_datetime(
['2016-11-15 1:00','2016-11-16 2:00','2016-11-16 3:00','2016-11-18 4:00']),
'values':['a','b','c','d']})
df.index = pd.DatetimeIndex(df['timestamps']).floor('D')
df
yields
timestamps values
2016-11-15 "2016-11-15 01:00:00" a
2016-11-16 "2016-11-16 02:00:00" b
2016-11-16 "2016-11-16 03:00:00" c
2016-11-18 "2016-11-18 04:00:00" d
Due to the duplicate 2016-11-16
date, an attempt to reindex:
all_days = pd.date_range(df.index.min(), df.index.max(), freq='D')
df.reindex(all_days)
fails with:
...
ValueError: cannot reindex from a duplicate axis
(by this it means the index has duplicates, not that it is itself a dup)
Instead, we can use .loc
to look up entries for all dates in range:
df.loc[all_days]
yields
timestamps values
2016-11-15 "2016-11-15 01:00:00" a
2016-11-16 "2016-11-16 02:00:00" b
2016-11-16 "2016-11-16 03:00:00" c
2016-11-17 NaN NaN
2016-11-18 "2016-11-18 04:00:00" d
fillna
can be used on the column series to fill blanks if needed.
The other solutions have one of a few problems:
x = [1, 2, 2, 2]
and y = [2, 2]
they convert y
to a set
, and either remove all matching elements (leaving [1]
only) or remove one of each unique element (leaving [1, 2, 2]
), when the proper behavior would be to remove 2
twice, leaving [1, 2]
, orO(m * n)
work, where an optimal solution can do O(m + n)
workAlain was on the right track with Counter
to solve #2 and #3, but that solution will lose ordering. The solution that preserves order (removing the first n
copies of each value for n
repetitions in the list
of values to remove) is:
from collections import Counter
x = [1,2,3,4,3,2,1]
y = [1,2,2]
remaining = Counter(y)
out = []
for val in x:
if remaining[val]:
remaining[val] -= 1
else:
out.append(val)
# out is now [3, 4, 3, 1], having removed the first 1 and both 2s.
To make it remove the last copies of each element, just change the for
loop to for val in reversed(x):
and add out.reverse()
immediately after exiting the for
loop.
Constructing the Counter
is O(n)
in terms of y
's length, iterating x
is O(n)
in terms of x
's length, and Counter
membership testing and mutation are O(1)
, while list.append
is amortized O(1)
(a given append
can be O(n)
, but for many append
s, the overall big-O averages O(1)
since fewer and fewer of them require a reallocation), so the overall work done is O(m + n)
.
You can also test for to determine if there were any elements in y
that were not removed from x
by testing:
remaining = +remaining # Removes all keys with zero counts from Counter
if remaining:
# remaining contained elements with non-zero counts
To get the post by George Howarth working properly with more than one replacement you need to remove the break, assign the output to a variable ($line) and then output the variable:
$lookupTable = @{
'something1' = 'something1aa'
'something2' = 'something2bb'
'something3' = 'something3cc'
'something4' = 'something4dd'
'something5' = 'something5dsf'
'something6' = 'something6dfsfds'
}
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
Get-Content -Path $original_file | ForEach-Object {
$line = $_
$lookupTable.GetEnumerator() | ForEach-Object {
if ($line -match $_.Key)
{
$line = $line -replace $_.Key, $_.Value
}
}
$line
} | Set-Content -Path $destination_file
I used the following code to get the last character of a string.
substr(output, nchar(stringOfInterest), nchar(stringOfInterest))
You can play with the nchar(stringOfInterest) to figure out how to get last few characters.
Usually this kind of error comes when you do DateTime conversion or parsing. Check the calendar setting in the server where the application is hosted, mainly the time zone and short date format, and ensure it's set to the right time zone for the location. Hope this would resolve the issue.
Please find below JavaScript
example to make a JSONP
call without JQuery:
Also, you can refer my GitHub
repository for reference.
https://github.com/shedagemayur/JavaScriptCode/tree/master/jsonp
window.onload = function(){_x000D_
var callbackMethod = 'callback_' + new Date().getTime();_x000D_
_x000D_
var script = document.createElement('script');_x000D_
script.src = 'https://jsonplaceholder.typicode.com/users/1?callback='+callbackMethod;_x000D_
_x000D_
document.body.appendChild(script);_x000D_
_x000D_
window[callbackMethod] = function(data){_x000D_
delete window[callbackMethod];_x000D_
document.body.removeChild(script);_x000D_
console.log(data);_x000D_
}_x000D_
}
_x000D_
in ruby for constantly using, add follow:
module Selenium
module WebDriver
class Element
def select(value)
self.find_elements(:tag_name => "option").find do |option|
if option.text == value
option.click
return
end
end
end
end
end
and you will be able to select value:
browser.find_element(:xpath, ".//xpath").select("Value")
// pages/about.js
import Link from 'next/link'
export default ({ url: { query: { name } } }) => (
<p>Welcome to About! { name }</p>
)
_x000D_
You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:
// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");
// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
// Append the element to the end of Array list
dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?
See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/
This assumes that you're not using JQuery, and you only have the basic DOM API to work with.
A constant value cannot change. A static variable exists to a function, or class, rather than an instance or object.
These two concepts are not mutually exclusive, and can be used together.
If you aren't allowing the column to be Null you need to provide a default to populate existing rows. e.g.
ALTER TABLE dbo.YourTbl ADD
newcol int NOT NULL CONSTRAINT DF_YourTbl_newcol DEFAULT 0
On Enterprise Edition this is a metadata only change since 2012
My guess is that $_.Name does not exist.
If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_
Proof is in the source code of PHP.
I'll take you through a quick process of how to find out this sort of thing on your own in the future any time you want. Bear with me, there'll be a lot of C source code you can skim over (I explain it). If you want to brush up on some C, a good place to start is our SO wiki.
Download the source (or use http://lxr.php.net/ to browse it online), grep all the files for the function name, you'll find something such as this:
PHP 5.3.6 (most recent at time of writing) describes the two functions in their native C code in the file url.c.
RawUrlEncode()
PHP_FUNCTION(rawurlencode)
{
char *in_str, *out_str;
int in_str_len, out_str_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
&in_str_len) == FAILURE) {
return;
}
out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len);
RETURN_STRINGL(out_str, out_str_len, 0);
}
UrlEncode()
PHP_FUNCTION(urlencode)
{
char *in_str, *out_str;
int in_str_len, out_str_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
&in_str_len) == FAILURE) {
return;
}
out_str = php_url_encode(in_str, in_str_len, &out_str_len);
RETURN_STRINGL(out_str, out_str_len, 0);
}
Okay, so what's different here?
They both are in essence calling two different internal functions respectively: php_raw_url_encode and php_url_encode
So go look for those functions!
PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length)
{
register int x, y;
unsigned char *str;
str = (unsigned char *) safe_emalloc(3, len, 1);
for (x = 0, y = 0; len--; x++, y++) {
str[y] = (unsigned char) s[x];
#ifndef CHARSET_EBCDIC
if ((str[y] < '0' && str[y] != '-' && str[y] != '.') ||
(str[y] < 'A' && str[y] > '9') ||
(str[y] > 'Z' && str[y] < 'a' && str[y] != '_') ||
(str[y] > 'z' && str[y] != '~')) {
str[y++] = '%';
str[y++] = hexchars[(unsigned char) s[x] >> 4];
str[y] = hexchars[(unsigned char) s[x] & 15];
#else /*CHARSET_EBCDIC*/
if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) {
str[y++] = '%';
str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4];
str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15];
#endif /*CHARSET_EBCDIC*/
}
}
str[y] = '\0';
if (new_length) {
*new_length = y;
}
return ((char *) str);
}
PHPAPI char *php_url_encode(char const *s, int len, int *new_length)
{
register unsigned char c;
unsigned char *to, *start;
unsigned char const *from, *end;
from = (unsigned char *)s;
end = (unsigned char *)s + len;
start = to = (unsigned char *) safe_emalloc(3, len, 1);
while (from < end) {
c = *from++;
if (c == ' ') {
*to++ = '+';
#ifndef CHARSET_EBCDIC
} else if ((c < '0' && c != '-' && c != '.') ||
(c < 'A' && c > '9') ||
(c > 'Z' && c < 'a' && c != '_') ||
(c > 'z')) {
to[0] = '%';
to[1] = hexchars[c >> 4];
to[2] = hexchars[c & 15];
to += 3;
#else /*CHARSET_EBCDIC*/
} else if (!isalnum(c) && strchr("_-.", c) == NULL) {
/* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */
to[0] = '%';
to[1] = hexchars[os_toascii[c] >> 4];
to[2] = hexchars[os_toascii[c] & 15];
to += 3;
#endif /*CHARSET_EBCDIC*/
} else {
*to++ = c;
}
}
*to = 0;
if (new_length) {
*new_length = to - start;
}
return (char *) start;
}
One quick bit of knowledge before I move forward, EBCDIC is another character set, similar to ASCII, but a total competitor. PHP attempts to deal with both. But basically, this means byte EBCDIC 0x4c byte isn't the L
in ASCII, it's actually a <
. I'm sure you see the confusion here.
Both of these functions manage EBCDIC if the web server has defined it.
Also, they both use an array of chars (think string type) hexchars
look-up to get some values, the array is described as such:
/* rfc1738:
...The characters ";",
"/", "?", ":", "@", "=" and "&" are the characters which may be
reserved for special meaning within a scheme...
...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
reserved characters used for their reserved purposes may be used
unencoded within a URL...
For added safety, we only leave -_. unencoded.
*/
static unsigned char hexchars[] = "0123456789ABCDEF";
Beyond that, the functions are really different, and I'm going to explain them in ASCII and EBCDIC.
URLENCODE:
+
sign to the output string.isalnum(c)
), and also isn't and _
, -
, or .
character, then we , output a %
sign to array position 0, do an array look up to the hexchars
array for a lookup for os_toascii
array (an array from Apache that translates char to hex code) for the key of c
(the present character), we then bitwise shift right by 4, assign that value to the character 1, and to position 2 we assign the same lookup, except we preform a logical and to see if the value is 15 (0xF), and return a 1 in that case, or a 0 otherwise. At the end, you'll end up with something encoded._-.
chars, it outputs exactly what it is.RAWURLENCODE:
Note: Many programmers have probably never seen a for loop iterate this way, it's somewhat hackish and not the standard convention used with most for-loops, pay attention, it assigns x
and y
, checks for exit on len
reaching 0, and increments both x
and y
. I know, it's not what you'd expect, but it's valid code.
str
._-.
chars, and if it isn't, we do almost the same assignment as with URLENCODE where it preforms lookups, however, we increment differently, using y++
rather than to[1]
, this is because the strings are being built in different ways, but reach the same goal at the end anyway.\0
byte. Differences:
\0
byte to the string, RawUrlEncode does (this may be a moot point)They basically iterate differently, one assigns a + sign in the event of ASCII 20.
URLENCODE:
0
, with the exception of being a .
or -
, OR less than A
but greater than char 9
, OR greater than Z
and less than a
but not a _
. OR greater than z
(yeah, EBCDIC is kinda messed up to work with). If it matches any of those, do a similar lookup as found in the ASCII version (it just doesn't require a lookup in os_toascii).RAWURLENCODE:
z
, it excludes ~
from the URL encode.\0
byte to the string before return.~
that UrlEncode does not (this is a reported issue). It's worth noting that ASCII and EBCDIC 0x20 are both spaces.+
, RawUrlEncode makes a space into %20
via array lookups.Disclaimer: I haven't touched C in years, and I haven't looked at EBCDIC in a really really long time. If I'm wrong somewhere, let me know.
Based on all of this, rawurlencode is the way to go most of the time. As you see in Jonathan Fingland's answer, stick with it in most cases. It deals with the modern scheme for URI components, where as urlencode does things the old school way, where + meant "space."
If you're trying to convert between the old format and new formats, be sure that your code doesn't goof up and turn something that's a decoded + sign into a space by accidentally double-encoding, or similar "oops" scenarios around this space/20%/+ issue.
If you're working on an older system with older software that doesn't prefer the new format, stick with urlencode, however, I believe %20 will actually be backwards compatible, as under the old standard %20 worked, just wasn't preferred. Give it a shot if you're up for playing around, let us know how it worked out for you.
Basically, you should stick with raw, unless your EBCDIC system really hates you. Most programmers will never run into EBCDIC on any system made after the year 2000, maybe even 1990 (that's pushing, but still likely in my opinion).
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
This is one way to do it:
SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
2 /
Type created
SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
2 BEGIN
3 FOR i IN 1..t_in.count LOOP
4 dbms_output.put_line(t_in(i));
5 END LOOP;
6 END;
7 /
Procedure created
SQL> DECLARE
2 v_t MyType;
3 BEGIN
4 v_t := MyType();
5 v_t.EXTEND(10);
6 v_t(1) := 'this is a test';
7 v_t(2) := 'A second test line';
8 testing(v_t);
9 END;
10 /
this is a test
A second test line
To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:
SQL> CREATE OR REPLACE PACKAGE p IS
2 TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
3
4 PROCEDURE pp (inp p_type);
5 END p;
6 /
Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
2 PROCEDURE pp (inp p_type) IS
3 BEGIN
4 FOR i IN 1..inp.count LOOP
5 dbms_output.put_line(inp(i));
6 END LOOP;
7 END pp;
8 END p;
9 /
Package body created
SQL> DECLARE
2 v_t p.p_type;
3 BEGIN
4 v_t(1) := 'this is a test of p';
5 v_t(2) := 'A second test line for p';
6 p.pp(v_t);
7 END;
8 /
this is a test of p
A second test line for p
PL/SQL procedure successfully completed
SQL>
This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.
May be easier using a java.util.HashSet. For example:
List <String> list = new ArrayList<String>();
list.add("behold");
list.add("bend");
list.add("bet");
//Load the list into a hashSet
Set<String> set = new HashSet<String>(list);
if (set.contains("bend"))
{
System.out.println("String found!");
}
You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:
$("#change_password").click(function() {
var target = $(this).attr("rel");
if($("#" + target).attr("disabled")) {
$("#" + target).attr("disabled", false);
} else {
$("#" + target).attr("disabled", true);
}
});
The "rel" attribute stores the id of the target input field.
Another option is to use the TimeUtils
utility method:
TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)
In my case I had two Constructors in the bean and I had the same error. I have just deleted one of them and now the issue is fixed!
it can do this for case statements as the values are compiler constants. An explanation in more detail is here http://sequence-points.blogspot.com/2007/10/why-is-switch-statement-faster-than-if.html
function abc() {
var color = document.getElementById("test").style.color;
if (color === "red")
document.getElementById("test").style.color="black";
else
document.getElementById("test").style.color="red";
}
Go to Manage Jenkins > Configure Global Security and select the Enable Security checkbox.
For the basic username/password authentication, I would recommend selecting Jenkins Own User Database for the security realm and then selecting Logged in Users can do anything or a matrix based strategy (in case when you have multiple users with different permissions) for the Authorization.
In my case, we have time series from different devices but some devices could not send any value during some period. So we should create NA values for every device and time period and after that do fillna.
df = pd.DataFrame([["device1", 1, 'first val of device1'], ["device2", 2, 'first val of device2'], ["device3", 3, 'first val of device3']])
df.pivot(index=1, columns=0, values=2).fillna(method='ffill').unstack().reset_index(name='value')
Result:
0 1 value
0 device1 1 first val of device1
1 device1 2 first val of device1
2 device1 3 first val of device1
3 device2 1 None
4 device2 2 first val of device2
5 device2 3 first val of device2
6 device3 1 None
7 device3 2 None
8 device3 3 first val of device3
for l in list1:
val = 50 - l[0] + l[1] - l[2]
print "val:", val
Loop through list and do operation on the sublist as you wanted.
found this here:
<!--[if lte IE 8]>
<script type="text/javascript">
if (Object.defineProperty && Object.getOwnPropertyDescriptor &&
!Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get)
(function() {
var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
Object.defineProperty(Element.prototype, "textContent",
{ // It won't work if you just drop in innerText.get
// and innerText.set or the whole descriptor.
get : function() {
return innerText.get.call(this)
},
set : function(x) {
return innerText.set.call(this, x)
}
}
);
})();
</script>
<![endif]-->
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
DateTime d = Calendar1.SelectedDate;
// int a;
TextBox2.Text = d.ToShortDateString();
string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
string s1 = Convert.ToDateTime(Label7.Text).ToShortDateString();
DateTime dt = Convert.ToDateTime(s).Date;
DateTime dt1 = Convert.ToDateTime(s1).Date;
if (dt <= dt1)
{
Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
}
else
{
string diff = dt.Subtract(dt1).ToString();
Response.Write(diff);
Label18.Text = diff;
Session["diff"] = Label18.Text;
}
}
another option ... needs remoting ...
(invoke-command -ComputerName mymachine -ScriptBlock {Get-ItemProperty HKLM:\SOFTWARE\VanDyke\VShell\License -Name Version }).version
I believe enum have a .name() in its API, pretty simple to use like this example:
private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }
private enum Security {
low,
high
}
With this you can simply call
yourObject.security()
and it returns high/low as String, in this example
server.session.timeout
in the application.properties
file is now deprecated. The correct setting is:
server.servlet.session.timeout=60s
Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.
how about:
return(sList.Contains("ok"));
That should do the trick if all you want to do is check for an "ok" and return the answer ...
There is a second parameter for the callback for collection.insert
that will return the doc or docs inserted, which should have _ids.
Try:
collection.insert(objectToInsert, function(err,docsInserted){
console.log(docsInserted);
});
and check the console to see what I mean.
The key is git submodules.
Start reading the Submodules chapter of the Git Community Book or of the Users Manual
Say you have repository PROJECT1, PROJECT2, and MEDIA...
cd /path/to/PROJECT1
git submodule add ssh://path.to.repo/MEDIA
git commit -m "Added Media submodule"
Repeat on the other repo...
Now, the cool thing is, that any time you commit changes to MEDIA, you can do this:
cd /path/to/PROJECT2/MEDIA
git pull
cd ..
git add MEDIA
git commit -m "Upgraded media to version XYZ"
This just recorded the fact that the MEDIA submodule WITHIN PROJECT2 is now at version XYZ.
It gives you 100% control over what version of MEDIA each project uses. git submodules are great, but you need to experiment and learn about them.
With great power comes the great chance to get bitten in the rump.
>>> t
[1, 3, 6]
>>> [j-i for i, j in zip(t[:-1], t[1:])] # or use itertools.izip in py2k
[2, 3]
Using session
, I successfully passed a parameter (name
) from servlet #1 to servlet #2, using response.sendRedirect
in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name
back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name");
---but you don't need this.
If Servlet #2 calls a JSP, you can show name
this way on the JSP webpage:
<h1>Welcome ${name}</h1>
I had the same on Android. This is how i fixed it:
including ONLY the file:
slf4j-api-1.7.6.jar
in my libs/ folder
Having any additional slf4j* file, caused the NoClassDefFoundError.
Obviously, the rest of the libs can be there (android-support-v4, etc)
Versions: Eclipse Kepler 2013 06 14 - 02 29 ADT 22.3 Android SDK: 4.4.2
Hope someone saves the time i wasted thanks to this!
In addition, gcc will look in the directories specified after the -I
option.
If you use :
new ArrayList<T>(Arrays.asList(myArray));
you may create and fill two lists ! Filling twice a big list is exactly what you don't want to do because it will create another Object[]
array each time the capacity needs to be extended.
Fortunately the JDK implementation is fast and Arrays.asList(a[])
is very well done. It create a kind of ArrayList named Arrays.ArrayList where the Object[] data points directly to the array.
// in Arrays
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
//still in Arrays, creating a private unseen class
private static class ArrayList<E>
private final E[] a;
ArrayList(E[] array) {
a = array; // you point to the previous array
}
....
}
The dangerous side is that if you change the initial array, you change the List ! Are you sure you want that ? Maybe yes, maybe not.
If not, the most understandable way is to do this :
ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity
for (Element element : myArray) {
list.add(element);
}
Or as said @glglgl, you can create another independant ArrayList with :
new ArrayList<T>(Arrays.asList(myArray));
I love to use Collections
, Arrays
, or Guava. But if it don't fit, or you don't feel it, just write another inelegant line instead.
Look in c:\windows\Microsoft.NET\Framework and you will see various folders starting with "v" indicating the versions of .NET installed.
That's because there was an error in your query. MySQli->query()
will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
There's no "guaranteed to work anywhere" method.
Step 1 is to check argv[0], if the program was started by its full path, this would (usually) have the full path. If it was started by a relative path, the same holds (though this requires getting teh current working directory, using getcwd().
Step 2, if none of the above holds, is to get the name of the program, then get the name of the program from argv[0], then get the user's PATH from the environment and go through that to see if there's a suitable executable binary with the same name.
Note that argv[0] is set by the process that execs the program, so it is not 100% reliable.
I don't have access to Python right now, but off the top of my head:
fig = plt.figure()
axes1 = fig.add_subplot(111)
# set props for left y-axis here
axes2 = axes1.twinx() # mirror them
axes2.set_ylabel(...)
If You are using eclipse then the following steps will solve your problem:
Go to Run -> Run Configurations -> Main Class Search -> Locate your class manually -> Apply -> Run
You must have the definition of class B
before you use the class. How else would the compiler otherwise know that there exists such a function as B::add
?
Either define class B
before class A
, or move the body of A::doSomething
to after class B
have been defined, like
class B;
class A
{
B* b;
void doSomething();
};
class B
{
A* a;
void add() {}
};
void A::doSomething()
{
b->add();
}
In my string I have Thai characters (TIS620 encoded) and German umlauts. The answer from agiles put me on the right path. Instead of .getBytes() I use now
int len = mString.length(); // Length of the string
byte[] dataset = new byte[len];
for (int i = 0; i < len; ++i) {
char c = mString.charAt(i);
dataset[i]= (byte) c;
}
[data-value] {
/* Attribute exists */
}
[data-value="foo"] {
/* Attribute has this exact value */
}
[data-value*="foo"] {
/* Attribute value contains this value somewhere in it */
}
[data-value~="foo"] {
/* Attribute has this value in a space-separated list somewhere */
}
[data-value^="foo"] {
/* Attribute value starts with this */
}
[data-value|="foo"] {
/* Attribute value starts with this in a dash-separated list */
}
[data-value$="foo"] {
/* Attribute value ends with this */
}
There are several sparse matrix classes in scipy.
bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix
Any of them can do the conversion.
import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)
(0, 0) 1
(0, 2) 1
(1, 2) 1
See http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information .
Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem
Split using a regular expression. Note I made the case more general with leading spaces. The list comprehension is to remove the null strings at the front and back.
>>> import re
>>> string = " blah, lots , of , spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['blah', 'lots', 'of', 'spaces', 'here']
This works even if ^\s+
doesn't match:
>>> string = "foo, bar "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>
Here's why you need ^\s+:
>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
[' blah', 'lots', 'of', 'spaces', 'here']
See the leading spaces in blah?
Clarification: above uses the Python 3 interpreter, but results are the same in Python 2.
Native way to get the mimetype:
For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()
Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.
While mime_content_type
is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).
If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.
function getMimeType($filename)
{
$mimetype = false;
if(function_exists('finfo_open')) {
// open with FileInfo
} elseif(function_exists('getimagesize')) {
// open with GD
} elseif(function_exists('exif_imagetype')) {
// open with EXIF
} elseif(function_exists('mime_content_type')) {
$mimetype = mime_content_type($filename);
}
return $mimetype;
}
Here's a function that wraps cope360's answer:
CREATE OR REPLACE FUNCTION getIndices(_table_name varchar)
RETURNS TABLE(table_name varchar, index_name varchar, column_name varchar) AS $$
BEGIN
RETURN QUERY
select
t.relname::varchar as table_name,
i.relname::varchar as index_name,
a.attname::varchar as column_name
from
pg_class t,
pg_class i,
pg_index ix,
pg_attribute a
where
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and a.attrelid = t.oid
and a.attnum = ANY(ix.indkey)
and t.relkind = 'r'
and t.relname = _table_name
order by
t.relname,
i.relname;
END;
$$ LANGUAGE plpgsql;
Usage:
select * from getIndices('<my_table>')
Add this code at the end of your .htaccess file
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
You could make the identifier a param for a query selector. For PHP and compatible languages use an associative array (in effect an objects) and then json_encode.
$temp=array('#id' =>array('href'=>'services.html')
,'img' =>array('src'=>"img/SolutionInnerbananer.jpg")
,'.html'=>'<h2 class="fg-white">AboutUs</h2><p class="fg-white">...</p>'
);
echo json_encode($temp);
But HTML don't do it for you without some JS.
{"#id":{"href":"services.html"},"img":{"src":"img\/SolutionInnerbananer.jpg"}
,".html":"<h2 class=\"fg-white\">AboutUs<\/h2><p class=\"fg-white\">...<\/p>"}
Consider below example
We will consider the integer and fractional part separately.
The integral part is easy, 2 = 10.
For the fractional part:
0.625 × 2 = 1.25 1 Generate 1 and continue with the rest.
0.25 × 2 = 0.5 0 Generate 0 and continue.
0.5 × 2 = 1.0 1 Generate 1 and nothing remains.
So 0.625 = 0.101, and 2.625 = 10.101.
See this link for more information.
I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fixed the missing DLLs.
I find it better and easier than downloading and pasting DLLs.
Just another information about CentOS. In this case, when using "systemctl" to launch process. You have to modify the system file ==> /usr/lib/systemd/system/processName.service .Had this line in the file :
LimitNOFILE=50000
And just reload your system conf :
systemctl daemon-reload
If you got any error on your console by saying, “Embedded servlet container failed to start. Port 8080 was already in use.” Then go to application.properties file and add this property “server.port = 8090”.
Actually the default port for spring boot is 8080, if you have something else on that port, the above error will occur. So we are asking spring boot to run on other port by adding “server.port = 8090” in application.properties file.
The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options
value as a default.
As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.
Mathematica or Maple will allow you to give as many decimal places as your heart desires.
EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.
On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin
(usually 2e-308).
Compare these two analyses.
x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1) #Should throw an error
x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2) #ok
In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.
As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr
package.
mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")
These are slower and more memory intensive to use than regular (double precision) numeric
vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.
I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.
Just move the var inside the "name" block:
- name: Download apache
vars:
url: czxcxz
shell: wget {{url}}
In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click
on android:theme = "@style/AppTheme"
in the Android manifest file. It will open styles.xml
file where you can change the parent attribute of the style tag.
At parent=
in styles.xml
you can browse all available styles by using auto-complete inside the ""
. E.g. try parent="Theme."
with your cursor right after the .
and then pressing Ctrl + Space
.
You can also preview themes in the preview window in Android Studio.
MD5 processes an arbitrary-length message into a fixed-length output of 128 bits, typically represented as a sequence of 32 hexadecimal digits.
If you want to move the position of the legend please use the following code:
library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom")
This should give you the desired result.
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
In Bjarne's words (The C++ Programming Language, 4th Edition, page 366):
Where termination is an acceptable response, an uncaught exception will achieve that because it turns into a call of terminate() (§13.5.2.5). Also, a
noexcept
specifier (§13.5.1.1) can make that desire explicit.Successful fault-tolerant systems are multilevel. Each level copes with as many errors as it can without getting too contorted and leaves the rest to higher levels. Exceptions support that view. Furthermore,
terminate()
supports this view by providing an escape if the exception-handling mechanism itself is corrupted or if it has been incompletely used, thus leaving exceptions uncaught. Similarly,noexcept
provides a simple escape for errors where trying to recover seems infeasible.double compute(double x) noexcept; { string s = "Courtney and Anya"; vector<double> tmp(10); // ... }
The vector constructor may fail to acquire memory for its ten doubles and throw a
std::bad_alloc
. In that case, the program terminates. It terminates unconditionally by invokingstd::terminate()
(§30.4.1.3). It does not invoke destructors from calling functions. It is implementation-defined whether destructors from scopes between thethrow
and thenoexcept
(e.g., for s in compute()) are invoked. The program is just about to terminate, so we should not depend on any object anyway. By adding anoexcept
specifier, we indicate that our code was not written to cope with a throw.
Use below code snippet This worked for me
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"symbol\":\"ABCD\}";
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Trade trade = objectMapper.readValue(jsonString, new TypeReference<Symbol>() {});
Model Class
@JsonIgnoreProperties public class Symbol {
@JsonProperty("symbol")
private String symbol;
}
ianhanniballake is right. You can get all the functionality of Activity
from FragmentActivity
. In fact, FragmentActivity
has more functionality.
Using FragmentActivity
you can easily build tab and swap
format. For each tab you can use different Fragment
(Fragments
are reusable). So for any FragmentActivity
you can reuse the same Fragment
.
Still you can use Activity
for single pages like list down something and edit element of the list in next page.
Also remember to use Activity
if you are using android.app.Fragment
; use FragmentActivity
if you are using android.support.v4.app.Fragment
. Never attach a android.support.v4.app.Fragment
to an android.app.Activity
, as this will cause an exception to be thrown.
Ubuntu :
data<-iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
legend(7,4.3,unique(data$Species),col=1:length(data$Species),pch=1)
should do it for you. But I prefer ggplot2
and would suggest that for better graphics in R.
If you have the capability to do so, I would recommend using either mod-jk or mod-proxy-ajp to pass requests from Apache to JBoss. The AJP protocol is much more efficient compared to using HTTP proxy requests and as a benefit, JBoss will see the request as coming from the original client and not Apache.
nowadays,2017-12-17. I don't find any description about Font-property-order‘s necessity in spec. And I test in chrome always works whatever the order is.
@font-face {
font-family: 'Font Awesome 5 Free';
font-weight: 900;
src: url('#{$fa-font-path}/fa-solid-900.eot');
src: url('#{$fa-font-path}/fa-solid-900.eot?#iefix') format('embedded-opentype'),
url('#{$fa-font-path}/fa-solid-900.woff2') format('woff2'),
url('#{$fa-font-path}/fa-solid-900.woff') format('woff'),
url('#{$fa-font-path}/fa-solid-900.ttf') format('truetype'),
url('#{$fa-font-path}/fa-solid-900.svg#fontawesome') format('svg');
}
@font-face {
font-family: 'Font Awesome 5 Free';
font-weight: 400;
src: url('#{$fa-font-path}/fa-regular-400.eot');
src: url('#{$fa-font-path}/fa-regular-400.eot?#iefix') format('embedded-opentype'),
url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
url('#{$fa-font-path}/fa-regular-400.woff') format('woff'),
url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype'),
url('#{$fa-font-path}/fa-regular-400.svg#fontawesome') format('svg');
}
I put together this test app to reproduce the issue using the HTTP testing framework from the Apache HttpClient package:
ClassLoader cl = HCTest.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
TrustManager[] tm = tmf.getTrustManagers();
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, pwd);
KeyManager[] km = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(km, tm, null);
LocalTestServer localServer = new LocalTestServer(sslcontext);
localServer.registerDefaultHandlers();
localServer.start();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
TrustStrategy trustStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for (X509Certificate cert: chain) {
System.err.println(cert);
}
return false;
}
};
SSLSocketFactory sslsf = new SSLSocketFactory("TLS", null, null, keystore, null,
trustStrategy, new AllowAllHostnameVerifier());
Scheme https = new Scheme("https", 443, sslsf);
httpclient.getConnectionManager().getSchemeRegistry().register(https);
InetSocketAddress address = localServer.getServiceAddress();
HttpHost target1 = new HttpHost(address.getHostName(), address.getPort(), "https");
HttpGet httpget1 = new HttpGet("/random/100");
HttpResponse response1 = httpclient.execute(target1, httpget1);
System.err.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
HttpHost target2 = new HttpHost("www.verisign.com", 443, "https");
HttpGet httpget2 = new HttpGet("/");
HttpResponse response2 = httpclient.execute(target2, httpget2);
System.err.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
EntityUtils.consume(entity2);
} finally {
localServer.stop();
}
Even though, Sun's JSSE implementation appears to always read the trust material from the default trust store for some reason, it does not seem to get added to the SSL context and to impact the process of trust verification during the SSL handshake.
Here's the output of the test app. As you can see, the first request succeeds whereas the second fails as the connection to www.verisign.com is rejected as untrusted.
[
[
Version: V1
Subject: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3
Key: Sun DSA Public Key
Parameters:DSA
p: fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
q: 9760508f 15230bcc b292b982 a2eb840b f0581cf5
g: f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a
y:
f0cc639f 702fd3b1 03fa8fa6 676c3756 ea505448 23cd1147 fdfa2d7f 662f7c59
a02ddc1a fd76673e 25210344 cebbc0e7 6250fff1 a814a59f 30ff5c7e c4f186d8
f0fd346c 29ea270d b054c040 c74a9fc0 55a7020f eacf9f66 a0d86d04 4f4d23de
7f1d681f 45c4c674 5762b71b 808ded17 05b74baf 8de3c4ab 2ef662e3 053af09e
Validity: [From: Sat Dec 11 14:48:35 CET 2004,
To: Tue Dec 09 14:48:35 CET 2014]
Issuer: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
SerialNumber: [ 41bafab3]
]
Algorithm: [SHA1withDSA]
Signature:
0000: 30 2D 02 15 00 85 BE 6B D0 91 EF 34 72 05 FF 1A 0-.....k...4r...
0010: DB F6 DE BF 92 53 9B 14 27 02 14 37 8D E8 CB AC .....S..'..7....
0020: 4E 6C 93 F2 1F 7D 20 A1 2D 6F 80 5F 58 AE 33 Nl.... .-o._X.3
]
HTTP/1.1 200 OK
[
[
Version: V3
Subject: CN=www.verisign.com, OU=" Production Security Services", O="VeriSign, Inc.", STREET=487 East Middlefield Road, L=Mountain View, ST=California, OID.2.5.4.17=94043, C=US, SERIALNUMBER=2497886, OID.2.5.4.15="V1.0, Clause 5.(b)", OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key: Sun RSA public key, 2048 bits
modulus: 20699622354183393041832954221256409980425015218949582822286196083815087464214375375678538878841956356687753084333860738385445545061253653910861690581771234068858443439641948884498053425403458465980515883570440998475638309355278206558031134532548167239684215445939526428677429035048018486881592078320341210422026566944903775926801017506416629554190534665876551381066249522794321313235316733139718653035476771717662585319643139144923795822646805045585537550376512087897918635167815735560529881178122744633480557211052246428978388768010050150525266771462988042507883304193993556759733514505590387262811565107773578140271
public exponent: 65537
Validity: [From: Wed May 26 02:00:00 CEST 2010,
To: Sat May 26 01:59:59 CEST 2012]
Issuer: CN=VeriSign Class 3 Extended Validation SSL SGC CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
SerialNumber: [ 53d2bef9 24a7245e 83ca01e4 6caa2477]
Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
[accessMethod: 1.3.6.1.5.5.7.48.1
accessLocation: URIName: http://EVIntl-ocsp.verisign.com, accessMethod: 1.3.6.1.5.5.7.48.2
accessLocation: URIName: http://EVIntl-aia.verisign.com/EVIntl2006.cer]
]
...
]
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:345)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.createLayeredSocket(SSLSocketFactory.java:446)
...
BrowserStack.com
On this site, you can emulate a lot of iOS's devices online.
I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.
CMD.EXE will not execute internal commands contained inside the string. Only actual files can be launched with that string.
You will need to actually call a batch file to do what you want.
BAT1.bat
start cmd.exe /k bat2.bat
BAT2.bat
cd C:\activiti-5.9\setup
ant demo.start
You may want to create a folder called BAT
, and add it's location to your path.
So if you create C:\BAT
, add C:\BAT\;
to the path. The path is located at:
click -> Start -> right-click Computer -> Properties ->
click -> Avanced System Settings -> Environment Variables
select -> Path (From either list. User Variables are specific to
your profile, System Variables are, duh, system-wide.)
Click -> Edit
Press the -> the [END] or [HOME] key.
Type -> C:\BAT\;
Click -> OK -> OK
Now place all your batch files in C:\BAT
and they will be found, regardless of the current directory.
Make sure "html_files" is a directory in your app's main bundle, and not just a group in Xcode.
I was facing same issue, tried restarting my server, reopening editor but computer restart did the magic.
P.S: I was facing issue on a windows machine and issue occurred when I moved module into a new folder.
Probably you have this:
const db = mongoose.connect('mongodb://localhost:27017/db');
// Do some stuff
db.disconnect();
but you can also have something like this:
mongoose.connect('mongodb://localhost:27017/db');
const model = mongoose.model('Model', ModelSchema);
model.find().then(doc => {
console.log(doc);
}
you cannot call db.disconnect()
but you can close the connection after you use it.
model.find().then(doc => {
console.log(doc);
}).then(() => {
mongoose.connection.close();
});
Thank you, Erik, for posting this. This worked for me. I'd like to add a note about an extra step I needed. Within "Payload/Application.app/" there was a directory named "CACertChains" that contained a file named "cacert.pem". I had to remove the directory and the .pem to complete these steps. Thanks again! –
You cannot.
According to the XML Schema specification, a boolean is true
or false
. True
is not valid:
3.2.2.1 Lexical representation An instance of a datatype that is defined as ·boolean· can have the following legal literals {true, false, 1, 0}. 3.2.2.2 Canonical representation The canonical representation for boolean is the set of literals {true, false}.
If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.
I know this is a bit late - but to be clear:
A string doesn't really have encoding... in .NET the a string is a collection of char objects. Essentially, if it is a string, it has already been decoded.
However if you are reading the contents of a file, which is made of bytes, and wish to convert that to a string, then the file's encoding must be used.
.NET includes encoding and decoding classes for: ASCII, UTF7, UTF8, UTF32 and more.
Most of these encodings contain certain byte-order marks that can be used to distinguish which encoding type was used.
The .NET class System.IO.StreamReader is able to determine the encoding used within a stream, by reading those byte-order marks;
Here is an example:
/// <summary>
/// return the detected encoding and the contents of the file.
/// </summary>
/// <param name="fileName"></param>
/// <param name="contents"></param>
/// <returns></returns>
public static Encoding DetectEncoding(String fileName, out String contents)
{
// open the file with the stream-reader:
using (StreamReader reader = new StreamReader(fileName, true))
{
// read the contents of the file into a string
contents = reader.ReadToEnd();
// return the encoding.
return reader.CurrentEncoding;
}
}
SELECT *
FROM (
SELECT *
FROM users
WHERE 1
ORDER BY
rand()
LIMIT 20
) q
ORDER BY
name
try:
header('Location: ' . $_SERVER['HTTP_REFERER']);
Note that this may not work with secure pages (HTTPS) and it's a pretty bad idea overall as the header can be hijacked, sending the user to some other destination. The header may not even be sent by the browser.
Ideally, you will want to either:
<div class="button_style">
This is your button value
</div>
.button_style{
background-color: Transparent;
border: none; /* Your can add different style/properties of button Here*/
cursor:pointer;
}
Meanwhile you can use the isSameOrAfter
method:
moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');
Wrap each individual condition in parentheses, and then use the &
operator to combine the conditions:
df.loc[(df['one'] >= df['two']) & (df['one'] <= df['three']), 'que'] = df['one']
You can fill the non-matching rows by just using ~
(the "not" operator) to invert the match:
df.loc[~ ((df['one'] >= df['two']) & (df['one'] <= df['three'])), 'que'] = ''
You need to use &
and ~
rather than and
and not
because the &
and ~
operators work element-by-element.
The final result:
df
Out[8]:
one two three que
0 10 1.2 4.2 10
1 15 70 0.03
2 8 5 0
Yes, let's use Select
as an example
sample code: Columns("A").select
How to loop through Columns:
Method 1: (You can use index to replace the Excel Address)
For i = 1 to 100
Columns(i).Select
next i
Method 2: (Using the address)
For i = 1 To 100
Columns(Columns(i).Address).Select
Next i
EDIT: Strip the Column for OP
columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")
e.g. you want to get the 27th Column --> AA, you can get it this way
I had this issue with an image gallery that I wanted to rerender due to changes made on a different tab. So tab1 = imageGallery, tab2 = favoriteImages
tab @change="updateGallery()" -> this forces my v-for directive to process the filteredImages function every time I switch tabs.
<script>
export default {
data() {
return {
currentTab: 0,
tab: null,
colorFilter: "",
colors: ["None", "Beige", "Black"],
items: ["Image Gallery", "Favorite Images"]
};
},
methods: {
filteredImages: function() {
return this.$store.getters.getImageDatabase.filter(img => {
if (img.color.match(this.colorFilter)) return true;
});
},
updateGallery: async function() {
// instance is responsive to changes
// change is made and forces filteredImages to do its thing
// async await forces the browser to slow down and allows changes to take effect
await this.$nextTick(function() {
this.colorFilter = "Black";
});
await this.$nextTick(function() {
// Doesnt hurt to zero out filters on change
this.colorFilter = "";
});
}
}
};
</script>
CURL request by default is GET, you don't have to set any options to make a GET CURL request.
I have used MySQL DB for Hive MetaStore. Please follow the below steps:
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:mysql://localhost/metastorecreateDatabaseIfNotExist=true&useSSL=false</value>
</property>
mysql -u hduser -p
drop database metastore
schematool -initSchema dbType mysql
Now error will go.
From another search. Worked for me!
"You can use Visual Studio 2010 and it does support it, provided your OS supports .NET 4.5.
Right click on your solution to add a reference (as you do). When the dialog box shows, select browse, then navigate to the following folder:
C:\Program Files(x86)\Reference Assemblies\Microsoft\Framework\.Net Framework\4.5
You will find it there."
You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Collection.update({
_id: parentDocumentId
}, {
$pull: {
subDocument: {
_id: SubDocumentId
}
}
});
This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.
Read more about pull here.
What worked for me was stopping the Internet Information Services (IIS). If you are using Windows 7, click on your Start button and in your search box, type "iis". Click on "Internet Information Services (IIS) Manager". When the window pops up, and assuming you've got none of the icons selected, you should just be able to click Stop on the right action pane. My XAMPP Apache started right up. Hope it all worked out for you.
I got a very simple but tricky method.
While deleting a row, you can preserve the IDs into another temporary table. After that, when you will insert new data into the main table then you can search and pick IDs from the temporary table. So use a checking here. If the temporary table has no IDs then calculate maximum ID into the main table and set the new ID as: new_ID = old_max_ID+1
.
NB: You can not use auto-increment feature here.
In order to use word-wrap: break-word
, you need to set a width (in px). For example:
div {
width: 250px;
word-wrap: break-word;
}
word-wrap is a CSS3 property, but it should work in all browsers, including IE 5.5-9.
To be able to use std::unordered_map
(or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:
A hash function; this must be a class that overrides operator()
and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash
template for your key-type.
A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator()
, or as a specialization of std::equal
, or – easiest of all – by overloading operator==()
for your key type (as you did already).
The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.
A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
With this in place, you can instantiate a std::unordered_map
for the key-type:
int main()
{
std::unordered_map<Key,std::string> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
It will automatically use std::hash<Key>
as defined above for the hash value calculations, and the operator==
defined as member function of Key
for equality checks.
If you don't want to specialize template inside the std
namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
int main()
{
std::unordered_map<Key,std::string,KeyHasher> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.
This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value
and hash_combine
function template from the Boost library. The former acts in a similar way as std::hash
for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:
#include <boost/functional/hash.hpp>
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
// Modify 'seed' by XORing and bit-shifting in
// one member of 'Key' after the other:
hash_combine(seed,hash_value(k.first));
hash_combine(seed,hash_value(k.second));
hash_combine(seed,hash_value(k.third));
// Return the result.
return seed;
}
};
And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:
namespace std
{
template <>
struct hash<Key>
{
size_t operator()( const Key& k ) const
{
// Compute individual hash values for first, second and third
// http://stackoverflow.com/a/1646913/126995
size_t res = 17;
res = res * 31 + hash<string>()( k.first );
res = res * 31 + hash<string>()( k.second );
res = res * 31 + hash<int>()( k.third );
return res;
}
};
}
I think you're looking for continue
The most basic way to iterate over a hash is as follows:
hash.each do |key, value|
puts key
puts value
end
for me works: TO_DATE('19700101', 'yyyymmdd') + (TIME / 24 / 60 / 60) (oracle DB)
Similar to what has already been said:
public String multStuff(String first, String toAdd, int amount) {
String append = "";
for (int i = 1; i <= amount; i++) {
append += toAdd;
}
return first + append;
}
Input multStuff("123", "0", 3);
Output "123000"
Your best bet is to have a look at strptime()
Something along the lines of
>>> from datetime import datetime
>>> date_str = 'Tue May 08 15:14:45 +0800 2012'
>>> date = datetime.strptime(date_str, '%a %B %d %H:%M:%S +0800 %Y')
>>> date
datetime.datetime(2012, 5, 8, 15, 14, 45)
Im not sure how to do the +0800 timezone unfortunately, maybe someone else can help out with that.
The formatting strings can be found at http://docs.python.org/library/time.html#time.strftime and are the same for formatting the string for printing.
Hope that helps
Mark
PS, Your best bet for timezones in installing pytz from pypi. ( http://pytz.sourceforge.net/ ) in fact I think pytz has a great datetime parsing method if i remember correctly. The standard lib is a little thin on the ground with timezone functionality.
Just for fun, here's a sample with a recursive function which (I hope) should be a bit simpler to understand and to use with your code:
Function Recurse(sPath As String) As String
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim mySubFolder As Folder
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
Call TestSub(mySubFolder.Path)
Recurse = Recurse(mySubFolder.Path)
Next
End Function
Sub TestR()
Call Recurse("D:\Projets\")
End Sub
Sub TestSub(ByVal s As String)
Debug.Print s
End Sub
Edit: Here's how you can implement this code in your workbook to achieve your objective.
Sub TestSub(ByVal s As String)
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim myFile As File
Set myFolder = FSO.GetFolder(s)
For Each myFile In myFolder.Files
If myFile.Name = Range("E1").Value Then
Debug.Print myFile.Name 'Or do whatever you want with the file
End If
Next
End Sub
Here, I just debug the name of the found file, the rest is up to you. ;)
Of course, some would say it's a bit clumsy to call twice the FileSystemObject so you could simply write your code like this (depends on wether you want to compartmentalize or not):
Function Recurse(sPath As String) As String
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim mySubFolder As Folder
Dim myFile As File
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
For Each myFile In mySubFolder.Files
If myFile.Name = Range("E1").Value Then
Debug.Print myFile.Name & " in " & myFile.Path 'Or do whatever you want with the file
Exit For
End If
Next
Recurse = Recurse(mySubFolder.Path)
Next
End Function
Sub TestR()
Call Recurse("D:\Projets\")
End Sub
Since Fedora 22 yum has been deprecated so the commands given in other answers will actually fire up 'Dandified yum' i.e. dnf
. So the new command to install g++ in recent distributions is
su -c "dnf install gcc-c++"
As of Nov 2015 this installs the 5.1.1 version.
Also note that in Fedora 23 when I gave the command g++ -v
, Fedora automatically asked me if I want to install gcc-c++ package. I think thats nice.(After the install it also ran the command g++ -v
for me)
Only nit pick that I can do about it is that instead of a progress indicator you just get * Downloading packages...
message which you may not like if you are on a slow internet connection.
I was facing same issue, used below query to resolve it.
While creating DB you can use utf-8 encoding
eg. create database my_db character set utf8 collate utf8mb4;
EDIT: (Considering suggestions from comments) Changed utf8_bin to utf8mb4
I think that there are situations where the inline if can yield "faster" code because of the scope it works at. Object creation and destruction can be costly so consider the follow scenario :
class A{
public:
A() : value(0) {
cout << "Default ctor" << endl;
}
A(int myInt) : value(myInt)
{
cout << "Overloaded ctor" << endl;
}
A& operator=(const A& other){
cout << "= operator" << endl;
value = other.value;
}
~A(){
cout << "destroyed" << std::endl;
}
int value;
};
int main()
{
{
A a;
if(true){
a = A(5);
}else{
a = A(10);
}
}
cout << "Next test" << endl;
{
A b = true? A(5) : A(10);
}
return 0;
}
With this code, the output will be :
Default ctor
Overloaded ctor
= operator
destroyed
destroyed
Next test
Overloaded ctor
destroyed
So by inlining the if, we save a bunch of operation needed to keep a
alive at the same scope as b
. While it is highly probable that the condition evaluation speed is pretty equal in both scenarios, changing scope forces you to take other factors into consideration that the inline if allows you to avoid.
According to MSDN, e.AddedItems
:
Gets a list that contains the items that were selected.
So you could use:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
}
You could also use SelectedItem
if you use string
values for the Items
from the sender
:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (sender as ComboBox).SelectedItem as string;
}
or
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
}
Since both Content
and SelectedItem
are objects, a safer approach would be to use .ToString()
instead of as string
There is HTML entity ✓ but it doesn't work in some older browsers.
Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!
Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278
Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
Dim rw As Long, ref
With ThisWorkbook.Sheets(1)
.Cells.Clear
rw = 1
.Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
For Each ref In ThisWorkbook.VBProject.References
rw = rw + 1
.Range("A" & rw & ":D" & rw) = Array(ref.Description, _
"v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
Next ref
.Range("A:D").Columns.AutoFit
End With
End Sub
Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.
Sub ListReferencePaths()
'Macro purpose: To determine full path and Globally Unique Identifier (GUID)
'to each referenced library. Select the reference in the Tools\References
'window, then run this code to get the information on the reference's library
On Error Resume Next
Dim i As Long
Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID"
For i = 1 To ThisWorkbook.VBProject.References.Count
With ThisWorkbook.VBProject.References(i)
Debug.Print .Name & " | " & .FullPath & " | " & .GUID
End With
Next i
On Error GoTo 0
End Sub
In addition to Doug Kavendek answer. One could use the following approach to get closer to tz_database.
var shapeFile = new ShapeFile(shapeFilePath); var shapeIndex = shapeFile.GetShapeIndexContainingPoint(new PointD(long, lat), 0D); var attrValues = shapeFile.GetAttributeFieldValues(shapeIndex); var timeZoneId = attrValues[0];
P.S. Can't insert all the links :( So please use search.
You could use "bash" before command:
bash ./gradlew compileDebug --stacktrace
create external table table_name(
Year int,
Month int,
column_name data_type )
row format delimited fields terminated by ','
location '/user/user_name/example_data' TBLPROPERTIES('serialization.null.format'='', 'skip.header.line.count'='1');
Add -ErrorAction SilentlyContinue
to your script and you'll be good to go.
Git will not store the password when you use URLs like that. Instead, it will just store the username, so it only needs to prompt you for the password the next time. As explained in the manual, to store the password, you should use an external credential helper. For Windows, you can use the Windows Credential Store for Git. This helper is also included by default in GitHub for Windows.
When using it, your password will automatically be remembered, so you only need to enter it once. So when you clone, you will be asked for your password, and then every further communication with the remote will not prompt you for your password again. Instead, the credential helper will provide Git with the authentication.
This of course only works for authentication via https; for ssh access ([email protected]/repository.git
) you use SSH keys and those you can remember using ssh-agent
(or PuTTY’s pageant if you’re using plink).
With current latest python 3.6.5
pip3 install PyQt5
works fine
The Mach-O object file format used by Mac OS X for executables and libraries distinguishes between shared libraries and dynamically loaded modules. Use otool -hv some_file
to see the filetype of some_file
.
Mach-O shared libraries have the file type MH_DYLIB
and carry the extension .dylib. They can be linked against with the usual static linker flags, e.g. -lfoo
for libfoo.dylib. They can be created by passing the -dynamiclib
flag to the compiler. (-fPIC
is the default and needn't be specified.)
Loadable modules are called "bundles" in Mach-O speak. They have the file type MH_BUNDLE
. They can carry any extension; the extension .bundle
is recommended by Apple, but most ported software uses .so
for the sake of compatibility. Typically, you'll use bundles for plug-ins that extend an application; in such situations, the bundle will link against the application binary to gain access to the application’s exported API. They can be created by passing the -bundle
flag to the compiler.
Both dylibs and bundles can be dynamically loaded using the dl
APIs (e.g. dlopen
, dlclose
). It is not possible to link against bundles as if they were shared libraries. However, it is possible that a bundle is linked against real shared libraries; those will be loaded automatically when the bundle is loaded.
Historically, the differences were more significant. In Mac OS X 10.0, there was no way to dynamically load libraries. A set of dyld APIs (e.g. NSCreateObjectFileImageFromFile
, NSLinkModule
) were introduced with 10.1 to load and unload bundles, but they didn't work for dylibs. A dlopen
compatibility library that worked with bundles was added in 10.3; in 10.4, dlopen
was rewritten to be a native part of dyld and added support for loading (but not unloading) dylibs. Finally, 10.5 added support for using dlclose
with dylibs and deprecated the dyld APIs.
On ELF systems like Linux, both use the same file format; any piece of shared code can be used as a library and for dynamic loading.
Finally, be aware that in Mac OS X, "bundle" can also refer to directories with a standardized structure that holds executable code and the resources used by that code. There is some conceptual overlap (particularly with "loadable bundles" like plugins, which generally contain executable code in the form of a Mach-O bundle), but they shouldn't be confused with Mach-O bundles discussed above.
Additional references:
call concat
and pass param axis=1
to concatenate column-wise:
In [5]:
pd.concat([df_a,df_b], axis=1)
Out[5]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
There is a useful guide to the various methods of merging, joining and concatenating online.
For example, as you have no clashing columns you can merge
and use the indices as they have the same number of rows:
In [6]:
df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
And for the same reasons as above a simple join
works too:
In [7]:
df_a.join(df_b)
Out[7]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
$('div').css({"-webkit-transform":"translate(100px,100px)"});?
Here is a complete function:
public function get_number_of_days_in_month($month, $year) {
// Using first day of the month, it doesn't really matter
$date = $year."-".$month."-1";
return date("t", strtotime($date));
}
This would output following:
echo get_number_of_days_in_month(2,2014);
Output: 28
Chrome apps including Postman are being deprecated as mentioned here. Now the recommendation is to go for native apps which are not detached from the sandboxed environment of the browser.
Quoting from the feature page:
FEATURES EXCLUSIVE TO THE NATIVE APPS:
COOKIES: The native apps let you work with cookies directly. Unlike the Chrome app, no separate extension (Interceptor) is needed.
BUILT-IN PROXY: The native apps come with a built-in proxy that you can use to capture network traffic.
RESTRICTED HEADERS: The latest version of the native apps let you send headers like Origin and User-Agent. These are restricted in the Chrome app. DON'T FOLLOW
REDIRECTS OPTION: This option exists in the native apps to prevent requests that return a 300-series response from being automatically redirected. Previously, users needed to use the Interceptor extension to do this in the Chrome app.
MENU BAR: The native apps are not restricted by the Chrome standards for the menu bar.
POSTMAN CONSOLE: The latest version of the native apps has a built-in console, which allows you to view the network request details for API calls.
So once you install the native Postman app from here you don't have to go looking for additional prerequisites like interceptor app just to check your cookies. I didn't have to change a single setting after installing the native postman app and all my cookies were visible in Cookies
tab as shown below:
For all those who are facing this issue in windows 10 even after trying the above mentiond steps, this worked for me -
For Windows 10 users trying to debug this same error, launch CMD as administrator (important!) and run dot -c
and then run dot -v
This fixed the issue for me
Using Guava (r07) you can do this:
for(char c : Lists.charactersOf(someString)) { ... }
This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf
returns a view of the string as a List
.
Looks like you are missing the printer name, driver, and port - in that order. Your final command should resemble:
AcroRd32.exe /t <file.pdf> <printer_name> <printer_driver> <printer_port>
For example:
"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" /t "C:\Folder\File.pdf" "Brother MFC-7820N USB Printer" "Brother MFC-7820N USB Printer" "IP_192.168.10.110"
Note: To find the printer information, right click your printer and choose properties. In my case shown above, the printer name and driver name matched - but your information may differ.
You could throw the enum value and string into an STL map. Then you could use it like so.
return myStringMap[Enum::Apple];