A good place to start your investigation into any failed binding is to use the "fuslogvw.exe" utility. This may give you the information you need related to the binding failure so that you don't have to go messing around with any registry values to turn binding logging on.
The utility should be in your Microsoft SDKs folder, which would be something like this, depending on your operating system: "C:\Program Files (x86)\Microsoft SDKs\Windows\v{SDK version}A\Bin\FUSLOGVW.exe"
Run this utility as Administrator, from Developer Command Prompt (as Admin) type FUSLOGVW
a new screen appears
Go to Settings to and select Enable all binds to disk also select Enable custom log path and select the path of the folder of your choice to store the binding log.
Restart IIS.
From the FUSLOGVW window click Delete all to clear the list of any previous bind failures
Reproduce the binding failure in your application
In the utility, click Refresh. You should then see the bind failure logged in the list.
You can view information about the bind failure by selecting it in the list and clicking View Log
The first thing I look for is the path in which the application is looking for the assembly. You should also make sure the version number of the assembly in question is what you expect.
This is something you really need to do server-side as each user's local time format differs, not to mention each browser behaves different.
Html Date inputs value should be in this format: yyyy-mm-dd otherwise it will not show a value.
ASP CLASSIC , OR VBSCRIPT:
current_year = DatePart("yyyy",date)
current_month = DatePart("m",date)
current_day = DatePart("d",date)
IF current_month < 10 THEN
current_month = "0"¤t_month
END IF
IF current_day < 10 THEN
current_day = "0"¤t_day
END IF
get_date = current_year&"-"¤t_month&"-"¤t_day
Response.Write get_date
Output of today's date : 2019-02-08
Then in your html:
<input type="date" value="<% =get_date %>"
PHP
just use this:
<input type="date" value="<?= date("Y-m-d"); ?>">
As I discovered from this similar post (ignorecase in AWK), on old versions of awk (such as on vanilla Mac OS X), you may need to use 'tolower($0) ~ /pattern/'
.
IGNORECASE
or (?i)
or /pattern/i
will either generate an error or return true for every line.
In Symfony 3.3 you can use
$projectRoot = $this->get('kernel')->getProjectDir();
to get the web/project root.
If anyone wants to get installed application package code, just execute below command with your application name in the command prompt. You will be getting product code along with package code.
wmic product where "Name like '%YOUR_APPLICATION_NAME%'" get IdentifyingNumber, PackageCode
Code To Get Today's date in any specific Format
You can define the desired format in SimpleDateFormat instance to get the date in that specific formate
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String todaysdate = dateFormat.format(date);
System.out.println("Today's date : " + todaysdate);
Follow below links to see the valid date format combination.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
CODE : To get x days ahead or Previous from Today's date, To get the past date or Future date.
For Example :
Today date : 11/27/2018
xdayFromTodaysDate = 2 to get date as 11/29/2018
xdayFromTodaysDate = -2 to get date as 11/25/2018
public String getAniversaryDate(int xdayFromTodaysDate ){
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("Today's date : " + todaysdate);
return aniversaryDate;
}
CODE : To get x days ahead or Previous from a Given date
public String getAniversaryDate(String givendate, int xdayFromTodaysDate ){
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = dateFormat.parse(givendate);
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("aniversaryDate : " + aniversaryDate);
return aniversaryDate;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
I found the answer is very very simple...
// It is in java, but it should be same in pyspark
Column col = ds.col("colName"); //the column object
String theNameOftheCol = col.toString();
The variable "theNameOftheCol" is "colName"
I don't think what your asking is possible.
Basically, adding a class is the only way to accomplish this that I am aware of.
Since this was answered there have been some meaningful changes to the ggplot
syntax. Summing up the discussion in the comments above:
require(ggplot2)
require(scales)
p <- ggplot(mydataf, aes(x = foo)) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
## version 3.0.0
scale_y_continuous(labels=percent)
Here's a reproducible example using mtcars
:
ggplot(mtcars, aes(x = factor(hp))) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(labels = percent) ## version 3.0.0
This question is currently the #1 hit on google for 'ggplot count vs percentage histogram' so hopefully this helps distill all the information currently housed in comments on the accepted answer.
Remark: If hp
is not set as a factor, ggplot returns:
eq is used to compare integers use equal '=' instead , example:
if [ 'AAA' = 'ABC' ];
then
echo "the same"
else
echo "not the same"
fi
good luck
You need the following functions to do this in PHP:
strpos
Find the position of the first occurrence of a substring in a string
strrpos
Find the position of the last occurrence of a substring in a string
substr
Return part of a string
Here's the signature of the substr
function:
string substr ( string $string , int $start [, int $length ] )
The signature of the substring
function (Java) looks a bit different:
string substring( int beginIndex, int endIndex )
substring
(Java) expects the end-index as the last parameter, but substr
(PHP) expects a length.
It's not hard, to get the desired length by the end-index in PHP:
$sub = substr($str, $start, $end - $start);
Here is the working code
$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
$pt_password = substr($message, $start);
}
else {
$end = strrpos($message, '-');
$pt_password = substr($message, $start, $end - $start);
}
You need to create a Bundle and then use putSerializable:
List<Thumbnail> all_thumbs = new ArrayList<Thumbnail>();
all_thumbs.add(new Thumbnail(string,bitmap));
Intent intent = new Intent(getApplicationContext(),SomeClass.class);
Bundle extras = new Bundle();
extras.putSerializable("value",all_thumbs);
intent.putExtras(extras);
@Liem Vo's answer is correct if you are using android.widget.Button without any overriding. If you are overriding your theme using MaterialComponents, this will not solve the issue.
So if you are
Use app:icon parameter.
<Button
android:id="@+id/bSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Search"
android:textSize="24sp"
app:icon="@android:drawable/ic_menu_search" />
Most of the work in overloading operators is boiler-plate code. That is little wonder, since operators are merely syntactic sugar, their actual work could be done by (and often is forwarded to) plain functions. But it is important that you get this boiler-plate code right. If you fail, either your operator’s code won’t compile or your users’ code won’t compile or your users’ code will behave surprisingly.
There's a lot to be said about assignment. However, most of it has already been said in GMan's famous Copy-And-Swap FAQ, so I'll skip most of it here, only listing the perfect assignment operator for reference:
X& X::operator=(X rhs)
{
swap(rhs);
return *this;
}
The bitshift operators <<
and >>
, although still used in hardware interfacing for the bit-manipulation functions they inherit from C, have become more prevalent as overloaded stream input and output operators in most applications. For guidance overloading as bit-manipulation operators, see the section below on Binary Arithmetic Operators. For implementing your own custom format and parsing logic when your object is used with iostreams, continue.
The stream operators, among the most commonly overloaded operators, are binary infix operators for which the syntax specifies no restriction on whether they should be members or non-members. Since they change their left argument (they alter the stream’s state), they should, according to the rules of thumb, be implemented as members of their left operand’s type. However, their left operands are streams from the standard library, and while most of the stream output and input operators defined by the standard library are indeed defined as members of the stream classes, when you implement output and input operations for your own types, you cannot change the standard library’s stream types. That’s why you need to implement these operators for your own types as non-member functions. The canonical forms of the two are these:
std::ostream& operator<<(std::ostream& os, const T& obj)
{
// write obj to stream
return os;
}
std::istream& operator>>(std::istream& is, T& obj)
{
// read obj from stream
if( /* no valid object of T found in stream */ )
is.setstate(std::ios::failbit);
return is;
}
When implementing operator>>
, manually setting the stream’s state is only necessary when the reading itself succeeded, but the result is not what would be expected.
The function call operator, used to create function objects, also known as functors, must be defined as a member function, so it always has the implicit this
argument of member functions. Other than this, it can be overloaded to take any number of additional arguments, including zero.
Here's an example of the syntax:
class foo {
public:
// Overloaded call operator
int operator()(const std::string& y) {
// ...
}
};
Usage:
foo f;
int a = f("hello");
Throughout the C++ standard library, function objects are always copied. Your own function objects should therefore be cheap to copy. If a function object absolutely needs to use data which is expensive to copy, it is better to store that data elsewhere and have the function object refer to it.
The binary infix comparison operators should, according to the rules of thumb, be implemented as non-member functions1. The unary prefix negation !
should (according to the same rules) be implemented as a member function. (but it is usually not a good idea to overload it.)
The standard library’s algorithms (e.g. std::sort()
) and types (e.g. std::map
) will always only expect operator<
to be present. However, the users of your type will expect all the other operators to be present, too, so if you define operator<
, be sure to follow the third fundamental rule of operator overloading and also define all the other boolean comparison operators. The canonical way to implement them is this:
inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator!=(const X& lhs, const X& rhs){return !operator==(lhs,rhs);}
inline bool operator< (const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator> (const X& lhs, const X& rhs){return operator< (rhs,lhs);}
inline bool operator<=(const X& lhs, const X& rhs){return !operator> (lhs,rhs);}
inline bool operator>=(const X& lhs, const X& rhs){return !operator< (lhs,rhs);}
The important thing to note here is that only two of these operators actually do anything, the others are just forwarding their arguments to either of these two to do the actual work.
The syntax for overloading the remaining binary boolean operators (||
, &&
) follows the rules of the comparison operators. However, it is very unlikely that you would find a reasonable use case for these2.
1 As with all rules of thumb, sometimes there might be reasons to break this one, too. If so, do not forget that the left-hand operand of the binary comparison operators, which for member functions will be *this
, needs to be const
, too. So a comparison operator implemented as a member function would have to have this signature:
bool operator<(const X& rhs) const { /* do actual comparison with *this */ }
(Note the const
at the end.)
2 It should be noted that the built-in version of ||
and &&
use shortcut semantics. While the user defined ones (because they are syntactic sugar for method calls) do not use shortcut semantics. User will expect these operators to have shortcut semantics, and their code may depend on it, Therefore it is highly advised NEVER to define them.
The unary increment and decrement operators come in both prefix and postfix flavor. To tell one from the other, the postfix variants take an additional dummy int argument. If you overload increment or decrement, be sure to always implement both prefix and postfix versions. Here is the canonical implementation of increment, decrement follows the same rules:
class X {
X& operator++()
{
// do actual increment
return *this;
}
X operator++(int)
{
X tmp(*this);
operator++();
return tmp;
}
};
Note that the postfix variant is implemented in terms of prefix. Also note that postfix does an extra copy.2
Overloading unary minus and plus is not very common and probably best avoided. If needed, they should probably be overloaded as member functions.
2 Also note that the postfix variant does more work and is therefore less efficient to use than the prefix variant. This is a good reason to generally prefer prefix increment over postfix increment. While compilers can usually optimize away the additional work of postfix increment for built-in types, they might not be able to do the same for user-defined types (which could be something as innocently looking as a list iterator). Once you got used to do i++
, it becomes very hard to remember to do ++i
instead when i
is not of a built-in type (plus you'd have to change code when changing a type), so it is better to make a habit of always using prefix increment, unless postfix is explicitly needed.
For the binary arithmetic operators, do not forget to obey the third basic rule operator overloading: If you provide +
, also provide +=
, if you provide -
, do not omit -=
, etc. Andrew Koenig is said to have been the first to observe that the compound assignment operators can be used as a base for their non-compound counterparts. That is, operator +
is implemented in terms of +=
, -
is implemented in terms of -=
etc.
According to our rules of thumb, +
and its companions should be non-members, while their compound assignment counterparts (+=
etc.), changing their left argument, should be a member. Here is the exemplary code for +=
and +
; the other binary arithmetic operators should be implemented in the same way:
class X {
X& operator+=(const X& rhs)
{
// actual addition of rhs to *this
return *this;
}
};
inline X operator+(X lhs, const X& rhs)
{
lhs += rhs;
return lhs;
}
operator+=
returns its result per reference, while operator+
returns a copy of its result. Of course, returning a reference is usually more efficient than returning a copy, but in the case of operator+
, there is no way around the copying. When you write a + b
, you expect the result to be a new value, which is why operator+
has to return a new value.3
Also note that operator+
takes its left operand by copy rather than by const reference. The reason for this is the same as the reason giving for operator=
taking its argument per copy.
The bit manipulation operators ~
&
|
^
<<
>>
should be implemented in the same way as the arithmetic operators. However, (except for overloading <<
and >>
for output and input) there are very few reasonable use cases for overloading these.
3 Again, the lesson to be taken from this is that a += b
is, in general, more efficient than a + b
and should be preferred if possible.
The array subscript operator is a binary operator which must be implemented as a class member. It is used for container-like types that allow access to their data elements by a key. The canonical form of providing these is this:
class X {
value_type& operator[](index_type idx);
const value_type& operator[](index_type idx) const;
// ...
};
Unless you do not want users of your class to be able to change data elements returned by operator[]
(in which case you can omit the non-const variant), you should always provide both variants of the operator.
If value_type is known to refer to a built-in type, the const variant of the operator should better return a copy instead of a const reference:
class X {
value_type& operator[](index_type idx);
value_type operator[](index_type idx) const;
// ...
};
For defining your own iterators or smart pointers, you have to overload the unary prefix dereference operator *
and the binary infix pointer member access operator ->
:
class my_ptr {
value_type& operator*();
const value_type& operator*() const;
value_type* operator->();
const value_type* operator->() const;
};
Note that these, too, will almost always need both a const and a non-const version.
For the ->
operator, if value_type
is of class
(or struct
or union
) type, another operator->()
is called recursively, until an operator->()
returns a value of non-class type.
The unary address-of operator should never be overloaded.
For operator->*()
see this question. It's rarely used and thus rarely ever overloaded. In fact, even iterators do not overload it.
Continue to Conversion Operators
Also, to complete what @claudio said, when cherry-picking you can also use a merging strategy.
So you could something like this git cherry-pick --strategy=recursive -X theirs commit
or git cherry-pick --strategy=recursive -X ours commit
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
You can remove inline properties this way:
$(selector).css({'property':'', 'property':''});
For example:
$(actpar).css({'top':'', 'opacity':''});
This is essentially mentioned above, and it definitely does the trick.
BTW, this is useful in instances such as when you need to clear a state after animation. Sure I could write a half dozen classes to deal with this, or I could use my base class and #id do some math, and clear the inline style that the animation applies.
$(actpar).animate({top:0, opacity:1, duration:500}, function() {
$(this).css({'top':'', 'opacity':''});
});
I usually think fairly highly of http://cdnjs.com/ and they are listing:
//cdnjs.cloudflare.com/ajax/libs/placeholder-shiv/0.2/placeholder-shiv.js
Not sure who's code that is but it looks straightforward:
document.observe('dom:loaded', function(){
var _test = document.createElement('input');
if( ! ('placeholder' in _test) ){
//we are in the presence of a less-capable browser
$$('*[placeholder]').each(function(elm){
if($F(elm) == ''){
var originalColor = elm.getStyle('color');
var hint = elm.readAttribute('placeholder');
elm.setStyle('color:gray').setValue(hint);
elm.observe('focus',function(evt){
if($F(this) == hint){
this.clear().setStyle({color: originalColor});
}
});
elm.observe('blur', function(evt){
if($F(this) == ''){
this.setValue(hint).setStyle('color:gray');
}
});
}
}).first().up('form').observe('submit', function(evt){
evt.stop();
this.select('*[placeholder]').each(function(elm){
if($F(elm) == elm.readAttribute('placeholder')) elm.clear();
});
this.submit();
});
}
});
select * from yourtable
where created < now()
and created > concat(curdate(),' 4:30:00 AM')
Referring to Spring Boot application as a Service as well, I would go for the systemd
version, since it's the easiest, least verbose, and best integrated into modern distros (and even the not-so-modern ones like CentOS 7.x).
In my case the problem was solved by Window -> Preferences -> Maven -> User Settings -> Update Settings. I don't know the problem cause at the first place.
const
in C++ does not mean that a value is a constant.
const
in C++ implies that the client of a contract undertakes not to alter its value.
Whether the value of a const
expression changes becomes more evident if you are in an environment which supports thread based concurrency.
As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that final
has.
eg:
#include <iostream>
int main ()
{
volatile const int x = 42;
std::cout << x << std::endl;
*const_cast<int*>(&x) = 7;
std::cout << x << std::endl;
return 0;
}
outputs 42 then 7.
Although x
marked as const
, as a non-const alias is created, x
is not a constant. Not every compiler requires volatile
for this behaviour (though every compiler is permitted to inline the constant)
With more complicated systems you get const/non-const aliases without use of const_cast
, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const
merely means that your code can't change it without a cast, not that the value is constant.
The cat <<EOF
syntax is very useful when working with multi-line text in Bash, eg. when assigning multi-line string to a shell variable, file or a pipe.
cat <<EOF
syntax usage in Bash:$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)
The $sql
variable now holds the new-line characters too. You can verify with echo -e "$sql"
.
$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF
The print.sh
file now contains:
#!/bin/bash
echo $PWD
echo /home/user
$ cat <<EOF | grep 'b' | tee b.txt
foo
bar
baz
EOF
The b.txt
file contains bar
and baz
lines. The same output is printed to stdout
.
Yes. Recent versions of IE (IE8 or above) let you adjust that. Here's how:
That should open the Developer Tools window. That window has two menu items that are of interest:
More at http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx
.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.
Well this is the MSDN page that deals with IntPtr
.
The first line reads:
A platform-specific type that is used to represent a pointer or a handle.
As to what a pointer or handle is the page goes on to state:
The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.
IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.
A pointer is a reference to an area of memory that holds some data you are interested in.
A handle can be an identifier for an object and is passed between methods/classes when both sides need to access that object.
I do it like this:
(Shortened the code a bit)
public struct Age
{
public readonly int Years;
public readonly int Months;
public readonly int Days;
}
public Age( int y, int m, int d ) : this()
{
Years = y;
Months = m;
Days = d;
}
public static Age CalculateAge ( DateTime birthDate, DateTime anotherDate )
{
if( startDate.Date > endDate.Date )
{
throw new ArgumentException ("startDate cannot be higher then endDate", "startDate");
}
int years = endDate.Year - startDate.Year;
int months = 0;
int days = 0;
// Check if the last year, was a full year.
if( endDate < startDate.AddYears (years) && years != 0 )
{
years--;
}
// Calculate the number of months.
startDate = startDate.AddYears (years);
if( startDate.Year == endDate.Year )
{
months = endDate.Month - startDate.Month;
}
else
{
months = ( 12 - startDate.Month ) + endDate.Month;
}
// Check if last month was a complete month.
if( endDate < startDate.AddMonths (months) && months != 0 )
{
months--;
}
// Calculate the number of days.
startDate = startDate.AddMonths (months);
days = ( endDate - startDate ).Days;
return new Age (years, months, days);
}
// Implement Equals, GetHashCode, etc... as well
// Overload equality and other operators, etc...
}
Maybe you were trying to do this?
#include <stdio.h>
int func(int * B){
/* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */
*(B + 2) = 5;
}
int main(void) {
int B[10];
func(B);
/* Let's say you edited only 2 and you want to show it. */
printf("b[0] = %d\n\n", B[2]);
return 0;
}
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.
You can use it like this in template without any filters
{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}
I wrote this generic type converter. It works with Nullable and standard values, converting between all convertible types - not just string. It handles all sorts of scenarios that you'd expect (default values, null values, other values, etc...)
I've been using this for about a year in dozens of production programs, so it should be pretty solid.
public static T To<T>(this IConvertible obj)
{
Type t = typeof(T);
if (t.IsGenericType
&& (t.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
if (obj == null)
{
return (T)(object)null;
}
else
{
return (T)Convert.ChangeType(obj, Nullable.GetUnderlyingType(t));
}
}
else
{
return (T)Convert.ChangeType(obj, t);
}
}
public static T ToOrDefault<T>
(this IConvertible obj)
{
try
{
return To<T>(obj);
}
catch
{
return default(T);
}
}
public static bool ToOrDefault<T>
(this IConvertible obj,
out T newObj)
{
try
{
newObj = To<T>(obj);
return true;
}
catch
{
newObj = default(T);
return false;
}
}
public static T ToOrOther<T>
(this IConvertible obj,
T other)
{
try
{
return To<T>(obj);
}
catch
{
return other;
}
}
public static bool ToOrOther<T>
(this IConvertible obj,
out T newObj,
T other)
{
try
{
newObj = To<T>(obj);
return true;
}
catch
{
newObj = other;
return false;
}
}
public static T ToOrNull<T>
(this IConvertible obj)
where T : class
{
try
{
return To<T>(obj);
}
catch
{
return null;
}
}
public static bool ToOrNull<T>
(this IConvertible obj,
out T newObj)
where T : class
{
try
{
newObj = To<T>(obj);
return true;
}
catch
{
newObj = null;
return false;
}
}
I was able to correct the flaw by changing the file below:
C:\Windows\System32\inetsrv\config\applicationHost.config
In:
<application path="/" applicationPool="ASP.NET v4.0">
<virtualDirectory path="/" physicalPath="C:\inetpub\wwwroot\Bonobo.Git.Server" />
</application>
<application path="/Bonobo.Git.Server" applicationPool="ASP.NET v4.0">
<virtualDirectory path="/" physicalPath="C:\inetpub\wwwroot\Bonobo.Git.Server" />
</application>
For:
<application path="/">
<virtualDirectory path="/" physicalPath="C:\inetpub\wwwroot\" />
</application>
<application path="/Bonobo.Git.Server" applicationPool="ASP.NET v4.0">
<virtualDirectory path="/" physicalPath="C:\inetpub\wwwroot\Bonobo.Git.Server" />
</application>
Changed the braced iterators, good call. Also, call this function with a reverse iterator.
You can probably do something like this:
#!/bin/bash
HISTFILE=~/.bash_history # if you are running it in a
# non interactive shell history would not work else
set -o history
for i in `seq $1 $2`;
do
history -d $i
done
history -w
Where you will evoke like this:
./nameOfYourScript 563 514
Notice I haven't put any error checking in for the bounds. I'll leave that as an exercise to the reader.
see also this question
You can always use a background image to do it too. I tend to vote for this option 100% of the time as the only other perfect solution is the Jquery option.
As with using the outer div with a background color you'll end up having to have the content in both divs reaching the same height.
DECLARE @i AS FLOAT = 2 SELECT @i / 3 SELECT cast(@i / cast(3 AS DECIMAL(18,2))as decimal (18,2))
Both factor and result requires casting to be considered as decimals.
You can try this:
td p {word-break:break-all;}
This, however, makes it appear like this when there's enough space, unless you add a <br>
tag:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
So, I would then suggest adding <br>
tags where there are newlines, if possible.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Also, if this doesn't solve your problem, there's a similar thread here.
I thought that my first answer gives the correct day of week as a number between 0 and 6. However, because you had not indicated why this answer does not give the result you want, I can only guess the reason.
The Batch file below create a log file each day with a digit in the name, 0=Sunday, 1=Monday, etc... The program assume that echo %date%
show the date in MM/DD/YYYY format; if this is not the case, just change the position of mm and dd variables in the for
command.
@echo off
for /F "tokens=1-3 delims=/" %%a in ("%date%") do set /A mm=10%%a %% 100, dd=10%%b %% 100, yy=%%c
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10, dow=(c+dd+e+f-1523)%%7
echo Today log data > Day-%dow%.txt
If this is not what you want, please indicate the problem so I can fix it.
EDIT: The version below get date parts independent of locale settings:
@echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
set %%A=%%a
set %%B=%%b
set %%C=%%c
)
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10,
dow=(c+dd+e+f-1523)%%7
echo Today log data > Day-%dow%.txt
EDIT: The version below insert day of week as 3-letter short name:
@echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
set %%A=%%a
set %%B=%%b
set %%C=%%c
)
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10,
dow=(c+dd+e+f-1523)%%7 + 1
for /F "tokens=%dow%" %%a in ("Sun Mon Tue Wed Thu Fri Sat") do set dow=%%a
echo Today log data > Day-%dow%.txt
Regards,
Antonio
try this css:
/* Show in default resolution screen*/
#container2 {
width: 960px;
position: relative;
margin:0 auto;
line-height: 1.4em;
}
/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */
@media only screen and (max-width: 479px){
#container2 { width: 90%; }
}
Here the demo: http://jsfiddle.net/ongisnade/CG9WN/
l
is a list of strings. When you put numbers between single quotes like that, you are creating strings, which are just a sequence of characters. To make your code work properly, you would have to do this:
l = [-1.2, 0.0, 1] # no quotation marks
x = 100.0
for i in l:
if i < x:
x = i
print x
If you must use a list of strings, you can try to let Python try to make a number out of each string. This is similar to Justin's answer, except it understands floating-point (decimal) numbers correctly.
l = ['-1.2', '0.0', '1']
x = 100.0
for i in l:
inum = float(i)
if inum < x:
x = inum
print x
I hope that this is code that you are writing to learn either Python or programming in general. If this is the case, great. However, if this is production code, consider using Python's built-in functions.
l = ['-1.2', '0.0', '1']
lnums = map(float, l) # turn strings to numbers
x = min(lnums) # find minimum value
print x
You can get all your fingerprints from https://console.developers.google.com/projectselector/apis/credentials
And use this Kotlin code to convert it to keyhash:
fun main(args: Array<String>) {
listOf("<your_production_sha1_fingerprint>",
"<your_debug1_sha1_fingerprint>",
"<your_debug2_sha1_fingerprint>")
.map { it.split(":") }
.map { it.map { it.toInt(16).toByte() }.toByteArray() }
.map { String(Base64.getEncoder().encode(it)) }
.forEach { println(it) }
}
In my case, there is a single table which happens to be a device list from a router. If you wish to read the table using TR/TH/TD (row, header, data) instead of a matrix as mentioned above, you can do something like the following:
List<TableRow> deviceTable = (from table in document.DocumentNode.SelectNodes(XPathQueries.SELECT_TABLE)
from row in table?.SelectNodes(HtmlBody.TR)
let rows = row.SelectSingleNode(HtmlBody.TR)
where row.FirstChild.OriginalName != null && row.FirstChild.OriginalName.Equals(HtmlBody.T_HEADER)
select new TableRow
{
Header = row.SelectSingleNode(HtmlBody.T_HEADER)?.InnerText,
Data = row.SelectSingleNode(HtmlBody.T_DATA)?.InnerText}).ToList();
}
TableRow is just a simple object with Header and Data as properties. The approach takes care of null-ness and this case:
<tr>_x000D_
<td width="28%"> </td>_x000D_
</tr>
_x000D_
which is row without a header. The HtmlBody object with the constants hanging off of it are probably readily deduced but I apologize for it even still. I came from the world where if you have " in your code, it should either be constant or localizable.
The JMeter docs say the following:
The summary report creates a table row for each differently named request in your test. This is similar to the Aggregate Report , except that it uses less memory. The thoughput is calculated from the point of view of the sampler target (e.g. the remote server in the case of HTTP samples). JMeter takes into account the total time over which the requests have been generated. If other samplers and timers are in the same thread, these will increase the total time, and therefore reduce the throughput value. So two identical samplers with different names will have half the throughput of two samplers with the same name. It is important to choose the sampler labels correctly to get the best results from the Report.
Times are in milliseconds.
This can also be achieved with jsp:include. Chad Darby explains well here in this video https://www.youtube.com/watch?v=EWbYj0qoNHo
Something along the lines:
import os
if os.name == "posix":
print(os.system("uname -a"))
# insert other possible OSes here
# ...
else:
print("unknown OS")
You can do it using jquery inputmask plugin.
HTML:
<input id="price" type="text">
Javascript:
$('#price').inputmask({
alias: 'numeric',
allowMinus: false,
digits: 2,
max: 999.99
});
Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:
GridLines="None"
CellSpacing="-1"
Extract unique words sorted ASC from a list of phrases:
List<String> phrases = Arrays.asList(
"sporadic perjury",
"confounded skimming",
"incumbent jailer",
"confounded jailer");
List<String> uniqueWords = phrases
.stream()
.flatMap(phrase -> Stream.of(phrase.split("\\s+")))
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println("Unique words: " + uniqueWords);
... and the output:
Unique words: [confounded, incumbent, jailer, perjury, skimming, sporadic]
One more solution REPLACE (CHAR(current date, ISO),'-','')
I load shader for openGL ES from static function.
Remember you must use lower case for your file and directory name, or else the operation will be failed
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
public static int loadShader() {
// Read file as input stream
InputStream inputStream = MyGLRenderer.class.getResourceAsStream("/res/raw/vertex_shader.txt");
// Convert input stream to string
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String shaderCode = s.hasNext() ? s.next() : "";
}
...
}
You can do this via the information_schema tables. For example:
SELECT
tc.table_schema,
tc.constraint_name,
tc.table_name,
kcu.column_name,
ccu.table_schema AS foreign_table_schema,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='mytable';
1/ I've been on projects where dynamic linking vs static linking was benchmarked and the difference wasn't determined small enough to switch to dynamic linking (I wasn't part of the test, I just know the conclusion)
2/ Dynamic linking is often associated with PIC (Position Independent Code, code which doesn't need to be modified depending on the address at which it is loaded). Depending on the architecture PIC may bring another slowdown but is needed in order to get benefit of sharing a dynamically linked library between two executable (and even two process of the same executable if the OS use randomization of load address as a security measure). I'm not sure that all OS allow to separate the two concepts, but Solaris and Linux do and ISTR that HP-UX does as well.
3/ I've been on other projects which used dynamic linking for the "easy patch" feature. But this "easy patch" makes the distribution of small fix a little easier and of complicated one a versioning nightmare. We often ended up by having to push everything plus having to track problems at customer site because the wrong version was token.
My conclusion is that I'd used static linking excepted:
for things like plugins which depend on dynamic linking
when sharing is important (big libraries used by multiple processes at the same time like C/C++ runtime, GUI libraries, ... which often are managed independently and for which the ABI is strictly defined)
If one want to use the "easy patch", I'd argue that the libraries have to be managed like the big libraries above: they must be nearly independent with a defined ABI that must not to be changed by fixes.
try this function $('div.total-title').text('test');
Like Moneypenny said in Skyfall: "Sometimes the old ways are best." Kincade said something similar later on.
$ printf ',s/false/true/g\nw\n' | ed {YourFileHere}
Happy editing in place. Added '\nw\n' to write the file. Apologies for delay answering request.
This method zips a folder and adds all of the child files & folders (including empty folders) into the zip file.
void zipFolder(Path sourceDir, Path targetFile) throws IOException {
ZipDirectoryVisitor zipVisitor = new ZipDirectoryVisitor(sourceDir);
Files.walkFileTree(sourceDir, zipVisitor);
FileOutputStream fos = new FileOutputStream(targetFile.toString());
ZipOutputStream zos = new ZipOutputStream(fos);
byte[] buffer = new byte[1024];
for (ZipEntry entry : zipVisitor.getZipEntries()) {
zos.putNextEntry(entry);
Path curFile = Paths.get(sourceDir.getParent().toString(), entry.toString());
if (!curFile.toFile().isDirectory()) {
FileInputStream in = new FileInputStream(Paths.get(sourceDir.getParent().toString(), entry.toString()).toString());
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
}
zos.close();
}
And here is the ZipDirectoryVisitor implementation:
class ZipDirectoryVisitor extends SimpleFileVisitor<Path> {
private Path dirToZip;
private List<ZipEntry> zipEntries; // files and folders inside source folder as zip entries
public ZipDirectoryVisitor(Path dirToZip) throws IOException {
this.dirToZip = dirToZip;
zipEntries = new ArrayList<>();
}
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException {
// According to zip standard backslashes
// should not be used in zip entries
String zipFile = dirToZip.getParent().relativize(path).toString().replace("\\", "/");
ZipEntry entry = new ZipEntry(zipFile);
zipEntries.add(entry);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes) throws IOException {
String zipDir = dirToZip.getParent().relativize(path).toString().replace("\\", "/");
// Zip directory entries should end with a forward slash
ZipEntry entry = new ZipEntry(zipDir + "/");
zipEntries.add(entry);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
System.err.format("Could not visit file %s while creating a file list from file tree", path);
return FileVisitResult.TERMINATE;
}
public List<ZipEntry> getZipEntries() {
return zipEntries;
}
}
Yes.
However, if you need to use Application.DoEvents
, this is mostly an indication of a bad application design. Perhaps you'd like to do some work in a separate thread instead?
import sys
userinput = sys.stdin.readline()
betAmount = int(userinput)
print betAmount
This works on my system. I checked int('23\n') would result in 23.
For %F In ("C:\From\*.*") Do If Not Exist "C:\To\%~nxF" Copy "%F" "C:\To\%~nxF"
This is how I would start to solve this:
Create a video writer:
import cv2.cv as cv
videowriter = cv.CreateVideoWriter( filename, fourcc, fps, frameSize)
Loop to retrieve[1] and write the frames:
cv.WriteFrame( videowriter, frame )
[1] zenpoy already pointed in the correct direction. You just need to know that you can retrieve images from a webcam or a file :-)
Hopefully I understood the requirements correct.
It may be appropriate to exit an app if it is a long lived app that also executes in the background, for example to get location updates (using the location updates background capability for that).
For example, let's say the user logs out of your location based app, and pushes the app to the background using the home button. In this case your app may keep running, but it could make sense to completely exit it. It would be good for the user (releases memory and other resources that don't need to be used), and good for app stability (i.e. making sure the app is periodically restarted when possible is a safety net against memory leaks and other low memory issues).
This could (though probably shouldn't, see below :-) be achieved with something like:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
if (/* logged out */) {
exit(0);
} else {
// normal handling.
}
}
Since the app would then exit out of the background it will not look wrong to the user, and will not resemble a crash, providing the user interface is restored the next time they run the app. In other words, to the user it would not look any different to a system initiated termination of the app when the app is in the background.
Still, it would be preferable to use a more standard approach to let the system know that the app can be terminated. For example in this case, by making sure the GPS is not in use by stopping requesting location updates, including turning off show current location on a map view if present. That way the system will take care of terminating the app a few minutes (i.e. [[UIApplication sharedApplication] backgroundTimeRemaining]
) after the app enters the background. This would get all the same benefits without having to use code to terminate the app.
- (void)applicationDidEnterBackground:(UIApplication *)application
{
if (/* logged out */) {
// stop requesting location updates if not already done so
// tidy up as app will soon be terminated (run a background task using beginBackgroundTaskWithExpirationHandler if needed).
} else {
// normal handling.
}
}
And of course, using exit(0)
would never be appropriate for the average production app that runs in the foreground, as per other answers that reference http://developer.apple.com/iphone/library/qa/qa2008/qa1561.html
In some circumstances, it's sufficient to just set all values of state
to null
.
If you're state is updated in such a way, that you don't know what might be in there, you might want to use
this.setState(Object.assign(...Object.keys(this.state).map(k => ({[k]: null}))))
Which will change the state as follows
{foo: 1, bar: 2, spam: "whatever"} > {foo: null, bar: null, spam: null}
Not a solution in all cases, but works well for me.
As simple as joining lists in python itself.
ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost
localhost | SUCCESS => {
"msg": "list-joined-together" }
Works the same way using variables:
ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost
For Rails (at least in my case) if you are using the angularjs-rails gem, please remember to add the sanitize module
//= require angular
//= require angular-sanitize
And then load it up in your app...
var myDummyApp = angular.module('myDummyApp', ['ngSanitize']);
Then you can do the following:
On the template:
%span{"ng-bind-html"=>"phone_with_break(x)"}
And eventually:
$scope.phone_with_break = function (x) {
if (x.phone != "") {
return x.phone + "<br>";
}
return '';
}
If you want to use a class:
from datetime import datetime,timedelta
class MyThread():
def __init__(self, name, timeLimit):
self.name = name
self.timeLimit = timeLimit
def run(self):
# get the start time
startTime = datetime.now()
while True:
# stop if the time limit is reached :
if((datetime.now()-startTime)>self.timeLimit):
break
print('A')
mt = MyThread('aThread',timedelta(microseconds=20000))
mt.run()
There is the Mono Project from Novell that will allow you to run ASP.Net on Apache.
You are out of luck, I think. THe problem is not a SQL level problem as all other answers seem to focus on, but simply one of the user interface. Management Studio is not meant to be a general purpose / generic data access interface. It is not there to be your interface, but your administrative area, and it has serious limitations handling binary data and large test data - because people using it within the specified usage profile will not run into this problem.
Presenting large text data is simply not the planned usage.
Your only choice would be a table valued function that takes the text input and cuts it rows for every line, so that Management Studio gets a list of rows, not a single row.
Try getWindow().getDecorView().findViewById(android.R.id.content).invalidate();
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter"><a href="#month" onclick="Data(this)">This Month</a></li>
<li class="filter"><a href="#year" onclick="Data(this)">Year</a></li>
<li class="filter"><a href="#last60" onclick="Data(this)">60 Days</a></li>
<li class="filter"><a href="#last90" onclick="Data(this)">90 Days</a></li>
</ul>
</div>
<script>
function Data(element)
{
element.removeClass('active');
element.addClass('active') ;
}
</script>
Set display.max_rows
:
pd.set_option('display.max_rows', 500)
For older versions of pandas (<=0.11.0) you need to change both display.height
and display.max_rows
.
pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)
See also pd.describe_option('display')
.
You can set an option only temporarily for this one time like this:
from IPython.display import display
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
display(df) #need display to show the dataframe when using with in jupyter
#some pandas stuff
You can also reset an option back to its default value like this:
pd.reset_option('display.max_rows')
And reset all of them back:
pd.reset_option('all')
When you start a thread, it begins executing a function you give it (if you're extending threading.Thread
, the function will be run()
). To end the thread, just return from that function.
According to this, you can also call thread.exit()
, which will throw an exception that will end the thread silently.
install by this command given below conda install -c conda-forge keras
this is error "CondaError: Cannot link a source that does not exist" ive get in win 10. for your error put this command in your command line.
conda update conda
this work for me .
if you are using themeroller:
.dataTables_wrapper .fg-toolbar { display: none; }
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
However, in C++0x, you can do this:
std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};
Of course, if you choose to use std::vector
instead of raw array.
The accepted answer by @kevinsa5 is correct, but you might be thinking "I swear this code used to work and now it doesn't," and you would be right.
There was an API change in the MySQLdb library between 1.2.3 and 1.2.5. The 1.2.3 versions supported
cursor.execute("SELECT * FROM foo WHERE bar = %s", 'baz')
but the 1.2.5 versions require
cursor.execute("SELECT * FROM foo WHERE bar = %s", ['baz'])
as the other answers state. I can't find the change in the changelogs, and it's possible the earlier behavior was considered a bug.
The Ubuntu 14.04 repository has python-mysqldb 1.2.3, but Ubuntu 16.04 and later have python-mysqldb 1.3.7+.
If you're dealing with a legacy codebase that requires the old behavior but your platform is a newish Ubuntu, install MySQLdb from PyPI instead:
$ pip install MySQL-python==1.2.3
delete
operator is used to remove
an object property
.
delete
operator does not returns the new object, only returns a boolean
: true or false.
In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry'];
, updatedjsonobj
variable will store a boolean
value.
How to remove Json object specific key and its value ?
You just need to know the property name in order to delete it from the object's properties.
delete myjsonobj['otherIndustry'];
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);
_x000D_
If you want to remove a key
when you know the value you can use Object.keys
function which returns an array of a given object's own enumerable properties.
let value="test";
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(myjsonobj);
_x000D_
Further to @T.J. Crowder 's answer, I've added a recursive outer loop that allows one to iterate through all the scripts in an array and then execute a function once all the scripts are loaded:
loadList([array of scripts], 0, function(){// do your post-scriptload stuff})
function loadList(list, i, callback)
{
{
loadScript(list[i], function()
{
if(i < list.length-1)
{
loadList(list, i+1, callback);
}
else
{
callback();
}
})
}
}
Of course you can make a wrapper to get rid of the '0' if you like:
function prettyLoadList(list, callback)
{
loadList(list, 0, callback);
}
Nice work @T.J. Crowder - I was cringing at the 'just add a couple seconds delay before running the callback' I saw in other threads.
For me I was working under Ubuntu
The error disappeared if I use sudo with ng
sudo ng build
sudo ng serve
NetBeans 7 has nice support for HTML5. Previously I was a heavy user of Eclipse, but spend more time with NetBeans to play with HTML5 and Servlet.
That can be caused by unicode or other charset mismatch. Try changing charset in your browser, in of the settings the text will look OK. Then it's question of how to convert your database contents to charset you use for displaying. (Which can actually be just adding utf-8 charset statement to your output.)
The >
is a child selector. So if your HTML looks like this:
<h1 class="hc-reform">
title
<p>stuff here</p>
</h1>
... then that's your ticket.
But if your HTML looks like this:
<h1 class="hc-reform">
title
</h1>
<p>stuff here</p>
Then you want the adjacent selector:
h1.hc-reform + p{
clear:both;
}
Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...
SELECT
(
col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
) AS my_column
FROM
mytable;
Tested on SQLite 3.8.8.3, Thanks!
Yes, it's OK - it's just like using it in an if
statement. Of course, you can't use a break
to break out of a loop from inside a switch.
A find/rename solution. rename is part of util-linux.
You need to descend depth first, because a whitespace filename can be part of a whitespace directory:
find /tmp/ -depth -name "* *" -execdir rename " " "_" "{}" ";"
You can also use: file.getCanonicalFile().delete();
Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.
Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.
Just for the sake of completion: when parsing a date using strptime()
and the date contains the name of a day, month, etc, be aware that you have to account for the locale.
It's mentioned as a footnote in the docs as well.
As an example:
import locale
print(locale.getlocale())
>> ('nl_BE', 'ISO8859-1')
from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'
locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> '2016-03-06'
It is never a good idea to break out of a for-loop. If you are using a for-loop it means that you know how many times you want to iterate. Use a while-loop with 2 conditions.
for example
var done = false
while (i <= length && !done) {
if (sum > 1000) {
done = true
}
}
You can use perl to replace various characters, for example:
$ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
Hello\\ world
Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.
You could use jQuery and do it as such way
$("li:last-child").addClass("someClass");
So this is way late, but I've discovered an answer, in case it becomes useful to anyone who comes across this thread.
Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.
function setUserID(myValue) {
$('#userid').val(myValue)
.trigger('change');
}
Once that's the case,
$('#userid').change(function(){
//fire your ajax call
})
should work as expected.
Chr(Number) should work for you.
select 'Hello' || chr(10) ||' world' from dual
Remember different platforms expect different new line characters:
r := strings(byteData)
This also works to turn []byte
into io.Reader
Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.
They can be removed using pod spec remove SPEC_NAME
then pod setup
It may help to do pod spec remove master
then pod setup
There's also an option to Auto Sync built-in in Aptana.
As another answer says, you can take advantage of truthy/falsy evaluations if you know that 0
is the only falsy element possibly in your array. All elements in an array are falsy iff there are not any truthy elements in it.*
>>> a = np.zeros(10)
>>> not np.any(a)
True
However, the answer claimed that any
was faster than other options due partly to short-circuiting. As of 2018, Numpy's all
and any
do not short-circuit.
If you do this kind of thing often, it's very easy to make your own short-circuiting versions using numba
:
import numba as nb
# short-circuiting replacement for np.any()
@nb.jit(nopython=True)
def sc_any(array):
for x in array.flat:
if x:
return True
return False
# short-circuiting replacement for np.all()
@nb.jit(nopython=True)
def sc_all(array):
for x in array.flat:
if not x:
return False
return True
These tend to be faster than Numpy's versions even when not short-circuiting. count_nonzero
is the slowest.
Some input to check performance:
import numpy as np
n = 10**8
middle = n//2
all_0 = np.zeros(n, dtype=int)
all_1 = np.ones(n, dtype=int)
mid_0 = np.ones(n, dtype=int)
mid_1 = np.zeros(n, dtype=int)
np.put(mid_0, middle, 0)
np.put(mid_1, middle, 1)
# mid_0 = [1 1 1 ... 1 0 1 ... 1 1 1]
# mid_1 = [0 0 0 ... 0 1 0 ... 0 0 0]
Check:
## count_nonzero
%timeit np.count_nonzero(all_0)
# 220 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit np.count_nonzero(all_1)
# 150 ms ± 4.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
### all
# np.all
%timeit np.all(all_1)
%timeit np.all(mid_0)
%timeit np.all(all_0)
# 56.8 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.4 ms ± 1.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 55.9 ms ± 2.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# sc_all
%timeit sc_all(all_1)
%timeit sc_all(mid_0)
%timeit sc_all(all_0)
# 44.4 ms ± 2.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.7 ms ± 599 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 288 ns ± 6.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
### any
# np.any
%timeit np.any(all_0)
%timeit np.any(mid_1)
%timeit np.any(all_1)
# 60.7 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 60 ms ± 287 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.7 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# sc_any
%timeit sc_any(all_0)
%timeit sc_any(mid_1)
%timeit sc_any(all_1)
# 41.7 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.4 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 287 ns ± 12.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
* Helpful all
and any
equivalences:
np.all(a) == np.logical_not(np.any(np.logical_not(a)))
np.any(a) == np.logical_not(np.all(np.logical_not(a)))
not np.all(a) == np.any(np.logical_not(a))
not np.any(a) == np.all(np.logical_not(a))
I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.
import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')
In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,
plt.legend(handles=[red_patch, black_patch])
And the legend ought to appear in the pointplot.
Here are a couple: http://www.amp-what.com/unicode/search/check%20mark
✓ ✔
The proper function is int fileno(FILE *stream)
. It can be found in <stdio.h>
, and is a POSIX standard but not standard C.
Solved using a solution i found googling by Yogi Anand: https://productforums.google.com/d/msg/docs/3qsR2m-1Xx8/sSU6Z6NYLOcJ
The example below counts the number of non-empty rows in the range A3:C, remember to update both ranges in the formula with your range of interest.
=ArrayFormula(SUM(SIGN(MMULT(LEN(A3:C), TRANSPOSE(SIGN(COLUMN(A3:C)))))))
Also make sure to avoid circular dependencies, it will happen if you for example count the number of non-empty rows in A:C and place this formula in the A or C column.
You do need to have a settings.xml linked under user settings (Located in preferences under maven)
But, if that doesn't fix it, like it didn't for many of you. You also have to delete the directory:
.m2/repository/org/apache/maven/archetypes/maven-archetype-quickstart
then quit eclipse and try again.
This is what solved my problem.
In Simple Rails terms:
h
remove html tags into number characters so that rendering won't break your html
html_safe
sets a boolean in string so that the string is considered as html save
raw
It converts to html_safe to string
I really like the concise and functional code provided by azrafe7. So, I have changed it a little bit to convert it to an extension method:
public static class StringExtensions
{
public static string RemoveDiacritics(this string text)
{
const string SINGLEBYTE_LATIN_ASCII_ENCODING = "ISO-8859-8";
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
return Encoding.ASCII.GetString(
Encoding.GetEncoding(SINGLEBYTE_LATIN_ASCII_ENCODING).GetBytes(text));
}
}
there's nothing wrong with your file. xlrd does not yet support xlsx (excel 2007+) files although it's purported to have supported this for some time.
2-days ago they committed a pre-alpha version to their git which integrates xlsx support. Other forums suggest that you use a DOM parser for xlsx files since the xlsx file type is just a zip archive containing XML. I have not tried this. there is another package with similar functionality as xlrd and this is called openpyxl which you can get from easy_install or pip. I have not tried this either, however, its API is supposed to be similar to xlrd.
First thing to do: Check for the PHP version your machine is running.
Command Line: php -version
This will show something like this (in my case):
PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS ) Copyright (c) 1997-2016 The PHP Group
If you are using PHP 5.x.x => run command: sudo apt-get install php5-curl
If PHP 7.x.x => run command (in my case): sudo apt-get install php7.0-curl
Enable this extension by running:
sudo gedit /etc/php/7.0/cli/php.ini
And in the file "php.ini" search for keyword "curl" to find this line below and change it from
;extension=php_curl.dll
To:
extension=php_curl.dll
Next, save your file "php.ini".
Finally, in your command line, restart your server by running: sudo service apache2 restart
.
All the radio buttons options must have the same name for you to be able to select one option at a time.
You can try with:
{% if theList.object_list.count > 0 %}
blah, blah...
{% else %}
blah, blah....
{% endif %}
I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:
<Directory "/Applications/MAMP/bin/mamp">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
You need to change: AllowOverride None To: AllowOverride All
You can do it. That is what big guys do as well.
First query:
» host google.com
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
Next query:
» host google.com
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
As you see, the list of IPs rotated around, but the relative order between two IPs stayed the same.
Update: I see several comments bragging about how DNS round-robin is not convenient for fail-over, so here is the summary: DNS is not for fail-over. So it is obviously not good for fail-over. It was never designed to be a solution for fail-over.
Put from before where, and order_by on last:
$this->db->select('*');
$this->db->from('courses');
$this->db->where('tennant_id',$tennant_id);
$this->db->order_by("UPPER(course_name)","desc");
Or try BINARY:
ORDER BY BINARY course_name DESC;
You should add manually on codeigniter for binary sorting.
And set "course_name" character column.
If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.
What type of structure data in courses table?
If you frustrated you can put into array and return using PHP:
Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)
Your array from database as example: $array_db = $result_from_db
:
$final_result = natcasesort($array_db);
print_r($final_result);
All you have to do is go to GitHub settings repositories and you see all the sizes right there in the browser no extra work needed.
git status
will also give the branch name along with changes.
e.g.
>git status
On branch master // <-- branch name here
.....
Try this out:
grep "Killed process" /var/log/syslog
I had the same issue. How I resolved it was:
in mac os you can try brew install gradle
The examples to os.walk in the documentation show how to do this:
for root, dirs, filenames in os.walk(indir):
for f in filenames:
log = open(os.path.join(root, f),'r')
How did you expect the "open" function to know that the string "1" is supposed to mean "/home/des/test/1" (unless "/home/des/test" happens to be your current working directory)?
As others have mentioned, comments are referenced with a #
and are documented here. However, unlike some languages, the #
must be at the beginning of the line. If they occur part way through the line, they are interpreted as an argument and may result in unexpected behavior.
# This is a comment
COPY test_dir target_dir # This is not a comment, it is an argument to COPY
RUN echo hello world # This is an argument to RUN but the shell may ignore it
It should also be noted that parser directives have recently been added to the Dockerfile which have the same syntax as a comment. They need to appear at the top of the file, before any other comments or commands. Originally, this directive was added for changing the escape character to support Windows:
# escape=`
FROM microsoft/nanoserver
COPY testfile.txt c:\
RUN dir c:\
The first line, while it appears to be a comment, is a parser directive to change the escape character to a backtick so that the COPY
and RUN
commands can use the backslash in the path. A parser directive is also used with BuildKit to change the frontend parser with a syntax
line. See the experimental syntax for more details on how this is being used in practice.
With a multi-line command, the commented lines are ignored, but you need to comment out every line individually:
$ cat Dockerfile
FROM busybox:latest
RUN echo first command \
# && echo second command disabled \
&& echo third command
$ docker build .
Sending build context to Docker daemon 23.04kB
Step 1/2 : FROM busybox:latest
---> 59788edf1f3e
Step 2/2 : RUN echo first command && echo third command
---> Running in b1177e7b563d
first command
third command
Removing intermediate container b1177e7b563d
---> 5442cfe321ac
Successfully built 5442cfe321ac
Easy! Just use jQuery's click function:
$("#theElement").click();
You just use dangerouslySetInnerHTML method of React
<div dangerouslySetInnerHTML={{ __html: htmlString }} />
Or you can implement more with this easy way: Render the HTML raw in React app
package com.tulu.ds;
public class EmailSecurity {
public static void main(String[] args) {
System.out.println(returnSecuredEmailID("[email protected]"));
}
private static String returnSecuredEmailID(String email){
String str=email.substring(1, email.lastIndexOf("@")-1);
return email.replaceAll(email.substring(1, email.lastIndexOf("@")-1),replacewith(str.length(),"*"));
}
private static String replacewith(int length,String replace) {
String finalStr="";
for(int i=0;i<length;i++){
finalStr+=replace;
}
return finalStr;
}
}
If /foo/bar
is on NFS (or possibly some FUSE filesystem), that might be the problem.
Either way, adding -O
/ --omit-dir-times
to your command line will avoid it trying to set modification times on directories.
you can turn the ":" to space, and do the split.eg
>>> f=open("/proc/net/dev")
>>> for line in f:
... line=line.replace(":"," ").split()
... print len(line)
no regex needed (for this case)
An Identifying relationship specifies that a child object cannot exist without the parent object
Non-identifying relationships specifies a regular association between objects, 1:1 or 1:n cardinality.
Non-identifying relationships can be specified as optional where a parent is not required or mandatory where a parent is required by setting the parent table cardinality...
<marquee behavior=scroll direction="left" scrollamount="5">Your message here</marquee>
_x000D_
scrollamount controls the speed of text: higher the value higher is the scrolling speed
Out of interest, this flags up one of R's weird multiple syntax inconsistencies. For example given a two-column data frame:
df <- data.frame(x=1, y=2)
This gives a data frame
subset(df, select=-y)
but this gives a vector
df[,-2]
This is all explained in ?[
but it's not exactly expected behaviour. Well at least not to me...
Just try these steps and i am sure it will definitely help you..
1.Just rename the project.properties to default.properties.
2.Delete your project from eclipse.
3.Again import your project into the eclipse.
Now the problem must be solve.
Please dont forget to give +1.
String.format("%03d", 1) // => "001"
// ¦¦¦ +-- print the number one
// ¦¦+------ ... as a decimal integer
// ¦+------- ... minimum of 3 characters wide
// +-------- ... pad with zeroes instead of spaces
See java.util.Formatter
for more information.
in Swift 4.2 it is a property now.
override var prefersStatusBarHidden: Bool {
return true
}
One way is to use ANSI escape sequences:
import sys
import time
for i in range(10):
print("Loading" + "." * i)
sys.stdout.write("\033[F") # Cursor up one line
time.sleep(1)
Also sometimes useful (for example if you print something shorter than before):
sys.stdout.write("\033[K") # Clear to the end of line
Take a look at this answer: ImportError: no module named win32api
You can use
pip install pypiwin32
If you want to use it as a background image, you will need to use the new <ImageBackground>
component introduced at the end of June 2017 in v0.46. It supports nesting while <Image>
soon won't.
Here is the commit summary:
We are removing support of nesting views inside component. We decided to do this because having this feature makes supporting
intrinsinc content size
of the<Image>
impossible; so when the transition process is complete, there will be no need to specify image size explicitly, it can be inferred from actual image bitmap.And this is the step #0.
is very simple drop-in replacement which implements this functionality via very simple styling. Please, use instead of if you want to put something inside.
When I encountered this exception, there was an InnerException "Transaction Timeout". Since this was during a debug session, when I halted my code for some time inside the TransactionScope, I chose to ignore this issue.
When this specific exception with a timeout appears in deployed code, I think that the following section in you .config file will help you out:
<system.transactions>
<machineSettings maxTimeout="00:05:00" />
</system.transactions>
Actually if you create func:
create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;
and view:
create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;
Then you can call a view with a parameter:
select s.* from (select @p1:=12 p) parm , h_parm s;
I hope it helps.
For all the standard library types the member function empty()
is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents".
The clear()
member function is inherited from ios
and is used to clear the error state of the stream, e.g. if a file stream has the error state set to eofbit
(end-of-file), then calling clear()
will set the error state back to goodbit
(no error).
For clearing the contents of a stringstream
, using:
m.str("");
is correct, although using:
m.str(std::string());
is technically more efficient, because you avoid invoking the std::string
constructor that takes const char*
. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.
// I used this code with the fpdf library.
// Este código lo usé con la libreria fpdf.
var datas = json1;
var xhr = new XMLHttpRequest();
xhr.open("POST", "carpeta/archivo.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status === 200) {
var blob = new Blob([xhr.response], {type: 'application/pdf'});
const url = window.URL.createObjectURL(blob);
window.open(url,"_blank");
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(datas)
, 100
})
}
};
xhr.send("men="+datas);
Server version: 8.0.19 Homebrew. macOS Catalina 10.15.5 and installed MySQL via Homebrew. Found this file here:
/usr/local/etc/my.cnf
This solution helped :)
Use the Java 8 solution. Note DatatypeConverter can still be used, but it is now within the java.xml.bind
module which will need to be included.
module org.example.foo {
requires java.xml.bind;
}
Java 8 now provides java.util.Base64
for encoding and decoding base64.
Encoding
byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
Decoding
byte[] decoded = Base64.getDecoder().decode("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// => hello world
Since Java 6 the lesser known class javax.xml.bind.DatatypeConverter
can be used. This is part of the JRE, no extra libraries required.
Encoding
byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
Decoding
byte[] decoded = DatatypeConverter.parseBase64Binary("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, "UTF-8"));
// => hello world
You can try VCS to ICS file converter (Java, works with Windows, Mac, Linux etc.). It has the feature of parsing events and todos. You can convert the VCS generated by your Nokia phone, with bluetooth export or via nbuexplorer.
"N/A"
is not an integer. It must throw NumberFormatException
if you try to parse it to an integer.
Check before parsing or handle Exception
properly.
Exception Handling
try{
int i = Integer.parseInt(input);
} catch(NumberFormatException ex){ // handle your exception
...
}
or - Integer pattern matching -
String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
...
}
Here is an example of Jon Adams suggestion above in order to fix a div (toolbar) to the right hand side of your page element using jQuery. The idea is to find the distance from the right hand side of the viewport to the right hand side of the page element and to keep the right hand side of the toolbar there!
<div id="pageElement"></div>
<div id="toolbar"></div>
#toolbar {
position: fixed;
}
....
function placeOnRightHandEdgeOfElement(toolbar, pageElement) {
$(toolbar).css("right", $(window).scrollLeft() + $(window).width()
- $(pageElement).offset().left
- parseInt($(pageElement).css("borderLeftWidth"),10)
- $(pageElement).width() + "px");
}
$(document).ready(function() {
$(window).resize(function() {
placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
});
$(window).scroll(function () {
placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
});
$("#toolbar").resize();
});
It seems there is a change in how Application.COUNTA works in VB7 vs VB6. I tried the following in both versions of VB.
ReDim allData(0 To 1, 0 To 15)
Debug.Print Application.WorksheetFunction.CountA(allData)
In VB6 this returns 0.
Inn VB7 it returns 32
Looks like VB7 doesn't consider COUNTA to be COUNTA anymore.
These are class stereotypes used in analysis.
boundary classes are ones at the boundary of the system - the classes that you or other systems interact with
entity classes classes are your typical business entities like "person" and "bank account"
control classes implement some business logic or other
Capture the onContextMenu
event, and return false in the event handler.
You can also capture the click event and check which mouse button fired the event with event.button
, in some browsers anyway.
For me, it worked best to add this in image css: max-width:100%;
and NOT specify image width and height in html parameters. This adjusted the width to fit in device screen while adjusting height automatically. Otherwise height might be distorted.
Try with bufferFileWriter.append, it works with me.
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
bufferFileWriter.append(obj.toJSONString());
bufferFileWriter.newLine();
bufferFileWriter.close();
} catch (IOException ex) {
Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
If your console supports ANSI colour codes (e.g. ConEmu, Clink or ANSICON) you can do this:
SET GRAY=%ESC%[0m
SET RED=%ESC%[1;31m
SET GREEN=%ESC%[1;32m
SET ORANGE=%ESC%[0;33m
SET BLUE=%ESC%[0;34m
SET MAGENTA=%ESC%[0;35m
SET CYAN=%ESC%[1;36m
SET WHITE=%ESC%[1;37m
where ESC variable contains ASCII character 27.
I found a way to populate the ESC variable here: http://www.dostips.com/forum/viewtopic.php?p=6827#p6827
and using tasklist
it's possible to test what DLLs are loaded into a process.
The following script gets the process ID of the cmd.exe that the script is running in. Checks if it has a dll that will add ANSI support injected, and then sets colour variables to contain escape sequences or be empty depending on whether colour is supported or not.
@echo off
call :INIT_COLORS
echo %RED%RED %GREEN%GREEN %ORANGE%ORANGE %BLUE%BLUE %MAGENTA%MAGENTA %CYAN%CYAN %WHITE%WHITE %GRAY%GRAY
:: pause if double clicked on instead of run from command line.
SET interactive=0
ECHO %CMDCMDLINE% | FINDSTR /L %COMSPEC% >NUL 2>&1
IF %ERRORLEVEL% == 0 SET interactive=1
@rem ECHO %CMDCMDLINE% %COMSPEC% %interactive%
IF "%interactive%"=="1" PAUSE
EXIT /B 0
Goto :EOF
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
: SUBROUTINES :
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::
:INIT_COLORS
::::::::::::::::::::::::::::::::
call :supportsANSI
if ERRORLEVEL 1 (
SET GREEN=
SET RED=
SET GRAY=
SET WHITE=
SET ORANGE=
SET CYAN=
) ELSE (
:: If you can, insert ASCII CHAR 27 after equals and remove BL.String.CreateDEL_ESC routine
set "ESC="
:: use this if can't type ESC CHAR, it's more verbose, but you can copy and paste it
call :BL.String.CreateDEL_ESC
SET GRAY=%ESC%[0m
SET RED=%ESC%[1;31m
SET GREEN=%ESC%[1;32m
SET ORANGE=%ESC%[0;33m
SET BLUE=%ESC%[0;34m
SET MAGENTA=%ESC%[0;35m
SET CYAN=%ESC%[1;36m
SET WHITE=%ESC%[1;37m
)
exit /b
::::::::::::::::::::::::::::::::
:BL.String.CreateDEL_ESC
::::::::::::::::::::::::::::::::
:: http://www.dostips.com/forum/viewtopic.php?t=1733
::
:: Creates two variables with one character DEL=Ascii-08 and ESC=Ascii-27
:: DEL and ESC can be used with and without DelayedExpansion
setlocal
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
ENDLOCAL
set "DEL=%%a"
set "ESC=%%b"
goto :EOF
)
::::::::::::::::::::::::::::::::
:supportsANSI
::::::::::::::::::::::::::::::::
:: returns ERRORLEVEL 0 - YES, 1 - NO
::
:: - Tests for ConEmu, ANSICON and Clink
:: - Returns 1 - NO support, when called via "CMD /D" (i.e. no autoruns / DLL injection)
:: on a system that would otherwise support ANSI.
if "%ConEmuANSI%" == "ON" exit /b 0
call :getPID PID
setlocal
for /f usebackq^ delims^=^"^ tokens^=^* %%a in (`tasklist /fi "PID eq %PID%" /m /fo CSV`) do set "MODULES=%%a"
set MODULES=%MODULES:"=%
set NON_ANSI_MODULES=%MODULES%
:: strip out ANSI dlls from module list:
:: ANSICON adds ANSI64.dll or ANSI32.dll
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ANSI=%"
:: ConEmu attaches ConEmuHk but ConEmu also sets ConEmuANSI Environment VAR
:: so we've already checked for that above and returned early.
@rem set "NON_ANSI_MODULES=%NON_ANSI_MODULES:ConEmuHk=%"
:: Clink supports ANSI https://github.com/mridgers/clink/issues/54
set "NON_ANSI_MODULES=%NON_ANSI_MODULES:clink_dll=%"
if "%MODULES%" == "%NON_ANSI_MODULES%" endlocal & exit /b 1
endlocal
exit /b 0
::::::::::::::::::::::::::::::::
:getPID [RtnVar]
::::::::::::::::::::::::::::::::
:: REQUIREMENTS:
::
:: Determine the Process ID of the currently executing script,
:: but in a way that is multiple execution safe especially when the script can be executing multiple times
:: - at the exact same time in the same millisecond,
:: - by multiple users,
:: - in multiple window sessions (RDP),
:: - by privileged and non-privileged (e.g. Administrator) accounts,
:: - interactively or in the background.
:: - work when the cmd.exe window cannot appear
:: e.g. running from TaskScheduler as LOCAL SERVICE or using the "Run whether user is logged on or not" setting
::
:: https://social.msdn.microsoft.com/Forums/vstudio/en-US/270f0842-963d-4ed9-b27d-27957628004c/what-is-the-pid-of-the-current-cmdexe?forum=msbuild
::
:: http://serverfault.com/a/654029/306
::
:: Store the Process ID (PID) of the currently running script in environment variable RtnVar.
:: If called without any argument, then simply write the PID to stdout.
::
::
setlocal disableDelayedExpansion
:getLock
set "lock=%temp%\%~nx0.%time::=.%.lock"
set "uid=%lock:\=:b%"
set "uid=%uid:,=:c%"
set "uid=%uid:'=:q%"
set "uid=%uid:_=:u%"
setlocal enableDelayedExpansion
set "uid=!uid:%%=:p!"
endlocal & set "uid=%uid%"
2>nul ( 9>"%lock%" (
for /f "skip=1" %%A in (
'wmic process where "name='cmd.exe' and CommandLine like '%%<%uid%>%%'" get ParentProcessID'
) do for %%B in (%%A) do set "PID=%%B"
(call )
))||goto :getLock
del "%lock%" 2>nul
endlocal & if "%~1" equ "" (echo(%PID%) else set "%~1=%PID%"
exit /b
Between tuple and nested dictionaries based approaches, it's almost always better to go for tuple based.
From maintainability point of view,
its much easier to implement a functionality that looks like:
var myDict = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
than
var myDict = new Dictionary<TypeA, Dictionary<TypeB, Dictionary<TypeC, string>>>();
from the callee side. In the second case each addition, lookup, removal etc require action on more than one dictionary.
Furthermore, if your composite key require one more (or less) field in future, you will need to change code a significant lot in the second case (nested dictionary) since you have to add further nested dictionaries and subsequent checks.
From performance perspective, the best conclusion you can reach is by measuring it yourself. But there are a few theoretical limitations which you can consider beforehand:
In the nested dictionary case, having an additional dictionary for every keys (outer and inner) will have some memory overhead (more than what creating a tuple would have).
In the nested dictionary case, every basic action like addition, updation, lookup, removal etc need to be carried out in two dictionaries. Now there is a case where nested dictionary approach can be faster, i.e., when the data being looked up is absent, since the intermediate dictionaries can bypass the full hash code computation & comparison, but then again it should be timed to be sure. In presence of data, it should be slower since lookups should be performed twice (or thrice depending on nesting).
Regarding tuple approach, .NET tuples are not the most performant when they're meant to be used as keys in sets since its Equals
and GetHashCode
implementation causes boxing for value types.
I would go with tuple based dictionary, but if I want more performance, I would use my own tuple with better implementation.
On a side note, few cosmetics can make the dictionary cool:
Indexer style calls can be a lot cleaner and intuitive. For eg,
string foo = dict[a, b, c]; //lookup
dict[a, b, c] = ""; //update/insertion
So expose necessary indexers in your dictionary class which internally handles the insertions and lookups.
Also, implement a suitable IEnumerable
interface and provide an Add(TypeA, TypeB, TypeC, string)
method which would give you collection initializer syntax, like:
new MultiKeyDictionary<TypeA, TypeB, TypeC, string>
{
{ a, b, c, null },
...
};
General sibling combinator
The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.
Global die() function for development purposes:
var die = function(msg) {
throw new Error(msg);
}
Use die():
die('Error message here');
Another way. Will preserve keys as well.
function array_unique_multidimensional($input)
{
$serialized = array_map('serialize', $input);
$unique = array_unique($serialized);
return array_intersect_key($input, $unique);
}
command > file >&1
Probably the simplest way is to use curl
for this, there is no need to install any additional packages and it can be configured directly in a request.
Here is an example using gmail smtp server:
curl --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from '[email protected]' \
--mail-rcpt '[email protected]' \
--user '[email protected]:YourPassword' \
-T <(echo -e 'From: [email protected]\nTo: [email protected]\nSubject: Curl Test\n\nHello')
If you used Aptitude (apt-get) to install Jenkins on Ubuntu 12.04, uncomment the JAVA_ARGS
line in the top few lines of /etc/default/jenkins
:
# arguments to pass to java
#JAVA_ARGS="-Xmx256m" # <--default value
JAVA_ARGS="-Xmx2048m"
#JAVA_ARGS="-Djava.net.preferIPv4Stack=true" # make jenkins listen on IPv4 address
The usual pattern is EXISTS(subselect)
:
BEGIN
IF EXISTS(SELECT name
FROM test_table t
WHERE t.id = x
AND t.name = 'test')
THEN
---
ELSE
---
END IF;
This pattern is used in PL/SQL, PL/pgSQL, SQL/PSM, ...
After not much success with any of the answers available here so far.
My solution:
I downloaded the jar file manually and then installed the dependency by using Apache Maven install:install-file
plugin, see more details here
A Full Example:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.4</version>
</dependency>
Download jar file from here
Install it by using the following command:
mvn -X install:install-file " -DgroupId=commons-net" "-DartifactId=commons-net" "-Dversion=3.4" "-Dpackaging=jar" "-Dfile={your_full_downloads_path}/commons-net-3.4.jar"
Maven->Update Project
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
#grad1 {
height: 400px;
width: 600px;
background-image: url(t1.jpg);/* Select Image Hare */
}
#gradup {
height: 100%;
width: 100%;
background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */
}
</style>
</head>
<body>
<h1>Fade Image Edge With Radial Gradient</h1>
<div id="grad1"><div id="gradup"></div></div>
</body>
</html>
The traffic will show up in Fiddler under your computer's IP address.
its better to bind a click handler to the entire table and then use event.target to get the clicked TD. Thats all i can add to this as its 1:20am
this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.
Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output
This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command
start -> run -> %temp%
The easiest way is to use a regular expression.
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
The above expression will remove the last dot followed by one or more characters. Here's a basic unit test.
public void testRegex() {
assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
Here has an easy way to solve this.
<?php
$date = "2015-11-17";
echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>
Output will be:
2015-11-22
Solution has found from here - How to Add Days to Date in PHP
The problem with homebrew/versions
is that someone has to have that specific version of software listed in the repository for you to be able to use it. Also, since brew versions
is no longer supported, another solution is required. For solutions that indicate using brew switch
, this will only work if you haven't done a brew cleanup
since the version needs to exist on your computer.
I had a problem with wanting to install a specific older version of docker-machine
which wasn't listed in homebrew/versions
. I solved this using the below, which should also work for any brew installed software. The example below will use docker-machine
as the package I want to downgrade from version 0.5.0 to 0.4.1.
Go to your homebrew Formula
directory.
You can determine this by running brew info [any package name]
.
For example, brew info docker-machine
gives me a line that shows me
a path - /usr/local/Cellar/docker-machine/0.5.0
. This tells me that on my machine, homebrew is installed at /usr/local
and my Formula
directory is located by default at /usr/local/Library/Formula
Locate the specific formula file (.rb) for your package.
Since I want to downgrade docker-machine
, I can see a docker-machine.rb
file.
Get the version history for this formula file .
Enter git log docker-machine.rb
. This will list out the complete commit history for this file. You will see output like this:
...more commit 20c7abc13d2edd67c8c1d30c407bd5e31229cacc Author: BrewTestBot Date: Thu Nov 5 16:14:18 2015 +0000 docker-machine: update 0.5.0 bottle. commit 8f615708184884e501bf5c16482c95eff6aea637 Author: Vincent Lesierse Date: Tue Oct 27 22:25:30 2015 +0100 docker-machine 0.5.0 Updated docker-machine to 0.5.0 Closes #45403. Signed-off-by: Dominyk Tiller commit 5970e1af9b13dcbeffd281ae57c9ab90316ba423 Author: BrewTestBot Date: Mon Sep 21 14:04:04 2015 +0100 docker-machine: update 0.4.1 bottle. commit 18fcbd36d22fa0c19406d699308fafb44e4c8dcd Author: BrewTestBot Date: Sun Aug 16 09:05:56 2015 +0100 docker-machine: update 0.4.1 bottle. ...more
The tricky part is to find the latest commit for the specific version you want. In the above, I can tell the latest 0.4.1 version was committed with this commit tag : commit 5970e1af9b13dcbeffd281ae57c9ab90316ba423
. The commits above this point start using version 0.5.0 (git log entries are listed from latest to earliest date).
Get a previous version of the formula file. Using the commit tag from step #3 (you can use the first 6 chars), you can get an older version of the formula file using the following:
git checkout 5970e1 docker-machine.rb
Uninstall your current package version.
Just run the normal brew commands to uninstall the current version of your package.
Ex. brew uninstall docker-machine
Install the older package version
Now, you can just run the normal brew install command and it will install the formula that you have checkout out.
Ex. brew install docker-machine
You may need to re-link by using the brew link docker-machine
if necessary.
If at any time you want to revert back to the latest version of a specific package, go into the Formula directory and issue the following commands on your formula file (.rb)
git reset HEAD docker-machine.rb
git checkout -- docker-machine.rb
Then you can brew uninstall docker-machine
and brew install docker-machine
to get the latest version and keep it that way going forward.
Update pandas 0.17.0
@7stud's answer for the newest pandas version would require to just call
s.plot(
kind='bar',
color=my_colors,
)
instead of
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
The plotting functions have become members of the Series, DataFrame objects and in fact calling pd.Series.plot
with a color
argument gives an error
Example in Swift, picturing the foundry's explanation above and the Apple's documentation:
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func dismissViewController1AndPresentViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
self.presentViewController(vc1, animated: true, completion: nil)
}
func dismissViewController1AndPresentViewController2() {
self.dismissViewControllerAnimated(false, completion: { () -> Void in
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.presentViewController(vc2, animated: true, completion: nil)
})
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.dismissViewController1AndPresentViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func popViewController1AndPushViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
self.navigationController?.pushViewController(vc1, animated: true)
}
func popViewController1AndPushViewController2() {
self.navigationController?.popViewControllerAnimated(false)
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.navigationController?.pushViewController(vc2, animated: true)
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.popViewController1AndPushViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
It uses the byte values of the characters, returning a negative value if the first string appears before the second (ordered by byte values), zero if they are equal, and a positive value if the first appears after the second. Since it operates on bytes, it is not encoding-aware.
For example:
strcmp("abc", "def") < 0
strcmp("abc", "abcd") < 0 // null character is less than 'd'
strcmp("abc", "ABC") > 0 // 'a' > 'A' in ASCII
strcmp("abc", "abc") == 0
More precisely, as described in the strcmp Open Group specification:
The sign of a non-zero return value shall be determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the strings being compared.
Note that the return value may not be equal to this difference, but it will carry the same sign.
Unless the role was made dbo, db_owner or db_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:
GRANT ALL ON table1 TO doctor
Users in that role will have no permissions whatsoever to other tables (not even read).
File names are case sensitive - please check your file name. it should be in same case in view folder
just for the record you can always compare using JSON.stringify
const arr = [1,2,3];
expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3]));
expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));
It's all meter of taste, this will also work for complex literal objects
There's an option in the Simulator to open the console
Debug > Open System Log
or use the
keyboard shortcut: ?/
Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none;
on a submit button in the form.
If you want to output ALL verbosity, not just stdout. But also any printf statements made by the program, any warnings, infos, etc, you have to add 2>&1
at the end of the command line.
In your case, the command will be
Program.exe > file.txt 2>&1
POSTGRESQL
String psqlAutoincrementQuery = "SELECT NEXTVAL(CONCAT(:psqlTableName, '_id_seq')) as id";
Long psqlAutoincrement = (Long) YOUR_SESSION_OBJ.createSQLQuery(psqlAutoincrementQuery)
.addScalar("id", Hibernate.LONG)
.setParameter("psqlTableName", psqlTableName)
.uniqueResult();
MYSQL
String mysqlAutoincrementQuery = "SELECT AUTO_INCREMENT as id FROM information_schema.tables WHERE table_name = :mysqlTableName AND table_schema = DATABASE()";
Long mysqlAutoincrement = (Long) YOUR_SESSION_OBJ.createSQLQuery(mysqlAutoincrementQuery)
.addScalar("id", Hibernate.LONG)
.setParameter("mysqlTableName", mysqlTableName)
.uniqueResult();
Do you want to chain the Task
s, or can they be invoked in a parallel manner?
For chaining
Just do something like
Task.Run(...).ContinueWith(...).ContinueWith(...).ContinueWith(...);
Task.Factory.StartNew(...).ContinueWith(...).ContinueWith(...).ContinueWith(...);
and don't forget to check the previous Task
instance in each ContinueWith
as it might be faulted.
For the parallel manner
The most simple method I came across: Parallel.Invoke
Otherwise there's Task.WaitAll
or you can even use WaitHandle
s for doing a countdown to zero actions left (wait, there's a new class: CountdownEvent
), or ...
I know I'm a little late to the party here, but I figured I might be able to help any future googlers since none of these answers fixed my issue. Ferdi265's answer helped immensely though.
I'm trying to create my own Linked list, so the following code is what worked for me:
package myList;
import java.lang.reflect.Array;
public class MyList<TYPE> {
private Node<TYPE> header = null;
public void clear() { header = null; }
public void add(TYPE t) { header = new Node<TYPE>(t,header); }
public TYPE get(int position) { return getNode(position).getObject(); }
@SuppressWarnings("unchecked")
public TYPE[] toArray() {
TYPE[] result = (TYPE[])Array.newInstance(header.getObject().getClass(),size());
for(int i=0 ; i<size() ; i++) result[i] = get(i);
return result;
}
public int size(){
int i = 0;
Node<TYPE> current = header;
while(current != null) {
current = current.getNext();
i++;
}
return i;
}
In the toArray() method lies the way to create an array of a generic type for me:
TYPE[] result = (TYPE[])Array.newInstance(header.getObject().getClass(),size());
Remember that window
is the global namespace. These two lines attempt to declare the same variable:
window.APP = { ... }
const APP = window.APP
The second definition is not allowed in strict
mode (enabled with 'use strict'
at the top of your file).
To fix the problem, simply remove the const APP =
declaration. The variable will still be accessible, as it belongs to the global namespace.
First convert your Chart.js canvas to base64 string.
var url_base64 = document.getElementById('myChart').toDataURL('image/png');
Set it as a href attribute for anchor tag.
link.href = url_base64;
<a id='link' download='filename.png'>Save as Image</a>
You have to remove the borders and add a background image on the input.
.imgClass {
background-image: url(path to image) no-repeat;
width: 186px;
height: 53px;
border: none;
}
It should be good now, normally.
Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel
Perhaps this can be useful for someone:
In my case, I was getting an array of objects, each containing a date set by Mongoose.
I used:
ng-repeat="comment in post.comments | orderBy : sortComment : true"
And defined the function:
$scope.sortComment = function(comment) {
var date = new Date(comment.created);
return date;
};
This worked for me.
the pattern text = <<"HERE" This Is A Multiline String HERE
is not available in js (I remember using it much in my good old Perl days).
To keep oversight with complex or long multiline strings I sometimes use an array pattern:
var myString =
['<div id="someId">',
'some content<br />',
'<a href="#someRef">someRefTxt</a>',
'</div>'
].join('\n');
or the pattern anonymous already showed (escape newline), which can be an ugly block in your code:
var myString =
'<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';
Here's another weird but working 'trick'1:
var myString = (function () {/*
<div id="someId">
some content<br />
<a href="#someRef">someRefTxt</a>
</div>
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];
external edit: jsfiddle
ES20xx supports spanning strings over multiple lines using template strings:
let str = `This is a text
with multiple lines.
Escapes are interpreted,
\n is a newline.`;
let str = String.raw`This is a text
with multiple lines.
Escapes are not interpreted,
\n is not a newline.`;
1 Note: this will be lost after minifying/obfuscating your code
if it's background, use background-size: cover;
body{_x000D_
background-image: url('http://i.stack.imgur.com/kx8MT.gif');_x000D_
background-size: cover;_x000D_
_x000D_
_x000D_
_x000D_
height: 100vh;_x000D_
padding:0;_x000D_
margin:0;_x000D_
}
_x000D_
import json
list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
Write to json File:
with open('/home/ubuntu/test.json', 'w') as fout:
json.dump(list , fout)
Read Json file:
with open(r"/home/ubuntu/test.json", "r") as read_file:
data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
use this i think it is useful for you
var endDate=startDate.setDate(startDate.getDate() + 1);
Remove the coma at the end of your SELECT statement (VALUE,), and also remove the one at the end of your FROM statement (rrf b,)
If your project has Roslyn references and you are deploying it on an IIS server, you might get unwanted errors on the website as many hosting providers still have not upgraded their servers and hence do not support Roslyn.
To resolve this issue, you will need to remove the Roslyn compiler from the project template. Removing Roslyn shouldn't affect your code's functionality. It worked fine for me and some other projects (C# 4.5.2) on which I worked.
Do the following steps:
Remove from following Nuget Packages using command line shown below (or you can use GUI of Nuget Package manager by Right Clicking on Root Project Solution and removing them).
PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
PM> Uninstall-package Microsoft.Net.Compilers
Remove the following code from your Web.Config file and restart IIS. (Use this method only if step 1 doesn't solve your problem.)
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
This can now be done using System.Text.Json
which is built-in to .NET Core 3.0. It's now possible to deserialize JSON without using third-party libraries.
var json = @"{""key1"":""value1"",""key2"":""value2""}";
var values = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
Also available in NuGet package System.Text.Json if using .NET Standard or .NET Framework.
If a pipeline is too complicated to wrap in $(...)
, consider writing a function. Any local variables available at the time of definition will be accessible.
function getHash {
genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5
}
hash=$(getHash)
http://www.gnu.org/software/bash/manual/bashref.html#Shell-Functions
Here we go... just copy the code to a module, it's ready to use
Private Type hashtable
key As Variant
value As Variant
End Type
Private GetErrMsg As String
Private Function CreateHashTable(htable() As hashtable) As Boolean
GetErrMsg = ""
On Error GoTo CreateErr
ReDim htable(0)
CreateHashTable = True
Exit Function
CreateErr:
CreateHashTable = False
GetErrMsg = Err.Description
End Function
Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
GetErrMsg = ""
On Error GoTo AddErr
Dim idx As Long
idx = UBound(htable) + 1
Dim htVal As hashtable
htVal.key = key
htVal.value = value
Dim i As Long
For i = 1 To UBound(htable)
If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
Next i
ReDim Preserve htable(idx)
htable(idx) = htVal
AddValue = idx
Exit Function
AddErr:
AddValue = 0
GetErrMsg = Err.Description
End Function
Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
GetErrMsg = ""
On Error GoTo RemoveErr
Dim i As Long, idx As Long
Dim htTemp() As hashtable
idx = 0
For i = 1 To UBound(htable)
If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
ReDim Preserve htTemp(idx)
AddValue htTemp, htable(i).key, htable(i).value
idx = idx + 1
End If
Next i
If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"
htable = htTemp
RemoveValue = True
Exit Function
RemoveErr:
RemoveValue = False
GetErrMsg = Err.Description
End Function
Private Function GetValue(htable() As hashtable, key As Variant) As Variant
GetErrMsg = ""
On Error GoTo GetValueErr
Dim found As Boolean
found = False
For i = 1 To UBound(htable)
If htable(i).key = key And IsEmpty(htable(i).key) = False Then
GetValue = htable(i).value
Exit Function
End If
Next i
Err.Raise 9997, , "Key [" & CStr(key) & "] not found"
Exit Function
GetValueErr:
GetValue = ""
GetErrMsg = Err.Description
End Function
Private Function GetValueCount(htable() As hashtable) As Long
GetErrMsg = ""
On Error GoTo GetValueCountErr
GetValueCount = UBound(htable)
Exit Function
GetValueCountErr:
GetValueCount = 0
GetErrMsg = Err.Description
End Function
To use in your VB(A) App:
Public Sub Test()
Dim hashtbl() As hashtable
Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
Debug.Print ""
Debug.Print "ID Test Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
Debug.Print ""
Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
Debug.Print ""
Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
Debug.Print ""
Debug.Print "Hashtable Content:"
For i = 1 To UBound(hashtbl)
Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
Next i
Debug.Print ""
Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub
<?php
$address = 'BTM 2nd Stage, Bengaluru, Karnataka 560076'; // Address
$apiKey = 'api-key'; // Google maps now requires an API key.
// Get JSON results from this request
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false&key='.$apiKey);
$geo = json_decode($geo, true); // Convert the JSON to an array
if (isset($geo['status']) && ($geo['status'] == 'OK')) {
$latitude = $geo['results'][0]['geometry']['location']['lat']; // Latitude
$longitude = $geo['results'][0]['geometry']['location']['lng']; // Longitude
}
?>
This one will also work
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
I think this may be a direct solution to calculate the average with a for loop and function.
var elmts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
function average(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++) {
total += arr[i];
}
console.log(Math.round(total/arr.length));
}
average(elmts);
if you mean get the last key alphabetically, you can (garanteed) :
var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var keys = Object.keys(obj);
keys.sort();
var lastkey = keys.pop() // c
var lastvalue = obj[lastkey] // 'carrot'
I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )
I've been using the same approach of saving the hidden TabPages in a private list, but the problem is that when I want to show the TabPage again, they doesn't appears in the original position (order). So, finally, I wrote a class in VB to add the TabControl with two methods: HideTabPageByName and ShowTabPageByName. You can just call the methods passing the name (not the TabPage instance).
Public Class CS_Control_TabControl
Inherits System.Windows.Forms.TabControl
Private mTabPagesHidden As New Dictionary(Of String, System.Windows.Forms.TabPage)
Private mTabPagesOrder As List(Of String)
Public Sub HideTabPageByName(ByVal TabPageName As String)
If mTabPagesOrder Is Nothing Then
' The first time the Hide method is called, save the original order of the TabPages
mTabPagesOrder = New List(Of String)
For Each TabPageCurrent As TabPage In Me.TabPages
mTabPagesOrder.Add(TabPageCurrent.Name)
Next
End If
If Me.TabPages.ContainsKey(TabPageName) Then
Dim TabPageToHide As TabPage
' Get the TabPage object
TabPageToHide = TabPages(TabPageName)
' Add the TabPage to the internal List
mTabPagesHidden.Add(TabPageName, TabPageToHide)
' Remove the TabPage from the TabPages collection of the TabControl
Me.TabPages.Remove(TabPageToHide)
End If
End Sub
Public Sub ShowTabPageByName(ByVal TabPageName As String)
If mTabPagesHidden.ContainsKey(TabPageName) Then
Dim TabPageToShow As TabPage
' Get the TabPage object
TabPageToShow = mTabPagesHidden(TabPageName)
' Add the TabPage to the TabPages collection of the TabControl
Me.TabPages.Insert(GetTabPageInsertionPoint(TabPageName), TabPageToShow)
' Remove the TabPage from the internal List
mTabPagesHidden.Remove(TabPageName)
End If
End Sub
Private Function GetTabPageInsertionPoint(ByVal TabPageName As String) As Integer
Dim TabPageIndex As Integer
Dim TabPageCurrent As TabPage
Dim TabNameIndex As Integer
Dim TabNameCurrent As String
For TabPageIndex = 0 To Me.TabPages.Count - 1
TabPageCurrent = Me.TabPages(TabPageIndex)
For TabNameIndex = TabPageIndex To mTabPagesOrder.Count - 1
TabNameCurrent = mTabPagesOrder(TabNameIndex)
If TabNameCurrent = TabPageCurrent.Name Then
Exit For
End If
If TabNameCurrent = TabPageName Then
Return TabPageIndex
End If
Next
Next
Return TabPageIndex
End Function
Protected Overrides Sub Finalize()
mTabPagesHidden = Nothing
mTabPagesOrder = Nothing
MyBase.Finalize()
End Sub
End Class
My general answer to this kind of question on "efficiency" is almost always, which ever version of the code is most readable, is the most efficient.
That being said, I think (val.ToLowerCase() == "astringvalue")
is pretty understandable at a glance by most people.
The efficience I refer to is not necesseraly in the execution of the code but rather in the maintanance and generally readability of the code in question.
This below query worked for me. This can able to show the databases,tables,column names,data types and columns count.
**select table_schema Schema_Name ,table_name TableName,column_name ColumnName,ordinal_position "Position",column_type DataType,COUNT(1) ColumnCount
FROM information_schema.columns
GROUP by table_schema,table_name,column_name,ordinal_position, column_type;**
You should probably take a look at the various flavours of getResource in the ClassLoader class: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html.
generate-schema
(NPM | Github) takes a JSON Object generates schemas from it, one output is JSON Schema, it's written in Node.js and comes with a REPL and ClI tool for piping files into.
Full Disclosure: I'm the author :)