Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
var obj2 = JSON.parse(JSON.stringify(obj1));
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
There is a well know relation between time and space complexity.
First of all, time is an obvious bound to space consumption: in time t you cannot reach more than O(t) memory cells. This is usually expressed by the inclusion
DTime(f) ? DSpace(f)
where DTime(f) and DSpace(f) are the set of languages recognizable by a deterministic Turing machine in time (respectively, space) O(f). That is to say that if a problem can be solved in time O(f), then it can also be solved in space O(f).
Less evident is the fact that space provides a bound to time. Suppose that, on an input of size n, you have at your disposal f(n) memory cells, comprising registers, caches and everything. After having written these cells in all possible ways you may eventually stop your computation, since otherwise you would reenter a configuration you already went through, starting to loop. Now, on a binary alphabet, f(n) cells can be written in 2^f(n) different ways, that gives our time upper bound: either the computation will stop within this bound, or you may force termination, since the computation will never stop.
This is usually expressed in the inclusion
DSpace(f) ? Dtime(2^(cf))
for some constant c. the reason of the constant c is that if L is in DSpace(f) you only know that it will be recognized in Space O(f), while in the previous reasoning, f was an actual bound.
The above relations are subsumed by stronger versions, involving nondeterministic models of computation, that is the way they are frequently stated in textbooks (see e.g. Theorem 7.4 in Computational Complexity by Papadimitriou).
For me the error came after changing my password for my AD account.
I had to remove the line from credential manager (which contained the previous password.)
Then it worked again.
You can't according to the PHP manual:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.
But you can work around it by also setting $_COOKIE
when you call setcookie()
:
if(!isset($_COOKIE['lg'])) {
setcookie('lg', 'ro');
$_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
To split the difference of opinion
I prefer:
xls.DisplayAlerts = False
wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
xls.DisplayAlerts = True
Based on the answers and comments here, a naming convention which includes the FK table, FK field, and PK table (FK_FKTbl_FKCol_PKTbl) should avoid FK constraint name collisions.
So, for the given tables here:
fk_task_userid_user
fk_note_userid_user
So, if you add a column to track who last modified a task or a note...
fk_task_modifiedby_user
fk_note_modifiedby_user
That's not possible with CSS, you will have to use the Javascript for that. Although you can set the width of the p to as much as 30 characters and next letters will automatically come down but again this won't be that accurate and will vary if the characters are in capital.
If multiple clock are generated with different frequencies, then clock generation can be simplified if a procedure is called as concurrent procedure call. The time resolution issue, mentioned by Martin Thompson, may be mitigated a little by using different high and low time in the procedure. The test bench with procedure for clock generation is:
library ieee;
use ieee.std_logic_1164.all;
entity tb is
end entity;
architecture sim of tb is
-- Procedure for clock generation
procedure clk_gen(signal clk : out std_logic; constant FREQ : real) is
constant PERIOD : time := 1 sec / FREQ; -- Full period
constant HIGH_TIME : time := PERIOD / 2; -- High time
constant LOW_TIME : time := PERIOD - HIGH_TIME; -- Low time; always >= HIGH_TIME
begin
-- Check the arguments
assert (HIGH_TIME /= 0 fs) report "clk_plain: High time is zero; time resolution to large for frequency" severity FAILURE;
-- Generate a clock cycle
loop
clk <= '1';
wait for HIGH_TIME;
clk <= '0';
wait for LOW_TIME;
end loop;
end procedure;
-- Clock frequency and signal
signal clk_166 : std_logic;
signal clk_125 : std_logic;
begin
-- Clock generation with concurrent procedure call
clk_gen(clk_166, 166.667E6); -- 166.667 MHz clock
clk_gen(clk_125, 125.000E6); -- 125.000 MHz clock
-- Time resolution show
assert FALSE report "Time resolution: " & time'image(time'succ(0 fs)) severity NOTE;
end architecture;
The time resolution is printed on the terminal for information, using the concurrent assert last in the test bench.
If the clk_gen
procedure is placed in a separate package, then reuse from test bench to test bench becomes straight forward.
Waveform for clocks are shown in figure below.
An more advanced clock generator can also be created in the procedure, which can adjust the period over time to match the requested frequency despite the limitation by time resolution. This is shown here:
-- Advanced procedure for clock generation, with period adjust to match frequency over time, and run control by signal
procedure clk_gen(signal clk : out std_logic; constant FREQ : real; PHASE : time := 0 fs; signal run : std_logic) is
constant HIGH_TIME : time := 0.5 sec / FREQ; -- High time as fixed value
variable low_time_v : time; -- Low time calculated per cycle; always >= HIGH_TIME
variable cycles_v : real := 0.0; -- Number of cycles
variable freq_time_v : time := 0 fs; -- Time used for generation of cycles
begin
-- Check the arguments
assert (HIGH_TIME /= 0 fs) report "clk_gen: High time is zero; time resolution to large for frequency" severity FAILURE;
-- Initial phase shift
clk <= '0';
wait for PHASE;
-- Generate cycles
loop
-- Only high pulse if run is '1' or 'H'
if (run = '1') or (run = 'H') then
clk <= run;
end if;
wait for HIGH_TIME;
-- Low part of cycle
clk <= '0';
low_time_v := 1 sec * ((cycles_v + 1.0) / FREQ) - freq_time_v - HIGH_TIME; -- + 1.0 for cycle after current
wait for low_time_v;
-- Cycle counter and time passed update
cycles_v := cycles_v + 1.0;
freq_time_v := freq_time_v + HIGH_TIME + low_time_v;
end loop;
end procedure;
Again reuse through a package will be nice.
check if a key is pressed, if yes, then do stuff
Consider 'select()', if this (reportedly Posix) function is available on your os.
'select()' uses 3 sets of bits, which you create using functions provided (see man select, FD_SET, etc). You probably only need create the input bits (for now)
from man page:
'select()' "allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2) without blocking...)"
When select is invoked:
a) the function looks at each fd identified in the sets, and if that fd state indicates you can do something (perhaps read, perhaps write), select will return and let you go do that ... 'all you got to do' is scan the bits, find the set bit, and take action on the fd associated with that bit.
The 1st set (passed into select) contains active input fd's (typically devices). Probably 1 bit in this set is all you will need. And with only 1 fd (i.e. an input from keyboard), 1 bit, this is all quite simple. With this return from select, you can 'do-stuff' (perhaps, after you have fetched the char).
b) the function also has a timeout, with which you identify how much time to await a change of the fd state. If the fd state does not change, the timeout will cause 'select()' to return with a 0. (i.e. no keyboard input) Your code can do something at this time, too, perhaps an output.
fyi - fd's are typically 0,1,2... Remembe that C uses 0 as STDIN, 1 and STDOUT.
Simple test set up: I open a terminal (separate from my console), and type the tty command in that terminal to find its id. The response is typically something like "/dev/pts/0", or 3, or 17...
Then I get an fd to use in 'select()' by using open:
// flag options are: O_RDONLY, O_WRONLY, or O_RDWR
int inFD = open( "/dev/pts/5", O_RDONLY );
It is useful to cout this value.
Here is a snippet to consider (from man select):
fd_set rfds;
struct timeval tv;
int retval;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval)
printf("Data is available now.\n"); // i.e. doStuff()
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n"); // i.e. key not pressed
One way I like to use is Vanilla JavaScript with template literal:
var templateLiteral = [`
<!-- HTML_CODE_COMES_HERE -->
`]
var head = document.querySelector("head");
head.innerHTML = templateLiteral;
Use the 'EntireColumn' property, that's what it is there for. C# snippet, but should give you a good indication of how to do this:
string rangeQuery = "A1:A1";
Range range = workSheet.get_Range(rangeQuery, Type.Missing);
range = range.EntireColumn;
In 2020 you can listen state changes with useEffect hook like this
export function MyComponent(props) {
const [myState, setMystate] = useState('initialState')
useEffect(() => {
console.log(myState, '- Has changed')
},[myState]) // <-- here put the parameter to listen
}
DataTable DT = new DataTable();
DT.Columns.Add("first", typeof(string));
DT.Columns.Add("second", typeof(string));
DT.Rows.Add("ss", "test1");
DT.Rows.Add("sss", "test2");
DT.Rows.Add("sys", "test3");
DT.Rows.Add("ss", "test4");
DT.Rows.Add("ss", "test5");
DT.Rows.Add("sts", "test6");
var dr = DT.AsEnumerable().GroupBy(S => S.Field<string>("first")).Select(S => S.First()).
Select(S => new KeyValuePair<string, string>(S.Field<string>("first"), S.Field<string>("second"))).
ToDictionary(S => S.Key, T => T.Value);
foreach (var item in dr)
{
Console.WriteLine(item.Key + "-" + item.Value);
}
Bootstrap styling for jQuery UI Autocomplete
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
padding: 4px 0;
margin: 0 0 10px 25px;
list-style: none;
background-color: #ffffff;
border-color: #ccc;
border-color: rgba(0, 0, 0, 0.2);
border-style: solid;
border-width: 1px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
*border-right-width: 2px;
*border-bottom-width: 2px;
}
.ui-menu-item > a.ui-corner-all {
display: block;
padding: 3px 15px;
clear: both;
font-weight: normal;
line-height: 18px;
color: #555555;
white-space: nowrap;
text-decoration: none;
}
.ui-state-hover, .ui-state-active {
color: #ffffff;
text-decoration: none;
background-color: #0088cc;
border-radius: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
background-image: none;
}
I tried about first 5 solutions and different variations of them, but they didn't work for me.
Finally I got it working with these two functions.
$(document).on('click', '.nav-link', function () {
$(".nav-item").find(".active").removeClass("active");
})
$(document).ready(function() {
$('a[href="' + location.pathname + '"]').closest('.nav-item').addClass('active');
});
The answer is given but think that for some situation this will be also interesting way to get string from NSInteger
NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];
Take one example - you have a table with huge data per row. That means every instance of the object is Big.
If you use B tree here then most of the time is spent scanning the pages with data - which is of no use. In databases that is the reason of using B+ Trees to avoid scanning object data.
B+ Trees separate keys from data.
But if your data size is less then you can store them with key which is what B tree does.
That character is the BOM or "Byte Order Mark". It is usually received as the first few bytes of a file, telling you how to interpret the encoding of the rest of the data. You can simply remove the character to continue. Although, since the error says you were trying to convert to 'ascii', you should probably pick another encoding for whatever you were trying to do.
I don't like the accepted answer or @fivetwentysix's comment regarding how to solve this. It gets at one method for doing this, but doesn't give the full solution to using toArray. You need to use toArray and give it an argument that's an array of the correct type and size so that you don't end up with an Object array. While an object array will work, I don't think it's best practice in a strongly typed language.
String[] array = arrayList.toArray(new String[arrayList.size()]);
JComboBox comboBox = new JComboBox(array);
Alternatively, you can also maintain strong typing by just using a for loop.
String[] array = new String[arrayList.size()];
for(int i = 0; i < array.length; i++) {
array[i] = arrayList.get(i);
}
JComboBox comboBox = new JComboBox(array);
This works great when you want to load a series from a csv file
x = pd.read_csv('x.csv', index_col=False, names=['x'],header=None).iloc[:,0]
print(type(x))
print(x.head(10))
<class 'pandas.core.series.Series'>
0 110.96
1 119.40
2 135.89
3 152.32
4 192.91
5 177.20
6 181.16
7 177.30
8 200.13
9 235.41
Name: x, dtype: float64
On spring boot 2 with webflux you need to define a ReactiveAuthenticationManager
I would like to make a addon for tiago's answer:
Suppose you're hiding element using ng-show
and adding a required
attribute on the same:
<div ng-show="false">
<input required name="something" ng-model="name"/>
</div>
will throw an error something like :
An invalid form control with name='' is not focusable
This is because you just cannot impose required
validation on hidden
elements. Using ng-required
makes it easier to conditionally apply required validation which is just awesome!!
string.Concat(los.ToArray());
If you just want to concatenate the strings then use string.Concat() instead of string.Join().
If using ActiveAdmin don't forget that there is also a permit_params in the model register block:
ActiveAdmin.register Api::V1::Person do
permit_params :name, :address, :etc
end
These need to be set along with those in the controller:
def api_v1_person_params
params.require(:api_v1_person).permit(:name, :address, :etc)
end
Otherwise you will get the error:
ActiveModel::ForbiddenAttributesError
Just got a solution to get height and width of a custom view:
@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
super.onSizeChanged(xNew, yNew, xOld, yOld);
viewWidth = xNew;
viewHeight = yNew;
}
Its working in my case.
It's just a method on your form, you can call it just like any other method. You just have to create an EventArgs object to pass to it, (and pass it the handle of the button as sender
)
select CONVERT(char(10), GetDate(),126)
I don't think there is any easy way to get only HTTP headers. You have to iterate through request.META dict to get what all you need.
django-debug-toolbar takes the same approach to show header information. Have a look at this file responsible for retrieving header information.
Two possible approaches:
I don't think popen()
is part of the C++ standard (it's part of POSIX from memory), but it's available on every UNIX I've worked with (and you seem to be targeting UNIX since your command is ./some_command
).
On the off-chance that there is no popen()
, you can use system("./some_command >/tmp/some_command.out");
, then use the normal I/O functions to process the output file.
Persist should be called only on new entities, while merge
is meant to reattach detached entities.
If you're using the assigned generator, using merge
instead of persist
can cause a redundant SQL statement.
Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.
datetime.timezone.utc
:The standard library makes it much easier to specify UTC as the time zone:
>>> import datetime
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2020, 11, 27, 14, 34, 34, 74823, tzinfo=datetime.timezone.utc)
You can also get a datetime that includes the local time offset using astimezone
:
>>> datetime.datetime.now(datetime.timezone.utc).astimezone()
datetime.datetime(2020, 11, 27, 15, 34, 34, 74823, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))
(In Python 3.6+, you can shorten the last line to: datetime.datetime.now().astimezone()
)
If you want a solution that uses only the standard library and that works in both Python 2 and Python 3, see jfs' answer.
zoneinfo
to use the IANA time zone database:In Python 3.9, you can specify particular time zones using the standard library, using zoneinfo
, like this:
>>> from zoneinfo import ZoneInfo
>>> datetime.datetime.now(ZoneInfo("America/Los_Angeles"))
datetime.datetime(2020, 11, 27, 6, 34, 34, 74823, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles'))
zoneinfo
gets its database of time zones from the operating system, or from the first-party PyPI package tzdata
if available.
You must change the cmake C/CXX default FLAGS .
According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE}
put in the main CMakeLists.txt
one of :
For C
set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")
For C++
set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")
This will override the values defined in CMakeCache.txt
I have made it from fastboot mode (Phone - Xiomi Mi5 Android 6.0.1)
Here is steps:
# check if device available
fastboot devices
# remove user data
fastboot erase userdata
# remove cache
fastboot erase cache
# reboot device
fastboot reboot
Without calculating height. Strict CSS and HTML. <span/>
only for Chrome, because the chrome isn't able change text direction for <th/>
.
th _x000D_
{_x000D_
vertical-align: bottom;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
th span _x000D_
{_x000D_
-ms-writing-mode: tb-rl;_x000D_
-webkit-writing-mode: vertical-rl;_x000D_
writing-mode: vertical-rl;_x000D_
transform: rotate(180deg);_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<th><span>Rotated text by 90 deg.</span></th>_x000D_
</tr>_x000D_
</table>
_x000D_
You can use pageX
and pageY
to get the position of the mouse in the window. You can also use jQuery's offset
to get the position of an element.
So, it should be pageX - offset.left
for how far from the left of the image and pageY - offset.top
for how far from the top of the image.
Here is an example:
$(document).ready(function() {
$('img').click(function(e) {
var offset = $(this).offset();
alert(e.pageX - offset.left);
alert(e.pageY - offset.top);
});
});
I've made a live example here and here is the source.
To calculate how far from the bottom or right, you would have to use jQuery's width
and height
methods.
Use git rebase
. Specifically:
git stash
to store the changes you want to add.git rebase -i HEAD~10
(or however many commits back you want to see).a0865...
) for edit by changing the word pick
at the start of the line into edit
. Don't delete the other lines as that would delete the commits.[^vimnote]git stash pop
git add <file>
.git commit --amend --no-edit
.git rebase --continue
which will rewrite the rest of your commits against the new one.[^vimnote]: If you are using vim
then you will have to hit the Insert key to edit, then Esc and type in :wq
to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano"
.
Basename wild cards were introduced in Java 6; i.e. "foo/*" means all ".jar" files in the "foo" directory.
In earlier versions of Java that do not support wildcard classpaths, I have resorted to using a shell wrapper script to assemble a Classpath by 'globbing' a pattern and mangling the results to insert ':' characters at the appropriate points. This would be hard to do in a BAT file ...
This might be useful for someone else: Using this sample html
<div class="ParentDiv">
<label for="label">labelName</label>
<input type="button" value="elementToSelect">
</div>
<div class="DontSelect">
<label for="animal">pig</label>
<input type="button" value="elementToSelect">
</div>
If for example, I want to select an element in the same section (e.g div) as a label, you can use this
//label[contains(., 'labelName')]/parent::*//input[@value='elementToSelect']
This just means, look for a label (it could anything like a
, h2
) called labelName
. Navigate to the parent of that label (i.e. div class="ParentDiv"
). Search within the descendants of that parent to find any child element with the value of elementToSelect
. With this, it will not select the second elementToSelect
with DontSelect
div as parent.
The trick is that you can reduce search areas for an element by navigating to the parent first and then searching descendant of that parent for the element you need.
Other Syntax like following-sibling::h2
can also be used in some cases. This means the sibling following element h2
. This will work for elements at the same level, having the same parent.
You can also reference the obj
once you are inside the function instead of this
.
var obj = {
key1: "it",
key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1')
change day/month position.
Go to File > Settings > Appearance & Behavior > Appearance > Show tool window bars
You need to declare @font-face
like this in your stylesheet
@font-face {
font-family: 'Awesome-Font';
font-style: normal;
font-weight: 400;
src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}
Now if you want to apply this font to a paragraph simply use it like this..
p {
font-family: 'Awesome-Font', Arial;
}
This answer is based on this excellent answer by 18446744073709551615. Their solution, though helpful, does not size the image icon with the surrounding text. It also doesn't set the icon colour to that of the surrounding text.
The solution below takes a white, square icon and makes it fit the size and colour of the surrounding text.
public class TextViewWithImages extends TextView {
private static final String DRAWABLE = "drawable";
/**
* Regex pattern that looks for embedded images of the format: [img src=imageName/]
*/
public static final String PATTERN = "\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E";
public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TextViewWithImages(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewWithImages(Context context) {
super(context);
}
@Override
public void setText(CharSequence text, BufferType type) {
final Spannable spannable = getTextWithImages(getContext(), text, getLineHeight(), getCurrentTextColor());
super.setText(spannable, BufferType.SPANNABLE);
}
private static Spannable getTextWithImages(Context context, CharSequence text, int lineHeight, int colour) {
final Spannable spannable = Spannable.Factory.getInstance().newSpannable(text);
addImages(context, spannable, lineHeight, colour);
return spannable;
}
private static boolean addImages(Context context, Spannable spannable, int lineHeight, int colour) {
final Pattern refImg = Pattern.compile(PATTERN);
boolean hasChanges = false;
final Matcher matcher = refImg.matcher(spannable);
while (matcher.find()) {
boolean set = true;
for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
if (spannable.getSpanStart(span) >= matcher.start()
&& spannable.getSpanEnd(span) <= matcher.end()) {
spannable.removeSpan(span);
} else {
set = false;
break;
}
}
final String resName = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
final int id = context.getResources().getIdentifier(resName, DRAWABLE, context.getPackageName());
if (set) {
hasChanges = true;
spannable.setSpan(makeImageSpan(context, id, lineHeight, colour),
matcher.start(),
matcher.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
}
return hasChanges;
}
/**
* Create an ImageSpan for the given icon drawable. This also sets the image size and colour.
* Works best with a white, square icon because of the colouring and resizing.
*
* @param context The Android Context.
* @param drawableResId A drawable resource Id.
* @param size The desired size (i.e. width and height) of the image icon in pixels.
* Use the lineHeight of the TextView to make the image inline with the
* surrounding text.
* @param colour The colour (careful: NOT a resource Id) to apply to the image.
* @return An ImageSpan, aligned with the bottom of the text.
*/
private static ImageSpan makeImageSpan(Context context, int drawableResId, int size, int colour) {
final Drawable drawable = context.getResources().getDrawable(drawableResId);
drawable.mutate();
drawable.setColorFilter(colour, PorterDuff.Mode.MULTIPLY);
drawable.setBounds(0, 0, size, size);
return new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
}
}
How to use:
Simply embed references to the desired icons in the text. It doesn't matter whether the text is set programatically through textView.setText(R.string.string_resource);
or if it's set in xml.
To embed a drawable icon named example.png, include the following string in the text: [img src=example/]
.
For example, a string resource might look like this:
<string name="string_resource">This [img src=example/] is an icon.</string>
The SettingWithCopyWarning
was created to flag potentially confusing "chained" assignments, such as the following, which does not always work as expected, particularly when the first selection returns a copy. [see GH5390 and GH5597 for background discussion.]
df[df['A'] > 2]['B'] = new_val # new_val not set in df
The warning offers a suggestion to rewrite as follows:
df.loc[df['A'] > 2, 'B'] = new_val
However, this doesn't fit your usage, which is equivalent to:
df = df[df['A'] > 2]
df['B'] = new_val
While it's clear that you don't care about writes making it back to the original frame (since you are overwriting the reference to it), unfortunately this pattern cannot be differentiated from the first chained assignment example. Hence the (false positive) warning. The potential for false positives is addressed in the docs on indexing, if you'd like to read further. You can safely disable this new warning with the following assignment.
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
Here's an example from AndroidManifest.xml. You need to specify the MAIN and LAUNCHER in the intent filter for the activity you want to start on launch
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="ExampleActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I used the plugin Smooth Scroll, at http://plugins.jquery.com/smooth-scroll/. With this plugin all you need to include is a link to jQuery and to the plugin code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/smoothscroll.js"></script>
(the links need to have the class smoothScroll
to work).
Another feature of Smooth Scroll is that the ancor name is not displayed in the URL!
PHP parser errors take some getting used to; if it complains about an unexpected 'something' at line X, look at line X-1 first. In this case it will not tell you that you forgot a semi-colon at the end of the previous line , instead it will complain about the if
that comes next.
You'll get used to it :)
Here is a more complete looking jquery 1.11.x $.ajax() usage:
<script type="text/javascript">
function uploadProgressHandler(event) {
$("#loaded_n_total").html("Uploaded " + event.loaded + " bytes of " + event.total);
var percent = (event.loaded / event.total) * 100;
var progress = Math.round(percent);
$("#uploadProgressBar").html(progress + " percent na ang progress");
$("#uploadProgressBar").css("width", progress + "%");
$("#status").html(progress + "% uploaded... please wait");
}
function loadHandler(event) {
$("#status").html(event.target.responseText);
$("#uploadProgressBar").css("width", "0%");
}
function errorHandler(event) {
$("#status").html("Upload Failed");
}
function abortHandler(event) {
$("#status").html("Upload Aborted");
}
$("#uploadFile").click(function (event) {
event.preventDefault();
var file = $("#fileUpload")[0].files[0];
var formData = new FormData();
formData.append("file1", file);
$.ajax({
url: 'http://testarea.local/UploadWithProgressBar1/file_upload_parser.php',
method: 'POST',
type: 'POST',
data: formData,
contentType: false,
processData: false,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress",
uploadProgressHandler,
false
);
xhr.addEventListener("load", loadHandler, false);
xhr.addEventListener("error", errorHandler, false);
xhr.addEventListener("abort", abortHandler, false);
return xhr;
}
});
});
</script>
$timestamp='2014-11-21 16:38:00';
list($date,$time)=explode(' ',$timestamp);
// just time
preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];
Always use either String.valueOf(number)
or Integer.toString(number)
.
Using "" + number is an overhead and does the following:
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(number);
return sb.toString();
The design guidelines defines two sizes and unless there is a strong reason to deviate from using either, the size can be controlled with the fabSize
XML attribute of the FloatingActionButton
component.
Consider specifying using either app:fabSize="normal"
or app:fabSize="mini"
, e.g.:
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_done_white_24px"
app:fabSize="mini" />
my .bash_profile function, it may be of any use
logcat() {
if [ -z "$1" ]
then
echo "Process Id argument missing."; return
fi
pidFilter="\b$1\b"
pid=$(adb shell ps | egrep $pidFilter | cut -c10-15)
if [ -z "$pid" ]
then
echo "Process $1 is not running."; return
fi
adb logcat | grep $pid
}
alias logcat-myapp="logcat com.sample.myapp"
Usage:
$ logcat-myapp
$ logcat com.android.something.app
SELECT * from table_name where date_field = DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY);
The error message “Primary script unknown or in your case is file not found.” is almost always related to a wrongly set in line SCRIPT_FILENAME in the Nginx fastcgi_param directive (Quote from https://serverfault.com/a/517327/560171).
In my case, I use Nginx 1.17.10 and my configuration is:
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_read_timeout 600;
}
You just change $document_root to $realpath_root, so whatever your root location, like /var/www/html/project/
, you don't need write fastcgi_param SCRIPT_FILENAME /var/www/html/project$fastcgi_script_name;
each time your root is changes. This configuration is more flexible. May this helps.
=================================================================================
For more information, if you got unix:/run/php/php7.2-fpm.sock failed (13: Permission denied) while connecting to upstream
, just change in /etc/nginx/nginx.conf
, from user nginx;
to user www-data;
.
Because the default user and group of PHP-FPM process is www-data as can be seen in /etc/php/7.2/fpm/pool.d/www.conf
file (Qoute from https://www.linuxbabe.com/ubuntu/install-nginx-latest-version-ubuntu-18-04):
user = www-data
group = www-data
May this information gives a big help
void Fillcombobox()
{
con.Open();
cmd = new SqlCommand("select ID From Employees",con);
Sdr = cmd.ExecuteReader();
while (Sdr.Read())
{
for (int i = 0; i < Sdr.FieldCount; i++)
{
comboID.Items.Add( Sdr.GetString(i));
}
}
Sdr.Close();
con.Close();
}
In the forms you listed here, there's not much difference between the two. CompareTo
ends up calling a CompareInfo
method that does a comparison using the current culture; Equals
is called by the ==
operator.
If you consider overloads, then things get different. Compare
and ==
can only use the current culture to compare a string. Equals
and String.Compare
can take a StringComparison
enumeration argument that let you specify culture-insensitive or case-insensitive comparisons. Only String.Compare
allows you to specify a CultureInfo
and perform comparisons using a culture other than the default culture.
Because of its versatility, I find I use String.Compare
more than any other comparison method; it lets me specify exactly what I want.
One clarification (and a point that confused me):
"remotes/origin/HEAD is the default branch" is not really correct.
remotes/origin/master was the default branch in the remote repository (last time you checked). HEAD is not a branch, it just points to a branch.
Think of HEAD as your working area. When you think of it this way then 'git checkout branchname' makes sense with respect to changing your working area files to be that of a particular branch. You "checkout" branch files into your working area. HEAD for all practical purposes is what is visible to you in your working area.
You can use the Linux based syntax in one of your startup scripts. Just tested this on an OS X Mountain Lion box.
eg. in your ~/.bash_profile
export TERM="xterm-color"
export PS1='\[\e[0;33m\]\u\[\e[0m\]@\[\e[0;32m\]\h\[\e[0m\]:\[\e[0;34m\]\w\[\e[0m\]\$ '
This gives you a nice colored prompt. To add the colored ls
output, you can add alias ls="ls -G"
.
To test, just run a source ~/.bash_profile
to update your current terminal.
Side note about the colors:
The colors are preceded by an escape sequence \e
and defined by a color value, composed of [style;color+m]
and wrapped in an escaped []
sequence.
eg.
\[\e[0;31m\]
\[\e[1;31m\]
\[\e[0m\]
I always add a slightly modified color-scheme in the root's .bash_profile to make the username red, so I always see clearly if I'm logged in as root (handy to avoid mistakes if I have many terminal windows open).
In /root/.bash_profile
:
PS1='\[\e[0;31m\]\u\[\e[0m\]@\[\e[0;32m\]\h\[\e[0m\]:\[\e[0;34m\]\w\[\e[0m\]\$ '
For all my SSH accounts online I make sure to put the hostname in red, to distinguish if I'm in a local or remote terminal. Just edit the .bash_profile
file in your home dir on the server.. If there is no .bash_profile
file on the server, you can create it and it should be sourced upon login.
If this is not working as expected for you, please read some of the comments below since I'm not using MacOS very often..
If you want to do this on a remote server, check if the ~/.bash_profile
file exists. If not, simply create it and it should be automatically sourced upon your next login.
I have finally found exactly what I have been looking for, i.e. a dark theme for PyDev (although I still feel like Eclipse is missing out on this).
Yes, a table row can slide up and down, but it's ugly, since it changes the shape of the table and makes everything jump. Instead, put and element in each td
... something that makes sense like a p
or h2
etc.
For how to implement a table slide toggle...
It's probably simplest to put the click handler on the entire table, .stopPropagation()
and check what was clicked.
If a td in a row with a colspan is clicked, close the p
in it. If it's not a td in a row with a colspan, then close then toggle the following row's p
.
It is essentially to wrap all your written content in an element inside the td
s, since you never want to slideUp
a td
or tr
or table shape will change!
Something like:
$(function() {
// Initially hide toggleable content
$("td[colspan=3]").find("p").hide();
// Click handler on entire table
$("table").click(function(event) {
// No bubbling up
event.stopPropagation();
var $target = $(event.target);
// Open and close the appropriate thing
if ( $target.closest("td").attr("colspan") > 1 ) {
$target.slideUp();
} else {
$target.closest("tr").next().find("p").slideToggle();
}
});
});?
... and try out this jsFiddle showing implementation of a +
- -
toggle.
The HTML just has to have alternating rows of several td
s and then a row with a td
of a colspan greater than 1. You can obviously adjust the specifics quite easily.
The HTML would look something like:
<table>
<tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
<tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
</td></tr>
<tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
<tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
</td></tr>
<tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
<tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
</td></tr>
</table>?
And yet another approach using the decorator pattern and PHPs magic getter & setters:
// A simple StdClass object
$stdclass = new StdClass();
$stdclass->foo = 'bar';
// Decorator base class to inherit from
class Decorator {
protected $object = NULL;
public function __construct($object)
{
$this->object = $object;
}
public function __get($property_name)
{
return $this->object->$property_name;
}
public function __set($property_name, $value)
{
$this->object->$property_name = $value;
}
}
class MyClass extends Decorator {}
$myclass = new MyClass($stdclass)
// Use the decorated object in any type-hinted function/method
function test(MyClass $object) {
echo $object->foo . '<br>';
$object->foo = 'baz';
echo $object->foo;
}
test($myclass);
You could wrap the not-bold text into a span and give the span the following properties:
.notbold{
font-weight:normal
}?
and
<h1>**This text should be bold**, <span class='notbold'>but this text should not</span></h1>
See: http://jsfiddle.net/MRcpa/1/
Use <span>
when you want to change the style of elements without placing them in a new block-level element in the document.
For those who have their wordpress root folder under their home folder:
** Ubuntu/apache
CREDIT Granting write permissions to www-data group
You want to call usermod
on your user. So that would be:
sudo usermod -aG www-data yourUserName
** Assuming www-data
group exists
Check your user is in www-data
group:
groups yourUserName
You should get something like:
youUserName : youUserGroupName www-data
** youUserGroupName is usually similar to you user name
Recursively change group ownership of the wp-content folder keeping your user ownership
chown yourUserName:www-data -R youWebSiteFolder/wp-content/*
Change directory to youWebSiteFolder/wp-content/
cd youWebSiteFolder/wp-content
Recursively change group permissions of the folders and sub-folders to enable write permissions:
find . -type d -exec chmod -R 775 {} \;
** mode of `/home/yourUserName/youWebSiteFolder/wp-content/' changed from 0755 (rwxr-xr-x) to 0775 (rwxrwxr-x)
Recursively change group permissions of the files and sub-files to enable write permissions:
find . -type f -exec chmod -R 664 {} \;
The result should look something like:
WAS:
-rw-r--r-- 1 yourUserName www-data 7192 Oct 4 00:03 filename.html
CHANGED TO:
-rw-rw-r-- 1 yourUserName www-data 7192 Oct 4 00:03 filename.html
Equivalent to:
chmod -R ug+rw foldername
Permissions will be like 664 for files or 775 for directories.
P.s. if anyone encounters error 'could not create directory'
when updating a plugin, do:
server@user:~/domainame.com$ sudo chown username:www-data -R wp-content
when you are at the root of your domain.
Assuming: wp-config.php
has
FTP credentials on LocalHost
define('FS_METHOD','direct');
You use ttk.Frame
, bg
option does not work for it. You should create style and apply it to the frame.
from tkinter import *
from tkinter.ttk import *
root = Tk()
s = Style()
s.configure('My.TFrame', background='red')
mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()
There's no easy solution. Each way has their pros and cons . But the canonical way is using the first option: multipart/form-data
. As W3 recommendation guide says
The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
We aren't sending forms,really, but the implicit principle still applies. Using base64 as a binary representation, is incorrect because you're using the incorrect tool for accomplish your goal, in other hand, the second option forces your API clients to do more job in order to consume your API service. You should do the hard work in the server side in order to supply an easy-to-consume API. The first option is not easy to debug, but when you do it, it probably never changes.
Using multipart/form-data
you're sticked with the REST/http philosophy. You can view an answer to similar question here.
Another option if mixing the alternatives, you can use multipart/form-data but instead of send every value separate, you can send a value named payload with the json payload inside it. (I tried this approach using ASP.NET WebAPI 2 and works fine).
You could have multiple Python versions on your macOS.
You may check that by command
, type
or which
command, like:
which -a python python2 python2.7 python3 python3.6
Or type python
in Terminal and hit Tab few times for auto completion, which is equivalent to:
compgen -c python
By default python
/pip
commands points to the first binary found in PATH
environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin
which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local
(such as /usr/local/bin
) are provided by external packages.
It is generally advised, that when working with multiple versions, for Python 2 you may use python2
/pip2
command, respectively for Python 3 you can use python3
/pip3
, but it depends on your configuration which commands are available.
It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python
formula has been upgraded to Python 3.x and a python@2
formula will be added for installing Python 2.7. Before, python
formula was pointing to Python 2.
For instance, if you've installed different version via Homebrew, try the following command:
brew list python python3
or:
brew list | grep ^python
it'll show you all Python files installed with the package.
Alternatively you may use apropos
or locate python
command to locate more Python related files.
To check any environment variables related to Python, run:
env | grep ^PYTHON
To address your issues:
Error: No such keg: /usr/local/Cellar/python
Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3
).
The locate database (
/var/db/locate.database
) does not exist.
Follow the advice and run:
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
After the database is rebuild, you can use locate
command.
in Xcode 8 use:
DispatchQueue.global(qos: .userInitiated).async { }
You shouldn't have to set height: 100%
at any point if you want your container to fill the page. Chances are, your problem is rooted in the fact that you haven't cleared the floats in the container's children. There are quite a few ways to solve this problem, mainly adding overflow: hidden
to the container.
#container { overflow: hidden; }
Should be enough to solve whatever height problem you're having.
I always have to check my cheatsheet :-)
Step 1: right-click on the top of putty window and select 'Change settings'.
Step 2: type the name of the session and save.
That's it!. Enjoy!
Sorry to dig an old grave here, but why not just do this?
<div class="form-group">
</div>
It will add a space the height of a normal form element.
It seems about 1 line on a form is roughly 50px (47px on my element I just inspected). This is a horizontal form, with label on left 2col and input on right 10col. So your pixels may vary.
Since mine is basically 50px, I would create a spacer of 50px tall with no margins or padding;
.spacer { margin:0; padding:0; height:50px; }
<div class="spacer"></div>
JObject
implements IDictionary<string, JToken>
, so you can use:
IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))
... or you could use TryGetValue
. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken>
though.
Use
git cherry-pick <commit-hash>
So this will pick your behind commit to git location you are on.
This works for modifying childkey value using JSONObject
.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
create an array of ones; multiply each list times the array; convert array to a list
import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
c = (np.ones(len(a))*a*b).tolist()
[2.0, 6.0, 12.0, 20.0]
The result set of a query in PHP offers a couple of functions allowing just that:
numCols()
columnName(int $column_number )
Example
$db = new SQLIte3('mysqlite.db');
$table = 'mytable';
$tableCol = getColName($db, $table);
for ($i=0; $i<count($tableCol); $i++){
echo "Column $i = ".$tableCol[$i]."\n";
}
function getColName($db, $table){
$qry = "SELECT * FROM $table LIMIT 1";
$result = $db->query($qry);
$nCols = $result->numCols();
for ($i = 0; $i < $ncols; $i++) {
$colName[$i] = $result->columnName($i);
}
return $colName;
}
It is worth noting that the accepted answer will round small floats down to zero.
>>> import numpy as np
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03 4.82011728e-08 1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0. , 0. , 0. ])
You can use set_printoptions
and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:
>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]
This way, you get the full versatility of format
and maintain the full precision of numpy's datatypes.
Also note that this only affects printing, not the actual precision of the stored values used for computation.
MailSystem.NET contains all your need for IMAP4. It's free & open source.
(I'm involved in the project)
The best and simplest way to read a line from a console is using the getchar() function, whereby you will store one character at a time in an array.
{
char message[N]; /* character array for the message, you can always change the character length */
int i = 0; /* loop counter */
printf( "Enter a message: " );
message[i] = getchar(); /* get the first character */
while( message[i] != '\n' ){
message[++i] = getchar(); /* gets the next character */
}
printf( "Entered message is:" );
for( i = 0; i < N; i++ )
printf( "%c", message[i] );
return ( 0 );
}
File uploads can not be done this way, no matter how you break it down. If you want to do an ajax/async upload, I would suggest looking into something like Uploadify, or Valums
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
set the type
of column named dateposted
as DATETIME
and run the following query:
INSERT INTO table (`dateposted`) VALUES (CURRENT_TIMESTAMP)
For example,
package main
import "fmt"
func CToGoString(c []byte) string {
n := -1
for i, b := range c {
if b == 0 {
break
}
n = i
}
return string(c[:n+1])
}
func main() {
c := [100]byte{'a', 'b', 'c'}
fmt.Println("C: ", len(c), c[:4])
g := CToGoString(c[:])
fmt.Println("Go:", len(g), g)
}
Output:
C: 100 [97 98 99 0]
Go: 3 abc
Since you are using a Mac, open a terminal, and
Find the php.ini, and sudo open it, for example, using the nano editor
Find use control+w to search for "mysqli.default_socket", and change the line to
Use control+x and then hit "y" and "return" to save the file. Restart Aapche if necessary.
Now you should be able to run mysqli.
shell("C:\Users\USERNAME\AppData\Local\Google\Chrome\Application\Chrome.exe -url http:google.ca")
In my case, It was from Stored Producers. I was removed a field from table and forgotten to remove it from my SP.
Put the line in a stringstream and extract word by word back:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string t;
getline(cin,t);
istringstream iss(t);
string word;
while(iss >> word) {
/* do stuff with word */
}
}
Of course, you can just skip the getline part and read word by word from cin
directly.
And here you can read why is using namespace std
considered bad practice.
I found out that single quote > double quote > wrapped in ampersands did work. So, for me it looks like this:
=QUERY('Youth Conference Registration'!C:Y,"select C where Y = '"&A1&"'", 0)
format = [".jpg",".png",".jpeg"]
for (path,dirs,files) in os.walk(path):
for file in files:
if file.endswith(tuple(format)):
print(path)
print ("Valid",file)
else:
print(path)
print("InValid",file)
If the browser uses this attribute, it is only as an help for the user, so he won't upload a multi-megabyte file just to see it rejected by the server...
Same for the <input type="hidden" name="MAX_FILE_SIZE" value="100000">
tag: if the browser uses it, it won't send the file but an error resulting in UPLOAD_ERR_FORM_SIZE
(2) error in PHP (not sure how it is handled in other languages).
Note these are helps for the user. Of course, the server must always check the type and size of the file on its end: it is easy to tamper with these values on the client side.
VERY IMPORTANT: If you are using LOMBOK, make shure to exclude attributes of collections like Set, List, etc...
Like this:
@EqualsAndHashCode(exclude = {"attributeOfTypeList", "attributeOfTypeSet"})
You can access this hello function anywhere in the module
Controller one
$scope.save = function() {
$scope.hello();
}
second controller
$rootScope.hello = function() {
console.log('hello');
}
I also faced this issue. My Operating system is Ubuntu 18.04 and my PHP version is PHP 7.2.
Here's how I solved it:
Install Simplexml on your Ubuntu Server:
sudo apt-get install php7.2-simplexml
Restart Apache Server
sudo systemctl restart apache2
That's all.
I hope this helps
Here you are :
echo "Body" | mailx -r "FROM_EMAIL" -s "SUBJECT" "To_EMAIL"
PS. Body and subject should be kept within double quotes.
Remove quotes from FROM_EMAIL
and To_EMAIL
while substituting email addresses.
In my taste, it's also very concise to combine zip()
with xrange(n)
(or range(n)
in Python3), which works nice on generators as well and seems to be more flexible for changes in general.
# Option #1: taking the first n elements as a list
[x for _, x in zip(xrange(n), generator)]
# Option #2, using 'next()' and taking care for 'StopIteration'
[next(generator) for _ in xrange(n)]
# Option #3: taking the first n elements as a new generator
(x for _, x in zip(xrange(n), generator))
# Option #4: yielding them by simply preparing a function
# (but take care for 'StopIteration')
def top_n(n, generator):
for _ in xrange(n): yield next(generator)
I observed the same issue, and added the command and args block in yaml file. I am copying sample of my yaml file for reference
apiVersion: v1
kind: Pod
metadata:
labels:
run: ubuntu
name: ubuntu
namespace: default
spec:
containers:
- image: gcr.io/ow/hellokubernetes/ubuntu
imagePullPolicy: Never
name: ubuntu
resources:
requests:
cpu: 100m
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello; sleep 10;done"]
dnsPolicy: ClusterFirst
enableServiceLinks: true
In my experience, ++i or i++ has never caused confusion other than when first learning about how the operator works. It is essential for the most basic for loops and while loops that are taught by any highschool or college course taught in languages where you can use the operator. I personally find doing something like what is below to look and read better than something with a++ being on a separate line.
while ( a < 10 ){_x000D_
array[a++] = val_x000D_
}
_x000D_
In the end it is a style preference and not anything more, what is more important is that when you do this in your code you stay consistent so that others working on the same code can follow and not have to process the same functionality in different ways.
Also, Crockford seems to use i-=1, which I find to be harder to read than --i or i--
To have a cron executed on Sunday you can use either of these:
5 8 * * 0
5 8 * * 7
5 8 * * Sun
Where 5 8
stands for the time of the day when this will happen: 8:05.
In general, if you want to execute something on Sunday, just make sure the 5th column contains either of 0
, 7
or Sun
. You had 6
, so it was running on Saturday.
The format for cronjobs is:
+---------------- minute (0 - 59)
| +------------- hour (0 - 23)
| | +---------- day of month (1 - 31)
| | | +------- month (1 - 12)
| | | | +---- day of week (0 - 6) (Sunday=0 or 7)
| | | | |
* * * * * command to be executed
You can always use crontab.guru as a editor to check your cron expressions.
A slightly faster approach than looping on xrange(N)
is:
import itertools
for _ in itertools.repeat(None, N):
do_something()
This structure works for me - I used it in a small tasks management application.
The controller:
public JsonResult taskCount(string fDate)
{
// do some stuff based on the date
// totalTasks is a count of the things I need to do today
// tasksDone is a count of the tasks I actually did
// pcDone is the percentage of tasks done
return Json(new {
totalTasks = totalTasks,
tasksDone = tasksDone,
percentDone = pcDone
});
}
In the AJAX call I access the data like this:
.done(function (data) {
// data.totalTasks
// data.tasksDone
// data.percentDone
});
For the listed three conditions only, these expressions might work also:
^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$
If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:
123451234
12345 1234
12345 1234
this expression for instance would be a secondary option with less constraints:
^\d{5}([-]|\s*)?(\d{4})?$
jex.im visualizes regular expressions:
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345-6789_x000D_
12345 1234_x000D_
123451234_x000D_
12345 1234_x000D_
12345 1234_x000D_
1234512341_x000D_
123451`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
ParseExact is told the format of the date it is expected to parse, not the format you wish to get out.
$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)
If you then wish to output a date string:
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')
Chris
Thank you to SLaks and jpm for their help. It was a pretty simple error that I simply did not see.
As SLaks pointed out, br.readLine() was being called twice each loop which made the program only get half of the values. Here is the fixed code:
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
String words[]=new String[5];
String line=null;
while((line=br.readLine())!=null){
words=line.split(" ");
int targetX=Integer.parseInt(words[0]);
int targetY=Integer.parseInt(words[1]);
int targetW=Integer.parseInt(words[2]);
int targetH=Integer.parseInt(words[3]);
int targetHits=Integer.parseInt(words[4]);
Target a=new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
Thanks again! You guys are great!
You could construct a dataframe from the series and then merge with the dataframe. So you specify the data as the values but multiply them by the length, set the columns to the index and set params for left_index and right_index to True:
In [27]:
df.merge(pd.DataFrame(data = [s.values] * len(s), columns = s.index), left_index=True, right_index=True)
Out[27]:
a b s1 s2
0 1 3 5 6
1 2 4 5 6
EDIT for the situation where you want the index of your constructed df from the series to use the index of the df then you can do the following:
df.merge(pd.DataFrame(data = [s.values] * len(df), columns = s.index, index=df.index), left_index=True, right_index=True)
This assumes that the indices match the length.
This is how Adding new column to Table
ALTER TABLE [tableName]
ADD ColumnName Datatype
E.g
ALTER TABLE [Emp]
ADD Sr_No Int
And If you want to make it auto incremented
ALTER TABLE [Emp]
ADD Sr_No Int IDENTITY(1,1) NOT NULL
From the matplotlib docs on scatter 1:
cmap is only used if c is an array of floats
So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.
How does this work for you?
import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()
If you need an empty folder you can loop until you get an empty folder
QString folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
while(QDir(folder).exists())
{
folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
}
QDir().mkdir(folder);
This case you will get a folder name with a number .
Today, I've got a similar error:
Servlet.service() for servlet [remoting] in context with path [/***] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: buildDocument failed.] with root cause
org.xml.sax.SAXParseException; lineNumber: 19; columnNumber: 91; An invalid XML character (Unicode: 0xc) was found in the value of attribute "text" and element is "label".
After my first encouter with the error, I had re-typed the entire line by hand, so that there was no way for a special character to creep in, and Notepad++ didn't show any non-printable characters (black on white), nevertheless I got the same error over and over.
When I looked up what I've done different than my predecessors, it turned out it was one additional space just before the closing /> (as I've heard was recommended for older parsers, but it shouldn't make any difference anyway, by the XML standards):
<label text="this label's text" layout="cell 0 0, align left" />
When I removed the space:
<label text="this label's text" layout="cell 0 0, align left"/>
everything worked just fine.
So it's definitely a misleading error message.
If you are unable to install with either of these:
sudo apt-get install python-distutils
sudo apt-get install python3-distutils
Try this instead:
sudo apt-get install python-distutils-extra
Ref: https://groups.google.com/forum/#!topic/beagleboard/RDlTq8sMxro
There's actually a way to do this without javascript.
If you set an <input>
's required
selector to true, you can check if there's text in it with the CSS :valid
tag.
References:
input {
background: red;
}
input:valid {
background: lightgreen;
}
_x000D_
<input type="text" required>
_x000D_
They're still types, so I always use the same naming conventions I use for classes.
I definitely would frown on putting "Class" or "Enum" in a name. If you have both a FruitClass
and a FruitEnum
then something else is wrong and you need more descriptive names. I'm trying to think about the kind of code that would lead to needing both, and it seems like there should be a Fruit
base class with subtypes instead of an enum. (That's just my own speculation though, you may have a different situation than what I'm imagining.)
The best reference that I can find for naming constants comes from the Variables tutorial:
If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.
Apple states about NSSearchPathForDirectoriesInDomains(_:_:_:)
:
You should consider using the
FileManager
methodsurls(for:in:)
andurl(for:in:appropriateFor:create:)
which return URLs, which are the preferred format.
With Swift 5, FileManager
has a method called contentsOfDirectory(at:includingPropertiesForKeys:options:)
. contentsOfDirectory(at:includingPropertiesForKeys:options:)
has the following declaration:
Performs a shallow search of the specified directory and returns URLs for the contained items.
func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]
Therefore, in order to retrieve the urls of the files contained in documents directory, you can use the following code snippet that uses FileManager
's urls(for:in:)
and contentsOfDirectory(at:includingPropertiesForKeys:options:)
methods:
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents)
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
As an example, the UIViewController
implementation below shows how to save a file from app bundle to documents directory and how to get the urls of the files saved in documents directory:
import UIKit
class ViewController: UIViewController {
@IBAction func copyFile(_ sender: UIButton) {
// Get file url
guard let fileUrl = Bundle.main.url(forResource: "Movie", withExtension: "mov") else { return }
// Create a destination url in document directory for file
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let documentDirectoryFileUrl = documentsDirectory.appendingPathComponent("Movie.mov")
// Copy file to document directory
if !FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) {
do {
try FileManager.default.copyItem(at: fileUrl, to: documentDirectoryFileUrl)
print("Copy item succeeded")
} catch {
print("Could not copy file: \(error)")
}
}
}
@IBAction func displayUrls(_ sender: UIButton) {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents) // may print [] or [file:///private/var/mobile/Containers/Data/Application/.../Documents/Movie.mov]
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
}
}
Additionally, return values are compatible with asynchronous design paradigms.
You cannot designate a function "async" if it uses ref or out parameters.
In summary, Return Values allow method chaining, cleaner syntax (by eliminating the necessity for the caller to declare additional variables), and allow for asynchronous designs without the need for substantial modification in the future.
I ran
docker info | grep Name: | xargs | cut -d' ' -f2
inside my container.
For latest Swift Version:
Create a file, name it UIWindowExtension.swift
and paste the following snippet:
import UIKit
public extension UIWindow {
public var visibleViewController: UIViewController? {
return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
}
public static func getVisibleViewControllerFrom(vc: UIViewController?) -> UIViewController? {
if let nc = vc as? UINavigationController {
return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
} else if let tc = vc as? UITabBarController {
return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
} else {
if let pvc = vc?.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(pvc)
} else {
return vc
}
}
}
}
func getTopViewController() -> UIViewController? {
let appDelegate = UIApplication.sharedApplication().delegate
if let window = appDelegate!.window {
return window?.visibleViewController
}
return nil
}
Use it anywhere as:
if let topVC = getTopViewController() {
}
I didn't find a complete answer here
Firstly
You should install your preferred language
Secondly
Go to Tools -> Options
2.Select International Settings in Environment
3.click on Menu and select you preferred language
4.Click on Ok
5.restart visual studio
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test("ABC") ("DEF")
You do not have permissions to access the file. Please be sure whether you can access the file in that drive.
string route= @"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);
You have to provide the file name to create. Please try this, now you can create.
You can do in a very simple way. The idea is to place a Label in the same place as your textbox. Your Label will be visible if textbox has no text and hasn't the focus.
<Label Name="PalceHolder" HorizontalAlignment="Left" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Height="40" VerticalAlignment="Top" Width="239" FontStyle="Italic" Foreground="BurlyWood">PlaceHolder Text Here
<Label.Style>
<Style TargetType="{x:Type Label}">
<Setter Property="Visibility" Value="Hidden"/>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding ="{Binding ElementName=PalceHolder, Path=Text.Length}" Value="0"/>
<Condition Binding ="{Binding ElementName=PalceHolder, Path=IsFocused}" Value="False"/>
</MultiDataTrigger.Conditions>
<Setter Property="Visibility" Value="Visible"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
<TextBox Background="Transparent" Name="TextBox1" HorizontalAlignment="Left" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Height="40"TextWrapping="Wrap" Text="{Binding InputText,Mode=TwoWay}" VerticalAlignment="Top" Width="239" />
Bonus:If you want to have default value for your textBox, be sure after to set it when submitting data (for example:"InputText"="PlaceHolder Text Here" if empty).
There can be 2 issues :=
1. Your are trying the command in machine that does not support apt-get command
because apt-get is suitable for Linux based Ubuntu machines; for MAC, try
apt-get equivalent such as Brew
2. The other issue can be that your installation was not completed properly So
Re-install Ubuntu from a Live CD or USB.
The long version would be a waste of your time: your system will never
be clean, but if you insist you could try:
==> Copying everything (missing) except for the /home folder from the Live
CD/USB to your HDD.
OR
==> Do a re-install/repair over the broken system again with the Live
CD / USB stick.
OR
==> Download the deb file for apt-get and install as explained on above posts.
I would definitely go for a fresh new install as there are so many things to
do and so little time.
queryForMap
is appropriate if you want to get a single row. You are selecting without a where
clause, so you probably want to queryForList
. The error is probably indicative of the fact that queryForMap
wants one row, but you query is retrieving many rows.
Check out the docs. There is a queryForList
that takes just sql; the return type is a
List<Map<String,Object>>
.
So once you have the results, you can do what you are doing. I would do something like
List results = template.queryForList(sql);
for (Map m : results){
m.get('userid');
m.get('username');
}
I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.
If you have a User
object, and you actually want to load User instances, you can use the queryForList
that takes sql and a class type
queryForList(String sql, Class<T> elementType)
(wow Spring has changed a lot since I left Javaland.)
Here is an expanded answer. A DecoratedBox
is what you need to add a border, but I am using a Container
for the convenience of adding margin and padding.
Here is the general setup.
Widget myWidget() {
return Container(
margin: const EdgeInsets.all(30.0),
padding: const EdgeInsets.all(10.0),
decoration: myBoxDecoration(), // <--- BoxDecoration here
child: Text(
"text",
style: TextStyle(fontSize: 30.0),
),
);
}
where the BoxDecoration
is
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(),
);
}
These have a border width of 1
, 3
, and 10
respectively.
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(
width: 1, // <--- border width here
),
);
}
These have a border color of
Colors.red
Colors.blue
Colors.green
Code
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(
color: Colors.red, // <--- border color
width: 5.0,
),
);
}
These have a border side of
Code
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border(
left: BorderSide( // <--- left side
color: Colors.black,
width: 3.0,
),
top: BorderSide( // <--- top side
color: Colors.black,
width: 3.0,
),
),
);
}
These have border radii of 5
, 10
, and 30
respectively.
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(
width: 3.0
),
borderRadius: BorderRadius.all(
Radius.circular(5.0) // <--- border radius here
),
);
}
DecoratedBox
/BoxDecoration
are very flexible. Read Flutter — BoxDecoration Cheat Sheet for many more ideas.
SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.
The specific keys you have to set are below:
javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.
javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).
javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes,
/
, in place of backslashes,\
.If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):
$JAVA_HOME/lib/security/jssecacerts
$JAVA_HOME/lib/security/cacerts
javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by
javax.net.ssl.trustStore
.javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.
javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.
Here in simpler words:
DOM
Tree model parser (Object based) (Tree of nodes).
DOM loads the file into the memory and then parse- the file.
Has memory constraints since it loads the whole XML file before parsing.
DOM is read and write (can insert or delete nodes).
If the XML content is small, then prefer DOM parser.
Backward and forward search is possible for searching the tags and evaluation of the information inside the tags. So this gives the ease of navigation.
Slower at run time.
SAX
Event based parser (Sequence of events).
SAX parses the file as it reads it, i.e. parses node by node.
No memory constraints as it does not store the XML content in the memory.
SAX is read only i.e. can’t insert or delete the node.
Use SAX parser when memory content is large.
SAX reads the XML file from top to bottom and backward navigation is not possible.
Faster at run time.
Dijkstra's algorithm applies more to weighted paths and it sounds like the poster was wanting to find all paths, not just the shortest.
For this application, I'd build a graph (your application sounds like it wouldn't need to be directed) and use your favorite search method. It sounds like you want all paths, not just a guess at the shortest one, so use a simple recursive algorithm of your choice.
The only problem with this is if the graph can be cyclic.
With the connections:
While looking for a path from 1->4, you could have a cycle of 1 -> 2 -> 3 -> 1.
In that case, then I'd keep a stack as traversing the nodes. Here's a list with the steps for that graph and the resulting stack (sorry for the formatting - no table option):
current node (possible next nodes minus where we came from) [stack]
There is a major gotcha associated with getting an ASCII code of a char
value.
In the proper sense, it can't be done.
It's because char
has a range of 65535
whereas ASCII is restricted to 128
. There is a huge amount of characters that have no ASCII representation at all.
The proper way would be to use a Unicode code point which is the standard numerical equivalent of a character in the Java universe.
Thankfully, Unicode is a complete superset of ASCII. That means Unicode numbers for Latin characters are equal to their ASCII counterparts. For example, A
in Unicode is U+0041
or 65
in decimal. In contrast, ASCII has no mapping for 99% of char-s. Long story short:
char ch = 'A';
int cp = String.valueOf(ch).codePointAt(0);
Furthermore, a 16-bit primitive char
actually represents a code unit, not a character and is thus restricted to Basic Multilingual Plane, for historical reasons. Entities beyond it require Character objects which deal away with the fixed bit-length limitation.
You could right click on those cells, go to format, select custom, then type mm yyyy.
this works: select * from table where column like '%(hit enter)%'
Ignore the brackets and hit enter to introduce new line.
Seems like getTime
is not function on above answer.
Date.parse(currentDate)/1000
In Microsoft SQL Server Management Studio (the admin tool for MSSQL) just go into "design" on a table and drag the column to the new position. Not command line but you can do it.
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
If you want to detect arrow keypresses but not need specific in Javascript
function checkKey(e) {
if (e.keyCode !== 38 || e.keyCode !== 40 || e.keyCode !== 37 || e.keyCode !== 39){
// do something
};
}
Try this code:
public static Map<String, Object> convertJsonIntoMap(String jsonFile) {
Map<String, Object> map = new HashMap<>();
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() {
});
map = mapper.readValue(jsonFile, new TypeReference<Map<String, String>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
I use std::getwchar()
in my environment which is with mingw32 - gcc-4.6.2 compiler, Here is a sample code.
#include <iostream>
#include "Arithmetics.h"
using namespace std;
int main() {
ARITHMETICS_H::testPriorities();
cout << "Press any key to exit." << endl;
getwchar();
return 0;
}
Your HTML file is not going to interact with C# directly, but you can write some C# to behave as if it were the HTML file.
For example: there is a class called System.Net.WebClient with simple methods:
using System.Net;
using System.Collections.Specialized;
...
using(WebClient client = new WebClient()) {
NameValueCollection vals = new NameValueCollection();
vals.Add("test", "test string");
client.UploadValues("http://www.someurl.com/page.php", vals);
}
For more documentation and features, refer to the MSDN page.
Certain versions of android do not fire proper tasks for updating the state of file system. You could trigger an explicit intent for updating the status of the file system. (I just tested after being in the same OP's situation)
adb shell am broadcast -a android.intent.action.MEDIA_MOUNTED -d file:///
(You could pass a specific filepath instead of file:///
like file:///sdcard
)
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
Add volley.jar
as library
[MyProjectPath]/app/libs/
folderUse the source files from git (a rather manual/general way described here)
git clone https://github.com/git/git
... sry bad one, but couldn't resist ^^)git clone https://android.googlesource.com/platform/frameworks/volley
com
folder from within [path_where_you_typed_git_clone]/volley/src
to your projects app/src/main/java
folder (Integrate it instead, if you already have a com folder there!! ;-))The files show up immediately in Android Studio. For Eclipse you will have to right-click
on the src
folder and press refresh
(or F5
) first.
Use gradle via the "unofficial" maven mirror
In your project's src/build.gradle
file add following volley dependency:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// ...
compile 'com.mcxiaoke.volley:library:1.+'
}
Click on Try Again
which should right away appear on the top of the file, or just Build
it if not
The main "advantage" here is, that this will keep the version up to date for you, whereas in the other two cases you would have to manually update volley.
On the "downside" it is not officially from google, but a third party weekly mirror.
But both of these points, are really relative to what you would need/want.
Also if you don't want updates, just put the desired version there instead e.g. compile 'com.mcxiaoke.volley:library:1.0.7'
.
If you just want to check the type, you can use jQuery's .is() function,
Like in my case I used below,
if($("#id").is("select")) {
alert('Select');
else if($("#id").is("input")) {
alert("input");
}
If one is on a Windows machine and in PowerShell, one needs to quote the argument such as:
git stash apply "stash@{0}"
...or to apply the changes and remove from the stash:
git stash pop "stash@{0}"
Otherwise without the quotes you might get this error:
fatal: ambiguous argument 'stash@': unknown revision or path not in the working tree.
Use urlencode()
rather than trying to implement your own. Be lazy.
All of the examples listed above for sed break on one platform or another. None of them work with the version of sed shipped on Macs.
However, Perl's regex works the same on any machine with Perl installed:
perl -pe 's/\s+/\n/g' file.txt
If you want to save the output:
perl -pe 's/\s+/\n/g' file.txt > newfile.txt
If you want only unique occurrences of words:
perl -pe 's/\s+/\n/g' file.txt | sort -u > newfile.txt
If you need something simple; once and done callback
//multiple ajax calls above
var callback = function () {
if ($.active !== 0) {
setTimeout(callback, '500');
return;
}
//whatever you need to do here
//...
};
callback();
Also note, if you have explicitly granted:
CONNECT ON DATABASE xxx TO GROUP
,
you will need to revoke this separately from DROP OWNED BY, using:
REVOKE CONNECT ON DATABASE xxx FROM GROUP
Time ago I had the same problem and did my own implementation. What I suggest you is to implement another class: Edge. Then, a Vertex will have a List of Edge.
public class Edge {
private Node a, b;
private directionEnum direction; // AB, BA or both
private int weight;
...
}
It worked for me. But maybe is so simple. There is this library that maybe can help you if you look into its code: http://jgrapht.sourceforge.net/
If you're using windows, this worked for me:
eval `ssh-agent -s`
ssh-add ~/.ssh/*_rsa
It'll ask for passphrase in the second command, and that's it.
You can use PSCP to copy files from Windows to Linux.
Type command pscp source_file user@host:destination_file
pscp sample.txt [email protected]:/mydata/sample.txt
It might be cleaner for some people to work with an Integer object so you can just call toString() directly on the object:
Integer length = my_text_view.getText().getLength();
counter_text_view.setText( length.toString() );
If you are using native javascript then you can use this code -
let ids = users.map(function(obj, index) {
return obj.id;
})
console.log(ids); //[12, 14, 16, 18]
<video width="320" height="240" controls autoplay>
<source src="movie.mp4" type="video/mp4"> Your browser does not support the video tag.
</video>
Remove autoplay
if you want to disable auto playing video.
A combination of @grahamparks and @snowindy answers with a couple of modifications is what worked for my Groovy scripts running on Tomcat:
Utils.groovy
class Utils {
def doSth() {...}
}
MyScript.groovy:
/* import Utils --> This import does not work. The class is not even defined at this time */
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(new File("full_path_to/Utils.groovy")); // Otherwise it assumes current dir is $CATALINA_HOME
def foo = groovyClass.newInstance(); // 'def' solves compile time errors!!
foo.doSth(); // Actually works!
Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.
Create new extension with
import UIKit
extension UINavigationController {
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
}
extension UITabBarController {
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
}
You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:
VAR=$(scan)
Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.
Preserving trailing Newlines:
One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.
function scan2 () {
local nl=$'\x0a'; # that's just \n
echo "output${nl}${nl}" # 2 in the string + 1 by echo
}
# append a character to the total output.
# and strip it with %% parameter expansion.
VAR=$(scan2; echo "x"); VAR="${VAR%%x}"
echo "${VAR}---"
prints (3 newlines kept):
output
---
Use an output parameter: avoiding the subshell (and preserving newlines)
If what the function tries to achieve is to "return" a string into a variable , with bash v4.3 and up, one can use what's called a nameref
. Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it 'points to/references'.
function scan3() {
local -n outvar=$1 # -n makes it a nameref.
local nl=$'\x0a'
outvar="output${nl}${nl}" # two total. quotes preserve newlines
}
VAR="some prior value which will get overwritten"
# you pass the name of the variable. VAR will be modified.
scan3 VAR
# newlines are also preserved.
echo "${VAR}==="
prints:
output
===
This form has a few advantages. Namely, it allows your function to modify the environment of the caller without using global variables everywhere.
Note: using namerefs can improve the performance of your program greatly if your functions rely heavily on bash builtins, because it avoids the creation of a subshell that is thrown away just after. This generally makes more sense for small functions reused often, e.g. functions ending in echo "$returnstring"
This is relevant. https://stackoverflow.com/a/38997681/5556676
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
Had the same problem, thanks for the Framelayout tip! I was using two overlapped images in a framelayout (the one at top was an alpha mask, to give the effect of soft borders)
I set in the xml android:clickable="true"
for the image I wanted to launch the onClickListener, and android:clickable="false"
to the alpha mask.
What is this? :)
background-color: #D8F0DA;
Try
background: none
And override works only if property is exactly the same.
background doesn't override background-color.
If you want alpha transparency, then use something like this
background: rgba(100, 100, 100, 0.5);
I was wraped it with <> </> as a parent when I changed it to normal , div , its worked fine
If you want the script to run in the current shell (e.g. you want it to be able to affect your directory or environment) you should say:
. /path/to/script.sh
or
source /path/to/script.sh
Note that /path/to/script.sh
can be relative, for instance . bin/script.sh
runs the script.sh
in the bin
directory under the current directory.
As stated above, the lambda operator in Python defines an anonymous function, and in Python functions are closures. It is important not to confuse the concept of closures with the operator lambda, which is merely syntactic methadone for them.
When I started in Python a few years ago, I used lambdas a lot, thinking they were cool, along with list comprehensions. However, I wrote and have to maintain a big website written in Python, with on the order of several thousand function points. I've learnt from experience that lambdas might be OK to prototype things with, but offer nothing over inline functions (named closures) except for saving a few key-stokes, or sometimes not.
Basically this boils down to several points:
That's enough reason to round them up and convert them to named closures. However, I hold two other grudges against anonymous closures.
The first grudge is simply that they are just another unnecessary keyword cluttering up the language.
The second grudge is deeper and on the paradigm level, i.e. I do not like that they promote a functional-programming style, because that style is less flexible than the message passing, object oriented or procedural styles, because the lambda calculus is not Turing-complete (luckily in Python, we can still break out of that restriction even inside a lambda). The reasons I feel lambdas promote this style are:
There is an implicit return, i.e. they seem like they 'should' be functions.
They are an alternative state-hiding mechanism to another, more explicit, more readable, more reusable and more general mechanism: methods.
I try hard to write lambda-free Python, and remove lambdas on sight. I think Python would be a slightly better language without lambdas, but that's just my opinion.
Using filter
, you'd just need one line
line = filter(lambda char: char not in " ?.!/;:", line)
This treats the string as an iterable and checks every character if the lambda
returns True
:
>>> help(filter) Help on built-in function filter in module __builtin__: filter(...) filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.
Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}
Which will give you: 2018-01-16T08:32:28.75Z
In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently
data = [...data, {"label": 2, "value": 13}]
Examples
var data = [_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
];_x000D_
_x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
For your case (i know it was in 2011), we can do it with map() & forEach() like below
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
Since the Length
property of System.String
is an Int32
, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32
size). If it allowed longer you couldn't check the Length since that would fail.
Just another option, which I wrote:
It's overkill if this is all the date processing that you need, but it will do what you want.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
Yes Depart is a solution for that but I think this kind of methods are long trips!
SQL SERVER:
SELECT CAST(DATEPART(DD,GETDATE()) AS VARCHAR)+'/'
+CAST(DATEPART(MM,GETDATE()) AS VARCHAR)
+'/'+CAST(DATEPART(YYYY,GETDATE()) AS VARCHAR)
+' '+CAST(DATEPART(HH,GETDATE()) AS VARCHAR)
+':'+CAST(DATEPART(MI,GETDATE()) AS VARCHAR)
Oracle:
Select to_char(sysdate,'DD/MM/YYYY HH24:MI') from dual
You may write your own function by this way you can get rid of this mess;
http://sql.dzone.com/news/custom-date-formatting-sql-ser
select myshortfun(getdate(),myformat)
GO
for windows try left Ctrl key with F11 or F12 or Num off 7
A container's logs can be found in :
/var/lib/docker/containers/<container id>/<container id>-json.log
(if you use the default log format which is json)
static void Main(string[] args)
{
long blah = 20948230498204;
Console.WriteLine(blah.ToString().Length);
}
Try this
UPDATE `table` SET `uid` = CASE
WHEN id = 1 THEN 2952
WHEN id = 2 THEN 4925
WHEN id = 3 THEN 1592
ELSE `uid`
END
WHERE id in (1,2,3)
Here are two ways you could do this, if you are scheduling the reboot.
First you could create a task on one machine using credentials that have rights needed to connect and reboot another machine. This makes the scheduler responsible for securely storing the credentials. The reboot command (I'm a Powershell guy, but this is cleaner.) is:
SHUTDOWN /r /f /m \\ComputerName
The command line to create a scheduled task on the local machine, to remotely reboot another, would be:
SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f /m \\ComputerName" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU "domain\username" /RP "password"
I prefer the second way, where you use your current credentials to create a scheduled task that runs with the system account on a remote machine.
SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU SYSTEM /S ComputerName
This also works through the GUI, just enter SYSTEM as the user name, leaving the password fields blank.
Reason : "Don't know why there is no descendingIterator with ArrayList..."
Since array list doesnot keep the list in the same order as data has been added to list. So, never use Arraylist .
Linked list will keep the data in same order of ADD to list.
So , above in my example, i used ArrayList() in order to make user to twist their mind and make them to workout something from their side.
Instead of this
List<String> list = new ArrayList<String>();
USE:
List<String> list = new LinkedList<String>();
list.add("ravi");
list.add("kant");
list.add("soni");
// Iterate to disply : result will be as --- ravi kant soni
for (String name : list) {
...
}
//Now call this method
Collections.reverse(list);
// iterate and print index wise : result will be as --- soni kant ravi
for (String name : list) {
...
}
As many already stated here you need to make the class static
.
Just small addition - if you want, there is a bit different way without static one.
Consider this. Implementing a builder by declaring something like withProperty(value)
type setters inside the class and make them return a reference to itself. In this approach, you have a single and an elegant class which is a thread safe and concise.
Consider this:
public class DataObject {
private String first;
private String second;
private String third;
public String getFirst(){
return first;
}
public void setFirst(String first){
this.first = first;
}
...
public DataObject withFirst(String first){
this.first = first;
return this;
}
public DataObject withSecond(String second){
this.second = second;
return this;
}
public DataObject withThird(String third){
this.third = third;
return this;
}
}
DataObject dataObject = new DataObject()
.withFirst("first data")
.withSecond("second data")
.withThird("third data");
Check it out for more Java Builder examples.
Use .prop instead:
$('#deliveryNext').prop('disabled')
If you are using graph for navigation between fragments you can do this: From fragment A:
Bundle bundle = new Bundle();
bundle.putSerializable(KEY, yourObject);
Navigation.findNavController(view).navigate(R.id.fragment, bundle);
To fragment B:
Bundle bundle = getArguments();
object = (Object) bundle.getSerializable(KEY);
Of course your object must implement Serializable
This will flatten a list or dictionary (or list of lists or dictionaries of dictionaries etc). It assumes that the values are strings and it creates a string that concatenates each item with a separator argument. If you wanted you could use the separator to split the result into a list object afterward. It uses recursion if the next value is a list or a string. Use the key argument to tell whether you want the keys or the values (set key to false) from the dictionary object.
def flatten_obj(n_obj, key=True, my_sep=''):
my_string = ''
if type(n_obj) == list:
for val in n_obj:
my_sep_setter = my_sep if my_string != '' else ''
if type(val) == list or type(val) == dict:
my_string += my_sep_setter + flatten_obj(val, key, my_sep)
else:
my_string += my_sep_setter + val
elif type(n_obj) == dict:
for k, v in n_obj.items():
my_sep_setter = my_sep if my_string != '' else ''
d_val = k if key else v
if type(v) == list or type(v) == dict:
my_string += my_sep_setter + flatten_obj(v, key, my_sep)
else:
my_string += my_sep_setter + d_val
elif type(n_obj) == str:
my_sep_setter = my_sep if my_string != '' else ''
my_string += my_sep_setter + n_obj
return my_string
return my_string
print(flatten_obj(['just', 'a', ['test', 'to', 'try'], 'right', 'now', ['or', 'later', 'today'],
[{'dictionary_test': 'test'}, {'dictionary_test_two': 'later_today'}, 'my power is 9000']], my_sep=', ')
yields:
just, a, test, to, try, right, now, or, later, today, dictionary_test, dictionary_test_two, my power is 9000
To get time in milliseconds, it's better to add .round(3)
, so it will be more accurate in some cases:
puts Time.now.to_f # => 1453402722.577573
(Time.now.to_f.round(3)*1000).to_i # => 1453402722578
You can use import components.core
directly if you append the current directory to sys.path
:
if __name__ == '__main__' and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
You can do:
select
count(<columnName>)
from
<tableName>
If the count returns 0 that means that all rows in that column all NULL (or there is no rows at all in the table)
can be changed to
select
case(count(<columnName>)) when 0 then 'Nulls Only' else 'Some Values' end
from
<tableName>
If you want to automate it you can use system tables to iterate the column names in the table you are interested in
Try this:
To accept theirs changes: git merge --strategy-option theirs
To accept yours: git merge --strategy-option ours
I tried to push to my own hosted bonobo-git server, and did not realise, that the http.postbuffer meant the project directory ...
so just for other confused ones:
why? In my case, I had large zip files with assets and some PSDs pushed as well - to big for the buffer I guess.
How to do this http.postbuffer: execute that command within your project src directory, next to the .git folder, not on the server.
be aware, large temp (chunk) files will be created of that buffer size.
Note: Just check your largest files, then set the buffer.
Recently I learned of the following syntax:
DELETE (SELECT *
FROM productfilters pf
INNER JOIN product pr
ON pf.productid = pr.id
WHERE pf.id >= 200
AND pr.NAME = 'MARK')
I think it looks much cleaner then other proposed code.
You can disable a tab in bootstrap 4 by adding class disabled
to the child of nav-item as follows
<li class="nav-item">
<a class="nav-link disabled" data-toggle="tab" href="#messages7" role="tab" aria-expanded="false">
<i class="icofont icofont-ui-message"></i>Home</a>
<div class="slide"></div>
</li>
This is totally system dependent. You should experiment to find the optimum solution.
Try starting with bs=8388608
. (As Hitachi HDDs seems to have 8MB cache.)
This code:
Option Explicit
Sub ExportMyPicture()
Dim MyChart As String, MyPicture As String
Dim PicWidth As Long, PicHeight As Long
Application.ScreenUpdating = False
On Error GoTo Finish
MyPicture = Selection.Name
With Selection
PicHeight = .ShapeRange.Height
PicWidth = .ShapeRange.Width
End With
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"
Selection.Border.LineStyle = 0
MyChart = Selection.Name & " " & Split(ActiveChart.Name, " ")(2)
With ActiveSheet
With .Shapes(MyChart)
.Width = PicWidth
.Height = PicHeight
End With
.Shapes(MyPicture).Copy
With ActiveChart
.ChartArea.Select
.Paste
End With
.ChartObjects(1).Chart.Export Filename:="MyPic.jpg", FilterName:="jpg"
.Shapes(MyChart).Cut
End With
Application.ScreenUpdating = True
Exit Sub
Finish:
MsgBox "You must select a picture"
End Sub
was copied directly from here, and works beautifully for the cases I tested.
You need to use:
await client.PostAsync(uri, content);
Something like that:
var comment = "hello world";
var questionId = 1;
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("comment", comment),
new KeyValuePair<string, string>("questionId", questionId)
});
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);
And if you need to get the response after post, you should use:
var stringContent = await response.Content.ReadAsStringAsync();
Hope it helps ;)
EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.
Original post
The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.
More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan
There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.
All you need to do is
android:isScrollContainer="true"
source: http://www.davidwparker.com/2011/08/25/android-fixing-window-resize-and-scrolling/
The best way is,
var first = '2012-11-21';
var second = '2012-11-03';
if (new Date(first) > new Date(second) {
.....
}
Your algorithm is correct. But we can do optimization as follows: While reversing, You may try keeping another variable to reduce backward counter since computing of array.length-(i+1) may take time! And also move declaration of temp outside so that everytime it needs not to be allocated
double temp;
for(int i=0,j=array.length-1; i < (array.length/2); i++, j--) {
// swap the elements
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Assuming that onMove
is an event handler, it is likely that its context is something other than the instance of MyContainer
, i.e. this
points to something different.
You can manually bind the context of the function during the construction of the instance via Function.bind
:
class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.test = "this is a test";
}
onMove() {
console.log(this.test);
}
}
Also, test !== testVariable
.
Starting from root
node and moving downwards if you find any node that has either p
or q
as its direct child then it is the LCA. (edit - this should be if p
or q
is the node's value, return it. Otherwise it will fail when one of p
or q
is a direct child of the other.)
Else if you find a node with p
in its right(or left) subtree and q
in its left(or right) subtree then it is the LCA.
The fixed code looks like:
treeNodePtr findLCA(treeNodePtr root, treeNodePtr p, treeNodePtr q) {
// no root no LCA.
if(!root) {
return NULL;
}
// if either p or q is the root then root is LCA.
if(root==p || root==q) {
return root;
} else {
// get LCA of p and q in left subtree.
treeNodePtr l=findLCA(root->left , p , q);
// get LCA of p and q in right subtree.
treeNodePtr r=findLCA(root->right , p, q);
// if one of p or q is in leftsubtree and other is in right
// then root it the LCA.
if(l && r) {
return root;
}
// else if l is not null, l is LCA.
else if(l) {
return l;
} else {
return r;
}
}
}
The below code fails when either is the direct child of other.
treeNodePtr findLCA(treeNodePtr root, treeNodePtr p, treeNodePtr q) {
// no root no LCA.
if(!root) {
return NULL;
}
// if either p or q is direct child of root then root is LCA.
if(root->left==p || root->left==q ||
root->right ==p || root->right ==q) {
return root;
} else {
// get LCA of p and q in left subtree.
treeNodePtr l=findLCA(root->left , p , q);
// get LCA of p and q in right subtree.
treeNodePtr r=findLCA(root->right , p, q);
// if one of p or q is in leftsubtree and other is in right
// then root it the LCA.
if(l && r) {
return root;
}
// else if l is not null, l is LCA.
else if(l) {
return l;
} else {
return r;
}
}
}
you need to add the javascript language file,after the moment library, example:
<script type="text/javascript" src="js/moment/moment.js"></script>
<script type="text/javascript" src="js/moment/es.js"></script>
now you can set a language.
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({locale:'es'});
});
</script>
Here are all language: https://github.com/moment/moment
Provided .wrapper is inside .item, and provided you're either not in IE 6 or .item is an a tag, the CSS you have should work just fine. Do you have evidence to suggest it isn't?
EDIT:
CSS alone can't affect something not contained within it. To make this happen, format your menu like so:
<ul class="menu">
<li class="menuitem">
<a href="destination">menu text</a>
<ul class="menu">
<li class="menuitem">
<a href="destination">part of pull-out menu</a>
... etc ...
and your CSS like this:
.menu .menu {
display: none;
}
.menu .menuitem:hover .menu {
display: block;
float: left;
// likely need to set top & left
}
It sounds like the best way is for you to iterate over entries using map.entrySet()
since map.containsValue()
probably does this anyway.