I had the same problem. I found solution here http://jakob.engbloms.se/archives/1403
c:\msysgit\bin>rebase.exe -b 0x50000000 msys-1.0.dll
For me solution was slightly different. It was
C:\Program Files (x86)\Git\bin>rebase.exe -b 0x50000000 msys-1.0.dll
Before you rebase dlls, you should make sure it is not in use:
tasklist /m msys-1.0.dll
And make a backup:
copy msys-1.0.dll msys-1.0.dll.bak
If the rebase command fails with something like:
ReBaseImage (msys-1.0.dll) failed with last error = 6
You will need to perform the following steps in order:
If any issue run the commands as Administrator
I think gitready is a great starting point. I'm using git for a project now and that site pretty much got the ball rolling for me.
Export it into some text format. The easiest will probably be a tab-delimited version, but CSV can work as well.
Use the load data capability. See http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Look half way down the page, as it will gives a good example for tab separated data:
FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\'
Check your data. Sometimes quoting or escaping has problems, and you need to adjust your source, import command-- or it may just be easier to post-process via SQL.
I kind of like this solution :
: `particular_script`
The command/script between the back ticks is executed and its output is fed to the command ":" (which is the equivalent of "true")
$ false
$ echo $?
1
$ : `false`
$ echo $?
0
edit: Fixed ugly typo
How about like this
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
{
return HiddenFor(htmlHelper, expression, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)
{
return htmlHelper.Hidden(ExpressionHelper.GetExpressionText(expression), value, htmlAttributes);
}
Use it like this
@Html.HiddenFor(customerId => reviewModel.CustomerId, Site.LoggedInCustomerId, null)
Another answer with later print/format style is:
res[0]=12
res[1]=23
print("my num is 0x{0:02x}{1:02x}".format(res[0],res[1]))
Before actually answering your question:
Parameters in a URL (e.g. key=listOfUsers/user1
) are GET
parameters and you shouldn't be using them for POST
requests. A quick explanation of the difference between GET and POST can be found here.
In your case, to make use of REST principles, you should probably have:
http://ip:5000/users
http://ip:5000/users/<user_id>
Then, on each URL, you can define the behaviour of different HTTP methods (GET
, POST
, PUT
, DELETE
). For example, on /users/<user_id>
, you want the following:
GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id>
So, in your example, you want do a POST
to /users/user_1
with the POST data being "John"
. Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.
Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
if request.method == 'GET':
"""return the information for <user_id>"""
.
.
.
if request.method == 'POST':
"""modify/update the information for <user_id>"""
# you can use <user_id>, which is a str but could
# changed to be int or whatever you want, along
# with your lxml knowledge to make the required
# changes
data = request.form # a multidict containing POST data
.
.
.
if request.method == 'DELETE':
"""delete user with ID <user_id>"""
.
.
.
else:
# POST Error 405 Method Not Allowed
.
.
.
There are a lot of other things to consider like the POST
request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.
Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.
Another way
@Html.TextAreaFor(model => model.Comments[0].Comment)
And in your css do this
textarea
{
font-family: inherit;
width: 650px;
height: 65px;
}
That DataType dealie allows carriage returns in the data, not everybody likes those.
May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20
what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",
Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11
You can find the last column of table and then fill the cell by looping throught it.
Sub test()
Dim lastCol As Long, i As Integer
lastCol = Range("AZ1").End(xlToLeft).Column
For i = 1 To lastCol
Cells(1, i).Value = "PHEV"
Next
End Sub
Here are few tips on how to iterate a Set along with their performances:
public class IterateSet {
public static void main(String[] args) {
//example Set
Set<String> set = new HashSet<>();
set.add("Jack");
set.add("John");
set.add("Joe");
set.add("Josh");
long startTime = System.nanoTime();
long endTime = System.nanoTime();
//using iterator
System.out.println("Using Iterator");
startTime = System.nanoTime();
Iterator<String> setIterator = set.iterator();
while(setIterator.hasNext()){
System.out.println(setIterator.next());
}
endTime = System.nanoTime();
long durationIterator = (endTime - startTime);
//using lambda
System.out.println("Using Lambda");
startTime = System.nanoTime();
set.forEach((s) -> System.out.println(s));
endTime = System.nanoTime();
long durationLambda = (endTime - startTime);
//using Stream API
System.out.println("Using Stream API");
startTime = System.nanoTime();
set.stream().forEach((s) -> System.out.println(s));
endTime = System.nanoTime();
long durationStreamAPI = (endTime - startTime);
//using Split Iterator (not recommended)
System.out.println("Using Split Iterator");
startTime = System.nanoTime();
Spliterator<String> splitIterator = set.spliterator();
splitIterator.forEachRemaining((s) -> System.out.println(s));
endTime = System.nanoTime();
long durationSplitIterator = (endTime - startTime);
//time calculations
System.out.println("Iterator Duration:" + durationIterator);
System.out.println("Lamda Duration:" + durationLambda);
System.out.println("Stream API:" + durationStreamAPI);
System.out.println("Split Iterator:"+ durationSplitIterator);
}
}
The code is self explanatory.
The result of the durations are:
Iterator Duration: 495287
Lambda Duration: 50207470
Stream Api: 2427392
Split Iterator: 567294
We can see the Lambda
takes the longest while Iterator
is the fastest.
While saying "the compiler can reserve", why rely on it? And what about automatic detection of move semantics? And what about all that repeating of the container name with the begin
s and end
s?
Wouldn't you want something, you know, simpler?
(Scroll down to main
for the punchline)
#include <type_traits>
#include <vector>
#include <iterator>
#include <iostream>
template<typename C,typename=void> struct can_reserve: std::false_type {};
template<typename T, typename A>
struct can_reserve<std::vector<T,A>,void>:
std::true_type
{};
template<int n> struct secret_enum { enum class type {}; };
template<int n>
using SecretEnum = typename secret_enum<n>::type;
template<bool b, int override_num=1>
using EnableFuncIf = typename std::enable_if< b, SecretEnum<override_num> >::type;
template<bool b, int override_num=1>
using DisableFuncIf = EnableFuncIf< !b, -override_num >;
template<typename C, EnableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t n ) {
c.reserve(n);
}
template<typename C, DisableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t ) { } // do nothing
template<typename C,typename=void>
struct has_size_method:std::false_type {};
template<typename C>
struct has_size_method<C, typename std::enable_if<std::is_same<
decltype( std::declval<C>().size() ),
decltype( std::declval<C>().size() )
>::value>::type>:std::true_type {};
namespace adl_aux {
using std::begin; using std::end;
template<typename C>
auto adl_begin(C&&c)->decltype( begin(std::forward<C>(c)) );
template<typename C>
auto adl_end(C&&c)->decltype( end(std::forward<C>(c)) );
}
template<typename C>
struct iterable_traits {
typedef decltype( adl_aux::adl_begin(std::declval<C&>()) ) iterator;
typedef decltype( adl_aux::adl_begin(std::declval<C const&>()) ) const_iterator;
};
template<typename C> using Iterator = typename iterable_traits<C>::iterator;
template<typename C> using ConstIterator = typename iterable_traits<C>::const_iterator;
template<typename I> using IteratorCategory = typename std::iterator_traits<I>::iterator_category;
template<typename C, EnableFuncIf< has_size_method<C>::value, 1>... >
std::size_t size_at_least( C&& c ) {
return c.size();
}
template<typename C, EnableFuncIf< !has_size_method<C>::value &&
std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 2>... >
std::size_t size_at_least( C&& c ) {
using std::begin; using std::end;
return end(c)-begin(c);
};
template<typename C, EnableFuncIf< !has_size_method<C>::value &&
!std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 3>... >
std::size_t size_at_least( C&& c ) {
return 0;
};
template < typename It >
auto try_make_move_iterator(It i, std::true_type)
-> decltype(make_move_iterator(i))
{
return make_move_iterator(i);
}
template < typename It >
It try_make_move_iterator(It i, ...)
{
return i;
}
#include <iostream>
template<typename C1, typename C2>
C1&& append_containers( C1&& c1, C2&& c2 )
{
using std::begin; using std::end;
try_reserve( c1, size_at_least(c1) + size_at_least(c2) );
using is_rvref = std::is_rvalue_reference<C2&&>;
c1.insert( end(c1),
try_make_move_iterator(begin(c2), is_rvref{}),
try_make_move_iterator(end(c2), is_rvref{}) );
return std::forward<C1>(c1);
}
struct append_infix_op {} append;
template<typename LHS>
struct append_on_right_op {
LHS lhs;
template<typename RHS>
LHS&& operator=( RHS&& rhs ) {
return append_containers( std::forward<LHS>(lhs), std::forward<RHS>(rhs) );
}
};
template<typename LHS>
append_on_right_op<LHS> operator+( LHS&& lhs, append_infix_op ) {
return { std::forward<LHS>(lhs) };
}
template<typename LHS,typename RHS>
typename std::remove_reference<LHS>::type operator+( append_on_right_op<LHS>&& lhs, RHS&& rhs ) {
typename std::decay<LHS>::type retval = std::forward<LHS>(lhs.lhs);
return append_containers( std::move(retval), std::forward<RHS>(rhs) );
}
template<typename C>
void print_container( C&& c ) {
for( auto&& x:c )
std::cout << x << ",";
std::cout << "\n";
};
int main() {
std::vector<int> a = {0,1,2};
std::vector<int> b = {3,4,5};
print_container(a);
print_container(b);
a +append= b;
const int arr[] = {6,7,8};
a +append= arr;
print_container(a);
print_container(b);
std::vector<double> d = ( std::vector<double>{-3.14, -2, -1} +append= a );
print_container(d);
std::vector<double> c = std::move(d) +append+ a;
print_container(c);
print_container(d);
std::vector<double> e = c +append+ std::move(a);
print_container(e);
print_container(a);
}
hehe.
Now with move-data-from-rhs, append-array-to-container, append forward_list-to-container, move-container-from-lhs, thanks to @DyP's help.
Note that the above does not compile in clang thanks to the EnableFunctionIf<>...
technique. In clang this workaround works.
var array = searchTerms.split(",");
for (var i in array){
alert(array[i]);
}
Here are some options for using AJAX to upload files:
AjaxFileUpload - Requires a form element on the page, but uploads the file without reloading the page. See the Demo.
Uploadify - A Flash-based method of uploading files.
Ten Examples of AJAX File Upload - This was posted this year.
UPDATE: Here is a JQuery plug-in for Multiple File Uploading.
I won't talk much. Already my respected fellow friends have given their valuable input. The full fledged running code at the last of this blog should remove any confusion. It's about a movie seat booking small program in multi-threaded scenario.
Some important elementary facts are as follows. 1> Different threads can only contend for instance and static member variables in the heap space. 2> Volatile read or write are completely atomic and serialized/happens before and only done from memory. By saying this I mean that any read will follow the previous write in memory. And any write will follow the previous read from memory. So any thread working with a volatile will always see the most up-to-date value. AtomicReference uses this property of volatile.
Following are some of the source code of AtomicReference. AtomicReference refers to an object reference. This reference is a volatile member variable in the AtomicReference instance as below.
private volatile V value;
get() simply returns the latest value of the variable (as volatiles do in a "happens before" manner).
public final V get()
Following is the most important method of AtomicReference.
public final boolean compareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}
The compareAndSet(expect,update) method calls the compareAndSwapObject() method of the unsafe class of Java. This method call of unsafe invokes the native call, which invokes a single instruction to the processor. "expect" and "update" each reference an object.
If and only if the AtomicReference instance member variable "value" refers to the same object is referred to by "expect", "update" is assigned to this instance variable now, and "true" is returned. Or else, false is returned. The whole thing is done atomically. No other thread can intercept in between. As this is a single processor operation (magic of modern computer architecture), it's often faster than using a synchronized block. But remember that when multiple variables need to be updated atomically, AtomicReference won't help.
I would like to add a full fledged running code, which can be run in eclipse. It would clear many confusion. Here 22 users (MyTh threads) are trying to book 20 seats. Following is the code snippet followed by the full code.
Code snippet where 22 users are trying to book 20 seats.
for (int i = 0; i < 20; i++) {// 20 seats
seats.add(new AtomicReference<Integer>());
}
Thread[] ths = new Thread[22];// 22 users
for (int i = 0; i < ths.length; i++) {
ths[i] = new MyTh(seats, i);
ths[i].start();
}
Following is the full running code.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class Solution {
static List<AtomicReference<Integer>> seats;// Movie seats numbered as per
// list index
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
seats = new ArrayList<>();
for (int i = 0; i < 20; i++) {// 20 seats
seats.add(new AtomicReference<Integer>());
}
Thread[] ths = new Thread[22];// 22 users
for (int i = 0; i < ths.length; i++) {
ths[i] = new MyTh(seats, i);
ths[i].start();
}
for (Thread t : ths) {
t.join();
}
for (AtomicReference<Integer> seat : seats) {
System.out.print(" " + seat.get());
}
}
/**
* id is the id of the user
*
* @author sankbane
*
*/
static class MyTh extends Thread {// each thread is a user
static AtomicInteger full = new AtomicInteger(0);
List<AtomicReference<Integer>> l;//seats
int id;//id of the users
int seats;
public MyTh(List<AtomicReference<Integer>> list, int userId) {
l = list;
this.id = userId;
seats = list.size();
}
@Override
public void run() {
boolean reserved = false;
try {
while (!reserved && full.get() < seats) {
Thread.sleep(50);
int r = ThreadLocalRandom.current().nextInt(0, seats);// excludes
// seats
//
AtomicReference<Integer> el = l.get(r);
reserved = el.compareAndSet(null, id);// null means no user
// has reserved this
// seat
if (reserved)
full.getAndIncrement();
}
if (!reserved && full.get() == seats)
System.out.println("user " + id + " did not get a seat");
} catch (InterruptedException ie) {
// log it
}
}
}
}
For windows server I think u can use this:
<?php
echo exec('getmac');
?>
I found this very helpful creating a feathersjs before hook to populate a 2 ref level deep relation. The mongoose models simply have
tables = new Schema({
..
tableTypesB: { type: Schema.Types.ObjectId, ref: 'tableTypesB' },
..
}
tableTypesB = new Schema({
..
tableType: { type: Schema.Types.ObjectId, ref: 'tableTypes' },
..
}
then in feathersjs before hook:
module.exports = function(options = {}) {
return function populateTables(hook) {
hook.params.query.$populate = {
path: 'tableTypesB',
populate: { path: 'tableType' }
}
return Promise.resolve(hook)
}
}
So simple compared to some other methods I was trying to achieve this.
DateTime.Now is what you're searching for...
You can simply do it with below command
git stash save --include-untracked
or
git stash save -u
For more about git stash Visit this post (Click Here)
if you want selector get the same id, use:
$("[id=task]:eq(0)").val();
$("[id=task]:eq(1)").val();
etc...
If you're a heavy visual studio user, you can simply open your preference settings and add the following to your settings.json:
...
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
....
Hopefully this can be helpful!
I think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.
As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:
$(window).resize(function() {
//update stuff
});
Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.
If you are not using IPython then just install it: "pip install ipython"
For lists
a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)
The output is [('a', 'p'), ('b', 'q'), ('c', 'r')
For dictionary:
c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)
The output is:
[('gaurav', 'amit'),
('nilesh', 'swapnil'),
('ramesh', 'anish'),
('anu', 'raghu')]
HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed
document.getElementById('here').innerHTML = data.name;
This needed to be changed to
document.getElementById('here').innerHTML = data.n;
I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .
There is nothing wrong with that type of code, provided that the author knows they are structs (or data shuttles) instead of objects. Lots of Java developers can't tell the difference between a well-formed object (not just a subclass of java.lang.Object, but a true object in a specific domain) and a pineapple. Ergo,they end up writing structs when they need objects and viceversa.
Old thread, still for future reference...:) even following works
git show-ref --head
by default HEAD is filtered out. Be careful about following though ; plural "heads" with a 's' at the end. The following command shows branches under "refs/heads"
git show-ref --heads
Try This
CKEDITOR.instances['textareaId'].setData(value);
If you have not yet commit you last changes before vacation.
- Command line to the project folder.
- Type 'svn diff
'
If you already commit you last changes before vacation.
No you can't they are different. When the app was deployed your controller mappings would be borked for example.
Why do you want to anyway, a controller is not a service, and vice versa.
PRINT_SUM PROC NEAR
CMP AL, 0
JNE PRINT_AX
PUSH AX
MOV AL, '0'
MOV AH, 0EH
INT 10H
POP AX
RET
PRINT_AX:
PUSHA
MOV AH, 0
CMP AX, 0
JE PN_DONE
MOV DL, 10
DIV DL
CALL PRINT_AX
MOV AL, AH
ADD AL, 30H
MOV AH, 0EH
INT 10H
PN_DONE:
POPA
RET
PRINT_SUM ENDP
For a horizontal ProgressBar, you can use a ColorFilter
, too, like this:
progressBar.getProgressDrawable().setColorFilter(
Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
Note: This modifies the appearance of all progress bars in your app. To only modify one specific progress bar, do this:
Drawable progressDrawable = progressBar.getProgressDrawable().mutate();
progressDrawable.setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(progressDrawable);
If progressBar is indeterminate then use getIndeterminateDrawable()
instead of getProgressDrawable()
.
Since Lollipop (API 21) you can set a progress tint:
progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
Well after doing some more searching I discovered the error may be related to other issues as invalid keystores, passwords etc.
I then remembered that I had set two VM arguments for when I was testing SSL for my network connectivity.
I removed the following VM arguments to fix the problem:
-Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456
Note: this keystore no longer exists so that's probably why the Exception.
Disabling tracking will also cause your result sets to be streamed into memory. This is more efficient when you're working with large sets of data and don't need the entire set of data all at once.
References:
Set it in the body selector of your css. E.g.
body {
font: 16px Arial, sans-serif;
}
x
be the expected number of milliseconds into the year of interest without factoring in daylight savings.y
be the number of milliseconds since the Epoch from the start of the year of the date of interest.z
be the number of milliseconds since the Epoch of the full date and time of interestt
be the subtraction of both x
and y
from z
: z - y - x
. This yields the offset due to DST. t
is zero, then DST is not in effect. If t
is not zero, then DST is in effect.(function(){"use strict";_x000D_
function dstOffsetAtDate(dateInput) {_x000D_
var fullYear = dateInput.getFullYear()|0;_x000D_
// "Leap Years are any year that can be exactly divided by 4 (2012, 2016, etc)_x000D_
// except if it can be exactly divided by 100, then it isn't (2100,2200,etc)_x000D_
// except if it can be exactly divided by 400, then it is (2000, 2400)"_x000D_
// (https://www.mathsisfun.com/leap-years.html)._x000D_
var isLeapYear = ((fullYear & 3) | (fullYear/100 & 3)) === 0 ? 1 : 0;_x000D_
// (fullYear & 3) = (fullYear % 4), but faster_x000D_
//Alternative:var isLeapYear=(new Date(currentYear,1,29,12)).getDate()===29?1:0_x000D_
var fullMonth = dateInput.getMonth()|0;_x000D_
return (_x000D_
// 1. We know what the time since the Epoch really is_x000D_
(+dateInput) // same as the dateInput.getTime() method_x000D_
// 2. We know what the time since the Epoch at the start of the year is_x000D_
- (+new Date(fullYear, 0, 0)) // day defaults to 1 if not explicitly zeroed_x000D_
// 3. Now, subtract what we would expect the time to be if daylight savings_x000D_
// did not exist. This yields the time-offset due to daylight savings._x000D_
- ((_x000D_
((_x000D_
// Calculate the day of the year in the Gregorian calendar_x000D_
// The code below works based upon the facts of signed right shifts_x000D_
// • (x) >> n: shifts n and fills in the n highest bits with 0s _x000D_
// • (-x) >> n: shifts n and fills in the n highest bits with 1s_x000D_
// (This assumes that x is a positive integer)_x000D_
(31 & ((-fullMonth) >> 4)) + // January // (-11)>>4 = -1_x000D_
((28 + isLeapYear) & ((1-fullMonth) >> 4)) + // February_x000D_
(31 & ((2-fullMonth) >> 4)) + // March_x000D_
(30 & ((3-fullMonth) >> 4)) + // April_x000D_
(31 & ((4-fullMonth) >> 4)) + // May_x000D_
(30 & ((5-fullMonth) >> 4)) + // June_x000D_
(31 & ((6-fullMonth) >> 4)) + // July_x000D_
(31 & ((7-fullMonth) >> 4)) + // August_x000D_
(30 & ((8-fullMonth) >> 4)) + // September_x000D_
(31 & ((9-fullMonth) >> 4)) + // October_x000D_
(30 & ((10-fullMonth) >> 4)) + // November_x000D_
// There are no months past December: the year rolls into the next._x000D_
// Thus, fullMonth is 0-based, so it will never be 12 in Javascript_x000D_
_x000D_
(dateInput.getDate()|0) // get day of the month_x000D_
_x000D_
)&0xffff) * 24 * 60 // 24 hours in a day, 60 minutes in an hour_x000D_
+ (dateInput.getHours()&0xff) * 60 // 60 minutes in an hour_x000D_
+ (dateInput.getMinutes()&0xff)_x000D_
)|0) * 60 * 1000 // 60 seconds in a minute * 1000 milliseconds in a second_x000D_
- (dateInput.getSeconds()&0xff) * 1000 // 1000 milliseconds in a second_x000D_
- dateInput.getMilliseconds()_x000D_
);_x000D_
}_x000D_
_x000D_
// Demonstration:_x000D_
var date = new Date(2100, 0, 1)_x000D_
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))_x000D_
console.log(date.getMonth()+":\t"+dstOffsetAtDate(date)/60/60/1000+"h\t"+date);_x000D_
date = new Date(1900, 0, 1);_x000D_
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))_x000D_
console.log(date.getMonth()+":\t"+dstOffsetAtDate(date)/60/60/1000+"h\t"+date);_x000D_
_x000D_
// Performance Benchmark:_x000D_
console.time("Speed of processing 16384 dates");_x000D_
for (var i=0,month=date.getMonth()|0; i<16384; i=i+1|0)_x000D_
date.setMonth(month=month+1+(dstOffsetAtDate(date)|0)|0);_x000D_
console.timeEnd("Speed of processing 16384 dates");_x000D_
})();
_x000D_
I believe that the above code snippet is superior to all other answers posted here for many reasons.
However, if you are not preparing for over 2 DST periods, then the below code can be used to determine whether DST is in effect as a boolean.
function isDaylightSavingsInEffect(dateInput) {
// To satisfy the original question
return dstOffsetAtDate(dateInput) !== 0;
}
The easiest way is to use the request module.
request('https://example.com/url?a=b', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
The short answer is: No. The only way to post images is through the mobile app.
From the Instagram API documentation: http://instagram.com/developer/endpoints/media/
At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:
- Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
- We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.
All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.
You may obtain the stream key via the API: https://github.com/justintv/twitch-api
I needed to print ALL lines after the pattern ( ok Ed, REGEX ), so I settled on this one:
sed -n '/pattern/,$p' # prints all lines after ( and including ) the pattern
But since I wanted to print all the lines AFTER ( and exclude the pattern )
sed -n '/pattern/,$p' | tail -n+2 # all lines after first occurrence of pattern
I suppose in your case you can add a head -1
at the end
sed -n '/pattern/,$p' | tail -n+2 | head -1 # prints line after pattern
You have to check which Python you are using. I had the same problem because the Python I was using was not the same one that brew was using. In your command line:
which python
which brew
cd /usr/local/lib/python2.7/site-packages
ls
//you can see PyQt4 and sip are hereusr/local/lib/python2.7/site-packages
to your python path.open ~/.bash_profile
//you will open your bash_profile file in your editor'export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH'
to your bash file and save itpython
import PyQt4
// it is ok nowI'd rather use the expression "serialization" than "casting into bytes". Serializing an object means converting it into a byte array (or XML, or something else) that can be used on the remote box to re-construct the object. In .NET, the Serializable
attribute marks types whose objects can be serialized.
you must kill child process too if any spawned to kill successfully your process
taskkill /IM "process_name" /T /F
/T = kills child process
/F = forceful termination of your process
Assuming that you have a primary key for this table (you should have), as well as using a CTE or a WITH, it is also possible to use an update with a self-join to the same table:
UPDATE a
SET a.interfaceId = b.sequence
FROM prices a
INNER JOIN
(
SELECT ROW_NUMBER() OVER ( ORDER BY b.priceId ) + ( SELECT MAX( interfaceId ) + 1 FROM prices ) AS sequence, b.priceId
FROM prices b
WHERE b.interfaceId IS NULL
) b ON b.priceId = a.priceId
I have assumed that the primary key is price-id.
The derived table, alias b, is used to generated the sequence via the ROW_NUMBER() function together with the primary key column(s). For each row where the column interface-id is NULL, this will generate a row with a unique sequence value together with the primary key value.
It is possible to order the sequence in some other order rather than the primary key.
The sequence is offset by the current MAX interface-id + 1 via a sub-query. The MAX() function ignores NULL values.
The WHERE clause limits the update to those rows that are NULL.
The derived table is then joined to the same table, alias a, joining on the primary key column(s) with the column to be updated set to the generated sequence.
I was using
SELECT * from TABLE1 WHERE Col1 NOT IN (SELECT Col1 FROM TABLE2)
and found that it was giving wrong results (By wrong I mean no results). As there was a NULL in TABLE2.Col1.
While changing the query to
SELECT * from TABLE1 T1 WHERE NOT EXISTS (SELECT Col1 FROM TABLE2 T2 WHERE T1.Col1 = T2.Col2)
gave me the correct results.
Since then I have started using NOT EXISTS every where.
You can also use
Cells.CurrentRegion
to give you a range representing the bounds of your data on the current active sheet
Msdn says on the topic
Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns. Read-only.
Then you can determine the column count via
Cells.CurrentRegion.Columns.Count
and the row count via
Cells.CurrentRegion.Rows.Count
bool IsExist = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("/UploadedFiles/"));
if (!IsExist)
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/UploadedFiles/"));
StreamWriter textWriter = File.CreateText(Path.Combine(HttpContext.Current.Server.MapPath("/UploadedFiles/") + "FileName.csv"));
var csvWriter = new CsvWriter(textWriter, System.Globalization.CultureInfo.CurrentCulture);
csvWriter.WriteRecords(classVM);
Verifying that a user is an admin in javascript leads to trouble because javascript code is visible to anyone. The server is the one who should tell the difference between an admin and a regular user AFTER the login process and then generate the new page accordingly.
Maybe that's not what you are trying to do so to answer your question:
window.location.href="<the page you are going to>";
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change). Initial value can be taken from defaultValue property:
function onChange() {
var oldValue = this.defaultValue;
var newValue = this.value;
}
Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.
From the docs:
_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.
So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.
Edit: Further reading led me here:
http://www.analyticsmarket.com/blog/edit-ecommerce-data
Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.
Alternatively, if you want to export a copy without modifying the working copy, you can use rsync:
rsync -a --exclude .svn path/to/working/copy path/to/export
Here is an example using HTML:
<input type="button" value="click me" onclick="this.style.color='#000000';
this.style.backgroundColor = '#ffffff'" />
And here is an example using JavaScript:
document.getElementById("button").bgcolor="#Insert Color Here";
Changing the width of the container also fixes it rather than changing the width and height of source file.
.SvgImage img{ width:80%; }
This fixes my issue of re sizing svg . you can give any % based on your requirement.
Example 1:
funct("z", function (x) { return x; });
function funct(a, foo){
foo(a) // this will return a
}
Example 2:
function foodemo(value){
return 'hello '+value;
}
function funct(a, foo){
alert(foo(a));
}
//call funct
funct('world!',foodemo); //=> 'hello world!'
To understand how the state of your working copy is different in both scenarios, you must understand the concept of the BASE revision:
BASE
The revision number of an item in a working copy. If the item has been locally modified, this refers to the way the item appears without those local modifications.
Your working copy contains a snapshot of each file (hidden in a .svn folder) in this BASE revision, meaning as it was when last retrieved from the repository. This explains why working copies take 2x the space and how it is possible that you can examine and even revert local modifications without a network connection.
Update item to Revision changes this base revision, making BASE out of date. When you try to commit local modifications, SVN will notice that your BASE does not match the repository HEAD. The commit will be refused until you do an update (and possibly a merge) to fix this.
Revert to revision does not change BASE. It is conceptually almost the same as manually editing the file to match an earlier revision.
hope this'll help you:
public boolean updatedetails(long rowId, String address)
{
SQLiteDatabase mDb= this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(KEY_ROWID, rowId);
args.put(KEY_ADDRESS, address);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null)>0;
}
In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.
<video controls>
<source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
<source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
<source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
<source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video>
We can add an external HLS js script in web application.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Your title</title>
<link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
<script src="https://unpkg.com/video.js/dist/video.js"></script>
<script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
</head>
<body>
<video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
data-setup='{}'>
<source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
</video>
<script>
var player = videojs('my_video_1');
player.play();
</script>
</body>
</html>
In any version of Eclipse IDE for source code indentation.
Select the source code and use the following keys
For default java indentation Ctrl + I
For right indentation Tab
For left indentation Shift + Tab
Just format after convert to a date (tested in SQL Server v.2017)
dd/mon/yyyy
Select Format(cast('25/jun/2013' as date),'dd/MMM/yyyy')
dd/mm/yyyy
Select Format(cast('25/jun/2013' as date),'dd/MM/yyyy')
dd/Month/yyyy
Select Format(cast('25/jun/2013' as date),'dd/MMMM/yyyy')
Just need to float both elements left:
.post-container{
margin: 20px 20px 0 0;
border:5px solid #333;
}
.post-thumb img {
float: left;
}
.post-content {
float: left;
}
Edit: actually, you do not need the width, just float both left
Believing this performance evaluation, the switch case is faster.
This is the conclusion:
The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler's ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to re-order the testing in such a way as to provide the fastest execution.
See Time Complexity. The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major Python implementation would be extremely unlikely. The average time complexity is of course O(1).
The best method would be to check and take a look at the hashs of the objects you are using. The CPython Dict uses int PyObject_Hash (PyObject *o) which is the equivalent of hash(o)
.
After a quick check, I have not yet managed to find two tuples that hash to the same value, which would indicate that the lookup is O(1)
l = []
for x in range(0, 50):
for y in range(0, 50):
if hash((x,y)) in l:
print "Fail: ", (x,y)
l.append(hash((x,y)))
print "Test Finished"
CodePad (Available for 24 hours)
First include the header corresponding to the .cpp... in other words, source1.cpp
should include source1.h
before including anything else. The only exception I can think of is when using MSVC with pre-compiled headers in which case, you are forced to include stdafx.h
before anything else.
Reasoning: Including the source1.h
before any other files ensures that it can stand alone without it's dependencies. If source1.h
takes on a dependency on a later date, the compiler will immediately alert you to add the required forward declarations to source1.h
. This in turn ensures that headers can be included in any order by their dependants.
Example:
source1.h
class Class1 {
Class2 c2; // a dependency which has not been forward declared
};
source1.cpp
#include "source1.h" // now compiler will alert you saying that Class2 is undefined
// so you can forward declare Class2 within source1.h
...
MSVC users: I strongly recommend using pre-compiled headers. So, move all #include
directives for standard headers (and other headers which are never going to change) to stdafx.h
.
Create jasper report in multiple languages(Unicode)
1)Install font in ireport desginer
2)create extension of font(we will use it in applications classpath)
3)install font on os(optional)
4)paste all .ttf of font in jre->lib->fonts directory (otherwise web application will throw error font is not available to JVM)
You have a single quotes conflict, so use:
echo "A,B,C" | sed "s/,/','/g"
If using bash, you can do too (<<<
is a here-string
):
sed "s/,/','/g" <<< "A,B,C"
but not
sed "s/,/','/g" "A,B,C"
because sed
expect file(s) as argument(s)
EDIT:
if you use ksh or any other ones :
echo string | sed ...
There is no such thing as :touch
in the W3C specifications, http://www.w3.org/TR/CSS2/selector.html#pseudo-class-selectors
:active
should work, I would think.
Order on the :active
/:hover
pseudo class is important for it to function correctly.
Here is a quote from that above link
Interactive user agents sometimes change the rendering in response to user actions. CSS provides three pseudo-classes for common cases:
- The :hover pseudo-class applies while the user designates an element (with some pointing device), but does not activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not supporting interactive media do not have to support this pseudo-class. Some conforming user agents supporting interactive media may not be able to support this pseudo-class (e.g., a pen device).
- The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.
- The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).
Besides the answer given above, I just want to add that this error can also occur while importing data with incorrect lines terminated character.
For example I save the dump file in csv format in windows. then while importing
LOAD DATA INFILE '/path_to_csv_folder/db.csv' INTO TABLE table1
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
Windows saved end of line as \r\n (i.e. CF LF) where as I was using \n. I was getting crazy why phpMyAdmin was able to import the file while I couldn't. Only when I open the file in notepadd++ and saw the end of file then I realized that mysql was unable to find any lines terminated symbol (and I guess it consider all the lines as input to the field; making it complain.)
Anyway after making from \n to \r\n; it work like a charm.
LOAD DATA INFILE '/path_to_csv_folder/db.csv' INTO TABLE table1
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;
Use CSS3
.container {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
-webkit-column-gap: 20px;
-moz-column-gap: 20px;
column-gap: 20px;
}
Browser Support
-webkit-
)-moz-
)-webkit-
)-webkit-
)Response status comes as second parameter in callback, (from docs):
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$scope.actions.data.concat is not a function
same problem with me but i solve the problem by
$scope.actions.data = [].concat($scope.actions.data , data)
You should take a look at Java date formatting, in particular SimpleDateFormat. There's some examples here: http://download.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html - but you can also find a lot more with a quick google.
To do it in place, you can use the RemoveAll method of the "List<>" class along with a custom "Predicate" class...but all that does is clean up the code... under the hood it's doing the same thing you are...but yes, it does it in place, so you do same the temp list.
Otherwise we may change the default property configurator name, setting the property spring.config.name=test
and then having class-path resource
src/test/test.properties
our native instance of org.springframework.boot.SpringApplication
will be auto-configured from this separated test.properties, ignoring application properties;
Benefit: auto-configuration of tests;
Drawback: exposing "spring.config.name" property at C.I. layer
ref: http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
spring.config.name=application # Config file name
You can just use exec
to replace your current shell with a new shell:
Switch to bash
:
exec bash
Switch to zsh
:
exec zsh
This won't affect new terminal windows or anything, but it's convenient.
I was getting the same issue "Cannot open git-upload-pack" in eclipse Juno while trying to clone ('Git Repository Exploring' perspective). https://[username]@[hostName]:[portNumber]/scm/TestRepo.git
Solution : Issue got solved after adding "-Dhttps.protocols=TLSv1" to the eclipse.ini file.
Possible Reason for Error : Some servers does not support TLSv1.2, or TLSv1.1, they might support only TLSv1.0. Java 8 default TLS protocol is 1.2 whereas it is 1.0 with Java 7. For an unknown reason, when Egit connects to the server, it does not fallback to TLSv1.1 after TLS1.2 fails to establish the connection. Don't know if it's an Egit or a Java 8 issue Courtesy : https://www.eclipse.org/forums/index.php/t/1065782/
I would suggest not to create general debug and release tasks if the project is really something that gets compiled and so results in files. You should go with file-tasks which is quite doable in your example, as you state, that your output goes into different directories. Say your project just compiles a test.c file to out/debug/test.out and out/release/test.out with gcc you could setup your project like this:
WAYS = ['debug', 'release']
FLAGS = {}
FLAGS['debug'] = '-g'
FLAGS['release'] = '-O'
def out_dir(way)
File.join('out', way)
end
def out_file(way)
File.join(out_dir(way), 'test.out')
end
WAYS.each do |way|
desc "create output directory for #{way}"
directory out_dir(way)
desc "build in the #{way}-way"
file out_file(way) => [out_dir(way), 'test.c'] do |t|
sh "gcc #{FLAGS[way]} -c test.c -o #{t.name}"
end
end
desc 'build all ways'
task :all => WAYS.map{|way|out_file(way)}
task :default => [:all]
This setup can be used like:
rake all # (builds debug and release)
rake debug # (builds only debug)
rake release # (builds only release)
This does a little more as asked for, but shows my points:
If your RESTFul call sends XML Messages back and forth embedded in the Html Body of the HTTP request, you should be able to have all the benefits of WS-Security such as XML encryption, Cerificates, etc in your XML messages while using whatever security features are available from http such as SSL/TLS encryption.
To count numbers or dates that meet a single test (such as equal to, greater than, less than, greater than or equal to, or less than or equal to), use the COUNTIF function. In Excel 2007 and later, to count numbers or dates that fall within a range (such as greater than 9000 and at the same time less than 22500), you can use the COUNTIFS function. If you are using Excel 2003 or earlier, you can use the SUMPRODUCT function to count the numbers that fall within a range (COUNTIFS was introduced in Excel 2007).
please see more
If you can't use a public/private keys, you can use expect:
#!/usr/bin/expect
spawn rsync SRC DEST
expect "password:"
send "PASS\n"
expect eof
if [catch wait] {
puts "rsync failed"
exit 1
}
exit 0
You will need to replace SRC and DEST with your normal rsync source and destination parameters, and replace PASS with your password. Just make sure this file is stored securely!
Yes. You can use foreach to update the records in linq.There is no performance degrade.
you can verify that the standard Where operator is implemented using the yield construct introduced in C# 2.0.
The use of yield has an interesting benefit which is that the query is not actually evaluated until it is iterated over, either with a foreach statement or by manually using the underlying GetEnumerator and MoveNext methods
For instance,
var query = db.Customers.Where (c => c.Name.StartsWith ("A"));
query = query.Where (c => c.Purchases.Count() >= 2);
var result = query.Select (c => c.Name);
foreach (string name in result) // Only now is the query executed!
Console.WriteLine (name);
Exceptional operators are: First, ElementAt, Sum, Average, All, Any, ToArray and ToList force immediate query evaluation.
So no need to scare to use foreach
for update
the linq result.
In your case code sample given below will be useful to update many properties,
var persons = (from p in Context.person_account_portfolio where p.person_name == personName select p);
//TO update using foreach
foreach(var person in persons)
{
//update property values
}
I hope it helps...
The HTML Tidy library is able to fix some malformed XML files. Running your feeds through that before passing them on to the parser may help.
I always solve this problem doing de following.. Settings>Inspections>Spring Core>Code than you shift from error to warning the severity option
Subtle point here...
There is an implicit typecast for i+j
when j
is a double and i
is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j
where i
is an integer and j
is a double can be described as
i = <int>(<double>i + j)
See: this description of implicit casting
You might want to typecast j
to (int)
in this case for clarity.
I tried the main parts of each answer, to no avail. What finally fixed it for me was to export the following environment variables:
LD_LIBRARY_PATH=/usr/local/lib:~/Qt/5.9.1/gcc_64/lib
QT_QPA_PLATFORM_PLUGIN_PATH=~/Qt/5.9.1/gcc_64/plugins/
content
doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.
Another problem with your code is "
inside a "
block. You should mix '
and "
(class='headingDetail'
).
If content
did support HTML you could end up in an infinite loop where content
is added inside content
.
Try following command sequence on Ubuntu terminal:
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip
there's nothing wrong with using CHAR like that..
I think your problem is that you have a space in your tablename. It should be: charteredflight
or chartered_flight
..
Even in 2009, it seems too many had a very limited idea of what designing for the WORLDWIDE web involved. In 2015, unless designing for a specific country, a blacklist is the only way to accommodate the vast number of characters that may be valid.
The characters to blacklist then need to be chosen according what is illegal for the purpose for which the data is required.
However, sometimes it pays to break down the requirements, and handle each separately. Here look-ahead is your friend. These are sections bounded by (?=)
for positive, and (?!)
for negative, and effectively become AND blocks, because when the block is processed, if not failed, the regex processor will begin at the start of the text with the next block. Effectively, each look-ahead block will be preceded by the ^
, and if its pattern is greedy, include up to the $
. Even the ancient VB6/VBA (Office) 5.5 regex engine supports look-ahead.
So, to build up a full regular expression, start with the look-ahead blocks, then add the blacklisted character block before the final $
.
For example, to limit the total numbers of characters, say between 3 and 15 inclusive, start with the positive look-ahead block (?=^.{3,15}$)
. Note that this needed its own ^
and $
to ensure that it covered all the text.
Now, while you might want to allow _ and -, you may not want to start or end with them, so add the two negative look-ahead blocks, (?!^[_-].+)
for starts, and (?!.+[_-]$)
for ends.
If you don't want multiple _
and -
, add a negative look-ahead block of (?!.*[_-]{2,})
. This will also exclude _-
and -_
sequences.
If there are no more look-ahead blocks, then add the blacklist block before the $
, such as [^<>[\]{\}|\\\/^~%# :;,$%?\0-\cZ]+
, where the \0-\cZ
excludes null and control characters, including NL (\n
) and CR (\r
). The final +
ensures that all the text is greedily included.
Within the Unicode domain, there may well be other code-points or blocks that need to be excluded as well, but certainly a lot less than all the blocks that would have to be included in a whitelist.
The whole regex of all of the above would then be
(?=^.{3,15}$)(?!^[_-].+)(?!.+[_-]$)(?!.*[_-]{2,})[^<>[\]{}|\\\/^~%# :;,$%?\0-\cZ]+$
which you can check out live on https://regex101.com/, for pcre (php), javascript and python regex engines. I don't know where the java regex fits in those, but you may need to modify the regex to cater for its idiosyncrasies.
If you want to include spaces, but not _
, just swap them every where in the regex.
The most useful application for this technique is for the pattern
attribute for HTML input
fields, where a single expression is required, returning a false for failure, thus making the field invalid, allowing input:invalid
css to highlight it, and stopping the form being submitted.
It is Work for me:
language:{"infoEmpty": "No records available",}
I assume that you know how to execute the command using the ProcessBuilder
.
Executing a command from Java always should read the stdout and stderr streams from the process. Otherwise it can happen that the buffer is full and the process cannot continue because writing its stdout or stderr blocks.
#define TRUE 0 // dumbass
The person who did this explained himself some years later - most (if not all) C library functions return 0 as an indication that everything went well. So, he wanted to be able to write code like:
if (memcpy(buffer, packet, BUFFER_SIZE) == TRUE) {
; // rape that packet
}
Needless to say, nobody in our team (tester or developer) ever dared to glance at his code again.
2>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc120-mt-sgd-1_55.lib
In my case, bootstrap/bjam was not available (libraries were precompiled and committed to SCM) on old inherited project. Libraries did not have VC or BOOST versioning in their filenames eg: libboost_regex-mt-sgd.lib
, however Processed /DEFAULTLIB:libboost_regex-vc120-mt-sgd-1_55.lib
was somehow triggered automatically.
Fixed by manually adding the non-versioned filename to:
<AdditionalDependencies>$(DK_BOOST)\lib64\libboost_regex-mt-sgd.lib</AdditionalDependencies>
and blacklisting the ...vc120-mt-sgd-1_55.lib
in
<IgnoreSpecificDefaultLibraries>libboost_regex-vc120-mt-sgd-1_55.lib</IgnoreSpecificDefaultLibraries>
To determine if the array is sparse, it may help to get a proportion of nan values
np.isnan(ndarr).sum() / ndarr.size
If that proportion exceeds a threshold, then use a sparse array, e.g. - https://sparse.pydata.org/en/latest/
In my case, I want to exclude an existing file. Only modifying .gitignore not work. I followed these steps:
git rm --cached dirToFile/file.php
vim .gitignore
git commit -a
In this way, I cleaned from cache the file that I wanted to exclude and after I added it to .gitignore.
One-to-one: Use a foreign key to the referenced table:
student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
# "link back" if you need
You must also put a unique constraint on the foreign key column (addess.student_id
) to prevent multiple rows in the child table (address
) from relating to the same row in the referenced table (student
).
One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:
teachers: teacher_id, first_name, last_name # the "one" side
classes: class_id, class_name, teacher_id # the "many" side
Many-to-many: Use a junction table (example):
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table
Example queries:
-- Getting all students for a class:
SELECT s.student_id, last_name
FROM student_classes sc
INNER JOIN students s ON s.student_id = sc.student_id
WHERE sc.class_id = X
-- Getting all classes for a student:
SELECT c.class_id, name
FROM student_classes sc
INNER JOIN classes c ON c.class_id = sc.class_id
WHERE sc.student_id = Y
You got a bunch of good answers, so I'll just throw out a suggestion. If you are going to be working on this project for more than 2 days, download eclipse or netbeans and build your project in there.
If you are not normally a java programmer, then the help it will give you will be invaluable.
It's not worth the 1/2 hour download/install if you are only spending 2 hours on it.
Both have hotkeys/menu items to "Fix imports", with this you should never have to worry about imports again.
I do not have a solution, just another flavour of the "present at compilation, absent at run time" case.
I was trying to use a very convenient method from a JUnit test class from another test class which resides in a different module. That's a no-no, since test code is not part of the packaged jar, but I didn't realize because it appears visible for the user class from within Eclipse.
My solution was to place the method in a existing utilities class that is part of the production code.
py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
@Mahender, you probably meant the difference between \W
(instead of \w
) and \b
. If not, then I would agree with @BoltClock and @jwismar above. Otherwise continue reading.
\W
would match any non-word character and so its easy to try to use it to match word boundaries. The problem is that it will not match the start or end of a line. \b
is more suited for matching word boundaries as it will also match the start or end of a line. Roughly speaking (more experienced users can correct me here) \b
can be thought of as (\W|^|$)
. [Edit: as @?mega mentions below, \b
is a zero-length match so (\W|^|$)
is not strictly correct, but hopefully helps explain the diff]
Quick example: For the string Hello World
, .+\W
would match Hello_
(with the space) but will not match World
. .+\b
would match both Hello
and World
.
As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....
The ?
and the OR
needs to be seperated by a space character. Do it wherever needed in the query string.
Here is an article on how to check and or install new patches :
To find the OPatch tool setup your database enviroment variables and then issue this comand:
cd $ORACLE_HOME/OPatch
> pwd
/oracle/app/product/10.2.0/db_1/OPatch
To list all the patches applies to your database use the lsinventory
option:
[oracle@DCG023 8828328]$ opatch lsinventory
Oracle Interim Patch Installer version 11.2.0.3.4
Copyright (c) 2012, Oracle Corporation. All rights reserved.
Oracle Home : /u00/product/11.2.0/dbhome_1
Central Inventory : /u00/oraInventory
from : /u00/product/11.2.0/dbhome_1/oraInst.loc
OPatch version : 11.2.0.3.4
OUI version : 11.2.0.1.0
Log file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/opatch2013-11-13_13-55-22PM_1.log
Lsinventory Output file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/lsinv/lsinventory2013-11-13_13-55-22PM.txt
Installed Top-level Products (1):
Oracle Database 11g 11.2.0.1.0
There are 1 products installed in this Oracle Home.
Interim patches (1) :
Patch 8405205 : applied on Mon Aug 19 15:18:04 BRT 2013
Unique Patch ID: 11805160
Created on 23 Sep 2009, 02:41:32 hrs PST8PDT
Bugs fixed:
8405205
OPatch succeeded.
To list the patches using sql :
select * from registry$history;
You should now use the .on()
function to bind events.
Size of a pointer should be 8 byte on any 64-bit C/C++ compiler, but not necessarily size of int.
Whatever approach you take, make sure in the end that you have an updated version of curl and libcurl. You can do curl --version
and see the versions.
Here's what I did to get the latest curl version installed in Ubuntu:
sudo add-apt-repository "deb http://mirrors.kernel.org/ubuntu wily main"
sudo apt-get update
sudo apt-get install curl
The answers above check if a filesystem contains a path that is a file or directory. But it doesn't identify if a given path alone is a file or directory.
The answer is to identify directory-based paths using "/." like --> "/c/dos/run/." <-- trailing period.
Like a path of a directory or file that has not been written yet. Or a path from a different computer. Or a path where both a file and directory of the same name exists.
// /tmp/
// |- dozen.path
// |- dozen.path/.
// |- eggs.txt
//
// "/tmp/dozen.path" !== "/tmp/dozen.path/"
//
// Very few fs allow this. But still. Don't trust the filesystem alone!
// Converts the non-standard "path-ends-in-slash" to the standard "path-is-identified-by current "." or previous ".." directory symbol.
function tryGetPath(pathItem) {
const isPosix = pathItem.includes("/");
if ((isPosix && pathItem.endsWith("/")) ||
(!isPosix && pathItem.endsWith("\\"))) {
pathItem = pathItem + ".";
}
return pathItem;
}
// If a path ends with a current directory identifier, it is a path! /c/dos/run/. and c:\dos\run\.
function isDirectory(pathItem) {
const isPosix = pathItem.includes("/");
if (pathItem === "." || pathItem ==- "..") {
pathItem = (isPosix ? "./" : ".\\") + pathItem;
}
return (isPosix ? pathItem.endsWith("/.") || pathItem.endsWith("/..") : pathItem.endsWith("\\.") || pathItem.endsWith("\\.."));
}
// If a path is not a directory, and it isn't empty, it must be a file
function isFile(pathItem) {
if (pathItem === "") {
return false;
}
return !isDirectory(pathItem);
}
Node version: v11.10.0 - Feb 2019
Last thought: Why even hit the filesystem?
In my case this was the error.
Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.T4CConnection.isValid(I)Z at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:917) at org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282) at org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:356) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2306) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2289) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2038) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1532) at beans.Test.main(Test.java:24)
Solution: I just change ojdbc14.jar
to ojdbc6.jar
To avoid problems with the batch parser (e.g. exclamation point), look at Problem with search and replace batch file.
Following modification of aflat's script will include special characters like exclamation points.
@echo off
setlocal DisableDelayedExpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=bath
set REPLACETEXT=hello
set OUTPUTLINE=
for /f "tokens=1,* delims=¶" %%A in ( '"type %INTEXTFILE%"') do (
SET string=%%A
setlocal EnableDelayedExpansion
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!
>> %OUTTEXTFILE% echo(!modified!
endlocal
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%
If you have no references, like foreign keys, you can do this. I do it a lot when testing proofs of concept and the test data gets duplicated.
SELECT DISTINCT [col1],[col2],[col3],[col4],[col5],[col6],[col7]
INTO [newTable]
FROM [oldTable]
Go into the object explorer and delete the old table.
Rename the new table with the old table's name.
By default, the access modifier for a class is internal
. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.
The CGRectZero
constant is equal to a rectangle at position (0,0)
with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.
But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)
Note that you also need to use addSubview
otherwise your view is not added to the view hierarchy.
Your concatenation syntax is correct.
Most likely the callback function isn't even being called. You can test that by putting an alert()
, console.log()
or debugger
line in that function.
If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail()
handler after $.post()
to find out what the error is, e.g.:
$.post('ajaxskeleton.php', {
red: text
}, function(){
$('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(arguments);
});
I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Dim SQL As String
SQL = _
"SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
"c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
"FROM tblClient AS c " & _
"WHERE c.ClientID = @ClientID"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
.Parameters.Append prm
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
mstrLastName = Nz(!LastName, "")
mstrFirstName = Nz(!FirstName, "")
mstrMI = Nz(!MI, "")
mdDOB = !DOB
mstrSSN = Nz(!SSN, "")
mlngRaceID = Nz(!RaceID, -1)
mlngEthnicityID = Nz(!EthnicityID, -1)
mlngGenderID = Nz(!GenderID, -1)
mbooDeleted = Deleted
mdRecordDate = Nz(!RecordDate, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
I started seeing this error after installing the latest command-line tools update (6.1) on Yosemite (10.10.1). In this particular case, a reboot of the system fixed the error (I had not rebooted since the update).
Mentioning this in case anyone with the same problem comes across this page, like I did.
In Bootstrap 3 I've added a table-no-border class
.table-no-border>thead>tr>th,
.table-no-border>tbody>tr>th,
.table-no-border>tfoot>tr>th,
.table-no-border>thead>tr>td,
.table-no-border>tbody>tr>td,
.table-no-border>tfoot>tr>td {
border-top: none;
}
See API for String class:
Returns a copy of the string, with leading and trailing whitespace omitted.
Whitespace on both sides is removed:
Note that trim()
does not change the String instance, it will return a new object:
String original = " content ";
String withoutWhitespace = original.trim();
// original still refers to " content "
// and withoutWhitespace refers to "content"
Try this...
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId="
+ pet.getOwner().getId();
}
}
}
Try
$(bla).click(function(){
if (something) {
console.log("A:"+$target.prev("input")) // gives out the right object
$target.toggleClass("open").prev("input").attr("disabled", "disabled");
}else{
console.log("A:"+$target.prev("input")) // any thing from there for a single click?
$target.toggleClass("open").prev("input").removeAttr("disabled"); //this works
}
});
If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?
public void fetchData(ResultSet res, JTable table) throws SQLException{
ResultSetMetaData metaData = res.getMetaData();
int fieldsCount = metaData.getColumnCount();
for (int i = 1; i <= fieldsCount; i++)
((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
if (!res.first())
JOptionPane.showMessageDialog(rootPane, "no data!");
else
do {
Vector<Object> v = new Vector<Object>();
for (int i = 1; i <= fieldsCount; i++)
v.addElement(res.getObject(i));
((DefaultTableModel) table.getModel()).addRow(v);
} while (res.next());
res.close();
}
I think the best solution I have come across is on this stackoverflow.
This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.
$('body').on('touchstart', function() {});
Hope this helps.
If you want formated number then use
SELECT TO_CHAR(number, 'fmt')
FROM DUAL;
SELECT TO_CHAR('123', 999.99)
FROM DUAL;
Result 123.00
Be aware that the path under src/main/resources must match the package path of your .class files wishing to access the resource. See my answer here.
Primitive Data Types :
Reference/Object Data Types :
Try this:
$('#form').submit(function(eventObj) {
$(this).append('<input type="hidden" name="field_name" value="value" /> ');
return true;
});
If you'd like to simply open a fancybox when a javascript function is called. Perhaps in your code flow and not as a result of a click. Here's how you do it:
function openFancybox() {
$.fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true,
'href' : '#contentdiv'
});
}
This creates the box using "contentdiv" and opens it.
I used Joseph Johnson created AndroidBug5497Workaround class but getting black space between softkeyboard and the view. I referred this link Greg Ennis. After doing some changes to the above this is my final working code.
public class SignUpActivity extends Activity {
private RelativeLayout rlRootView; // this is my root layout
private View rootView;
private ViewGroup contentContainer;
private ViewTreeObserver viewTreeObserver;
private ViewTreeObserver.OnGlobalLayoutListener listener;
private Rect contentAreaOfWindowBounds = new Rect();
private FrameLayout.LayoutParams rootViewLayout;
private int usableHeightPrevious = 0;
private View mDecorView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
mDecorView = getWindow().getDecorView();
contentContainer =
(ViewGroup) this.findViewById(android.R.id.content);
listener = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
};
rootView = contentContainer.getChildAt(0);
rootViewLayout = (FrameLayout.LayoutParams)
rootView.getLayoutParams();
rlRootView = (RelativeLayout) findViewById(R.id.rlRootView);
rlRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = rlRootView.getRootView().getHeight() - rlRootView.getHeight();
if (heightDiff > Util.dpToPx(SignUpActivity.this, 200)) {
// if more than 200 dp, it's probably a keyboard...
// Logger.info("Soft Key Board ", "Key board is open");
} else {
Logger.info("Soft Key Board ", "Key board is CLOSED");
hideSystemUI();
}
}
});
}
// This snippet hides the system bars.
protected void hideSystemUI() {
// Set the IMMERSIVE flag.
// Set the content to appear under the system bars so that the
content
// doesn't resize when the system bars hide and show.
mDecorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
@Override
protected void onPause() {
super.onPause();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeOnGlobalLayoutListener(listener);
}
}
@Override
protected void onResume() {
super.onResume();
if (viewTreeObserver == null || !viewTreeObserver.isAlive()) {
viewTreeObserver = rootView.getViewTreeObserver();
}
viewTreeObserver.addOnGlobalLayoutListener(listener);
}
@Override
protected void onDestroy() {
super.onDestroy();
rootView = null;
contentContainer = null;
viewTreeObserver = null;
}
private void possiblyResizeChildOfContent() {
contentContainer.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds);
int usableHeightNow = contentAreaOfWindowBounds.height();
if (usableHeightNow != usableHeightPrevious) {
rootViewLayout.height = usableHeightNow;
rootView.layout(contentAreaOfWindowBounds.left,
contentAreaOfWindowBounds.top, contentAreaOfWindowBounds.right, contentAreaOfWindowBounds.bottom);
rootView.requestLayout();
usableHeightPrevious = usableHeightNow;
} else {
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
}
}
The equivalent is:
python3 -m http.server
My favorite way to handle a thread is to encapsulate it inside a C++ object. Here's an example:
class MyThreadClass
{
public:
MyThreadClass() {/* empty */}
virtual ~MyThreadClass() {/* empty */}
/** Returns true if the thread was successfully started, false if there was an error starting the thread */
bool StartInternalThread()
{
return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
}
/** Will not return until the internal thread has exited. */
void WaitForInternalThreadToExit()
{
(void) pthread_join(_thread, NULL);
}
protected:
/** Implement this method in your subclass with the code you want your thread to run. */
virtual void InternalThreadEntry() = 0;
private:
static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}
pthread_t _thread;
};
To use it, you would just create a subclass of MyThreadClass with the InternalThreadEntry() method implemented to contain your thread's event loop. You'd need to call WaitForInternalThreadToExit() on the thread object before deleting the thread object, of course (and have some mechanism to make sure the thread actually exits, otherwise WaitForInternalThreadToExit() would never return)
For me, such tags are enabled by default. You can configure which task tags should be used in the workspace options: Java > Compiler > Task tags
Check if they are enabled in this location, and that should be enough to have them appear in the Task list (or the Markers view).
Extra note: reinstalling Eclipse won't change anything most of the time if you work on the same workspace. Most settings used by Eclipse are stored in the .metadata folder, in your workspace folder.
This works:
assertThat(list,IsEmptyCollection.empty())
pd.DataFrame.loc
can take one or two indexers. For the rest of the post, I'll represent the first indexer as i
and the second indexer as j
.
If only one indexer is provided, it applies to the index of the dataframe and the missing indexer is assumed to represent all columns. So the following two examples are equivalent.
df.loc[i]
df.loc[i, :]
Where :
is used to represent all columns.
If both indexers are present, i
references index values and j
references column values.
Now we can focus on what types of values i
and j
can assume. Let's use the following dataframe df
as our example:
df = pd.DataFrame([[1, 2], [3, 4]], index=['A', 'B'], columns=['X', 'Y'])
loc
has been written such that i
and j
can be
scalars that should be values in the respective index objects
df.loc['A', 'Y']
2
arrays whose elements are also members of the respective index object (notice that the order of the array I pass to loc
is respected
df.loc[['B', 'A'], 'X']
B 3
A 1
Name: X, dtype: int64
Notice the dimensionality of the return object when passing arrays. i
is an array as it was above, loc
returns an object in which an index with those values is returned. In this case, because j
was a scalar, loc
returned a pd.Series
object. We could've manipulated this to return a dataframe if we passed an array for i
and j
, and the array could've have just been a single value'd array.
df.loc[['B', 'A'], ['X']]
X
B 3
A 1
boolean arrays whose elements are True
or False
and whose length matches the length of the respective index. In this case, loc
simply grabs the rows (or columns) in which the boolean array is True
.
df.loc[[True, False], ['X']]
X
A 1
In addition to what indexers you can pass to loc
, it also enables you to make assignments. Now we can break down the line of code you provided.
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
iris_data['class'] == 'versicolor'
returns a boolean array.class
is a scalar that represents a value in the columns object.iris_data.loc[iris_data['class'] == 'versicolor', 'class']
returns a pd.Series
object consisting of the 'class'
column for all rows where 'class'
is 'versicolor'
When used with an assignment operator:
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
We assign 'Iris-versicolor'
for all elements in column 'class'
where 'class'
was 'versicolor'
i set my bind-address correctly as above but forgot to restart the mysql server (or reboot) :) face palm - so that's the source of this error for me!
I would sugest using array native reverse method is always better choice over creating filter or using $index
.
<div ng-repeat="friend in friends.reverse()">{{friend.name}}</div>
Here is a pure PHP class to perform backups on MySQL databases not using mysqldump or mysql commands: Backing up MySQL databases with pure PHP
Ad-hoc Query -
If You need the text to be centered, and the image to be besides it, like this:
Then You can achieve it with this widget tree:
RaisedButton(
onPressed: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(child: Text(
'Push it! '*10,
textAlign: TextAlign.center,
),),
Image.network(
'https://picsum.photos/250?image=9',
),
],
),
),
it is for empty table:
ALTER TABLE `table_name` AUTO_INCREMENT = 1;
if you have data but you want to tidy up it, i recommend use this :
ALTER TABLE `table_name` DROP `auto_colmn`;
ALTER TABLE `table_name` ADD `auto_colmn` INT( {many you want} ) NOT NULL AUTO_INCREMENT FIRST ,ADD PRIMARY KEY (`auto_colmn`);
Marek Sebera's is great most of the time, but if you're like me and find that you need to check the iOS version frequently, you don't want to constantly run a macro in memory because you'll experience a very slight slowdown, especially on older devices.
Instead, you want to compute the iOS version as a float once and store it somewhere. In my case, I have a GlobalVariables
singleton class that I use to check the iOS version in my code using code like this:
if ([GlobalVariables sharedVariables].iOSVersion >= 6.0f) {
// do something if iOS is 6.0 or greater
}
To enable this functionality in your app, use this code (for iOS 5+ using ARC):
GlobalVariables.h:
@interface GlobalVariables : NSObject
@property (nonatomic) CGFloat iOSVersion;
+ (GlobalVariables *)sharedVariables;
@end
GlobalVariables.m:
@implementation GlobalVariables
@synthesize iOSVersion;
+ (GlobalVariables *)sharedVariables {
// set up the global variables as a static object
static GlobalVariables *globalVariables = nil;
// check if global variables exist
if (globalVariables == nil) {
// if no, create the global variables class
globalVariables = [[GlobalVariables alloc] init];
// get system version
NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
// separate system version by periods
NSArray *systemVersionComponents = [systemVersion componentsSeparatedByString:@"."];
// set ios version
globalVariables.iOSVersion = [[NSString stringWithFormat:@"%01d.%02d%02d", \
systemVersionComponents.count < 1 ? 0 : \
[[systemVersionComponents objectAtIndex:0] integerValue], \
systemVersionComponents.count < 2 ? 0 : \
[[systemVersionComponents objectAtIndex:1] integerValue], \
systemVersionComponents.count < 3 ? 0 : \
[[systemVersionComponents objectAtIndex:2] integerValue] \
] floatValue];
}
// return singleton instance
return globalVariables;
}
@end
Now you're able to easily check the iOS version without running macros constantly. Note in particular how I converted the [[UIDevice currentDevice] systemVersion]
NSString to a CGFloat that is constantly accessible without using any of the improper methods many have already pointed out on this page. My approach assumes the version string is in the format n.nn.nn (allowing for later bits to be missing) and works for iOS5+. In testing, this approach runs much faster than constantly running the macro.
Hope this helps anyone experiencing the issue I had!
In my opinion, it's better to explicitly mark the end of the function by comment
def func():
# funcbody
## end of subroutine func ##
The point is that some subroutine is very long and is not convenient to scroll up the editor to check for which function is ended. In addition, if you use Sublime, you can right click -> Goto Definition and it will automatically jump to the subroutine declaration.
If you are using Flask-Restful like me, it is also possible this way:
api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint = 'user')
a then in your Resource class:
class UserAPI(Resource):
def get(self, userId, username=None):
pass
boolean
is a primitive type, and therefore can not be null.
Its boxed type, Boolean
, can be null.
The function is probably returning a Boolean
as opposed to a boolean
, so assigning the result to a Boolean
-type variable will allow you to test for nullity.
in visual studio 2012 you can simply select the browser you want to debug with from the dropdown box placed just over the code editor
There are two ways you can use spinner:
static way
android:spinnerMode="dialog"
and then set:
android:prompt="@string/hint_resource"
dynamic way
spinner.setPrompt("Gender");
Note: It will work like a Hint but not actually it is.
May it help!
For Chrome and Firefox, I have been using a purely JavaScript method.
(My application cannot make use of a package such as Blob.js
because it is served from a special engine: a DSP with a WWWeb server crammed in and little room for anything at all.)
function FileSave(sourceText, fileIdentity) {
var workElement = document.createElement("a");
if ('download' in workElement) {
workElement.href = "data:" + 'text/plain' + "charset=utf-8," + escape(sourceText);
workElement.setAttribute("download", fileIdentity);
document.body.appendChild(workElement);
var eventMouse = document.createEvent("MouseEvents");
eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
workElement.dispatchEvent(eventMouse);
document.body.removeChild(workElement);
} else throw 'File saving not supported for this browser';
}
Notes, caveats, and weasel-words:
sourceText
is larger than a MB, Chrome sometimes (only sometimes) gets stuck in its own download without any failure indication; Firefox, so far, has not exhibited this behavior. The cause might be some blob limitation in Chrome. Frankly, I just don't know; if anybody has any ideas how to correct (or at least detect), please post. If the download anomaly occurs, when the Chrome browser is closed, it generates a diagnostic such as
Please see this, more current solution before using a custom parsing function like below, or a 3rd party library.
The a code below works and is still useful in situations where URLSearchParams
is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.
function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") return;
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=", 2);
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) parms[n] = [];
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}
Use as follows:
var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
urlParams = parseURLParams(urlString);
which returns a an object like this:
{
"a" : ["a a"], /* param values are always returned as arrays */
"b b": ["b"], /* param names can have special chars as well */
"c" : ["1", "2"] /* an URL param can occur multiple times! */
"d" : [null] /* parameters without values are set to null */
}
So
parseURLParams("www.mints.com?name=something")
gives
{name: ["something"]}
EDIT: The original version of this answer used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser.
Just put close cross like drawableEnd
in your EditText
:
<EditText
...
android:drawableEnd="@drawable/ic_close"
android:drawablePadding="8dp"
... />
and use extension to handle click (or use OnTouchListener
directly on your EditText
):
fun EditText.onDrawableEndClick(action: () -> Unit) {
setOnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_UP) {
v as EditText
val end = if (v.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL)
v.left else v.right
if (event.rawX >= (end - v.compoundPaddingEnd)) {
action.invoke()
return@setOnTouchListener true
}
}
return@setOnTouchListener false
}
}
extension usage:
editText.onDrawableEndClick {
// TODO clear action
etSearch.setText("")
}
echo "<span style = 'font-color: #ff0000'> Movie List for {$key} 2013 </span>";
Variables are only expanded inside double quotes, not single quotes. Since the above uses double quotes for the PHP string, I switched to single quotes for the embedded HTML, to avoid having to escape the quotes.
The other problem with your code is that <style>
tags are for entering CSS blocks, not for styling individual elements. To style an element, you need an element tag with a style
attribute; <span>
is the simplest element -- it doesn't have any formatting of its own, it just serves as a place to attach attributes.
Another popular way to write it is with string concatenation:
echo '<span style = "font-color: #ff0000"> Movie List for ' . $key . ' 2013 </span>';
My best guess is that this is not a bug, but a feature of Sql 2012. ;-) In other contexts, you'd be happy to retain your cr-lf's, like when copying a big chunk of text. It's just that it doesn't work well in your situation.
You could always strip them out in your select. This would make your query for as you intend in both versions:
select REPLACE(col, CHAR(13) + CHAR(10), ', ') from table
You should use partial views. I use the following approach:
Use a view model so you're not passing your domain models to your views:
public class EditPersonViewModel
{
public int Id { get; set; } // this is only used to retrieve record from Db
public string Name { get; set; }
public string Age { get; set; }
}
In your PersonController:
[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{
var viewModel = new EditPersonViewModel();
viewModel.Id = id;
return PartialView("_EditPersonPartial", viewModel);
}
[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
if (ModelState.IsValid)
{
var toUpdate = personRepo.Find(viewModel.Id);
toUpdate.Name = viewModel.Name;
toUpdate.Age = viewModel.Age;
personRepo.InsertOrUpdate(toUpdate);
personRepo.Save();
return View("Index");
}
}
Next create a partial view called _EditPersonPartial
. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.
@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "list-of-people"
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
<div class="modal-body">
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
</div>
<div class="modal-footer">
<button class="btn btn-inverse" type="submit">Save</button>
</div>
}
Now somewhere in your application, say another partial _peoplePartial.cshtml etc:
<div>
@foreach(var person in Model.People)
{
<button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
}
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
<div id="edit-person-container"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.edit-person').click(function () {
var url = "/Person/EditPerson"; // the url to the controller
var id = $(this).attr('data-id'); // the id that's given to each button in the list
$.get(url + '/' + id, function (data) {
$('#edit-person-container').html(data);
$('#edit-person').modal('show');
});
});
});
</script>
to get the last row of a SQL-Database use this sql string:
SELECT * FROM TableName WHERE id=(SELECT max(id) FROM TableName);
Output:
Last Line of your db!
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
Add this if you want the number of citations to appear in order in the document they will only be unsorted in the reference page:
\bibliographystyle{unsrt}
Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.
Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET HttpModule
s basically have nearly as much power as an ISAPI filter would have had and ASP.NET HttpHandler
s can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.
Git itself has no provision to specify the repository name. The root directory's name is the single source of truth pertaining to the repository name.
The .git/description
though is used only by some applications, like GitWeb.
The best practice for this sort of situation is to create a method that hold all the logics, and call the method in both events, rather than calling an event from another event;
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
LogicMethod()
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
LogicMethod()
End Sub
Private Sub LogicMethod()
// All your logic goes here
End Sub
In case you need the properties of the EventArgs (e), you can easily pass it through parameters in your method, that will avoid errors if ever the sender is of different types. But that won't be a problem in your case, as both senders are of type Button.
The combined answer for writing to a file can be;
MemoryStream ms = new MemoryStream();
FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
we can generate wsdl file from xsd but you have to use oracle enterprise pack of eclipse(OEPE). simply create xsd and then right click->new->wsdl...
string.Format
will not change the original value, but it will return a formatted string. For example:
Console.WriteLine("Earnings this week: {0:0.00}", answer);
Note: Console.WriteLine
allows inline string formatting. The above is equivalent to:
Console.WriteLine("Earnings this week: " + string.Format("{0:0.00}", answer));
A better and optimised solution to display multiple validation messages for a single element would be like this.
<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
<span class="error" ng-message="required"> <your message> </span>
<span class="error" ng-message="size"> <your message> </span>
<span class="error" ng-message="filetype"> <your message> </span>
</div>
Controller Code should be the one suggested by @ Ben Lesh
on tomcat v.7 (vanilla installation)
in your conf/server.xml add the following bit towards the end of the file, just before the </Host>
closing tag:
<Context path="" docBase="app_name">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
Note that docBase attribute. It's the important bit. You either make sure you've deployed app_name before you change your root web app, or just copy your unpacked webapp (app_name) into your tomcat's webapps folder. Startup, visit root, see your app_name there!
This snippet works in the specific situation where you have a boolean: it answers "how many non-Ns are there?".
SELECT LEN(REPLACE(col, 'N', ''))
If, in a different situation, you were actually trying to count the occurrences of a certain character (for example 'Y') in any given string, use this:
SELECT LEN(col) - LEN(REPLACE(col, 'Y', ''))
This is now possible with flex box. Just set the 'display' of parent div as 'flex' and set the 'margin-top' property to 'auto'. This does not distort any property of both the div.
.parent {_x000D_
display: flex;_x000D_
height: 100px;_x000D_
border: solid 1px #0f0f0f;_x000D_
}_x000D_
.child {_x000D_
margin-top: auto;_x000D_
border: solid 1px #000;_x000D_
width: 40px;_x000D_
word-break: break-all;_x000D_
}
_x000D_
<div class=" parent">_x000D_
<div class="child">I am at the bottom!</div>_x000D_
</div>
_x000D_
Have you already tried like
var open_link = window.open('','_blank');
open_link.location="somepage.html";
I assume you want to know the performance difference between the following:
WHERE foo IN ('a', 'b', 'c')
WHERE foo = 'a' OR foo = 'b' OR foo = 'c'
According to the manual for MySQL if the values are constant IN
sorts the list and then uses a binary search. I would imagine that OR
evaluates them one by one in no particular order. So IN
is faster in some circumstances.
The best way to know is to profile both on your database with your specific data to see which is faster.
I tried both on a MySQL with 1000000 rows. When the column is indexed there is no discernable difference in performance - both are nearly instant. When the column is not indexed I got these results:
SELECT COUNT(*) FROM t_inner WHERE val IN (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000);
1 row fetched in 0.0032 (1.2679 seconds)
SELECT COUNT(*) FROM t_inner WHERE val = 1000 OR val = 2000 OR val = 3000 OR val = 4000 OR val = 5000 OR val = 6000 OR val = 7000 OR val = 8000 OR val = 9000;
1 row fetched in 0.0026 (1.7385 seconds)
So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.
In addition to Guffa's answer, you could use this variant to have a more shorthanded notation.
public static bool ScrambledEquals<T>(this IEnumerable<T> list1, IEnumerable<T> list2)
{
var deletedItems = list1.Except(list2).Any();
var newItems = list2.Except(list1).Any();
return !newItems && !deletedItems;
}
A Problem with csgillespie solution appears, when You have an logarithmic X axis. The you will have a different length of the small bars on the right an the left side (the epsilon follows the x-values).
You should better use the errbar
function from the Hmisc
package:
d = data.frame(
x = c(1:5)
, y = c(1.1, 1.5, 2.9, 3.8, 5.2)
, sd = c(0.2, 0.3, 0.2, 0.0, 0.4)
)
##install.packages("Hmisc", dependencies=T)
library("Hmisc")
# add error bars (without adjusting yrange)
plot(d$x, d$y, type="n")
with (
data = d
, expr = errbar(x, y, y+sd, y-sd, add=T, pch=1, cap=.1)
)
# new plot (adjusts Yrange automatically)
with (
data = d
, expr = errbar(x, y, y+sd, y-sd, add=F, pch=1, cap=.015, log="x")
)
I had the following hosts file
127.0.0.1 localhost
192.168.1.2 localhost
and i started getting the error continously and it was very annoying
“Can't bind to local 8600 for debugger”
“Can't bind to local 8601 for debugger”
“Can't bind to local 8602 for debugger” and so on
I deleted the second line from the hosts file
192.168.1.2 localhost
and everything is back to normal.
Hope this helps.
first, store the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
in subsequent request, check how long ago they made their previous request (10 minutes in this example)
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
Alternatively, by changing a line of the above code:
# df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.date = df.date.apply(lambda d: datetime.datetime.fromtimestamp(int(d)).strftime('%Y-%m-%d'))
It should also work.
The method shouldShowRequestPermissionRationale() can be used to check whether the user selected the 'never asked again' option and denied the permission. There's plenty of code examples, so I would rather explain how to use it for such a purpose, because I think its name and its implementation makes this more complicated that it actually is.
As explained in Requesting Permissions at Run Time, that method returns true if the option 'never ask again' is visible, false otherwise; so it returns false the very first time a dialog is shown, then from the second time on it returns true, and only if the user deny the permission selecting the option, at that point it returns false again.
To detect such a case, either you can detect the sequence false-true-false, or (more simple) you can have a flag which keeps track of the initial time the dialog is shown. After that, that method returns either true or false, where the false will allow you to detect when the option is selected.
Map the array is the quickest and cleanest.
var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })
will return values as an array like:
array => [2,3]
assuming castle and barn were checked and the others were not.
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
Same Answer in Swift 4.2
For UILable
extension UILabel {
func underline() {
if let textString = self.text {
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: NSRange(location: 0, length: textString.count))
self.attributedText = attributedString
}
}
}
Call for UILabel like below
myLable.underline()
For UIButton
extension UIButton {
func underline() {
if let textString = self.titleLabel?.text {
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: NSRange(location: 0, length: textString.count))
self.setAttributedTitle(attributedString, for: .normal)
}
}
}
Call for UIButton like below
myButton.underline()
I looked into above answers and some of them are force unwrapping text value. I will suggest to get value by safely unwrapping. This will avoid crash in case of nil value. Hope This helps :)
As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils
module (Thanks Oliver)
Here is the proper way to do it:
#xlrd, xlutils and xlwt modules need to be installed.
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook("names.xls")
wb = copy(rb)
s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')
This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.
You could use tf.config.set_visible_devices
. One possible function that allows you to set if and which GPUs to use is:
import tensorflow as tf
def set_gpu(gpu_ids_list):
gpus = tf.config.list_physical_devices('GPU')
if gpus:
try:
gpus_used = [gpus[i] for i in gpu_ids_list]
tf.config.set_visible_devices(gpus_used, 'GPU')
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
except RuntimeError as e:
# Visible devices must be set before GPUs have been initialized
print(e)
Suppose you are on a system with 4 GPUs and you want to use only two GPUs, the one with id = 0
and the one with id = 2
, then the first command of your code, immediately after importing the libraries, would be:
set_gpu([0, 2])
In your case, to use only the CPU, you can invoke the function with an empty list:
set_gpu([])
For completeness, if you want to avoid that the runtime initialization will allocate all memory on the device, you can use tf.config.experimental.set_memory_growth
.
Finally, the function to manage which devices to use, occupying the GPUs memory dynamically, becomes:
import tensorflow as tf
def set_gpu(gpu_ids_list):
gpus = tf.config.list_physical_devices('GPU')
if gpus:
try:
gpus_used = [gpus[i] for i in gpu_ids_list]
tf.config.set_visible_devices(gpus_used, 'GPU')
for gpu in gpus_used:
tf.config.experimental.set_memory_growth(gpu, True)
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
except RuntimeError as e:
# Visible devices must be set before GPUs have been initialized
print(e)
You need to wrap the text in a div
element and include the absolutely positioned element inside of it.
<div class="container">
<div class="inner">
<div class="full-height"></div>
[Your text here]
</div>
</div>
Css:
.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }
Setting the inner div's position to relative
makes the absolutely position elements inside of it base their position and height on it rather than on the .container
div, which has a fixed height. Without the inner, relatively positioned div
, the .full-height
div will always calculate its dimensions and position based on .container
.
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
position: relative;_x000D_
border: solid 1px red;_x000D_
height: 256px;_x000D_
width: 256px;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
position: relative;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 128px;_x000D_
bottom: 0;_x000D_
height: 100%;_x000D_
background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
<div class="inner">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
quidem._x000D_
</div>_x000D_
</div>
_x000D_
Say the other guy created bar on top of foo, but you created baz in the meantime and then merged, giving a history of
$ git lola * 2582152 (HEAD, master) Merge branch 'otherguy' |\ | * c7256de (otherguy) bar * | b7e7176 baz |/ * 9968f79 foo
Note: git lola is a non-standard but useful alias.
No dice with git revert
:
$ git revert HEAD fatal: Commit 2582152... is a merge but no -m option was given.
Charles Bailey gave an excellent answer as usual. Using git revert
as in
$ git revert --no-edit -m 1 HEAD [master e900aad] Revert "Merge branch 'otherguy'" 0 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 bar
effectively deletes bar
and produces a history of
$ git lola * e900aad (HEAD, master) Revert "Merge branch 'otherguy'" * 2582152 Merge branch 'otherguy' |\ | * c7256de (otherguy) bar * | b7e7176 baz |/ * 9968f79 foo
But I suspect you want to throw away the merge commit:
$ git reset --hard HEAD^ HEAD is now at b7e7176 baz $ git lola * b7e7176 (HEAD, master) baz | * c7256de (otherguy) bar |/ * 9968f79 foo
As documented in the git rev-parse
manual
<rev>^
, e.g. HEAD^,v1.5.1^0
A suffix^
to a revision parameter means the first parent of that commit object.^<n>
means the n-th parent (i.e.<rev>^
is equivalent to<rev>^1
). As a special rule,<rev>^0
means the commit itself and is used when<rev>
is the object name of a tag object that refers to a commit object.
so before invoking git reset
, HEAD^
(or HEAD^1
) was b7e7176 and HEAD^2
was c7256de, i.e., respectively the first and second parents of the merge commit.
Be careful with git reset --hard
because it can destroy work.
You should \usepackage{longtable}
.
It depends on whether you process IDNs before or after the IDN toASCII
algorithm (that is, do you see the domain name pa??de??µa.d???µ?
in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp
?).
In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:
U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).
and U+002E (.) of course; the rules for labels allow the others, with dots between labels.
If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.
Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar
.
I just stumbled upon this and using @b_stil's snippet, I was able to figure the culprit column. And on futher investigation, I figured i needed to trim the column just like @Liji Chandran suggested but I was using IExcelDataReader and I couldn't figure out an easy way to validate and trim each of my 160 columns.
Then I stumbled upon this class, (ValidatingDataReader) class from CSVReader.
Interesting thing about this class is that it gives you the source and destination columns data length, the culprit row and even the column value that's causing the error.
All I did was just trim all (nvarchar, varchar, char and nchar) columns.
I just changed my GetValue
method to this:
object IDataRecord.GetValue(int i)
{
object columnValue = reader.GetValue(i);
if (i > -1 && i < lookup.Length)
{
DataRow columnDef = lookup[i];
if
(
(
(string)columnDef["DataTypeName"] == "varchar" ||
(string)columnDef["DataTypeName"] == "nvarchar" ||
(string)columnDef["DataTypeName"] == "char" ||
(string)columnDef["DataTypeName"] == "nchar"
) &&
(
columnValue != null &&
columnValue != DBNull.Value
)
)
{
string stringValue = columnValue.ToString().Trim();
columnValue = stringValue;
if (stringValue.Length > (int)columnDef["ColumnSize"])
{
string message =
"Column value \"" + stringValue.Replace("\"", "\\\"") + "\"" +
" with length " + stringValue.Length.ToString("###,##0") +
" from source column " + (this as IDataRecord).GetName(i) +
" in record " + currentRecord.ToString("###,##0") +
" does not fit in destination column " + columnDef["ColumnName"] +
" with length " + ((int)columnDef["ColumnSize"]).ToString("###,##0") +
" in table " + tableName +
" in database " + databaseName +
" on server " + serverName + ".";
if (ColumnException == null)
{
throw new Exception(message);
}
else
{
ColumnExceptionEventArgs args = new ColumnExceptionEventArgs();
args.DataTypeName = (string)columnDef["DataTypeName"];
args.DataType = Type.GetType((string)columnDef["DataType"]);
args.Value = columnValue;
args.SourceIndex = i;
args.SourceColumn = reader.GetName(i);
args.DestIndex = (int)columnDef["ColumnOrdinal"];
args.DestColumn = (string)columnDef["ColumnName"];
args.ColumnSize = (int)columnDef["ColumnSize"];
args.RecordIndex = currentRecord;
args.TableName = tableName;
args.DatabaseName = databaseName;
args.ServerName = serverName;
args.Message = message;
ColumnException(args);
columnValue = args.Value;
}
}
}
}
return columnValue;
}
Hope this helps someone
Your code is fine. There's no problem with returning Strings
in this manner.
In Java, a String
is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String
around without worrying that it would disapper on you, or that someone somewhere would modify it.
If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:
public String time_to_string(long t) // time in milliseconds
{
if (t < 0)
{
return "-";
}
else
{
int secs = (int)(t/1000);
int mins = secs/60;
secs = secs - (mins * 60);
return String.format("%d:%02d", mins, secs);
}
}
As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans
and have replaced the mix of string concatenation and String.format()
with a single call to String.format()
.
I recommend using Prettier as it's very extensible but still works perfectly out of the box:
1. CMD + Shift + P -> Format Document
or
1. Select the text you want to Prettify
2. CMD + Shift + P -> Format Selection
The Left join in this query is pointless:
UPDATE md SET md.status = '3'
FROM pd_mounting_details AS md
LEFT OUTER JOIN pd_order_ecolid AS oe ON md.order_data = oe.id
It would update all rows of pd_mounting_details
, whether or not a matching row exists in pd_order_ecolid
. If you wanted to only update matching rows, it should be an inner join.
If you want to apply some condition based on the join occurring or not, you need to add a WHERE
clause and/or a CASE
expression in your SET
clause.
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
I just had to dig through this issue myself and succeeded. Contrary to what others have offered as solutions, the path to my happy ending was directly correlated to JavaDoc. No "src.zip" files necessary. My trials and tribulations in the process involved finding the CORRECT JavaDoc to point at. Pointing a Java 1.7 project at Java 8 Javadoc does NOT work. (Even if "jre8" appears to be the only installed JRE available.) Thus, I beat my head against the brick wall unnecessarily.
Window > Preferences > Java > Installed JREs
If the JRE of your project is not listed (as happened to me when I migrated a jre7 project to a new jre8 workspace), you will need to add it here. Click "Add..." and point your Workspace at the desired jre folder. (Mine was C://Program Files/Java/jre7). Then "Edit..." the now-available JRE, select the rt.jar, and click "Javadoc Location..." and aim it at the correct javadoc location. For my use:
For jre7 -- http://docs.oracle.com/javase/7/docs/api/ For jre8 -- http://docs.oracle.com/javase/8/docs/api/
Voila, hover tooltip javadoc is re-enabled. I hope this helps anyone else trying to figure this problem out.
The MacGyver way,just for lulz
var a = [80, 77, 88, 95, 68];_x000D_
_x000D_
console.log(eval(a.join('+'))/a.length)
_x000D_
Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize
and add following two methods:
public class SerilizeDeserialize
{
// Serialize collection of any type to a byte stream
public static byte[] Serialize<T>(T obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binSerializer = new BinaryFormatter();
binSerializer.Serialize(memStream, obj);
return memStream.ToArray();
}
}
// DSerialize collection of any type to a byte stream
public static T Deserialize<T>(byte[] serializedObj)
{
T obj = default(T);
using (MemoryStream memStream = new MemoryStream(serializedObj))
{
BinaryFormatter binSerializer = new BinaryFormatter();
obj = (T)binSerializer.Deserialize(memStream);
}
return obj;
}
}
How To use these method in your Class:
ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);
ArrayList arrayListMemDes = new ArrayList();
arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);
Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
Console.WriteLine(item);
}
If you have access to apache bin directory you can use,
httpd -M
to check loaded modules first.
info_module (shared) isapi_module (shared) log_config_module (shared) cache_disk_module (shared) mime_module (shared) negotiation_module (shared) proxy_module (shared) proxy_ajp_module (shared) rewrite_module (shared) setenvif_module (shared) socache_shmcb_module (shared) ssl_module (shared) status_module (shared) version_module (shared) php5_module (shared)
After that simple directives like Options -Indexes
or deny from all
will solidify that .htaccess are working correctly.
SQLTools is an almost fully functional and free Oracle GUI:
Floats have less precision than doubles. Although you already know, read What WE Should Know About Floating-Point Arithmetic for better understanding.
There is one thing that may be optimized in the suggested solutions. Having many calls to Replace()
makes the code to do multiple passes over the same string. With very long strings the solutions may be slow because of CPU cache capacity misses. May be one should consider replacing multiple strings in a single pass.
Please refer to this for the example .The main point is to use the groupProperty()
, and the related aggregate functions provided by the Projections class.
For example :
SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name
Its equivalent criteria object is :
List result = session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).list();
I had a list of dataframes with no common id column.
I had missing data on many dfs. There were Null values.
The dataframes were produced using table function.
The Reduce, Merging, rbind, rbind.fill, and their like could not help me to my aim.
My aim was to produce an understandable merged dataframe, irrelevant of the missing data and common id column.
Therefore, I made the following function. Maybe this function can help someone.
##########################################################
#### Dependencies #####
##########################################################
# Depends on Base R only
##########################################################
#### Example DF #####
##########################################################
# Example df
ex_df <- cbind(c( seq(1, 10, 1), rep("NA", 0), seq(1,10, 1) ),
c( seq(1, 7, 1), rep("NA", 3), seq(1, 12, 1) ),
c( seq(1, 3, 1), rep("NA", 7), seq(1, 5, 1), rep("NA", 5) ))
# Making colnames and rownames
colnames(ex_df) <- 1:dim(ex_df)[2]
rownames(ex_df) <- 1:dim(ex_df)[1]
# Making an unequal list of dfs,
# without a common id column
list_of_df <- apply(ex_df=="NA", 2, ( table) )
it is following the function
##########################################################
#### The function #####
##########################################################
# The function to rbind it
rbind_null_df_lists <- function ( list_of_dfs ) {
length_df <- do.call(rbind, (lapply( list_of_dfs, function(x) length(x))))
max_no <- max(length_df[,1])
max_df <- length_df[max(length_df),]
name_df <- names(length_df[length_df== max_no,][1])
names_list <- names(list_of_dfs[ name_df][[1]])
df_dfs <- list()
for (i in 1:max_no ) {
df_dfs[[i]] <- do.call(rbind, lapply(1:length(list_of_dfs), function(x) list_of_dfs[[x]][i]))
}
df_cbind <- do.call( cbind, df_dfs )
rownames( df_cbind ) <- rownames (length_df)
colnames( df_cbind ) <- names_list
df_cbind
}
Running the example
##########################################################
#### Running the example #####
##########################################################
rbind_null_df_lists ( list_of_df )
I'm not sure what you're doing, but this will go from JSON to CSV using JavaScript. This is using the open source JSON library, so just download JSON.js into the same folder you saved the code below into, and it will parse the static JSON value in json3
into CSV and prompt you to download/open in Excel.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSON to CSV</title>
<script src="scripts/json.js" type="text/javascript"></script>
<script type="text/javascript">
var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName\":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary Zupers\"}]" }
DownloadJSON2CSV(json3.d);
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
line += array[i][index] + ',';
}
// Here is an example where you would wrap the values in double quotes
// for (var index in array[i]) {
// line += '"' + array[i][index] + '",';
// }
line.slice(0,line.Length-1);
str += line + '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + escape(str))
}
</script>
</head>
<body>
<h1>This page does nothing....</h1>
</body>
</html>
You could use:
cordova plugins list | awk '{print $1}' | xargs cordova plugins rm
and use cordova plugins list
to verify if plugins are all removed.
Postman
.http://{server:port}/json/metallica/post
.Headers
button and enter Content-Type
as header and application/json
in value.POST
from the dropdown next to the URL text box.raw
from the buttons available below URL text box.JSON
from the following dropdown.In the textarea available below, post your request object:
{
"title" : "test title",
"singer" : "some singer"
}
Hit Send
.
Refer to screenshot below:
I think your best shot is a border-left
property that is assigned to each one of the li
s except the first one (You would have to give the first one a class named first
and explicitly remove the border for that).
Even if you are generating the <li>
programmatically, assigning a first
class should be easy.
I constantly forget the names of the colors I want to use and keep coming back to this question =)
The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.
I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.
I really didn't change much from the matplotlib example, but here is the code for completeness.
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]
n = len(sorted_names)
ncols = 4
nrows = n // ncols
fig, ax = plt.subplots(figsize=(12, 10))
# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols
for i, name in enumerate(sorted_names):
row = i % nrows
col = i // nrows
y = Y - (row * h) - h
xi_line = w * (col + 0.05)
xf_line = w * (col + 0.25)
xi_text = w * (col + 0.3)
ax.text(xi_text, y, name, fontsize=(h * 0.8),
horizontalalignment='left',
verticalalignment='center')
ax.hlines(y + h * 0.1, xi_line, xf_line,
color=colors[name], linewidth=(h * 0.8))
ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()
fig.subplots_adjust(left=0, right=1,
top=1, bottom=0,
hspace=0, wspace=0)
plt.show()
Updated 2017-10-25. I merged my previous updates into this section.
If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:
plt.plot([1,2], lw=4, c='xkcd:baby poop green')
Now you have access to a plethora of named colors!
The default Tableau colors are available in matplotlib via the 'tab:' prefix:
plt.plot([1,2], lw=4, c='tab:green')
There are ten distinct colors:
You can also plot colors by their HTML hex code:
plt.plot([1,2], lw=4, c='#8f9805')
This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...
For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py
.