var array = string.split(',')
and good morning, too, since I have to type 30 chars ...
Here is the Angular version of LightBox. Just Awesome :)
Note : I have put this answer hence No Js library has been mentioned under the Tags.
<ul ng-controller="GalleryCtrl">
<li ng-repeat="image in images">
<a ng-click="openLightboxModal($index)">
<img ng-src="{{image.thumbUrl}}" class="img-thumbnail">
</a>
</li>
</ul>
When you use DateTime you are able to store a date and a time inside a variable.
The date can be a local time or a UTC time, it depend on you.
For example, I'm in Italy (+2 UTC)
var dt1 = new DateTime(2011, 6, 27, 12, 0, 0); // store 2011-06-27 12:00:00
var dt2 = dt1.ToUniversalTime() // store 2011-06-27 10:00:00
So, what happen when I print dt1 and dt2 including the timezone?
dt1.ToString("MM/dd/yyyy hh:mm:ss z")
// Compiler alert...
// Output: 06/27/2011 12:00:00 +2
dt2.ToString("MM/dd/yyyy hh:mm:ss z")
// Compiler alert...
// Output: 06/27/2011 10:00:00 +2
dt1 and dt2 contain only a date and a time information. dt1 and dt2 don't contain the timezone offset.
So where the "+2" come from if it's not contained in the dt1 and dt2 variable?
It come from your machine clock setting.
The compiler is telling you that when you use the 'zzz' format you are writing a string that combine "DATE + TIME" (that are store in dt1 and dt2) + "TIMEZONE OFFSET" (that is not contained in dt1 and dt2 because they are DateTyme type) and it will use the offset of the server machine that it's executing the code.
The compiler tell you "Warning: the output of your code is dependent on the machine clock offset"
If i run this code on a server that is positioned in London (+1 UTC) the result will be completly different: instead of "+2" it will write "+1"
...
dt1.ToString("MM/dd/yyyy hh:mm:ss z")
// Output: 06/27/2011 12:00:00 +1
dt2.ToString("MM/dd/yyyy hh:mm:ss z")
// Output: 06/27/2011 10:00:00 +1
The right solution is to use DateTimeOffset data type in place of DateTime. It's available in sql Server starting from the 2008 version and in the .Net framework starting from the 3.5 version
Not hardcore technology but I really enjoy Drunk and Retired. It's like you're talking to your programmer buddy mixed in with life stuff.
Javascript inheritance seems to be like an open debate everywhere. It can be called "The curious case of Javascript language".
The idea is that there is a base class and then you extend the base class to get an inheritance-like feature (not completely, but still).
The whole idea is to get what prototype really means. I did not get it until I saw John Resig's code (close to what jQuery.extend
does) wrote a code chunk that does it and he claims that base2 and prototype libraries were the source of inspiration.
Here is the code.
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
There are three parts which are doing the job. First, you loop through the properties and add them to the instance. After that, you create a constructor for later to be added to the object.Now, the key lines are:
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
You first point the Class.prototype
to the desired prototype. Now, the whole object has changed meaning that you need to force the layout back to its own one.
And the usage example:
var Car = Class.Extend({
setColor: function(clr){
color = clr;
}
});
var volvo = Car.Extend({
getColor: function () {
return color;
}
});
Read more about it here at Javascript Inheritance by John Resig 's post.
Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.
The entity type 'DisplayFormatAttribute' requires a primary key to be defined.
In my case I figured out the problem was that I used properties like this:
public string LastName { get; set; } //OK
public string Address { get; set; } //OK
public string State { get; set; } //OK
public int? Zip { get; set; } //OK
public EmailAddressAttribute Email { get; set; } // NOT OK
public PhoneAttribute PhoneNumber { get; set; } // NOT OK
Not sure if there is a better way to solve it but I changed the Email and PhoneNumber attribute to a string. Problem solved.
If you want to reset the window layout. Then
go to "WINDOW" -> "RESET WINDOW LAYOUT"
Except when it is the operand of the sizeof
or unary &
operator, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T
" is converted ("decays") to an expression of type "pointer to T
", and the value of the expression is the address of the first element of the array.
If the declaration of the array being passed is
int S[4][4] = {...};
then when you write
rotateArr( S );
the expression S
has type "4-element array of 4-element array of int
"; since S
is not the operand of the sizeof
or unary &
operators, it will be converted to an expression of type "pointer to 4-element array of int
", or int (*)[4]
, and this pointer value is what actually gets passed to rotateArr
. So your function prototype needs to be one of the following:
T rotateArr( int (*arr)[4] )
or
T rotateArr( int arr[][4] )
or even
T rotateArr( int arr[4][4] )
In the context of a function parameter list, declarations of the form T a[N]
and T a[]
are interpreted as T *a
; all three declare a
as a pointer to T
.
You're probably wondering why I changed the return type from int
to T
. As written, you're trying to return a value of type "4-element array of 4-element array of int
"; unfortunately, you can't do that. C functions cannot return array types, nor can you assign array types. IOW, you can't write something like:
int a[N], b[N];
...
b = a; // not allowed
a = f(); // not allowed either
Functions can return pointers to arrays, but that's not what you want here. D
will cease to exist once the function returns, so any pointer you return will be invalid.
If you want to assign the results of the rotated array to a different array, then you'll have to pass the target array as a parameter to the function:
void rotateArr( int (*dst)[4], int (*src)[4] )
{
...
dst[i][n] = src[n][M - i + 1];
...
}
And call it as
int S[4][4] = {...};
int D[4][4];
rotateArr( D, S );
pretty sure you just want the plain old replace function. use like this:
myString.replace('username1','');
i suppose if you want to remove the trailing comma do this instead:
myString.replace('username1,','');
edit:
here is your site specific code:
jQuery("#post_like_list-510").text().replace(...)
Adding solution for CentOs 7 (python 3.6.x)
yum install python36-tkinter
I had tried about every version possible, hopefully this helps out others.
I use this way with Resource file (don't need Prompt anymore !)
@Html.TextBoxFor(m => m.Name, new
{
@class = "form-control",
placeholder = @Html.DisplayName(@Resource.PleaseTypeName),
autofocus = "autofocus",
required = "required"
})
All standard implementations of java.util.List
already implement java.io.Serializable
.
So even though java.util.List
itself is not a subtype of java.io.Serializable
, it should be safe to cast the list to Serializable
, as long as you know it's one of the standard implementations like ArrayList
or LinkedList
.
If you're not sure, then copy the list first (using something like new ArrayList(myList)
), then you know it's serializable.
If you have a foreign key definition in some table and the name of the foreign key is used elsewhere as another foreign key you will have this error.
Above one has some syntax error, Please use following on oracle:
SELECT ROUND (totalSeconds / (24 * 60 * 60), 1) TotalTimeSpendIn_DAYS,
ROUND (totalSeconds / (60 * 60), 0) TotalTimeSpendIn_HOURS,
ROUND (totalSeconds / 60) TotalTimeSpendIn_MINUTES,
ROUND (totalSeconds) TotalTimeSpendIn_SECONDS
FROM
(SELECT ROUND ( EXTRACT (DAY FROM timeDiff) * 24 * 60 * 60 + EXTRACT (HOUR FROM timeDiff) * 60 * 60 + EXTRACT (MINUTE FROM timeDiff) * 60 + EXTRACT (SECOND FROM timeDiff)) totalSeconds
FROM
(SELECT TO_TIMESTAMP(TO_CHAR( date2 , 'yyyy-mm-dd HH24:mi:ss'), 'yyyy-mm-dd HH24:mi:ss') - TO_TIMESTAMP(TO_CHAR(date1, 'yyyy-mm-dd HH24:mi:ss'),'yyyy-mm-dd HH24:mi:ss') timeDiff
FROM TABLENAME
)
);
I really liked these articles:
He really dumbs down the concept in a humorous way. Worth reading.
A stream is an object used to transfer data. There is a generic stream class System.IO.Stream
, from which all other stream classes in .NET are derived. The Stream
class deals with bytes.
The concrete stream classes are used to deal with other types of data than bytes. For example:
FileStream
class is used when the outside source is a fileMemoryStream
is used to store data in memorySystem.Net.Sockets.NetworkStream
handles network dataReader/writer streams such as StreamReader
and StreamWriter
are not streams - they are not derived from System.IO.Stream
, they are designed to help to write and read data from and to stream!
From iOS 8 we can use the new isOperatingSystemAtLeastVersion
method on NSProcessInfo
NSOperatingSystemVersion ios8_0_1 = (NSOperatingSystemVersion){8, 0, 1};
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:ios8_0_1]) {
// iOS 8.0.1 and above logic
} else {
// iOS 8.0.0 and below logic
}
Beware that this will crash on iOS 7, as the API didn't exist prior to iOS 8. If you're supporting iOS 7 and below, you can safely perform the check with
if ([NSProcessInfo instancesRespondToSelector:@selector(isOperatingSystemAtLeastVersion:)]) {
// conditionally check for any version >= iOS 8 using 'isOperatingSystemAtLeastVersion'
} else {
// we're on iOS 7 or below
}
For the sake of completeness, here's an alternative approach proposed by Apple itself in the iOS 7 UI Transition Guide, which involves checking the Foundation Framework version.
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
// Load resources for iOS 6.1 or earlier
} else {
// Load resources for iOS 7 or later
}
Try this script to get your browser language
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
Cheers
The li
tag has a property called list-style-position
. This makes your bullets inside or outside the list. On default, it’s set to inside
. That makes your text wrap around it. If you set it to outside
, the text of your li
tags will be aligned.
The downside of that is that your bullets won't be aligned with the text outside the ul
. If you want to align it with the other text you can use a margin.
ul li {
/*
* We want the bullets outside of the list,
* so the text is aligned. Now the actual bullet
* is outside of the list’s container
*/
list-style-position: outside;
/*
* Because the bullet is outside of the list’s
* container, indent the list entirely
*/
margin-left: 1em;
}
Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement
em
’sul
elementThere is an important bit that is not mentioned in the article to which you linked and that is flex-basis
. By default flex-basis
is auto
.
From the spec:
If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)
Each flex item has a flex-basis
which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow
) among the items. With auto
, that basis is the contents size (or defined size with width
, etc.). As a result, items with bigger text within are being given more space overall in your example.
If you want your elements to be completely even, you can set flex-basis: 0
. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow
.
li {
flex-grow: 1;
flex-basis: 0;
/* ... */
}
This diagram from the spec does a pretty good job of illustrating the point.
And here is a working example with your fiddle.
The answer is not to add a newline after writing your string. That may solve a different problem. What you are asking is how to add a newline before you start appending your string. If you want to add a newline, but only if one does not already exist, you need to find out first, by reading the file.
For example,
with open('hst.txt') as fobj:
text = fobj.read()
name = 'Bob'
with open('hst.txt', 'a') as fobj:
if not text.endswith('\n'):
fobj.write('\n')
fobj.write(name)
You might want to add the newline after name, or you may not, but in any case, it isn't the answer to your question.
You update core-js with the following command:
npm install --save core-js@^3
If you read the React Docs you will find that the command is derived from when you need to upgrade React itself.
There are two ways. The easy one is to use the -run
flag and provide a pattern matching names of the tests you want to run.
Example:
$ go test -run NameOfTest
See the docs for more info.
The other way is to name the specific file, containing the tests you want to run:
$ go test foo_test.go
But there's a catch. This works well if:
foo.go
is in package foo
.foo_test.go
is in package foo_test
and imports 'foo'.If foo_test.go
and foo.go
are the same package (a common case) then you must name all other files required to build foo_test
. In this example it would be:
$ go test foo_test.go foo.go
I'd recommend to use the -run
pattern. Or, where/when possible, always run all package tests.
Using method 5 from above (The Pseudo File) we can get very good perf and flexibility
from cStringIO import StringIO
class StringBuilder:
_file_str = None
def __init__(self):
self._file_str = StringIO()
def Append(self, str):
self._file_str.write(str)
def __str__(self):
return self._file_str.getvalue()
now using it
sb = StringBuilder()
sb.Append("Hello\n")
sb.Append("World")
print sb
For react-router
2.4.0+
NOTE: It is advisable to migrate all your code to the latest react-router
to get all the new goodies.
As recommended in the react-router documentation:
One should use the withRouter
higher order component:
We think this new HoC is nicer and easier, and will be using it in documentation and examples, but it is not a hard requirement to switch.
As an ES6 example from the documentation:
import React from 'react'
import { withRouter } from 'react-router'
const Page = React.createClass({
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, () => {
if (this.state.unsaved)
return 'You have unsaved information, are you sure you want to leave this page?'
})
}
render() {
return <div>Stuff</div>
}
})
export default withRouter(Page)
Don't use $(document).ready() just put the script directly in the head section of the page. Pages are processed top to bottom so things at the top are processed first.
Here's another example, showing that operator[]
overwrites the value for the key if it exists, but .insert
does not overwrite the value if it exists.
void mapTest()
{
map<int,float> m;
for( int i = 0 ; i <= 2 ; i++ )
{
pair<map<int,float>::iterator,bool> result = m.insert( make_pair( 5, (float)i ) ) ;
if( result.second )
printf( "%d=>value %f successfully inserted as brand new value\n", result.first->first, result.first->second ) ;
else
printf( "! The map already contained %d=>value %f, nothing changed\n", result.first->first, result.first->second ) ;
}
puts( "All map values:" ) ;
for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )
printf( "%d=>%f\n", iter->first, iter->second ) ;
/// now watch this..
m[5]=900.f ; //using operator[] OVERWRITES map values
puts( "All map values:" ) ;
for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )
printf( "%d=>%f\n", iter->first, iter->second ) ;
}
$('div#someDiv').height('auto');
I like using this, because it's symmetric with how you explicitly used .height(val) to set it in the first place, and works across browsers.
If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:
git log --no-merges --pretty=format:"%s" 'old-tag^'...new-tag > /path/to/changelog.md
--no-merges
omits the merge commits from the listold-tag^
refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).Changing from https:// to http:// worked for me
It's better to avoid unnecessary autoboxing for 2 reasons.
For one thing, it's a bit slower than int < int
, as you're (sometimes) creating an extra object;
void doSomethingWith(Integer integerObject){ ...
int i = 1000;
doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));
The bigger issue is that hidden autoboxing can hide exceptions:
void doSomethingWith (Integer count){
if (count>0) // gets compiled into count.intValue()>0
Calling this method with null
will throw a NullPointerException
.
The split between primitives and wrapper objects in java was always described as a kludge for speed. Autoboxing almost hides this, but not quite - it's cleaner just to keep track of the type. So if you've got an Integer object, you can just call compare()
or intValue()
, and if you've got the primitive just check the value directly.
If you have a res/raw
folder, be sure to add a file with a valid filename, otherwise the entire folder won't show up in the R class. If there's an error with a filename, it will appear in red in the console.
For java 8 the following single line statements are working. In this example I use UTC timezone. Please consider to change TimeZone that you currently used.
System.out.println(new Date());
final LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
final Date endOfDayAsDate = Date.from(endOfDay.toInstant(ZoneOffset.UTC));
System.out.println(endOfDayAsDate);
final LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
final Date startOfDayAsDate = Date.from(startOfDay.toInstant(ZoneOffset.UTC));
System.out.println(startOfDayAsDate);
If no time difference with output. Try: ZoneOffset.ofHours(0)
A thread is an execution context, which is all the information a CPU needs to execute a stream of instructions.
Suppose you're reading a book, and you want to take a break right now, but you want to be able to come back and resume reading from the exact point where you stopped. One way to achieve that is by jotting down the page number, line number, and word number. So your execution context for reading a book is these 3 numbers.
If you have a roommate, and she's using the same technique, she can take the book while you're not using it, and resume reading from where she stopped. Then you can take it back, and resume it from where you were.
Threads work in the same way. A CPU is giving you the illusion that it's doing multiple computations at the same time. It does that by spending a bit of time on each computation. It can do that because it has an execution context for each computation. Just like you can share a book with your friend, many tasks can share a CPU.
On a more technical level, an execution context (therefore a thread) consists of the values of the CPU's registers.
Last: threads are different from processes. A thread is a context of execution, while a process is a bunch of resources associated with a computation. A process can have one or many threads.
Clarification: the resources associated with a process include memory pages (all the threads in a process have the same view of the memory), file descriptors (e.g., open sockets), and security credentials (e.g., the ID of the user who started the process).
This works for me:
input.valid {_x000D_
border-color: #28a745;_x000D_
padding-right: 30px;_x000D_
background-image: url('https://www.stephenwadechryslerdodgejeep.com/wp-content/plugins/pm-motors-plugin/modules/vehicle_save/images/check.png');_x000D_
background-repeat: no-repeat;_x000D_
background-size: 20px 20px;_x000D_
background-position: right center;_x000D_
}
_x000D_
<form>_x000D_
<label for="name">Name</label>_x000D_
<input class="valid" type="text" name="name" />_x000D_
</form>
_x000D_
It looks like Microsoft has published some their drivers to maven central:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
My preferred centering method:
position: absolute;
margin: auto;
width: x%
A JSFiddle is here.
Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray()
and be done with it.
If you only have a non-generic IEnumerable, do something like this:
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
If you don't know the type within that method but the method's callers do know it, make the method generic and try this:
public static void T[] PerformQuery<T>()
{
IEnumerable query = ...;
T[] array = query.Cast<T>().ToArray();
return array;
}
along with below command line parameters ,
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
Sometimes in the linux servers , imx connection doesn't get succeeded. that is because , in cloud linux host, in /etc/hosts so that the hostname resolves to the host address.
the best way to fix it is, ping the particular linux server from other machine in network and use that host IP address in the
-Djava.rmi.server.hostname=IP address that obtained when you ping that linux server.
But never rely on the ipaddress that you get from linux server using ifconfig.me. the ip that you get there is masked one which is present in the host file.
@Inherently Curious - thanks for posting this. You are almost there - you have to add two more params to SSLContext.init() method.
TrustManager[] trustManagers = new TrustManager[] { new TrustManagerManipulator() };
sc.init(null, trustManagers, new SecureRandom());
it will start working. Again thank you very much for posting this. I solved this/my issue with your code.
/*
Returns the current time.
*/
char *time_stamp(){
char *timestamp = (char *)malloc(sizeof(char) * 16);
time_t ltime;
ltime=time(NULL);
struct tm *tm;
tm=localtime(<ime);
sprintf(timestamp,"%04d%02d%02d%02d%02d%02d", tm->tm_year+1900, tm->tm_mon,
tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
return timestamp;
}
int main(){
printf(" Timestamp: %s\n",time_stamp());
return 0;
}
Output: Timestamp: 20110912130940 // 2011 Sep 12 13:09:40
You can declare the variable final, or make it an instance (or global) variable. If you declare it final, you won't be able to change it later.
Any variable defined in a method and accessed by an anonymous inner class must be final. Otherwise, you could use that variable in the inner class, unaware that if the variable changes in the inner class, and then it is used later in the enclosing scope, the changes made in the inner class did not persist in the enclosing scope. Basically, what happens in the inner class stays in the inner class.
I wrote a more in-depth explanation here. It also explains why instance and global variables do not need to be declared final.
To get full information: column name, table name as well as schema of the table..
SELECT COLUMN_NAME, TABLE_NAME, TABLE_SCHEMA
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%col_Name%'
I had to run chown recursively for all subfolders With /* . Than it worked:
sudo chown -R user:usergroup /home/user/.local/share/jupyter/*
Try this in MySQL.
right(field,((CHAR_LENGTH(field))-(InStr(field,','))))
The most straightforward way (in my opinion) would be to simply put together a CSV file. If you want to get into formatting and actually writing to a *.xlsx file, there are more complicated solutions (and APIs) to do that for you.
I faced this issue on php 7.1 that comes with High Sierra (OS X 10.13.5), editing /etc/apache2/httpd.conf
with following changes helped:
Uncomment this line
LoadModule php7_module libexec/apache2/libphp7.so
Paste following at the end
<IfModule php7_module>
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
</IfModule>
Change this:
if(isset($_POST['submit'])){
if(!(isset($_POST['userName']))){
$username = 'Anonymous';
}
else $username = $_POST['userName'];
}
To this:
if(!empty($_POST['userName'])){
$username = $_POST['userName'];
}
if(empty($_POST['userName'])){
$username = 'Anonymous';
}
Using JavaScript reduce function should do a trick for all browsers, including IE9 >:
Array.prototype.slice.call(form.elements) // convert form elements to array
.reduce(function(acc,cur){ // reduce
var o = {type : cur.type, name : cur.name, value : cur.value}; // get needed keys
if(['checkbox','radio'].indexOf(cur.type) !==-1){
o.checked = cur.checked;
} else if(cur.type === 'select-multiple'){
o.value=[];
for(i=0;i<cur.length;i++){
o.value.push({
value : cur.options[i].value,
selected : cur.options[i].selected
});
}
}
acc.push(o);
return acc;
},[]);
Live example bellow.
var _formId = document.getElementById('formId'),_x000D_
formData = Array.prototype.slice.call(_formId.elements).reduce(function(acc,cur,indx,arr){_x000D_
var i,o = {type : cur.type, name : cur.name, value : cur.value};_x000D_
if(['checkbox','radio'].indexOf(cur.type) !==-1){_x000D_
o.checked = cur.checked;_x000D_
} else if(cur.type === 'select-multiple'){_x000D_
o.value=[];_x000D_
for(i=0;i<cur.length;i++){_x000D_
o.value.push({_x000D_
value : cur.options[i].value,_x000D_
selected : cur.options[i].selected_x000D_
});_x000D_
}_x000D_
}_x000D_
acc.push(o);_x000D_
return acc;_x000D_
},[]);_x000D_
_x000D_
// view_x000D_
document.getElementById('formOutput').innerHTML = JSON.stringify(formData, null, 4);
_x000D_
<form id="formId">_x000D_
<input type="text" name="texttype" value="some text">_x000D_
<select>_x000D_
<option value="Opt 1">Opt 1</option>_x000D_
<option value="Opt 2" selected>Opt 2</option>_x000D_
<option value="Opt 3">Opt 3</option>_x000D_
</select>_x000D_
<input type="checkbox" name="checkboxtype" value="Checkbox 1" checked> Checkbox 1_x000D_
<input type="checkbox" name="checkboxtype" value="Checkbox 2"> Checkbox 2_x000D_
<input type="radio" name="radiotype" value="Radio Btn 1"> Radio Btn 1_x000D_
<input type="radio" name="radiotype" value="Radio Btn 2" checked> Radio Btn 2_x000D_
<select multiple>_x000D_
<option value="Multi 1" selected>Multi 1</option>_x000D_
<option value="Multi 2">Saab</option>_x000D_
<option value="Multi 3" selected>Multi 3</option>_x000D_
</select>_x000D_
</form>_x000D_
<pre><code id="formOutput"></code></pre>
_x000D_
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
Since in Javascript a string is a char array, you can access the last character by the length of the string.
var lastChar = myString[myString.length -1];
You should use localhost:portnumber/phpmyadmin
Here the Portnumber
is the number which you set for your web server or if you have not set it until now it is by Default - 80
.
grep
matches, grep -v
does the inverse. If you need to "match A but not B" you usually use pipes:
grep "${PATT}" file | grep -v "${NOTPATT}"
Default assignments apply to class members, but not to local variables. As Eric Lippert explained it in this answer, Microsoft could have initialized locals by default, but they choose not to do it because using an unassigned local is almost certainly a bug.
I did debugging and finally returned my 'stuffed' query to it it's normal way.
Simply
select * from myTable for xml path('myTable')
gives me contents of the table to write to a log table from a trigger I debug.
Make sure you are using the SSH URL for the GitHub repository rather than the HTTPS URL. It will ask for username and password when you are using HTTPS and not SSH. You can check the file .git/config
or run git config -e
or git remote show origin
to verify the URL and change it if needed.
If you have IIS Express (with Visual Studio):
To enable the SSL within IIS Express, you have to just set “SSL Enabled = true” in the project properties window.
See the steps and pictures at this code project.
IIS Express will generate a certificate for you (you'll be prompted for it, etc.). Note that depending on configuration the site may still automatically start with the URL rather than the SSL URL. You can see the SSL URL - note the port number and replace it in your browser address bar, you should be able to get in and test.
From there you can right click on your project, click property pages, then start options and assign the start URL - put the new https with the new port (usually 44301 - notice the similarity to port 443) and your project will start correctly from then on.
Another helpful but simple solution might be restarting your computer after doing the download if Python is in the PATH variable. This has been a mistake I usually make when downloading Python onto a new machine.
return Task.CompletedTask; // this will make the compiler happy
To avoid the global lock, you can use SingletonCache to implement one lock per key, without exploding memory usage (the lock objects are removed when no longer referenced, and acquire/release is thread safe guaranteeing that only 1 instance is ever in use via compare and swap).
Using it looks like this:
SingletonCache<string, object> keyLocks = new SingletonCache<string, object>();
const string CacheKey = "CacheKey";
static string GetCachedData()
{
string expensiveString =null;
if (MemoryCache.Default.Contains(CacheKey))
{
return MemoryCache.Default[CacheKey] as string;
}
// double checked lock
using (var lifetime = keyLocks.Acquire(url))
{
lock (lifetime.Value)
{
if (MemoryCache.Default.Contains(CacheKey))
{
return MemoryCache.Default[CacheKey] as string;
}
cacheItemPolicy cip = new CacheItemPolicy()
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
};
expensiveString = SomeHeavyAndExpensiveCalculation();
MemoryCache.Default.Set(CacheKey, expensiveString, cip);
return expensiveString;
}
}
}
Code is here on GitHub: https://github.com/bitfaster/BitFaster.Caching
Install-Package BitFaster.Caching
There is also an LRU implementation that is lighter weight than MemoryCache, and has several advantages - faster concurrent reads and writes, bounded size, no background thread, internal perf counters etc. (disclaimer, I wrote it).
You can set also blank condition, in place of set null
var isDisable=true;
RaisedButton(
padding: const EdgeInsets.all(20),
textColor: Colors.white,
color: Colors.green,
onPressed: isDisable
? () => (){} : myClickingData(),
child: Text('Button'),
)
Before data bind change gridview databinding method, assign GridView.EditIndex
to -1. It solved the same issue for me :
gvTypes.EditIndex = -1;
gvTypes.DataBind();
gvTypes
is my GridView ID.
There are two common ways of doing that with built-in JSON serializers:
var serializer = new JavaScriptSerializer();
return serializer.Serialize(TheList);
var serializer = new DataContractJsonSerializer(TheList.GetType());
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, TheList);
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
Note, that this option requires definition of a data contract for your class:
[DataContract]
public class MyObjectInJson
{
[DataMember]
public long ObjectID {get;set;}
[DataMember]
public string ObjectInJson {get;set;}
}
There is no easy way to remove the "outdated" stuff from an existing workspace. Using the "clean" parameter will not really help, as many of the files you refer to are "free form data", only known to the plugins that are no longer available.
Your best bet is to optimize the re-import, where I would like to point out the following:
${old_workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings
folder from the old to the new workspace. This is surely the fastest way, but it may lead to weird behaviour, because some of your plugins may depend on these settings and on some of the mentioned "free form data" stored elsewhere. (There are even people symlinking these folders over multiple workspaces, but this really requires to use the same plugins on all workspaces.)My experience in this matter tells me , most of these software work good with small projects .
But what about big projects? e.g: Zend Framework 2 and some things like that.
Some of them need browser to run and this is difficult to tell customer "please type http://localhost/
" in your browser address bar !!
I create a simple project to do this : PHPPy
This is not complete way for create stand alone executable file for running php projects but helps you to do this.
I couldn't compile python file with PyInstaller or Py2exe to .exe file , hope you can.
You don't need uniformserver executable files.
Float the image right, which will at first cause your text to wrap around it.
Then whatever the very next element is, set it to { clear: right; } and everything will stop wrapping around the image.
Below can be 2 reasons for this issue:
Backup taken on SQL 2012 and Restore Headeronly was done in SQL 2008 R2
Backup media is corrupted.
If we run below command, we can find actual error always:
restore headeronly
from disk = 'C:\Users\Public\Database.bak'
Give complete location of your database file in the quot
Hope it helps
Here's another way to do it without using external libraries:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public String readFile(String filename)
{
String content = null;
File file = new File(filename); // For example, foo.txt
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
reader.close();
}
}
return content;
}
The Guava library contains convenience methods for creating lists and other collections which makes this much prettier than using the standard library classes.
Example:
ArrayList<String> list = newArrayList("a", "b", "c");
(This assumes import static com.google.common.collect.Lists.newArrayList;
)
It is still one intersting moment:
ev.preventDefault()
ev.stopPropagation();
ev.nativeEvent.stopImmediatePropagation();
Use this construction, if your function is wrapped by tag
Goto App.config
Find
<setting name="RunAsWindowsService" serializeAs="String">
<value>True</value>
</setting>
Set to False
Another way using template reference variable and ViewChild, as proposed by Frelseren:
import { ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" #fileInput/>
</div>
`
})
export class AppComponent {
@ViewChild("fileInput") fileInputVariable: any;
randomMethod() {
const files = this.fileInputVariable.nativeElement.files;
console.log(files);
}
}
try this:
powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"
I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.
Assuming your data is in ColumnA:C
and has column labels in Row 1, also that Month is formatted mmm
(this last for ease of sorting):
D2
=IF(AND(A2=A1,C2=C1),D1+1,1)
(One way to deal with what is the tricky issue of multiple entries for the same person for the same month).A1:D(last occupied row no.)
F1
.I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.
L1
.L1
and shift down.L1
.ColumnL
, select Row Labels
and numeric values.L2:L(last selected cell)
Happy to explain further/try again (I've not really tested this) if does not suit.
EDIT (To avoid second block of steps above and facilitate updating for source data changes)
.0. Before first step 2. add a blank row at the very top and move A2:D2
up.
.2. Adjust cell references accordingly (in D3
=IF(AND(A3=A2,C3=C2),D2+1,1)
.
.3. Create pivot table from A:D
.6. Overwrite Row Labels
with Name
.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1
, ColumnG
and rows and columns that show (blank)
.
Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).
Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank)
into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.
If Foo is the class enclose this method
class Foo{
public ArrayList<Integer> myNumbers() {
//code code code
}
}
then
new Foo().myNumbers();
Using Integer.toHexString(...)
is a good answer. But personally prefer to use String.format(...)
.
Try this sample as a test.
byte[] values = new byte[64];
Arrays.fill(values, (byte)8); //Fills array with 8 just for test
String valuesStr = "";
for(int i = 0; i < values.length; i++)
valuesStr += String.format("0x%02x", values[i] & 0xff) + " ";
valuesStr.trim();
To get the variable name of var
as a string:
var = 1000
var_name = [k for k,v in locals().items() if v == var][0]
print(var_name) # ---> outputs 'var'
It says "POST not supported", so the request is not calling your servlet. If I were you, I will issue a GET (e.g. access using a browser) to the exact URL you are issuing your POST request, and see what you get. I bet you'll see something unexpected.
There are different valid answers already, but none seems to properly suggest which method(s) to use in which case, except for the corresponding API level restrictions:
If you can wait for a layout cycle and the parent view group supports MarginLayoutParams
(or a subclass), set marginLeft
/ marginTop
accordingly.
If you need to change the position immediately and persistently (e.g. for a PopupMenu anchor), additionally call layout(l, t, r, b)
with the same coordinates. This preempts what the layout system will confirm later.
For immediate (temporary) changes (such as animations), use setX()
/ setY()
instead. In cases where the parent size doesn't depend on WRAP_CHILDREN, it might be fine to use setX()
/ setY()
exclusively.
Never use setLeft()
/ setRight()
/ setBottom()
/ setTop()
, see below.
Background:
The mLeft
/ mTop
/ mBottom
/ mRight
fields get filled from the corresponding LayoutParams in layout(). Layout is called implicitly and asynchronously by the Android view layout system. Thus, setting the MarginLayoutParams
seems to be the safest and cleanest way to set the position permanently. However, the asynchronous layout lag might be a problem in some cases, e.g. when using a View to render a cursor, and it's supposed to be re-positioned and serve as a PopupMenu anchor at the same time. In this case, calling layout()
worked fine for me.
The problems with setLeft()
and setTop()
are:
Calling them alone is not sufficient -- you also need to call setRight()
and setBottom()
to avoid stretching or shrinking the view.
The implementation of these methods looks relatively complex (= doing some work to account for the view size changes caused by each of them)
They seem to cause strange issues with input fields: EditText soft numeric keyboard sometimes does not allow digits
setX()
and setY()
work outside of the layout system, and the corresponding values are treated as an additional offset to the left / top / bottom / right values determined by the layout system, shifting the view accordingly. They seem to have been added for animations (where an immediate effect without going through a layout cycle is required).
Something like this should do it:
for element in list_:
sys.stdout.write(str(element))
Most guides I've seen suggest that you should use
if A:
unless you have a reason to be more specific.
There are some slight differences. There are values other than None that return False, for example empty lists, or 0, so have a think about what it is you're really testing for.
Either Cybernate or OMG Ponies solution will work. The fundamental problem is that the DATE_FORMAT()
function returns a string, not a date. When you wrote
(Select Date_Format(orders.date_purchased,'%m/%d/%Y')) As Date
I think you were essentially asking MySQL to try to format the values in date_purchased
according to that format string, and instead of calling that column date_purchased
, call it "Date". But that column would no longer contain a date, it would contain a string. (Because Date_Format()
returns a string, not a date.)
I don't think that's what you wanted to do, but that's what you were doing.
Don't confuse how a value looks with what the value is.
You have to implement getItemViewType()
method in RecyclerView.Adapter
. By default onCreateViewHolder(ViewGroup parent, int viewType)
implementation viewType
of this method returns 0
. Firstly you need view type of the item at position for the purposes of view recycling and for that you have to override getItemViewType()
method in which you can pass viewType
which will return your position of item. Code sample is given below
@Override
public MyViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
int listViewItemType = getItemViewType(viewType);
switch (listViewItemType) {
case 0: return new ViewHolder0(...);
case 2: return new ViewHolder2(...);
}
}
@Override
public int getItemViewType(int position) {
return position;
}
// and in the similar way you can set data according
// to view holder position by passing position in getItemViewType
@Override
public void onBindViewHolder(MyViewholder viewholder, int position) {
int listViewItemType = getItemViewType(position);
// ...
}
A simple example for writing multiple data to excel at a time. And also when you want to append data to a sheet on a written excel file (closed excel file).
When it is your first time writing to an excel. (Writing "df1" and "df2" to "1st_sheet" and "2nd_sheet")
import pandas as pd
from openpyxl import load_workbook
df1 = pd.DataFrame([[1],[1]], columns=['a'])
df2 = pd.DataFrame([[2],[2]], columns=['b'])
df3 = pd.DataFrame([[3],[3]], columns=['c'])
excel_dir = "my/excel/dir"
with pd.ExcelWriter(excel_dir, engine='xlsxwriter') as writer:
df1.to_excel(writer, '1st_sheet')
df2.to_excel(writer, '2nd_sheet')
writer.save()
After you close your excel, but you wish to "append" data on the same excel file but another sheet, let's say "df3" to sheet name "3rd_sheet".
book = load_workbook(excel_dir)
with pd.ExcelWriter(excel_dir, engine='openpyxl') as writer:
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
## Your dataframe to append.
df3.to_excel(writer, '3rd_sheet')
writer.save()
Be noted that excel format must not be xls, you may use xlsx one.
I know that you said that adding indexes is not an option but that would be the only option to eliminate the table scan you have. When you do a scan, SQL Server reads all 2 million rows on the table to fulfill your query.
this article provides more info but remember: Seek = good, Scan = bad.
Second, can't you eliminate the select * and select only the columns you need? Third, no "where" clause? Even if you have a index, since you are reading everything the best you will get is a index scan (which is better than a table scan, but it is not a seek, which is what you should aim for)
Uninstall all previous JDK including 1.8 Install JDK 1.8
if the current thread is killed and you use Thread.Sleep
and it is executing then you might get a ThreadAbortException
.
With Task.Delay
you can always provide a cancellation token and gracefully kill it. Thats one reason I would choose Task.Delay
. see http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx
I also agree efficiency is not paramount in this case.
Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.
$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'
& $app $arg1 $arg2 $arg3
This might be obvious, but it might help someone who has never seen it before. This also happens for regular functions if you mistakenly assign a parameter by position and explicitly by name.
>>> def foodo(thing=None, thong='not underwear'):
... print thing if thing else "nothing"
... print 'a thong is',thong
...
>>> foodo('something', thing='everything')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foodo() got multiple values for keyword argument 'thing'
I still think that Harry's answer is the simplest and completed but if you need something even simpler, then use:
struct AppError {
let message: String
init(message: String) {
self.message = message
}
}
extension AppError: LocalizedError {
var errorDescription: String? { return message }
// var failureReason: String? { get }
// var recoverySuggestion: String? { get }
// var helpAnchor: String? { get }
}
And use or test it like this:
printError(error: AppError(message: "My App Error!!!"))
func print(error: Error) {
print("We have an ERROR: ", error.localizedDescription)
}
I had the same problem with pip==1.5.6
. I had to correct my system time.
# date -s "2014-12-09 10:09:50"
Bootstrap 4 has the class .no-gutters that you can add to the row element.
<div class="container-fluid">
<div class="row no-gutters">
<div class="col-md-12">
[YOUR CONTENT HERE]
</div>
</div>
</div>
Reference: http://getbootstrap.com/docs/4.0/layout/grid/#grid-options
NSArray *array = [mutableArray copy];
Copy
makes immutable copies. This is quite useful because Apple can make various optimizations. For example sending copy
to a immutable array only retains the object and returns self
.
If you don't use garbage collection or ARC remember that -copy
retains the object.
I had the same problem when using a 32 bit version of java in a 64 bit environment. When using 64 java in a 64 OS it was ok.
It is not necessary to declare the interface abstract.
Just like declaring all those methods public (which they already are if the interface is public) or abstract (which they already are in an interface) is redundant.
No one is stopping you, though.
Other things you can explicitly state, but don't need to:
extends Object
Is there other rules that applies with an abstract interface?
An interface is already "abstract". Applying that keyword again makes absolutely no difference.
Since AngularJS 1.3.4 you can use $setDirty()
on fields (source). For example, for each field with error and marked required you can do the following:
angular.forEach($scope.form.$error.required, function(field) {
field.$setDirty();
});
Uri is wrong, there is a way to add parameters to main method in Eclipse directly, however the parameters won't be very flexible (some dynamic parameters are allowed). Here's what you need to do:
Run -> Run configurations...
Java Application
or by typing its name to filter box.Program arguments
box. Just in case it isn't clear, they're whitespace-separated so "a b c"
(without quotes) would mean you'd pass arguments a, b and c to your program.I do however recommend using JUnit/wrapper class just like Uri did say since that way you get a lot better control over the actual parameters than by doing this.
jimmyorr's answer does not work on Windows. it helps to use --not
instead of ^
like so:
git log oldbranch --not newbranch --no-merges
Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");
. See this.
I had trouble with the most popular answer (overthinking). It put AFolder in the \Server\MyFolder\AFolder and I wanted the contents of AFolder and below in MyFolder. This didn't work.
Copy-Item -Verbose -Path C:\MyFolder\AFolder -Destination \\Server\MyFolder -recurse -Force
Plus I needed to Filter and only copy *.config files.
This didn't work, with "\*" because it did not recurse
Copy-Item -Verbose -Path C:\MyFolder\AFolder\* -Filter *.config -Destination \\Server\MyFolder -recurse -Force
I ended up lopping off the beginning of the path string, to get the childPath relative to where I was recursing from. This works for the use-case in question and went down many subdirectories, which some other solutions do not.
Get-Childitem -Path "$($sourcePath)/**/*.config" -Recurse |
ForEach-Object {
$childPath = "$_".substring($sourcePath.length+1)
$dest = "$($destPath)\$($childPath)" #this puts a \ between dest and child path
Copy-Item -Verbose -Path $_ -Destination $dest -Force
}
check this...
#include <stdio.h>
class Base {
public:
virtual void gogo(int a) { printf(" Base :: gogo (int) \n"); };
virtual void gogo1(int a) { printf(" Base :: gogo1 (int) \n"); };
void gogo2(int a) { printf(" Base :: gogo2 (int) \n"); };
void gogo3(int a) { printf(" Base :: gogo3 (int) \n"); };
};
class Derived : protected Base {
public:
virtual void gogo(int a) { printf(" Derived :: gogo (int) \n"); };
void gogo1(int a) { printf(" Derived :: gogo1 (int) \n"); };
virtual void gogo2(int a) { printf(" Derived :: gogo2 (int) \n"); };
void gogo3(int a) { printf(" Derived :: gogo3 (int) \n"); };
};
int main() {
std::cout << "Derived" << std::endl;
auto obj = new Derived ;
obj->gogo(7);
obj->gogo1(7);
obj->gogo2(7);
obj->gogo3(7);
std::cout << "Base" << std::endl;
auto base = (Base*)obj;
base->gogo(7);
base->gogo1(7);
base->gogo2(7);
base->gogo3(7);
std::string s;
std::cout << "press any key to exit" << std::endl;
std::cin >> s;
return 0;
}
output
Derived
Derived :: gogo (int)
Derived :: gogo1 (int)
Derived :: gogo2 (int)
Derived :: gogo3 (int)
Base
Derived :: gogo (int)
Derived :: gogo1 (int)
Base :: gogo2 (int)
Base :: gogo3 (int)
press any key to exit
the best way is using the base::function as say @sth
Although I have seen the suggested methods used and working, I think that setting the value of an hidden field only using the JSON.stringify breaks the HTML...
Here I'll explain what I mean:
<input type="hidden" value="{"name":"John"}">
As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:
<input type="hidden" value="{" rubbish >
So for a better approach to this I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we shold have something like the following:
> encodeURIComponent(JSON.stringify({"name":"John"}))
> "%7B%22name%22%3A%22John%22%7D"
Now that value can be safely stored in an input hidden type like so:
<input type="hidden" value="%7B%22name%22%3A%22John%22%7D">
or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:
<div id="something" data-json="%7B%22name%22%3A%22John%22%7D"></div>
Now to read the data back we can do something like:
> var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json")))
> console.log(data)
> Object {name: "John"}
All development is done using your choice of C#, Boo, or a dialect of JavaScript.
Most of the example code in the documentation is in JavaScript; if you poke around the official forums and wiki you'll see a pretty even mix of C# and Javascript. Very few people seem to use Boo, but it's just as good; pick the language you already know or are the happiest learning.
Unity takes your C#/JS/Boo code and compiles it to run on iOS, Android, PC, Mac, XBox, PS3, Wii, or web plugin. Depending on the platform that might end up being Objective C or something else, but that's completely transparent to you. There's really no benefit to knowing Objective C; you can't program in it.
Update 2019/31/01
Starting from Unity 2017.2 "UnityScript" (Unity's version of JavaScript, but not identical to) took its first step towards complete deprecation by removing the option to add a "JavaScript" file from the UI. Though JS files could still be used, support for it will completely be dropped in later versions.
This also means that Boo will become unusable as its compiler is actually built as a layer on top of UnityScript and will thus be removed as well.
This means that in the future only C# will have native support.
unity has released a full article on the deprecation of UnityScript and Boo back in August 2017.
You can't do that using open. use codecs.
when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:
import codecs
file = codecs.open('data.txt','w','utf-8')
Use with window
global keyword:-
window.localStorage.removeItem('keyName');
Code of SpYk3HH with addition for shrinking size.
function get_height(elt) {
return elt.scrollHeight + parseFloat($(elt).css("borderTopWidth")) + parseFloat($(elt).css("borderBottomWidth"));
}
$("textarea").keyup(function(e) {
var found = 0;
while (!found) {
$(this).height($(this).height() - 10);
while($(this).outerHeight() < get_height(this)) {
$(this).height($(this).height() + 1);
found = 1;
};
}
});
you can get a files modified date using vbscript too
Set objFS=CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strFile= objArgs(0)
WScript.Echo objFS.GetFile(strFile).DateLastModified
save the above as mygetdate.vbs and on command line
c:\test> cscript //nologo mygetdate.vbs myfile
Use this code in Swift 2.0
let strWithFloat = "78.65"
let floatFromString = Double(strWithFloat)
This will update all the rows in that columns if safe mode is not enabled.
UPDATE table SET columnB = columnA;
If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated
UPDATE table SET columnB = columnA where table.column>0;
You can just AND the results together if they are stored as TRUE / FALSE values:
=AND(A1:D2)
Or if stored as text, use an array formula - enter the below and press Ctrl+Shift+Enter instead of Enter.
=AND(EXACT(A1:D2,"TRUE"))
function pageLoad() is very dangerous to use in this situation. You could have events become wired multiple times. I would also stay away from .live() as it attaches to the document element and has to traverse the entire page (slow and crappy).
The best solution I have seen so far is to use jQuery .delegate() function on a wrapper outside the update panel and make use of bubbling. Other then that, you could always wire up the handlers using Microsoft's Ajax library which was designed to work with UpdatePanels.
You can use the by_row
function from the package purrrlyr
for this:
myfn <- function(row) {
#row is a tibble with one row, and the same
#number of columns as the original df
#If you'd rather it be a list, you can use as.list(row)
}
purrrlyr::by_row(df, myfn)
By default, the returned value from myfn
is put into a new list column in the df called .out
.
If this is the only output you desire, you could write purrrlyr::by_row(df, myfn)$.out
Do you only need to load jquery?
1) Like the other guides say, register your script in your functions.php file like so:
// register scripts
if (!is_admin()) {
// here is an example of loading a custom script in a /scripts/ folder in your theme:
wp_register_script('sandbox.common', get_bloginfo('template_url').'/scripts/common.js', array('jquery'), '1.0', true);
// enqueue these scripts everywhere
wp_enqueue_script('jquery');
wp_enqueue_script('sandbox.common');
}
2) Notice that we don't need to register jQuery because it's already in the core. Make sure wp_footer() is called in your footer.php and wp_head() is called in your header.php (this is where it will output the script tag), and jQuery will load on every page. When you enqueue jQuery with WordPress it will be in "no conflict" mode, so you have to use jQuery instead of $. You can deregister jQuery if you want and re-register your own by doing wp_deregister_script('jquery').
I ran into the same problem recently and finally figured it out.
Using your list, here is a paste from my Excel with the formula.
I recommend writing the formula somewhere in the middle of the list, like, for example, in cell C6
of my example and then copying it and pasting it up and down your column, the formula should adjust automatically without you needing to retype it.
The only cell that has a uniquely different formula is in the first row.
Using your list ("red", "blue", "red", "green", "blue", "black"); here is the result: (I don't have a high enough level to post an image so hope this txt version makes sense)
[Column C: Unique List Formula]
=A3
=IF(ISERROR(MATCH(A4,A$3:A3,0)),A4,"")
=IF(ISERROR(MATCH(A5,A$3:A4,0)),A5,"")
=IF(ISERROR(MATCH(A6,A$3:A5,0)),A6,"")
=IF(ISERROR(MATCH(A7,A$3:A6,0)),A7,"")
=IF(ISERROR(MATCH(A8,A$3:A7,0)),A8,"")
For this you can have a Car base class that implement the year field, and all other implementations can inheritance from it.
Check status (git status
) of your repository. Every unmerged file (after you resolve conficts by yourself) should be added (git add
), and if there is no unmerged file you should git commit
I think this should do the work:
File dir = new File(dirname);
String[] files = dir.list();
This way you have files and dirs. Now use recursion and do the same for dirs (File
class has isDirectory()
method).
In my case, i tried all solutions but nothing worked.
My SO is windows 7 x64, with all the Redistributable Packages (x86,x64 / 2010,2013,2015)
The problem was that i tried to install the x64 workbench, but for some reason did not work (even my SO is x64).
so, the solution was download the x86 installer from : https://downloads.mysql.com/archives/workbench/
From MSDN:
This property returns null in the following cases:
1) if the specified key is not found;
So you can just:
NameValueCollection collection = ...
string value = collection[key];
if (value == null) // key doesn't exist
2) if the specified key is found and its associated value is null.
collection[key]
calls base.Get()
then base.FindEntry()
which internally uses Hashtable
with performance O(1).
Both the Perl and Python solutions in this post helped me solve this problem on Mac OS X:
How to list files sorted by modification date recursively (no stat command available!)
Quoting from the post:
Perl:
find . -type f -print |
perl -l -ne '
$_{$_} = -M; # store file age (mtime - now)
END {
$,="\n";
print sort {$_{$b} <=> $_{$a}} keys %_; # print by decreasing age
}'
Python:
find . -type f -print |
python -c 'import os, sys; times = {}
for f in sys.stdin.readlines(): f = f[0:-1]; times[f] = os.stat(f).st_mtime
for f in sorted(times.iterkeys(), key=lambda f:times[f]): print f'
First I installed the Nvidia driver.
Next I installed cuda.
Ater that I got the "Driver/library version mismatch" ERROR but I could see the cuda version so I purged the Nvidia driver and reinstall it.
Then it worked correctly.
Here is @Joseph's accepted answer, but with the default Mac install path location of kdiff3
(Note that you can copy and paste this and run it in one go)
git config --global --add merge.tool kdiff3
git config --global --add mergetool.kdiff3.path "/Applications/kdiff3.app/Contents/MacOS/kdiff3"
git config --global --add mergetool.kdiff3.trustExitCode false
git config --global --add diff.guitool kdiff3
git config --global --add difftool.kdiff3.path "/Applications/kdiff3.app/Contents/MacOS/kdiff3"
git config --global --add difftool.kdiff3.trustExitCode false
You should ensure the HTTP server headers are correct.
In particular, the header:
Content-Type: text/html; charset=utf-8
should be present.
The meta tag is ignored by browsers if the HTTP header is present.
Also ensure that your file is actually encoded as UTF-8 before serving it, check/try the following:
&#uuu;
.Note: If you use an unicode character for which your system can't find a glyph (no font with that character), your browser should display a question mark or some block like symbol. But if you see multiple roman characters like you do, this denotes an encoding problem.
Here's another CSS only solution that works with any HTML layout.
It works with any element you need to switch. Whatever your toggle layout is you just put it inside a couple of elements with the if-collapsed
and if-not-collapsed
classes inside the toggle element.
The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed
class on the toggle.
It also requires the :not
selector, so it doesn't work on IE8.
HTML example:
<a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
<!--You can put any valid html inside these!-->
<span class="if-collapsed">Open</span>
<span class="if-not-collapsed">Close</span>
</a>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
Less version:
[data-toggle="collapse"] {
&.collapsed .if-not-collapsed {
display: none;
}
&:not(.collapsed) .if-collapsed {
display: none;
}
}
CSS version:
[data-toggle="collapse"].collapsed .if-not-collapsed {
display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
display: none;
}
Goto xampp folder in local drive c, click on mysql folder, then click on bin and finally click on "mysqladmin" application. Then go back and refresh your browser and the problem is solved.
Another solution, this time making use of regular expressions:
using System.Text.RegularExpressions;
...
Regex parts = new Regex(@"^\d+\t(\d+)\t.+?\t(item\\[^\t]+\.ddj)");
StreamReader reader = FileInfo.OpenText("filename.txt");
string line;
while ((line = reader.ReadLine()) != null) {
Match match = parts.Match(line);
if (match.Success) {
int number = int.Parse(match.Group(1).Value);
string path = match.Group(2).Value;
// At this point, `number` and `path` contain the values we want
// for the current line. We can then store those values or print them,
// or anything else we like.
}
}
That expression's a little complex, so here it is broken down:
^ Start of string
\d+ "\d" means "digit" - 0-9. The "+" means "one or more."
So this means "one or more digits."
\t This matches a tab.
(\d+) This also matches one or more digits. This time, though, we capture it
using brackets. This means we can access it using the Group method.
\t Another tab.
.+? "." means "anything." So "one or more of anything". In addition, it's lazy.
This is to stop it grabbing everything in sight - it'll only grab as much
as it needs to for the regex to work.
\t Another tab.
(item\\[^\t]+\.ddj)
Here's the meat. This matches: "item\<one or more of anything but a tab>.ddj"
You are right in 3.1 .container-fluid and .container are same and works like container but if you remove them it works like .container-fluid (full width). They had removed .container-fluid for "Mobile First Approach", but now it's back in 3.3.4 (and they will work differently)
To get latest bootstrap please read this post on stackoverflow it will help check it out.
The best way is:
git reset --hard <commidId> && git push --force
This will reset the branch to the specific commit and then will upload the remote server with the same commits as you have in local.
Be careful with the --force
flag as it removes all the subsequent commits after the selected commit without the option to recover them.
You already have what you need, with a minor syntax change:
<a href="www.mysite.com" onclick="return theFunction();">Item</a>
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
</script>
The default behavior of the <a>
tag's onclick
and href
properties is to execute the onclick
, then follow the href
as long as the onclick
doesn't return false
, canceling the event (or the event hasn't been prevented)
I have tried a lot of the suggestions on SO but this is the one that actually worked for me:
sudo sh -c 'echo /usr/local/mysql/bin > /etc/paths.d/mysql'
then you type
mysql
It will prompt you to enter your password.
As @Ofer said, when you are using another libraries or modules, you should import all of them inside the if __name__ == '__main__':
So, in my case, ended like this:
if __name__ == '__main__':
import librosa
import os
import pandas as pd
run_my_program()
state - It is a special mutable property that hold a Component data. it has default value when Componet mounts.
props - It is a special property which is immutable by nature and used in case of pass by value from parent to child. props are just a communation channel between Components, always moving from top (parent) to buttom(child).
below are complete example of combinding the state & props :-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>state&props example</title>
<script src="https://unpkg.com/[email protected]/dist/react.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.min.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
var TodoList = React.createClass({
render(){
return <div className='tacos-list'>
{
this.props.list.map( ( todo, index ) => {
return <p key={ `taco-${ index }` }>{ todo }</p>;
})}
</div>;
}
});
var Todo = React.createClass({
getInitialState(){
return {
list : [ 'Banana', 'Apple', 'Beans' ]
}
},
handleReverse(){
this.setState({list : this.state.list.reverse()});
},
render(){
return <div className='parent-component'>
<h3 onClick={this.handleReverse}>List of todo:</h3>
<TodoList list={ this.state.list } />
</div>;
}
});
ReactDOM.render(
<Todo/>,
document.getElementById('root')
);
</script>
</body>
</html>
As other have mentioned you can't display an image in an alert. The solution is to show it on the webpage.
If I have my webpage paused in the debugger and I already have an image loaded, I can display it. There is no need to use jQuery; with this native 14 lines of Javascript it will work from code or the debugger command line:
function show(img){
var _=document.getElementById('_');
if(!_){_=document.createElement('canvas');document.body.appendChild(_);}
_.id='_';
_.style.top=0;
_.style.left=0;
_.width=img.width;
_.height=img.height;
_.style.zIndex=9999;
_.style.position='absolute';
_.getContext('2d').drawImage(img,0,0);
}
Usage:
show( myimage );
First step:- Read first row i.e all columns the remove all duplicate columns.
Second step:- Finally read only that columns.
cols = pd.read_csv("file.csv", header=None, nrows=1).iloc[0].drop_duplicates()
df = pd.read_csv("file.csv", usecols=cols)
Best one is Axios library for fetching.
use npm i --save axios
for installng and use it like fetch, just write axios instead of fetch and then get response in then().
A DTO is a dumb object - it just holds properties and has getters and setters, but no other logic of any significance (other than maybe a compare()
or equals()
implementation).
Typically model classes in MVC (assuming .net MVC here) are DTOs, or collections/aggregates of DTOs
There are two differences:
We can use Iterator to traverse Set and List and also Map type of Objects. While a ListIterator can be used to traverse for List-type Objects, but not for Set-type of Objects.
That is, we can get a Iterator object by using Set and List, see here:
By using Iterator we can retrieve the elements from Collection Object in forward direction only.
Methods in Iterator:
hasNext()
next()
remove()
Iterator iterator = Set.iterator();
Iterator iterator = List.iterator();
But we get ListIterator object only from the List interface, see here:
where as a ListIterator allows you to traverse in either directions (Both forward and backward). So it has two more methods like hasPrevious()
and previous()
other than those of Iterator. Also, we can get indexes of the next or previous elements (using nextIndex()
and previousIndex()
respectively )
Methods in ListIterator:
ListIterator listiterator = List.listIterator();
i.e., we can't get ListIterator object from Set interface.
Reference : - What is the difference between Iterator and ListIterator ?
You could do it like this:
<button (click)="scroll(target)"></button>
<div #target>Your target</div>
and then in your component:
scroll(el: HTMLElement) {
el.scrollIntoView();
}
Edit: I see comments stating that this no longer works due to the element being undefined. I created a StackBlitz example in Angular 7 and it still works. Can someone please provide an example where it does not work?
Following Shane's answer above (which works great BTW)…
You might encounter a slew of yellow triangles in the reference list.
Most of these can be eliminated by a Build->Clean Solution
and Build->Rebuild Solution
.
I did happen to have some Google API references that were a little more stubborn...as well as NewtonSoft JSon.
Trying to reinstall the NuGet package of the same version didn't work.
Visual Studio thinks you already have it installed.
To get around this:
1: Write down the original version.
2: Install the next higher/lower version...then uninstall it.
3: Install the original version from step #1.
Look at the following commands (especially the commented block).
DROP TABLE foo;
DROP TABLE bar;
CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);
INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;
-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a; -- 8.2 or later
SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5); -- replace 5 by SELECT MAX result
INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');
SELECT * FROM foo;
SELECT * FROM bar;
Graphs are tough, because most non-trivial graph problems tend to require a decent amount of actual code to implement, if more than a sketch of an algorithm is required. A lot of it tends to come down to whether or not the candidate knows the shortest path and graph traversal algorithms, is familiar with cycle types and detection, and whether they know the complexity bounds. I think a lot of questions about this stuff comes down to trivia more than on the spot creative thinking ability.
I think problems related to trees tend to cover most of the difficulties of graph questions, but without as much code complexity.
I like the Project Euler problem that asks to find the most expensive path down a tree (16/67); common ancestor is a good warm up, but a lot of people have seen it. Asking somebody to design a tree class, perform traversals, and then figure out from which traversals they could rebuild a tree also gives some insight into data structure and algorithm implementation. The Stern-Brocot programming challenge is also interesting and quick to develop on a board (http://online-judge.uva.es/p/v100/10077.html).
Here's what I'm using to get plain response object with non-stringified values and all nested associations from sequelize
v4 query.
With plain JavaScript (ES2015+):
const toPlain = response => {
const flattenDataValues = ({ dataValues }) => {
const flattenedObject = {};
Object.keys(dataValues).forEach(key => {
const dataValue = dataValues[key];
if (
Array.isArray(dataValue) &&
dataValue[0] &&
dataValue[0].dataValues &&
typeof dataValue[0].dataValues === 'object'
) {
flattenedObject[key] = dataValues[key].map(flattenDataValues);
} else if (dataValue && dataValue.dataValues && typeof dataValue.dataValues === 'object') {
flattenedObject[key] = flattenDataValues(dataValues[key]);
} else {
flattenedObject[key] = dataValues[key];
}
});
return flattenedObject;
};
return Array.isArray(response) ? response.map(flattenDataValues) : flattenDataValues(response);
};
With lodash (a bit more concise):
const toPlain = response => {
const flattenDataValues = ({ dataValues }) =>
_.mapValues(dataValues, value => (
_.isArray(value) && _.isObject(value[0]) && _.isObject(value[0].dataValues)
? _.map(value, flattenDataValues)
: _.isObject(value) && _.isObject(value.dataValues)
? flattenDataValues(value)
: value
));
return _.isArray(response) ? _.map(response, flattenDataValues) : flattenDataValues(response);
};
Usage:
const res = await User.findAll({
include: [{
model: Company,
as: 'companies',
include: [{
model: Member,
as: 'member',
}],
}],
});
const plain = toPlain(res);
// 'plain' now contains simple db object without any getters/setters with following structure:
// [{
// id: 123,
// name: 'John',
// companies: [{
// id: 234,
// name: 'Google',
// members: [{
// id: 345,
// name: 'Paul',
// }]
// }]
// }]
Your problem is that you're not closing your HEREDOC correctly. The line containing END;
must not contain any whitespace afterwards.
Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.
/**
* HTTP request types
*/
public static final int POST_TYPE = 1;
public static final int GET_TYPE = 2;
public static final int PUT_TYPE = 3;
public static final int DELETE_TYPE = 4;
/**
* HTTP request header constants
*/
public static final String CONTENT_TYPE = "Content-Type";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String ENCODING_GZIP = "gzip";
public static final String MIME_FORM_ENCODED = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN = "text/plain";
private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
final Map<String, String> headers, final Map<String, String> params, final int requestType)
throws IOException {
DefaultHttpClient client = HTTPClientFactory.newClient();
client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);
// add user and pass to client credentials if present
if ((user != null) && (pass != null)) {
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
}
// process headers using request interceptor
final Map<String, String> sendHeaders = new HashMap<String, String>();
if ((headers != null) && (headers.size() > 0)) {
sendHeaders.putAll(headers);
}
if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
}
// request gzip encoding for response
sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);
if (sendHeaders.size() > 0) {
client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException,
IOException {
for (String key : sendHeaders.keySet()) {
if (!request.containsHeader(key)) {
request.addHeader(key, sendHeaders.get(key));
}
}
}
});
}
//.... code omitted ....//
}
The error can be caused by access restrictions. Solution:
GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;
Following codes will return list of names of the numeric columns of a data set.
cnames=list(marketing_train.select_dtypes(exclude=['object']).columns)
here marketing_train
is my data set and select_dtypes()
is function to select data types using exclude and include arguments and columns is used to fetch the column name of data set
output of above code will be following:
['custAge',
'campaign',
'pdays',
'previous',
'emp.var.rate',
'cons.price.idx',
'cons.conf.idx',
'euribor3m',
'nr.employed',
'pmonths',
'pastEmail']
Thanks
You could also check out paramiko. There's no scp module (yet), but it fully supports sftp.
[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.
Make
Make is the program that’s used to install the program that’s compiled from the source code. It’s not the Linux package manager so it doesn’t keep track of the files it installs. This makes it difficult to uninstall the files afterward.
The Make Install command copies the built program and packages into the library directory and specified locations from the makefile. These locations can vary based on the examination that’s performed by the configure script.
CheckInstall
CheckInstall is the program that’s used to install or uninstall programs that are compiled from the source code. It monitors and copies the files that are installed using the make program. It also installs the files using the Linux package manager which allows it to be uninstalled like any regular package.
The CheckInstall command is used to call the Make Install command. It monitors the files that are installed and creates a binary package from them. It also installs the binary package with the Linux package manager.
Replace "source_location.deb" and "name" with your information from the Screenshot.
Execute the following commands in the source package directory:
sudo apt-get install checkinstall
sudo ./configure
sudo make
sudo checkinstall
sudo dpkg --install --force-overwrite source_location.deb
sudo apt remove name
Here's an article article I wrote that covers the whole process with explanations.
@petah and Acrylic DNS Proxy is the best answer, and at the end he references the ability to do multi-site using an Apache which @jeremyasnyder describes a little further down...
... however, in our case we're testing a multi-tenant hosting system and so most domains we want to test go to the same virtualhost
, while a couple others are directed elsewhere.
So in our case, you simply use regex wildcards in the ServerAlias
directive, like so...
ServerAlias *.foo.local
Here's a javascript example from mozilla:
var o = { a:0 } // `o` is now a basic object
Object.defineProperty(o, "b", {
get: function () {
return this.a + 1;
}
});
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number
which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.
Example from sof
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
citings:
Python 3.6+:
coordinates = [('a',1,2), ('b',3,4), ('c',5,6)]
for x in coordinates: plt.annotate(x[0], (x[1], x[2]))
p {
float: left;
margin: 0;
}
No spacing will be around, it looks similar to span.
getElementsByName()
method accesses all elements with the
specified name.
this method returns collection of elements that is an array.getElementsByTagName()
method accesses all elements with the
specified tagname.
this method returns collection of elements that is an array.eg:
<script type="text/javascript">
function getElements() {
var x=document.getElementById("y");
alert(x.value);
}
</script>
</head>
<body>
<input name="x" id="y" type="text" size="20" /><br />
This will return a single HTML element and display the value attribute of it.
<script type="text/javascript">
function getElements() {
var x=document.getElementsByName("x");
alert(x.length);
}
</script>
</head>
<body>
<input name="x" id="y" type="text" size="20" /><br />
<input name="x" id="y" type="text" size="20" /><br />
this will return an array of HTML elements and number of elements that match the name attribute.
Extracted from w3schools.
Your font
tag is not correct, so it won't work in some browsers. The px
unit is used with CSS, not HTML attributes. The font tag should look like this:
<font size="100">
Well, actually it shouldn't be there at all. The font
tag is deprecated, you should use CSS to style the content, like you do already with the text-decoration
:
<a href="selectTopic?html" style="font-size: 100px; text-decoration: none">HTML 5</a>
To separate the content from the styling, you should of course work towards putting the CSS in a style sheet rather than as inline style
attributes. That way you can apply one style to several elements without having to put the same style
attribute in all of them.
Example:
<a href="selectTopic?html" class="topic">HTML 5</a>
CSS:
.topic { font-size: 100px; text-decoration: none; }
I think people here got sidetracked by the UrlEncode message. URLEncoding is not what you want -- you want to encode stuff that won't work as a filename on the target system.
Assuming that you want some generality -- feel free to find the illegal characters on several systems (MacOS, Windows, Linux and Unix), union them to form a set of characters to escape.
As for the escape, a HexEscape should be fine (Replacing the characters with %XX). Convert each character to UTF-8 bytes and encode everything >128 if you want to support systems that don't do unicode. But there are other ways, such as using back slashes "\" or HTML encoding """. You can create your own. All any system has to do is 'encode' the uncompatible character away. The above systems allow you to recreate the original name -- but something like replacing the bad chars with spaces works also.
On the same tangent as above, the only one to use is
Uri.EscapeDataString
-- It encodes everything that is needed for OAuth, it doesn't encode the things that OAuth forbids encoding, and encodes the space as %20 and not + (Also in the OATH Spec) See: RFC 3986. AFAIK, this is the latest URI spec.
If you want to get the correct result even for the time that corresponds to an ambiguous local time (e.g., during a DST transition) and/or the local utc offset is different at different times in your local time zone then use pytz
timezones:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal
local_timezone = tzlocal.get_localzone() # get pytz tzinfo
utc_time = datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)
This is just the XML Name Space declaration. We use this Name Space in order to specify that the attributes listed below, belongs to Android. Thus they starts with "android:"
You can actually create your own custom attributes. So to prevent the name conflicts where 2 attributes are named the same thing, but behave differently, we add the prefix "android:" to signify that these are Android attributes.
Thus, this Name Space declaration must be included in the opening tag of the root view of your XML file.
type=submit
it is a Submit Button type=button
it is just a button, It does not submit your form inputs. and also you don't want to use both of these
You can submit the regex to preg_match
which will return false if the regex is not valid. Don't forget to use the @
to suppress error messages:
@preg_match($regexToTest, '');
//
. Your main fun will call firstFun then on complete of it your next fun will call.
async firstFunction() {
const promise = new Promise((resolve, reject) => {
for (let i = 0; i < 5; i++) {
// do something
console.log(i);
if (i == 4) {
resolve(i);
}
}
});
const result = await promise;
}
second() {
this.firstFunction().then( res => {
// third function call do something
console.log('Gajender here');
});
}
$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
$url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}
Runtime Code Generation with JVM and CLR
-
Peter Sestoft
Work for persons that are really interested in this type of programming.
My tip for You is that if You declare something try to avoid string, so if You have class Field it is better to use class System.Type to store the field type than a string. And for the sake of best solutions instead of creation new classes try to use those that has been created FiledInfo instead of creation new.
Besides the Stanford lib that tylerl mentioned. I found jsrsasign very useful (Github repo here:https://github.com/kjur/jsrsasign). I don't know how exactly trustworthy it is, but i've used its API of SHA256, Base64, RSA, x509 etc. and it works pretty well. In fact, it includes the Stanford lib as well.
If all you want to do is SHA256, jsrsasign might be a overkill. But if you have other needs in the related area, I feel it's a good fit.
body, html {
display: table;
height: 100%;
width: 100%;
}
.container {
display: table-cell;
vertical-align: middle;
}
.container .box {
width: 100px;
height: 100px;
background: red;
margin: 0 auto;
}
"width:100%" for the "body" tag is only for an example. In a real project you may remove this property.
A JavaScript Date has several methods allowing you to extract its parts:
getFullYear()
- Returns the 4-digit year
getMonth()
- Returns a zero-based integer (0-11) representing the month of the year.
getDate()
- Returns the day of the month (1-31).
getDay()
- Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours()
- Returns the hour of the day (0-23).
getMinutes()
- Returns the minute (0-59).
getSeconds()
- Returns the second (0-59).
getMilliseconds()
- Returns the milliseconds (0-999).
getTimezoneOffset()
- Returns the number of minutes between the machine local time and UTC.
There are no built-in methods allowing you to get localized strings like "Friday", "February", or "PM". You have to code that yourself. To get the string you want, you at least need to store string representations of days and months:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
Then, put it together using the methods above:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];_x000D_
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];_x000D_
var d = new Date();_x000D_
var day = days[d.getDay()];_x000D_
var hr = d.getHours();_x000D_
var min = d.getMinutes();_x000D_
if (min < 10) {_x000D_
min = "0" + min;_x000D_
}_x000D_
var ampm = "am";_x000D_
if( hr > 12 ) {_x000D_
hr -= 12;_x000D_
ampm = "pm";_x000D_
}_x000D_
var date = d.getDate();_x000D_
var month = months[d.getMonth()];_x000D_
var year = d.getFullYear();_x000D_
var x = document.getElementById("time");_x000D_
x.innerHTML = day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year;
_x000D_
<span id="time"></span>
_x000D_
I have a date format function I like to include in my standard library. It takes a format string parameter that defines the desired output. The format strings are loosely based on .Net custom Date and Time format strings. For the format you specified the following format string would work: "dddd h:mmtt d MMM yyyy"
.
var d = new Date();
var x = document.getElementById("time");
x.innerHTML = formatDate(d, "dddd h:mmtt d MMM yyyy");
Demo: jsfiddle.net/BNkkB/1
Here is my full date formatting function:
function formatDate(date, format, utc) {
var MMMM = ["\x00", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var MMM = ["\x01", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dddd = ["\x02", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var ddd = ["\x03", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function ii(i, len) {
var s = i + "";
len = len || 2;
while (s.length < len) s = "0" + s;
return s;
}
var y = utc ? date.getUTCFullYear() : date.getFullYear();
format = format.replace(/(^|[^\\])yyyy+/g, "$1" + y);
format = format.replace(/(^|[^\\])yy/g, "$1" + y.toString().substr(2, 2));
format = format.replace(/(^|[^\\])y/g, "$1" + y);
var M = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
format = format.replace(/(^|[^\\])MMMM+/g, "$1" + MMMM[0]);
format = format.replace(/(^|[^\\])MMM/g, "$1" + MMM[0]);
format = format.replace(/(^|[^\\])MM/g, "$1" + ii(M));
format = format.replace(/(^|[^\\])M/g, "$1" + M);
var d = utc ? date.getUTCDate() : date.getDate();
format = format.replace(/(^|[^\\])dddd+/g, "$1" + dddd[0]);
format = format.replace(/(^|[^\\])ddd/g, "$1" + ddd[0]);
format = format.replace(/(^|[^\\])dd/g, "$1" + ii(d));
format = format.replace(/(^|[^\\])d/g, "$1" + d);
var H = utc ? date.getUTCHours() : date.getHours();
format = format.replace(/(^|[^\\])HH+/g, "$1" + ii(H));
format = format.replace(/(^|[^\\])H/g, "$1" + H);
var h = H > 12 ? H - 12 : H == 0 ? 12 : H;
format = format.replace(/(^|[^\\])hh+/g, "$1" + ii(h));
format = format.replace(/(^|[^\\])h/g, "$1" + h);
var m = utc ? date.getUTCMinutes() : date.getMinutes();
format = format.replace(/(^|[^\\])mm+/g, "$1" + ii(m));
format = format.replace(/(^|[^\\])m/g, "$1" + m);
var s = utc ? date.getUTCSeconds() : date.getSeconds();
format = format.replace(/(^|[^\\])ss+/g, "$1" + ii(s));
format = format.replace(/(^|[^\\])s/g, "$1" + s);
var f = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
format = format.replace(/(^|[^\\])fff+/g, "$1" + ii(f, 3));
f = Math.round(f / 10);
format = format.replace(/(^|[^\\])ff/g, "$1" + ii(f));
f = Math.round(f / 10);
format = format.replace(/(^|[^\\])f/g, "$1" + f);
var T = H < 12 ? "AM" : "PM";
format = format.replace(/(^|[^\\])TT+/g, "$1" + T);
format = format.replace(/(^|[^\\])T/g, "$1" + T.charAt(0));
var t = T.toLowerCase();
format = format.replace(/(^|[^\\])tt+/g, "$1" + t);
format = format.replace(/(^|[^\\])t/g, "$1" + t.charAt(0));
var tz = -date.getTimezoneOffset();
var K = utc || !tz ? "Z" : tz > 0 ? "+" : "-";
if (!utc) {
tz = Math.abs(tz);
var tzHrs = Math.floor(tz / 60);
var tzMin = tz % 60;
K += ii(tzHrs) + ":" + ii(tzMin);
}
format = format.replace(/(^|[^\\])K/g, "$1" + K);
var day = (utc ? date.getUTCDay() : date.getDay()) + 1;
format = format.replace(new RegExp(dddd[0], "g"), dddd[day]);
format = format.replace(new RegExp(ddd[0], "g"), ddd[day]);
format = format.replace(new RegExp(MMMM[0], "g"), MMMM[M]);
format = format.replace(new RegExp(MMM[0], "g"), MMM[M]);
format = format.replace(/\\(.)/g, "$1");
return format;
};
Go to Windows->Preferences->Validation.
There would be a list of validators with checkbox options for Manual & Build, go and individually disable the javascript validator there.
If you select the Suspend All Validators checkbox on the top it doesn't necessarily take affect.
I am not sure but as per my knowledge I share my views. I always accept best answer if I am wrong .
Alarm Manager
The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive()
method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive()
returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive()
method completes. If your alarm receiver called Context.startService()
, it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver
and Service
will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
Timer
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
\\ here your todo;
}
}, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));
Timer
has some drawbacks that are solved by ScheduledThreadPoolExecutor
. So it's not the best choice
ScheduledThreadPoolExecutor.
You can use java.util.Timer
or ScheduledThreadPoolExecutor
(preferred) to schedule an action to occur at regular intervals on a background thread.
Here is a sample using the latter:
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
// call service
}
}, 0, 10, TimeUnit.MINUTES);
So I preferred ScheduledExecutorService
But Also think about that if the updates will occur while your application is running, you can use a Timer
, as suggested in other answers, or the newer ScheduledThreadPoolExecutor
.
If your application will update even when it is not running, you should go with the AlarmManager
.
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.
Take note that if you plan on updating when your application is turned off, once every ten minutes is quite frequent, and thus possibly a bit too power consuming.
int a = 0;
try {
int x = 4;
int y ;
try {
y = x / a;
} catch (Exception e) {
Console.WriteLine("inner ex");
//throw; // Line 1
//throw e; // Line 2
//throw new Exception("devide by 0"); // Line 3
}
} catch (Exception ex) {
Console.WriteLine(ex);
throw ex;
}
if all Line 1 ,2 and 3 are commented - Output - inner ex
if all Line 2 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------
if all Line 1 and 2 are commented - Output - inner ex System.Exception: devide by 0 ----
if all Line 1 and 3 are commented - Output - inner ex System.DevideByZeroException: {"Attempted to divide by zero."}---------
and StackTrace will be reset in case of throw ex;
Additional to this answer, create a function like
CREATE FUNCTION myrandom(
pmin INTEGER,
pmax INTEGER
)
RETURNS INTEGER(11)
DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
BEGIN
RETURN floor(pmin+RAND()*(pmax-pmin));
END;
and call like
SELECT myrandom(100,300);
This gives you random number between 100 and 300
In the MySQL interactive client you can type:
source yourfile.sql
Alternatively you can pipe the data into mysql from the command line:
mysql < yourfile.sql
If the file doesn't specify a database then you will also need to add that:
mysql db_name < yourfile.sql
See the documentation for more details:
I agree that @DaveAbrahams's answer using the bisect module is the correct approach. He did not mention one important detail in his answer.
From the docs bisect.bisect_left(a, x, lo=0, hi=len(a))
The bisection module does not require the search array to be precomputed ahead of time. You can just present the endpoints to the bisect.bisect_left
instead of it using the defaults of 0
and len(a)
.
Even more important for my use, looking for a value X such that the error of a given function is minimized. To do that, I needed a way to have the bisect_left's algorithm call my computation instead. This is really simple.
Just provide an object that defines __getitem__
as a
For example, we could use the bisect algorithm to find a square root with arbitrary precision!
import bisect
class sqrt_array(object):
def __init__(self, digits):
self.precision = float(10**(digits))
def __getitem__(self, key):
return (key/self.precision)**2.0
sa = sqrt_array(4)
# "search" in the range of 0 to 10 with a "precision" of 0.0001
index = bisect.bisect_left(sa, 7, 0, 10*10**4)
print 7**0.5
print index/(10**4.0)
I'd like to report a bug regarding the section Source of data to search in the first answer when using en dash (–) or em dash (—) within the filename.
More specifically, if you are about to use the first option - filenames specified as arguments, the file won't be found. As soon as you use either option 2 - stdin via redirection or 3 - data stream from a pipe, findstr will find the file.
For example, this simple batch script:
echo off
chcp 1250 > nul
set INTEXTFILE1=filename with – dash.txt
set INTEXTFILE2=filename with — dash.txt
rem 3 way of findstr use with en dashed filename
echo.
echo Filename with en dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE1%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE1%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE1%" | findstr .
echo.
echo.
rem The same set of operations with em dashed filename
echo Filename with em dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE2%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE2%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE2%" | findstr .
echo.
pause
will print:
Filename with en dash:
As argument
FINDSTR: Cannot open filename with - dash.txt
As stdin via redirection
I am the file with an en dash.
As datastream from a pipe
I am the file with an en dash.
Filename with em dash:
As argument
FINDSTR: Cannot open filename with - dash.txt
As stdin via redirection
I am the file with an em dash.
As datastream from a pipe
I am the file with an em dash.
Hope it helps.
M.
From the documentation for sys.exit
:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.
One example where exit codes are used are in shell scripts. In Bash you can check the special variable $?
for the last exit status:
me@mini:~$ python -c ""; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(0)"; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(43)"; echo $?
43
Personally I try to use the exit codes I find in /usr/include/asm-generic/errno.h
(on a Linux system), but I don't know if this is the right thing to do.
You can't do this with plain vanilla HTML, so JSF can't do much for you here as well.
If you're targeting decent browsers only, then just make use of CSS3:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<label class="unselectable">Unselectable label</label>
If you'd like to cover older browsers as well, then consider this JavaScript fallback:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734</title>
<script>
window.onload = function() {
var labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
disableSelection(labels[i]);
}
};
function disableSelection(element) {
if (typeof element.onselectstart != 'undefined') {
element.onselectstart = function() { return false; };
} else if (typeof element.style.MozUserSelect != 'undefined') {
element.style.MozUserSelect = 'none';
} else {
element.onmousedown = function() { return false; };
}
}
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
If you're already using jQuery, then here's another example which adds a new function disableSelection()
to jQuery so that you can use it anywhere in your jQuery code:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734 with jQuery</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.fn.extend({
disableSelection: function() {
this.each(function() {
if (typeof this.onselectstart != 'undefined') {
this.onselectstart = function() { return false; };
} else if (typeof this.style.MozUserSelect != 'undefined') {
this.style.MozUserSelect = 'none';
} else {
this.onmousedown = function() { return false; };
}
});
}
});
$(document).ready(function() {
$('label').disableSelection();
});
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
I tried this code to find out if a customer is logged in or anonymous. I did using the th:if
and th:unless
conditional expressions. Pretty simple way to do it.
<!-- IF CUSTOMER IS ANONYMOUS -->
<div th:if="${customer.anonymous}">
<div>Welcome, Guest</div>
</div>
<!-- ELSE -->
<div th:unless="${customer.anonymous}">
<div th:text=" 'Hi,' + ${customer.name}">Hi, User</div>
</div>
try my code In JavaScript
var settings = {
"url": "https://myinboxhub.co.in/example",
"method": "GET",
"timeout": 0,
"headers": {},
};
$.ajax(settings).done(function (response) {
console.log(response);
if (response.auth) {
console.log('on success');
}
}).fail(function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === '(failed)net::ERR_INTERNET_DISCONNECTED') {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 413) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 405) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
});;
In PHP
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
This might help you to open all page links:
$(".myClass").each(
function(i,e){
window.open(e, '_blank');
}
);
It will open every <a href="" class="myClass"></a>
link items to another tab like you would had clicked each one.
You only need to paste it to browser console. jQuery framework required
For individual element the code below could be used:
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
for (int second = 0;; second++) {
if (second >= 60){
fail("timeout");
}
try {
if (isElementPresent(By.id("someid"))){
break;
}
}
catch (Exception e) {
}
Thread.sleep(1000);
}
This one is I think more efficient to check prime number :
function prime(num){
if(num == 1) return true;
var t = num / 2;
var k = 2;
while(k <= t) {
if(num % k == 0) {
return false
} else {
k++;
}
}
return true;
}
console.log(prime(37))
Here are the steps to install JSToolNPP
plugin on your Notepad++.
Download 64bit version from Sourceforge or the 32bit version if you are on a 32-bit OS.
64bit - JSToolNPP.1.21.0.uni.64.zip: Download from SourceForget.net
Notepad++ before installation
Unzip the downloaded JSToolNPP.1.21.0.uni.64
and copy the JSMinNPP.dll
and place it under C:\Program Files\Notepad++\plugins
.
Close Notepad++ and reopen it. If you have downloaded an incompatible dll, then it will complain, else it will open successfully. If it complains about incompatibility, go back to STEP 1 and download the correct bit version as per your OS. Check Plugins in Notepad++.
Paste a sample unformatted but valid JSON data in Notepad++.
Select all text in Notepad++ (CTRL+A)
and format using Plugins -> JSTool -> JSFormat
.
NOTE: On side note, if you do not want to install any plugins like this, I would recommend using the following 2 best online formatters.
//gradle.properties
systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6.
public class CustomObjectMapper extends ObjectMapper {
@PostConstruct
public void customConfiguration() {
// Uses Enum.toString() for serialization of an Enum
this.enable(WRITE_ENUMS_USING_TO_STRING);
// Uses Enum.toString() for deserialization of an Enum
this.enable(READ_ENUMS_USING_TO_STRING);
}
}
There are more enum-related features available, see here:
https://github.com/FasterXML/jackson-databind/wiki/Serialization-features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features
There are several ways to do an email from HTML. Typically you see people doing a mailto like so:
<a href="mailto:[email protected]">Click to email</a>
But if you are doing it from a button you may want to look into a javascript solution.
You can simply add these lines of codes here to hide a row,
Either you can write border:0
or border-style:hidden;
border: none
or it will happen the same thing
<style type="text/css">_x000D_
table, th, td {_x000D_
border: 1px solid;_x000D_
}_x000D_
_x000D_
tr.hide_all > td, td.hide_all{_x000D_
border: 0;_x000D_
_x000D_
}_x000D_
}_x000D_
</style>_x000D_
<table>_x000D_
<tr>_x000D_
<th>Firstname</th>_x000D_
<th>Lastname</th>_x000D_
<th>Savings</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Peter</td>_x000D_
<td>Griffin</td>_x000D_
<td>$100</td>_x000D_
</tr>_x000D_
<tr class= hide_all>_x000D_
<td>Lois</td>_x000D_
<td>Griffin</td>_x000D_
<td>$150</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Joe</td>_x000D_
<td>Swanson</td>_x000D_
<td>$300</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Cleveland</td>_x000D_
<td>Brown</td>_x000D_
<td>$250</td>_x000D_
</tr>_x000D_
</table>
_x000D_
running these lines of codes can solve the problem easily
And using "pure SQL" benchmarks (without any external script)
use any string_generator with UTF8
main benchmarks:
2.1. INSERT
2.2. SELECT comparing and counting
CREATE FUNCTION string_generator(int DEFAULT 20,int DEFAULT 10) RETURNS text AS $f$
SELECT array_to_string( array_agg(
substring(md5(random()::text),1,$1)||chr( 9824 + (random()*10)::int )
), ' ' ) as s
FROM generate_series(1, $2) i(x);
$f$ LANGUAGE SQL IMMUTABLE;
Prepare specific test (examples)
DROP TABLE IF EXISTS test;
-- CREATE TABLE test ( f varchar(500));
-- CREATE TABLE test ( f text);
CREATE TABLE test ( f text CHECK(char_length(f)<=500) );
Perform a basic test:
INSERT INTO test
SELECT string_generator(20+(random()*(i%11))::int)
FROM generate_series(1, 99000) t(i);
And other tests,
CREATE INDEX q on test (f);
SELECT count(*) FROM (
SELECT substring(f,1,1) || f FROM test WHERE f<'a0' ORDER BY 1 LIMIT 80000
) t;
... And use EXPLAIN ANALYZE
.
UPDATED AGAIN 2018 (pg10)
little edit to add 2018's results and reinforce recommendations.
My results, after average, in many machines and many tests: all the same
(statistically less tham standard deviation).
Use text
datatype,
avoid old varchar(x)
because sometimes it is not a standard, e.g. in CREATE FUNCTION
clauses varchar(x)
?varchar(y)
.
express limits (with same varchar
performance!) by with CHECK
clause in the CREATE TABLE
e.g. CHECK(char_length(x)<=10)
.
With a negligible loss of performance in INSERT/UPDATE you can also to control ranges and string structure
e.g. CHECK(char_length(x)>5 AND char_length(x)<=20 AND x LIKE 'Hello%')
If your main element has some child elements or text, you could make use of it.
Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).
Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.
This element will start acting like his owner is your main element.
HTML
<div class="circle">
<span>Some text</span>
</div>
CSS
.circle {
position: relative; /* or absolute/fixed */
}
.circle:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle:after {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle span {
/* not relative/absolute/fixed */
}
.circle span:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
You can do it with animate function in jQuery.
$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
duration: 8000,
easing: 'linear',
step: function () {
$('.yourelement').html(Math.floor(this.countNum));
},
complete: function () {
$('.code').html(this.countNum);
//alert('finished');
}
});
I've created a service + filter that could help you guys with this, and maybe also with some other providers if you choose to add them in the future.
Check out https://github.com/mgonto/angularytics and let me know how this works out for you.
To test the error handling, you can do something like this:
feature ErrorHandling do
before do
Rails.application.config.consider_all_requests_local = false
Rails.application.config.action_dispatch.show_exceptions = true
end
scenario 'renders not_found template' do
visit '/blah'
expect(page).to have_content "The page you were looking for doesn't exist."
end
end
A. If using "target": "es5"
and TypeScript version below 2.0:
typings install es6-promise --save --global --source dt
B. If using "target": "es5"
and TypeScript version 2.0 or higer:
"compilerOptions": {
"lib": ["es5", "es2015.promise"]
}
C. If using "target": "es6"
, there's no need to do anything.
Mainly, you've got 2 major problems:
You are using adding a List
of String
s. You want a List
containing List
s of Strings
.
Note as well that when you invoke this:
NodeList.addAll(nodes);
... all you say is to add all elements of nodes (which is a list of Strings) to the (badly named) NodeList
, which is using Objects and thus adds only the strings inside. Which leads me to the next point.
You seem to be confused between your nodes
and NodeList
. Your NodeList
keeps growing over time, and that's what you add to your list.
So, even if doing things right, if we were to look at the end of each iteration at your nodes
, nodeList
and list
, we'd see:
i = 0
nodes: [PropertyStart,a,b,c,PropertyEnd]
nodeList: [PropertyStart,a,b,c,PropertyEnd]
list: [[PropertyStart,a,b,c,PropertyEnd]]
i = 1
nodes: [PropertyStart,d,e,f,PropertyEnd]
nodeList: [PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]
list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]]
i = 2
nodes: [PropertyStart,g,h,i,PropertyEnd]
nodeList: [PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]
list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]]
and so on...
Don't use variable names starting with uppercase letters. So here, replace NodeList
with nodeList
).
You say "I want the "list" array [...]". This is confusing for whoever you will be communicating with: It's not an array. It's an implementation of List
backed by an array.
There's a difference between a type, an interface, and an implementation.
Use generic types, because static typing really helps with these errors. Also, use interfaces where possible, except if you have a good reason to use the concrete type.
So your code becomes:
List<String> nodes = new ArrayList<String>();
List<String> nodeList = new ArrayList<String>();
List<List<String>> list = new ArrayList<List<String>>();
You could do away with the nodeList
entirely, and write the following once you've fixed your types:
list.add(nodes);
Except if you have a very strong reason to do so, prefer to use the inner-most scope to declare variables and limit both their lifespan for their references and facilitate the separation of concerns in your code.
Here you could then move List<String> nodes
to be declared within the loop (and then forget the nodes.clear()
invocation).
A reason not to do this could be performance, as you might want to avoid recreating an ArrayList
on each iteration of the loop, but it's very unlikely that's a concern to you (and clean, readable and maintainable code has priority over pre-optimized code).
Last but not least, if you want help give us the exact reproducible case with a short, self-Contained, correct example.
Here you give us your program's outputs, but don't mention how you got them, so we're left to assume you did a System.out.println(list)
. And you confused a lot of people, as I think the output you give us is not what you actually got.
If you call printStackTrace()
on an exception the trace is written to System.err
and it's hard to route it elsewhere (or filter it). Instead of doing this you are adviced to use a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.error("some exception message", e)
).
Doing that allows you to:
In my case I wanted my field to have leading 0's in 10 character field (NVARCHAR(10)). The source file does not have the leading 0's needed to then join to in another table. Did this simply due to being on SQL Server 2008R2:
Set Field = right(('0000000000' + [Field]),10) (Can't use Format() as this is pre SQL2012)
Performed this against the existing data. So this way 1 or 987654321 will still fill all 10 spaces with leading 0's.
As the new data is being imported & then dumped to the table through an Access database, I am able to use Format([Field],"0000000000") when appending from Access to the SQL server table for any new records.
I know that this question is old, but it is first in google searches
For the windows 8.1, the tools can be downloaded here
http://support.microsoft.com/kb/2693643
For the windows 10, the tools can be downloaded here
https://www.microsoft.com/en-us/download/details.aspx?id=45520
EDIT: After installing the Windows 10 2015 "Fall Update", I had to reinstall the remote server administration tools.
string.matches("^\\W*$");
should do what you want, but it does not include whitespace. string.matches("^(?:\\W|\\s)*$");
does match whitespace as well.
Luckily this question doesn't specify if the number of the current day is required, leaving room for this answer.
Also some answers (also on other questions) had leap-year problems or used the Date-object. Although javascript's Date object
covers approximately 285616 years (100,000,000 days) on either side of January 1 1970, I was fed up with all kinds of unexpected date inconsistencies across different browsers (most notably year 0 to 99). I was also curious how to calculate it.
So I wrote a simple and above all, small algorithm to calculate the correct (Proleptic Gregorian / Astronomical / ISO 8601:2004 (clause 4.3.2.1), so year 0
exists and is a leap year and negative years are supported) day of the year based on year, month and day.
Note that in AD/BC
notation, year 0 AD/BC does not exist: instead year 1 BC
is the leap-year! IF you need to account for BC notation then simply subtract one year of the (otherwise positive) year-value first!!
I modified (for javascript) the short-circuit bitmask-modulo leapYear algorithm and came up with a magic number to do a bit-wise lookup of offsets (that excludes jan and feb, thus needing 10 * 3 bits (30 bits is less than 31 bits, so we can safely save another character on the bitshift instead of >>>
)).
Note that neither month or day may be 0
. That means that if you need this equation just for the current day (feeding it using .getMonth()
) you just need to remove the --
from --m
.
Note this assumes a valid date (although error-checking is just some characters more).
function dayNo(y,m,d){_x000D_
return --m*31-(m>1?(1054267675>>m*3-6&7)-(y&3||!(y%25)&&y&15?0:1):0)+d;_x000D_
}
_x000D_
<!-- some examples for the snippet -->_x000D_
<input type=text value="(-)Y-M-D" onblur="_x000D_
var d=this.value.match(/(-?\d+)[^\d]+(\d\d?)[^\d]+(\d\d?)/)||[];_x000D_
this.nextSibling.innerHTML=' Day: ' + dayNo(+d[1], +d[2], +d[3]);_x000D_
" /><span></span>_x000D_
_x000D_
<br><hr><br>_x000D_
_x000D_
<button onclick="_x000D_
var d=new Date();_x000D_
this.nextSibling.innerHTML=dayNo(d.getFullYear(), d.getMonth()+1, d.getDate()) + ' Day(s)';_x000D_
">get current dayno:</button><span></span>
_x000D_
Here is the version with correct range-validation.
function dayNo(y,m,d){_x000D_
return --m>=0 && m<12 && d>0 && d<29+( _x000D_
4*(y=y&3||!(y%25)&&y&15?0:1)+15662003>>m*2&3 _x000D_
) && m*31-(m>1?(1054267675>>m*3-6&7)-y:0)+d;_x000D_
}
_x000D_
<!-- some examples for the snippet -->_x000D_
<input type=text value="(-)Y-M-D" onblur="_x000D_
var d=this.value.match(/(-?\d+)[^\d]+(\d\d?)[^\d]+(\d\d?)/)||[];_x000D_
this.nextSibling.innerHTML=' Day: ' + dayNo(+d[1], +d[2], +d[3]);_x000D_
" /><span></span>
_x000D_
Again, one line, but I split it into 3 lines for readability (and following explanation).
The last line is identical to the function above, however the (identical) leapYear algorithm is moved to a previous short-circuit section (before the day-number calculation), because it is also needed to know how much days a month has in a given (leap) year.
The middle line calculates the correct offset number (for max number of days) for a given month in a given (leap)year using another magic number: since 31-28=3
and 3
is just 2 bits, then 12*2=24
bits, we can store all 12 months. Since addition can be faster then subtraction, we add the offset (instead of subtract it from 31
). To avoid a leap-year decision-branch for February, we modify that magic lookup-number on the fly.
That leaves us with the (pretty obvious) first line: it checks that month and date are within valid bounds and ensures us with a false
return value on range error (note that this function also should not be able to return 0, because 1 jan 0000 is still day 1.), providing easy error-checking: if(r=dayNo(/*y, m, d*/)){}
.
If used this way (where month and day may not be 0
), then one can change --m>=0 && m<12
to m>0 && --m<12
(saving another char).
The reason I typed the snippet in it's current form is that for 0-based month values, one just needs to remove the --
from --m
.
Extra:
Note, don't use this day's per month algorithm if you need just max day's per month. In that case there is a more efficient algorithm (because we only need leepYear when the month is February) I posted as answer this question: What is the best way to determine the number of days in a month with javascript?.