A Data Transfer Object is an object that is used to encapsulate data, and send it from one subsystem of an application to another.
DTOs are most commonly used by the Services layer in an N-Tier application to transfer data between itself and the UI layer. The main benefit here is that it reduces the amount of data that needs to be sent across the wire in distributed applications. They also make great models in the MVC pattern.
Another use for DTOs can be to encapsulate parameters for method calls. This can be useful if a method takes more than 4 or 5 parameters.
When using the DTO pattern, you would also make use of DTO assemblers. The assemblers are used to create DTOs from Domain Objects, and vice versa.
The conversion from Domain Object to DTO and back again can be a costly process. If you're not creating a distributed application, you probably won't see any great benefits from the pattern, as Martin Fowler explains here
scp will do the job, but there is one wrinkle: the connection to the second remote destination will use the configuration on the first remote destination, so if you use .ssh/config on the local environment, and you expect rsa and dsa keys to work, you have to forward your agent to the first remote host.
You could use AJAX to send a POST request if you don't want forms.
Using jquery $.post method it is pretty simple:
$.post('/foo.php', { key1: 'value1', key2: 'value2' }, function(result) {
alert('successfully posted key1=value1&key2=value2 to foo.php');
});
A solution that accept exceptions(passed by parameters):
Copy the below code and use it like this: $('myselector').maskOwnName(['of', 'on', 'a', 'as', 'at', 'for', 'in', 'to']);
(function($) {
$.fn.maskOwnName = function(not_capitalize) {
not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;
$(this).keypress(function(e){
if(e.altKey || e.ctrlKey)
return;
var new_char = String.fromCharCode(e.which).toLowerCase();
if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
var start = this.selectionStart,
end = this.selectionEnd;
if(e.keyCode == 8){
if(start == end)
start--;
new_char = '';
}
var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
var maxlength = this.getAttribute('maxlength');
var words = new_value.split(' ');
start += new_char.length;
end = start;
if(maxlength === null || new_value.length <= maxlength)
e.preventDefault();
else
return;
for (var i = 0; i < words.length; i++){
words[i] = words[i].toLowerCase();
if(not_capitalize.indexOf(words[i]) == -1)
words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
}
this.value = words.join(' ');
this.setSelectionRange(start, end);
}
});
}
$.fn.maskLowerName = function(pos) {
$(this).css('text-transform', 'lowercase').bind('blur change', function(){
this.value = this.value.toLowerCase();
});
}
$.fn.maskUpperName = function(pos) {
$(this).css('text-transform', 'uppercase').bind('blur change', function(){
this.value = this.value.toUpperCase();
});
}
})(jQuery);
print date('H:i');
$var = date('H:i');
Should do it, for the current time. Use a lower case h
for 12 hour clock instead of 24 hour.
More date time formats listed here.
The project type set as the Start-up project in that solution is of type ClassLibrary. DUe to that, the output is a dll not an executable and so, you cannot start it.
If this is an error then you can do this:
A quick and dirty fix for this, if that is the only csproj in the solution is to open the .csproj file in a text editor and change the value of the node <ProjectGuid>
to the Guid corresponding to a WinForms C# project. (That you may obtain from a google search or by creating a new project and opening the .csproj file generated by Visual Studio to find out what the GUID for that type is). (Enjoy - not many people know about this sneaky trick)
BUT: the project might be a class library rightfully and then you should reference it in another project and use it that way.
I dont know if this is still useful. I achieved something like this with a java library at http://www.pushlets.com/
Althoug doing it in a service won't prevent android from shutting it down an killing the listener thread.
You mention you are using Pandas (in your title). If so, there is no need to use an external library, you can just use to_datetime
>>> pandas.to_datetime('today').normalize()
Timestamp('2015-10-14 00:00:00')
This will always return today's date at midnight, irrespective of the actual time, and can be directly used in pandas to do comparisons etc. Pandas always includes 00:00:00 in its datetimes.
Replacing today
with now
would give you the date in UTC instead of local time; note that in neither case is the tzinfo (timezone) added.
In pandas versions prior to 0.23.x, normalize
may not have been necessary to remove the non-midnight timestamp.
I didn't like bhavya's answer because of using AppDelegate
inside View Controllers and setting rootViewController
has no animation. And Trevor's answer has issue with flashing view controller on iOS8.
UPD 07/18/2015
AppDelegate inside View Controllers:
Changing AppDelegate state (properties) inside view controller breaks encapsulation.
Very simple hierarchy of objects in every iOS project:
AppDelegate (owns window
and rootViewController
)
ViewController (owns view
)
It's ok that objects from the top change objects at the bottom, because they are creating them. But it's not ok if objects on the bottom change objects on top of them (I described some basic programming/OOP principle : DIP (Dependency Inversion Principle : high level module must not depend on the low level module, but they should depend on abstractions)).
If any object will change any object in this hierarchy, sooner or later there will be a mess in the code. It might be ok on the small projects but it's no fun to dig through this mess on the bit projects =]
UPD 07/18/2015
I replicate modal controller animations using UINavigationController
(tl;dr: check the project).
I'm using UINavigationController
to present all controllers in my app. Initially I displayed login view controller in navigation stack with plain push/pop animation. Than I decided to change it to modal with minimal changes.
How it works:
Initial view controller (or self.window.rootViewController
) is UINavigationController with ProgressViewController as a rootViewController
. I'm showing ProgressViewController because DataModel can take some time to initialize because it inits core data stack like in this article (I really like this approach).
AppDelegate is responsible for getting login status updates.
DataModel handles user login/logout and AppDelegate is observing it's userLoggedIn
property via KVO. Arguably not the best method to do this but it works for me. (Why KVO is bad, you can check in this or this article (Why Not Use Notifications? part).
ModalDismissAnimator and ModalPresentAnimator are used to customize default push animation.
How animators logic works:
AppDelegate sets itself as a delegate of self.window.rootViewController
(which is UINavigationController).
AppDelegate returns one of animators in -[AppDelegate navigationController:animationControllerForOperation:fromViewController:toViewController:]
if necessary.
Animators implement -transitionDuration:
and -animateTransition:
methods. -[ModalPresentAnimator animateTransition:]
:
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
[[transitionContext containerView] addSubview:toViewController.view];
CGRect frame = toViewController.view.frame;
CGRect toFrame = frame;
frame.origin.y = CGRectGetHeight(frame);
toViewController.view.frame = frame;
[UIView animateWithDuration:[self transitionDuration:transitionContext]
animations:^
{
toViewController.view.frame = toFrame;
} completion:^(BOOL finished)
{
[transitionContext completeTransition:![transitionContext transitionWasCancelled]];
}];
}
Test project is here.
an apache server is an http server which can serve any simple http requests, where tomcat server is actually a servlet container which can serve java servlet requests.
Web server [apache] process web client (web browsers) requests and forwards it to servlet container [tomcat] and container process the requests and sends response which gets forwarded by web server to the web client [browser].
Also you can check this link for more clarification:-
https://sites.google.com/site/sureshdevang/servlet-architecture
Also check this answer for further researching :-
Don't put the @ before the id
new { id = "1" }
The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route
I got the same error.
On my view I was overriding get_form_kwargs() like this:
class UserAccountView(FormView):
form_class = UserAccountForm
success_url = '/'
template_name = 'user_account/user-account.html'
def get_form_kwargs(self):
kwargs = super(UserAccountView, self).get_form_kwargs()
kwargs.update({'user': self.request.user})
return kwargs
But on my form I failed to override the init() method. Once I did it. Problem solved
class UserAccountForm(forms.Form):
first_name = forms.CharField(label='Your first name', max_length=30)
last_name = forms.CharField(label='Your last name', max_length=30)
email = forms.EmailField(max_length=75)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(UserAccountForm, self).__init__(*args, **kwargs)
If the array contains strings, you can use the String
's join
method:
var array = ["1", "2", "3"]
let stringRepresentation = "-".join(array) // "1-2-3"
In Swift 2:
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
This can be useful if you want to use a specific separator (hypen, blank, comma, etc).
Otherwise you can simply use the description
property, which returns a string representation of the array:
let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"
Hint: any object implementing the Printable
protocol has a description
property. If you adopt that protocol in your own classes/structs, you make them print friendly as well
In Swift 3
join
becomes joined
, example [nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
becomes joined(separator:)
(only available to Array of Strings)In Swift 4
var array = ["1", "2", "3"]
array.joined(separator:"-")
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
You can use SimlpeDateFormat to format your date like this:
long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L);
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
The pattern that SimpleDateFormat
takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date
. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Date
provides a getTime()
method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat
a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)You should look at the with
binding, as well as controlsDescendantBindings
http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.html
A colleague of mine recommended Internet Explorer Collection. It appears to work without issues, but I'm far from a power user. It also supports installing IE 1 (!!) through 8.
I was also facing same problem but i renamed contact-form-7 plugin from /wp-content/plugins directory to contact-form-7-rename and problem solved.
So this is due to unsupportable plugins or theme.
The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.
http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html
if 'seek' in 'those who seek shall find':
print('Success!')
but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example, 'word' in 'swordsmith'
is True. If you only want to match whole words, you ought to use regular expressions:
import re
def findWholeWord(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
findWholeWord('seek')('those who seek shall find') # -> <match object>
findWholeWord('word')('swordsmith') # -> None
Check that the application on the test device and Google Play developer console really match.
I might have a bit of a special case but it might help someone: First, I had uploaded a package to Google Play that I had created with an ant build script. Second, on the test device, I debugged the same application (or so I thought). I got the "Error while retrieving information from server. [RPC:S-7:AEC-0]", and logcat displayed:
Class not found when unmarshalling: com.google.android.finsky.billing.lightpurchase.PurchaseParams, e: java.lang.ClassNotFoundException: com.google.android.finsky.billing.lightpurchase.PurchaseParams
The problem was that in the ant script, I have aapt
command for modifying the package name. However, Eclipse does not run that command, so there was a package name mismatch between the applications in Google Play and the test device.
As the above people stated, select PostGIS_full_version(); will answer your question. On my machine, where I'm running PostGIS 2.0 from trunk, I get the following output:
postgres=# select PostGIS_full_version();
postgis_full_version
-------------------------------------------------------------------------------------------------------------------------------------------------------
POSTGIS="2.0.0alpha4SVN" GEOS="3.3.2-CAPI-1.7.2" PROJ="Rel. 4.7.1, 23 September 2009" GDAL="GDAL 1.8.1, released 2011/07/09" LIBXML="2.7.3" USE_STATS
(1 row)
You do need to care about the versions of PROJ and GEOS that are included if you didn't install an all-inclusive package - in particular, there's some brokenness in GEOS prior to 3.3.2 (as noted in the postgis 2.0 manual) in dealing with geometry validity.
Just for the record:
DirectoryInfo di = new DirectoryInfo(currentDirName);
FileInfo[] smFiles = di.GetFiles("*.txt");
string fileNames = String.Join(", ", smFiles.Select<FileInfo, string>(fi => Path.GetFileNameWithoutExtension(fi.FullName)));
This way you don't use StringBuilder
but String.Join()
. Also please remark that Path.GetFileNameWithoutExtension()
needs a full path (fi.FullName
), not fi.Name
as I saw in one of the other answers.
$("#message > span").text("your text");
or
$("#message").find("span").text("your text");
or
$("span","#message").text("your text");
or
$("#message > a.close-notify").siblings('span').text("your text");
private makes the class accessible only to the class in which it is declared. If we make entire class private no one from outside can access the class and makes it useless.
Inner class can be made private because the outer class can access inner class where as it is not the case with if you make outer class private.
Suppose you have text field and submit button,
<input type="text" id="text-field" />
<input type="submit" class="btn" value="Submit"/>
To disable any button, for example, submit button you just need to add disabled attribute as,
$('input[type="submit"]').attr('disabled','disabled');
After executing above line, your submit button html tag would look like this:
<input type="submit" class="btn" value="Submit" disabled/>
Notice the 'disabled' attribute has added.
For enabling button, such as when you have some text in text field. You will need to remove the disable attribute to enable button as,
if ($('#text-field').val() != '') {
$('input[type="submit"]').removeAttr('disabled');
}
Now the above code will remove the 'disabled' attribute.
if you are using tortoise svn client - while exporting - it displays ..export / checkout , it is confusing , it is just export only. only view/read use export , to commit use - "checkout"
in Windows in the search option Go to administrative tools>component services>OracleServiceXE(start this service)
Adding ->getContents()
doesn't return jSON response, instead it returns as text.
You can simply use json_decode
If you are having any one or more row(s) with less or more number of columns than 2 in the dataset then this error may arise.
I am also new to Pyspark and trying to read CSV file. Following code worked for me:
In this code I am using dataset from kaggle the link is: https://www.kaggle.com/carrie1/ecommerce-data
1. Without mentioning the schema:
from pyspark.sql import SparkSession
scSpark = SparkSession \
.builder \
.appName("Python Spark SQL basic example: Reading CSV file without mentioning schema") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
sdfData = scSpark.read.csv("data.csv", header=True, sep=",")
sdfData.show()
Now check the columns: sdfData.columns
Output will be:
['InvoiceNo', 'StockCode','Description','Quantity', 'InvoiceDate', 'CustomerID', 'Country']
Check the datatype for each column:
sdfData.schema
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,StringType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,StringType,true),StructField(CustomerID,StringType,true),StructField(Country,StringType,true)))
This will give the data frame with all the columns with datatype as StringType
2. With schema: If you know the schema or want to change the datatype of any column in the above table then use this (let's say I am having following columns and want them in a particular data type for each of them)
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType
schema = StructType([\
StructField("InvoiceNo", IntegerType()),\
StructField("StockCode", StringType()), \
StructField("Description", StringType()),\
StructField("Quantity", IntegerType()),\
StructField("InvoiceDate", StringType()),\
StructField("CustomerID", DoubleType()),\
StructField("Country", StringType())\
])
scSpark = SparkSession \
.builder \
.appName("Python Spark SQL example: Reading CSV file with schema") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
sdfData = scSpark.read.csv("data.csv", header=True, sep=",", schema=schema)
Now check the schema for datatype of each column:
sdfData.schema
StructType(List(StructField(InvoiceNo,IntegerType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(CustomerID,DoubleType,true),StructField(Country,StringType,true)))
Edited: We can use the following line of code as well without mentioning schema explicitly:
sdfData = scSpark.read.csv("data.csv", header=True, inferSchema = True)
sdfData.schema
The output is:
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,DoubleType,true),StructField(CustomerID,IntegerType,true),StructField(Country,StringType,true)))
The output will look like this:
sdfData.show()
+---------+---------+--------------------+--------+--------------+----------+-------+
|InvoiceNo|StockCode| Description|Quantity| InvoiceDate|CustomerID|Country|
+---------+---------+--------------------+--------+--------------+----------+-------+
| 536365| 85123A|WHITE HANGING HEA...| 6|12/1/2010 8:26| 2.55| 17850|
| 536365| 71053| WHITE METAL LANTERN| 6|12/1/2010 8:26| 3.39| 17850|
| 536365| 84406B|CREAM CUPID HEART...| 8|12/1/2010 8:26| 2.75| 17850|
| 536365| 84029G|KNITTED UNION FLA...| 6|12/1/2010 8:26| 3.39| 17850|
| 536365| 84029E|RED WOOLLY HOTTIE...| 6|12/1/2010 8:26| 3.39| 17850|
| 536365| 22752|SET 7 BABUSHKA NE...| 2|12/1/2010 8:26| 7.65| 17850|
| 536365| 21730|GLASS STAR FROSTE...| 6|12/1/2010 8:26| 4.25| 17850|
| 536366| 22633|HAND WARMER UNION...| 6|12/1/2010 8:28| 1.85| 17850|
| 536366| 22632|HAND WARMER RED P...| 6|12/1/2010 8:28| 1.85| 17850|
| 536367| 84879|ASSORTED COLOUR B...| 32|12/1/2010 8:34| 1.69| 13047|
| 536367| 22745|POPPY'S PLAYHOUSE...| 6|12/1/2010 8:34| 2.1| 13047|
| 536367| 22748|POPPY'S PLAYHOUSE...| 6|12/1/2010 8:34| 2.1| 13047|
| 536367| 22749|FELTCRAFT PRINCES...| 8|12/1/2010 8:34| 3.75| 13047|
| 536367| 22310|IVORY KNITTED MUG...| 6|12/1/2010 8:34| 1.65| 13047|
| 536367| 84969|BOX OF 6 ASSORTED...| 6|12/1/2010 8:34| 4.25| 13047|
| 536367| 22623|BOX OF VINTAGE JI...| 3|12/1/2010 8:34| 4.95| 13047|
| 536367| 22622|BOX OF VINTAGE AL...| 2|12/1/2010 8:34| 9.95| 13047|
| 536367| 21754|HOME BUILDING BLO...| 3|12/1/2010 8:34| 5.95| 13047|
| 536367| 21755|LOVE BUILDING BLO...| 3|12/1/2010 8:34| 5.95| 13047|
| 536367| 21777|RECIPE BOX WITH M...| 4|12/1/2010 8:34| 7.95| 13047|
+---------+---------+--------------------+--------+--------------+----------+-------+
only showing top 20 rows
numpy.array
is just a convenience function to create an ndarray
; it is not a class itself.
You can also create an array using numpy.ndarray
, but it is not the recommended way. From the docstring of numpy.ndarray
:
Arrays should be constructed using
array
,zeros
orempty
... The parameters given here refer to a low-level method (ndarray(...)
) for instantiating an array.
Most of the meat of the implementation is in C code, here in multiarray, but you can start looking at the ndarray interfaces here:
https://github.com/numpy/numpy/blob/master/numpy/core/numeric.py
There are 2 steps to resolve this:
Add UseAccessibleHeader="true"
to Gridview tag:
<asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
Add the following Code to the PreRender
event:
Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
Try
MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
Catch ex As Exception
End Try
End Sub
Note setting Header Row in DataBound()
works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.
I needed something like this but which resolved symbolic links too. I discovered that pwd has a -P flag for that purpose. A fragment of my script is appended. It's within a function in a shell script, hence the $1 and $2. The result value, which is the relative path from START_ABS to END_ABS, is in the UPDIRS variable. The script cd's into each parameter directory in order to execute the pwd -P and this also means that relative path parameters are handled. Cheers, Jim
SAVE_DIR="$PWD"
cd "$1"
START_ABS=`pwd -P`
cd "$SAVE_DIR"
cd "$2"
END_ABS=`pwd -P`
START_WORK="$START_ABS"
UPDIRS=""
while test -n "${START_WORK}" -a "${END_ABS/#${START_WORK}}" '==' "$END_ABS";
do
START_WORK=`dirname "$START_WORK"`"/"
UPDIRS=${UPDIRS}"../"
done
UPDIRS="$UPDIRS${END_ABS/#${START_WORK}}"
cd "$SAVE_DIR"
Try rename
command:
rename 's/_h.png/_half.png/' *.png
Update:
example usage:
create some content
$ mkdir /tmp/foo
$ cd /tmp/foo
$ touch one_h.png two_h.png three_h.png
$ ls
one_h.png three_h.png two_h.png
test solution:
$ rename 's/_h.png/_half.png/' *.png
$ ls
one_half.png three_half.png two_half.png
delete[] monsters;
Is incorrect because monsters
isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.
Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster
objects.
Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)
I would perform a git clone via the command line (outside Eclipse) then use File -> Import... -> Existing Maven Projects.
Your projects will be understood as using Git and Maven. It's the fastest and most reliable way to import IMO.
The easiest way is to use the library commands
import commands
print commands.getstatusoutput('echo "test" | wc')
Also make sure you test it both in firefox and IE. There are some nasty bugs with JS manipulated checkboxes.
You can use conda remove --force
.
The documentation says:
--force Forces removal of a package without removing packages
that depend on it. Using this option will usually
leave your environment in a broken and inconsistent
state
If you want to use jQuery, it has a nice example in its documentation:
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
Yes, you can make a button not submit a form by adding an attribute of type of value button:
<button type="button"><button>
Another easy way to handle this is to use the argument allowSetters=true
in the annotation. This will allow the password to be deserialized into your dto but it will not serialize it into a response body that uses contains object.
example:
@JsonIgnoreProperties(allowSetters = true, value = {"bar"})
class Pojo{
String foo;
String bar;
}
Both foo
and bar
are populated in the object, but only foo is written into a response body.
To hide the prompt set xls.DisplayAlerts = False
ConflictResolution
is not a true
or false
property, it should be xlLocalSessionChanges
Note that this has nothing to do with displaying the Overwrite prompt though!
Set xls = CreateObject("Excel.Application")
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"
wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
wb.Close (True)
Apparently, you can now use NLog with Growl for Windows.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<extensions>
<add assembly="NLog.Targets.GrowlNotify" />
</extensions>
<targets>
<target name="growl" type="GrowlNotify" password="" host="" port="" />
</targets>
<rules>
<logger name="*" minLevel="Trace" appendTo="growl"/>
</rules>
</nlog>
In fact the real solution for this issue is to use the jms-api-1.1-rev-1.jar artifact available on Maven Central : http://search.maven.org/#artifactdetails%7Cjavax.jms%7Cjms-api%7C1.1-rev-1%7Cjar
When trying to make changes to a Pandas dataframe using a function, we use 'inplace=True' if we want to commit the changes to the dataframe. Therefore, the first line in the following code changes the name of the first column in 'df' to 'Grades'. We need to call the database if we want to see the resulting database.
df.rename(columns={0: 'Grades'}, inplace=True)
df
We use 'inplace=False' (this is also the default value) when we don't want to commit the changes but just print the resulting database. So, in effect a copy of the original database with the committed changes is printed without altering the original database.
Just to be more clear, the following codes do the same thing:
#Code 1
df.rename(columns={0: 'Grades'}, inplace=True)
#Code 2
df=df.rename(columns={0: 'Grades'}, inplace=False}
There were two conditions that caused the expression ((var++))
to fail for me:
If I set bash to strict mode (set -euo pipefail
) and if I start my increment at zero (0).
Starting at one (1) is fine but zero causes the increment to return "1" when evaluating "++" which is a non-zero return code failure in strict mode.
I can either use ((var+=1))
or var=$((var+1))
to escape this behavior
The correct command is the following one.
VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"
The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.
primary keys are automatically indexed
you can create additional indices using the pk depending on your usage
I had the same problem when trying to make a connection on OBIEE to Oracle db. I changed my Windows timezone from (GMT+01:00) West Central Africa to (GMT+01:00) Brussels, Copenhagen, Madrid, Paris. Then I rebooted my computer and it worked just fine. Seems like Oracle was not able to recognize the west central Africa timezone.
The +
operator is the normal concatenation choice, and is probably the fastest way to concatenate strings.
The difference between +
and <<
is that <<
changes the object on its left hand side, and +
doesn't.
irb(main):001:0> s = 'a'
=> "a"
irb(main):002:0> s + 'b'
=> "ab"
irb(main):003:0> s
=> "a"
irb(main):004:0> s << 'b'
=> "ab"
irb(main):005:0> s
=> "ab"
Update
I've written a cross-browser range and selection library called Rangy that incorporates an improved version of the code I posted below. You can use the selection save and restore module for this particular question, although I'd be tempted to use something like @Nico Burns's answer if you're not doing anything else with selections in your project and don't need the bulk of a library.
Previous answer
You can use IERange (http://code.google.com/p/ierange/) to convert IE's TextRange into something like a DOM Range and use it in conjunction with something like eyelidlessness's starting point. Personally I would only use the algorithms from IERange that do the Range <-> TextRange conversions rather than use the whole thing. And IE's selection object doesn't have the focusNode and anchorNode properties but you should be able to just use the Range/TextRange obtained from the selection instead.
I might put something together to do this, will post back here if and when I do.
EDIT:
I've created a demo of a script that does this. It works in everything I've tried it in so far except for a bug in Opera 9, which I haven't had time to look into yet. Browsers it works in are IE 5.5, 6 and 7, Chrome 2, Firefox 2, 3 and 3.5, and Safari 4, all on Windows.
http://www.timdown.co.uk/code/selections/
Note that selections may be made backwards in browsers so that the focus node is at the start of the selection and hitting the right or left cursor key will move the caret to a position relative to the start of the selection. I don't think it is possible to replicate this when restoring a selection, so the focus node is always at the end of the selection.
I will write this up fully at some point soon.
SELECT c1, c2, c3, ... INTO @v1, @v2, @v3,... FROM table_name WHERE condition;
Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.
git add
does not create any files. See also http://gitref.org/basic/#add
Github probably creates the file with touch
and adds the file for tracking automatically. You can do this on the bash
as well.
If you are using GNU time instead of the bash built-in, try
time -o outfile command
(Note: GNU time formats a little differently than the bash built-in).
This worked for me
$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");
ng-init
is a directive that can be placed inside div
's, span
's, whatever, whereas onload
is an attribute specific to the ng-include
directive that functions as an ng-init
. To see what I mean try something like:
<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>
You'll see that only the second one shows up.
An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.
args
contains the command-line arguments passed to the Java program upon invocation. For example, if I invoke the program like so:
$ java MyProg -f file.txt
Then args
will be an array containing the strings "-f"
and "file.txt"
.
If you know Package name then Use following snippet
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(packageName, 0);
} catch (final NameNotFoundException e) {
ai = null;
}
final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
I just made my own UniqueList in my own little library like this:
package com.bprog.collections;//my own little set of useful utilities and classes
import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Jonathan
*/
public class UniqueList {
private HashSet masterSet = new HashSet();
private ArrayList growableUniques;
private Object[] returnable;
public UniqueList() {
growableUniques = new ArrayList();
}
public UniqueList(int size) {
growableUniques = new ArrayList(size);
}
public void add(Object thing) {
if (!masterSet.contains(thing)) {
masterSet.add(thing);
growableUniques.add(thing);
}
}
/**
* Casts to an ArrayList of unique values
* @return
*/
public List getList(){
return growableUniques;
}
public Object get(int index) {
return growableUniques.get(index);
}
public Object[] toObjectArray() {
int size = growableUniques.size();
returnable = new Object[size];
for (int i = 0; i < size; i++) {
returnable[i] = growableUniques.get(i);
}
return returnable;
}
}
I have a TestCollections class that looks like this:
package com.bprog.collections;
import com.bprog.out.Out;
/**
*
* @author Jonathan
*/
public class TestCollections {
public static void main(String[] args){
UniqueList ul = new UniqueList();
ul.add("Test");
ul.add("Test");
ul.add("Not a copy");
ul.add("Test");
//should only contain two things
Object[] content = ul.toObjectArray();
Out.pl("Array Content",content);
}
}
Works fine. All it does is it adds to a set if it does not have it already and there's an Arraylist that is returnable, as well as an object array.
Your problem here is that to_datetime
silently failed so the dtype remained as str/object
, if you set param errors='coerce'
then if the conversion fails for any particular string then those rows are set to NaT
.
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
So you need to find out what is wrong with those specific row values.
See the docs
from collections import defaultdict
def count_vowels(word):
vowels = 'aeiouAEIOU'
count = defaultdict(int) # init counter
for char in word:
if char in vowels:
count[char] += 1
return count
A pythonic way to count vowels in a word, not like in java
or c++
, actually no need to preprocess the word string, no need for str.strip()
or str.lower()
. But if you'd like to count vowels case-insensitively, then before go into the for-loop, use str.lower()
.
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
If I understand you correctly, you want to do something like this:
In such case, it should be just enough to use:
<item name="android:colorButtonNormal">#2196f3</item>
Or for API less than 21:
<item name="colorButtonNormal">#2196f3</item>
In addition to Using Material Theme Tutorial.
Animated variant is here.
Its all depend on your client data access-layer. Many ORM frameworks rely on explicitly querying the SCOPE_IDENTITY during the insert operation.
If you are in complete control over the data access layer then is arguably better to return SCOPE_IDENTITY() as an output parameter. Wrapping the return in a result set adds unnecessary meta data overhead to describe the result set, and complicates the code to process the requests result.
If you prefer a result set return, then again is arguable better to use the OUTPUT clause:
INSERT INTO MyTable (col1, col2, col3)
OUTPUT INSERTED.id, col1, col2, col3
VALUES (@col1, @col2, @col3);
This way you can get the entire inserted row back, including default and computed columns, and you get a result set containing one row for each row inserted, this working correctly with set oriented batch inserts.
Overall, I can't see a single case when returning SCOPE_IDENTITY()
as a result set would be a good practice.
In my case the select2 would open correctly if there was zero or more pills.
But if there was one or more pills, and I deleted them all, it would shrink to the smallest width. My solution was simply:
$("#myselect").select2({ width: '100%' });
check if a key is pressed, if yes, then do stuff
Consider 'select()', if this (reportedly Posix) function is available on your os.
'select()' uses 3 sets of bits, which you create using functions provided (see man select, FD_SET, etc). You probably only need create the input bits (for now)
from man page:
'select()' "allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2) without blocking...)"
When select is invoked:
a) the function looks at each fd identified in the sets, and if that fd state indicates you can do something (perhaps read, perhaps write), select will return and let you go do that ... 'all you got to do' is scan the bits, find the set bit, and take action on the fd associated with that bit.
The 1st set (passed into select) contains active input fd's (typically devices). Probably 1 bit in this set is all you will need. And with only 1 fd (i.e. an input from keyboard), 1 bit, this is all quite simple. With this return from select, you can 'do-stuff' (perhaps, after you have fetched the char).
b) the function also has a timeout, with which you identify how much time to await a change of the fd state. If the fd state does not change, the timeout will cause 'select()' to return with a 0. (i.e. no keyboard input) Your code can do something at this time, too, perhaps an output.
fyi - fd's are typically 0,1,2... Remembe that C uses 0 as STDIN, 1 and STDOUT.
Simple test set up: I open a terminal (separate from my console), and type the tty command in that terminal to find its id. The response is typically something like "/dev/pts/0", or 3, or 17...
Then I get an fd to use in 'select()' by using open:
// flag options are: O_RDONLY, O_WRONLY, or O_RDWR
int inFD = open( "/dev/pts/5", O_RDONLY );
It is useful to cout this value.
Here is a snippet to consider (from man select):
fd_set rfds;
struct timeval tv;
int retval;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval)
printf("Data is available now.\n"); // i.e. doStuff()
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n"); // i.e. key not pressed
Open application if it is exist, or open Play Store application for install it:
private void open() {
openApplication(getActivity(), "com.app.package.here");
}
public void openApplication(Context context, String packageN) {
Intent i = context.getPackageManager().getLaunchIntentForPackage(packageN);
if (i != null) {
i.addCategory(Intent.CATEGORY_LAUNCHER);
context.startActivity(i);
} else {
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
}
catch (android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
}
}
}
The latest version of the Android SDK ships with two different applications: an SDK Manager and an AVD Manager rather than one single app that was valid when this question was originally asked.
My particular problem was unrelated to the other suggestions. I'm on a network at the moment where HTTPS traffic is mostly disallowed. In order to install the Android Platform Tools I needed to turn on the option to "Force https://... sources to be fetched using http://..." and then this allowed me to install the other tools.
Use below code for HTML5 validation pattern alphanumeric without / with space :-
for HTML5 validation pattern alphanumeric without space :- onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90"
for HTML5 validation pattern alphanumeric with space :-
onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90 || event.charCode == 32"
$sum = 0;
foreach($group as $key=>$value)
{
$sum+= $value;
}
echo $sum;
You can try out this code. Since you cannot override valueOf
method you have to define a custom method (getEnum
in the sample code below) which returns the value that you need and change your client to use this method instead.
public enum RandomEnum {
StartHere("Start Here"),
StopHere("Stop Here");
private String value;
RandomEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return this.getValue();
}
public static RandomEnum getEnum(String value) {
for(RandomEnum v : values())
if(v.getValue().equalsIgnoreCase(value)) return v;
throw new IllegalArgumentException();
}
}
You can try:
df[0] = df[0].str.strip()
or more specifically for all string columns
non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())
Okay this is how datatypes work in Java. (You have to excuse my English, I am prob. not using the right vocab. You have to differentiate between two of them. The base datatypes and the normal datatypes. Base data types pretty much make up everything that exists. For example, there are all numbers, char, boolean etc. The normal data types or complex data types is everything else. A String is an array of chars, therefore a complex data type.
Every variable that you create is actually a pointer on the value in your memory. For example:
String s = new String("This is just a test");
the variable "s" does NOT contain a String. It is a pointer. This pointer points on the variable in your memory.
When you call System.out.println(anyObject)
, the toString()
method of that object is called. If it did not override toString
from Object, it will print the pointer.
For example:
public class Foo{
public static void main(String[] args) {
Foo f = new Foo();
System.out.println(f);
}
}
>>>>
>>>>
>>>>Foo@330bedb4
Everything behind the "@" is the pointer. This only works for complex data types. Primitive datatypes are DIRECTLY saved in their pointer. So actually there is no pointer and the values are stored directly.
For example:
int i = 123;
i does NOT store a pointer in this case. i will store the integer value 123 (in byte ofc).
Okay so lets come back to the ==
operator.
It always compares the pointer and not the content saved at the pointer's position in the memory.
Example:
String s1 = new String("Hallo");
String s2 = new String("Hallo");
System.out.println(s1 == s2);
>>>>> false
This both String have a different pointer. String.equals(String other) however compares the content. You can compare primitive data types with the '==' operator because the pointer of two different objects with the same content is equal.
Null would mean that the pointer is empty. An empty primitive data type by default is 0 (for numbers). Null for any complex object however means, that object does not exist.
Greetings
Lets say your HTML looks something like this:
<div class="box">
<!-- stuff -->
<p class="bet_time">Bet 5 days ago</p>
</div>
Then, with CSS, you can make that text appear in the bottom right like so:
.box {
position:relative;
}
.bet_time {
position:absolute;
bottom:0;
right:0;
}
The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time
positions its right edge to the right edge of .box
and its bottom edge to the bottom edge of .box
Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.
Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.
Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.
Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?
What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.
Just execute brew info openssl
and read the information where it says:
If you need to have this software first in your PATH run:
echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
You can put them into a list and then sort them using their natural ordering, like so:
final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list
If the numbers are stored in the same variable, then you'll have to somehow put them into a List
and then call sort
, like so:
final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...
Collections.sort( list );
// Use the sorted list
With version 3 of PowerShell you can chain the replace calls together:
(Get-Content $sourceFile) | ForEach-Object {
$_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
} | Set-Content $destinationFile
Binding to 0.0.0.0 is half the battle. There is an ip firewall (different from the one in system preferences) that blocks TCP ports. Hence port must be unblocked there as well by doing:
sudo ipfw add <PORT NUMBER> allow tcp from any to any
For no InnoDB solution: you can use a procedure
don't forgot to set the delimiter for storing the procedure with ;
CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
BEGIN
LOCK TABLES `table1` WRITE;
INSERT INTO `table1` ( `title` ) VALUES ( @title );
SET @id = LAST_INSERT_ID();
UNLOCK TABLES;
INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1);
END
And you can use it...
SET @myid;
CALL myproc( @myid, 1, "my title" );
SELECT @myid;
ISSUE RESOVLED:
USE docker run -it -p 80:80 --name nginx --net=host -d nginx
that's issue we face with VM some time instead of bridge network try with host that will work for you
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN - tcp6 0 0 :::80 :::* LISTEN -
Unfortunately, adding the javaee-(web)-api as a dependency doesn't give you the Javadoc or the Source to the Servlet Api to browse them from within the IDE. This is also the case for all other dependencies (JPA, EJB, ...) If you need the Servlet API sources/javadoc, you can add the following to your pom.xml (works at least for JBoss&Glassfish):
Repository:
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Repository Group</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
Dependency:
<!-- Servlet 3.0 Api Specification -->
<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_3.0_spec</artifactId>
<version>1.0.0.Beta2</version>
<scope>provided</scope>
</dependency>
I completely removed the javaee-api from my dependencies and replaced it with the discrete parts (javax.ejb, javax.faces, ...) to get the sources and Javadocs for all parts of Java EE 6.
EDIT:
Here is the equivalent Glassfish dependency (although both dependencies should work, no matter what appserver you use).
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.servlet</artifactId>
<version>3.0</version>
<scope>provided</scope>
</dependency>
Depending on how complicated your regular expression is, you could possibly just use simple string slicing. I'm not sure about the practicality of this for your application or whether or not it would actually offer any speed improvements.
'testsentence'['stsen']
=> 'stsen' # evaluates to true
'testsentence'['koala']
=> nil # evaluates to false
Step 1: Open an elevated Task Scheduler (ie. right-click on the Task Scheduler icon and choose Run as administrator)
Step 2: In the Actions pane (right pane, not the actions tab), click Enable All Tasks History
That's it. Not sure why this isn't on by default, but it isn't.
The child views in your list row should be considered selected whenever the parent row is selected, so you should be able to just set a normal state drawable/color-list on the views you want to change, no messy Java code necessary. See this SO post.
Specifically, you'd set the textColor
of your textViews to an XML resource like this one:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
<item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
<item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
<item android:drawable="@color/black" /> <!-- default -->
</selector>
You could do this:
verts = list(xrange(1000))
That would give you a list of 1000 elements in size and which happens to be initialised with values from 0-999. As list
does a __len__
first to size the new list it should be fairly efficient.
My sample, Tested in Android studio 2.1
Define button in xml layout
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Java pulsation detect
Button clickButton = (Button) findViewById(R.id.btn1);
if (clickButton != null) {
clickButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
/***Do what you want with the click here***/
}
});
}
create table Customer(
CustId int primary key,
CustName varchar(20),
DOB date);
insert into Customer values(1,'kingle', TO_DATE('1994-12-16 12:00:00', 'yyyy-MM-dd hh:mi:ss'));
I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.
I'm omitting the com port settings here:
>>>import serial
>>>ser = serial.Serial(5)
>>>ser.close()
>>>ser.open()
>>>ser.write("1".encode())
1
>>>
According to RFC 4337 § 2, video/mp4
is indeed the correct Content-Type for MPEG-4 video.
Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.
EditText state = (EditText) findViewById(R.id.txtState);
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(state.getText().toString());
boolean bs = ms.matches();
if (bs == false) {
if (ErrorMessage.contains("invalid"))
ErrorMessage = ErrorMessage + "state,";
else
ErrorMessage = ErrorMessage + "invalid state,";
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, new MySchedule()).commit();
MySchedule is the name of my java class.
Using exclude and filter
results = Model.objects.filter(x=5).exclude(a=true)
cat script.sh
var1=$1
var2=$2
if [ "$#" -eq 2 ]
then
if [ -d $var1 ]
then
echo directory ${var1} exist
else
echo Directory ${var1} Does not exists
fi
if [ -d $var2 ]
then
echo directory ${var2} exist
else
echo Directory ${var2} Does not exists
fi
else
echo "Arguments are not equals to 2"
exit 1
fi
execute it like below -
./script.sh directory1 directory2
Output will be like -
directory1 exit
directory2 Does not exists
The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode()
function.
That same page contains the answer you need - use rawurlencode()
instead to get RFC 3986 compatible encoding.
I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName
to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By
clause at the end.
I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?
Almost all answers I searched for this issue say that Python on Windows comes with tkinter and tcl already installed, and I had no luck trying to download or install them using pip, or actviestate.com site. I eventually found that when I was installing python using the binary installer, I had unchecked the module related to TCL and tkinter. So, I ran the binary installer again and chose to modify my python version by this time selecting this option. No need to do anything manually then. If you go to your python terminal, then the following commands should show you version of tkinter installed with your Python:
import tkinter
import _tkinter
tkinter._test()
@Ned Batchelder and @newacct provided the right answer, but ...
Just in case if you have comma(,) decimal(.) in your string:
import re
re.sub("[^\d\.]", "", "$1,999,888.77")
'1999888.77'
The download from java.com
which installs in /Library/Internet Plug-Ins
is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home
which you can then add to Eclipse via Preferences -> Java -> Installed JREs.
I extended PDO to do something similar to what stefs suggests, and it was easier for me in the long run:
class Array_Capable_PDO extends PDO {
/**
* Both prepare a statement and bind array values to it
* @param string $statement mysql query with colon-prefixed tokens
* @param array $arrays associatve array with string tokens as keys and integer-indexed data arrays as values
* @param array $driver_options see php documention
* @return PDOStatement with given array values already bound
*/
public function prepare_with_arrays($statement, array $arrays, $driver_options = array()) {
$replace_strings = array();
$x = 0;
foreach($arrays as $token => $data) {
// just for testing...
//// tokens should be legit
//assert('is_string($token)');
//assert('$token !== ""');
//// a given token shouldn't appear more than once in the query
//assert('substr_count($statement, $token) === 1');
//// there should be an array of values for each token
//assert('is_array($data)');
//// empty data arrays aren't okay, they're a SQL syntax error
//assert('count($data) > 0');
// replace array tokens with a list of value tokens
$replace_string_pieces = array();
foreach($data as $y => $value) {
//// the data arrays have to be integer-indexed
//assert('is_int($y)');
$replace_string_pieces[] = ":{$x}_{$y}";
}
$replace_strings[] = '('.implode(', ', $replace_string_pieces).')';
$x++;
}
$statement = str_replace(array_keys($arrays), $replace_strings, $statement);
$prepared_statement = $this->prepare($statement, $driver_options);
// bind values to the value tokens
$x = 0;
foreach($arrays as $token => $data) {
foreach($data as $y => $value) {
$prepared_statement->bindValue(":{$x}_{$y}", $value);
}
$x++;
}
return $prepared_statement;
}
}
You can use it like this:
$db_link = new Array_Capable_PDO($dsn, $username, $password);
$query = '
SELECT *
FROM test
WHERE field1 IN :array1
OR field2 IN :array2
OR field3 = :value
';
$pdo_query = $db_link->prepare_with_arrays(
$query,
array(
':array1' => array(1,2,3),
':array2' => array(7,8,9)
)
);
$pdo_query->bindValue(':value', '10');
$pdo_query->execute();
In Angular, there is the support elvis operator ?.
to protect against a view render failure. They call it the safe navigation operator. Take the example below:
The current person name is {{nullObject?.name}}
Since it is trying to access name property of a null
value, the whole view disappears and you can see the error inside the browser console. It works perfectly with long property paths such as a?.b?.c?.d
. So I recommend you to use it everytime you need to access a property inside a template.
Just a hint... think twice before using "transform: rotate()", or even "-ms-transform :rotate()" (IE9) with mobiles!
I've been knocking hard to the wall for days. I have a 'kinetic' system going on, that slides images and, on top of it, a command area. I did "transform" on an arrow button so it simulates pointing up and down... I've reviewd the 1.000 plus code lines for ages!!! ;-)
All ok, once I removed transform:rotate from the CSS. It's a bit (not to use bad words) tricky the way IE handles it, comparing to other borwsers.
Great answer @Spudley! Thanks for writing it!
SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.
You can use xpath
as follows, try this one :
driver.findElement(By.xpath("(.//[@href='/docs/configuration'])")).click();
A good alternative is this:
find . -type f | xargs chmod -v 644
and for directories:
find . -type d | xargs chmod -v 755
and to be more explicit:
find . -type f | xargs -I{} chmod -v 644 {}
The idea of a foreign key is based on the concept of referencing a value that already exists in the main table. That is why it is called a foreign key in the other table. This concept is called referential integrity. If a foreign key is declared as a null field it will violate the the very logic of referential integrity. What will it refer to? It can only refer to something that is present in the main table. Hence, I think it would be wrong to declare a foreign key field as null.
This page is a neat summary, but is not entirely accurate:
I had the same problem with a Gradle project with a test SourceSet with two resource directories.
This snippet comes from a main-module.gradle and adds a resource dir to the test SourceSet:
sourceSets {
test {
resources {
srcDir('../other-module/src/test/resources')
}
}
}
Doing this I had two resource directories related to the test SourceSet of the project main-module:
../other-module/src/test/resources src/test/resources (relative to the main-module folder, automatically added by the java plugin)
I find out that if I had two files with the same name in both the source directories, something in the process resources stage went wrong. As result, no compilation started and for this reason no .class were copied in the bin directory, where JUnit was looking for the classes. The ClassNotFoundException disappeared just renaming one of the two files.
If you use Spring Framework. There is: org.springframework.util.MultiValueMap
.
To create unmodifiable multi value map:
Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);
Or use org.springframework.util.LinkedMultiValueMap
It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.
I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:
map(do_something, a_list_of_objects)
This replaces a bunch of code that looks like this:
do_something(a)
do_something(b)
do_something(c)
...
But can also be achieved with a pedestrian "for" loop:
for obj in a_list_of_objects:
do_something(obj)
The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.
You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):
[ do_something(x) for x in a_list_of_objects ]
For methods, I suppose either of these would work (with the same reservations):
map(lambda x: x.method_call(), a_list_of_objects)
or
[ x.method_call() for x in a_list_of_objects ]
So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.
for those who need it in Java, using apache httpcomponents 4.0:
public class PostFile {
protected HttpPost httppost ;
protected MultipartEntity mpEntity;
protected File filePath;
public PostFile(final String fullUrl, final String filePath){
this.httppost = new HttpPost(fullUrl);
this.filePath = new File(filePath);
this.mpEntity = new MultipartEntity();
}
public void authenticate(String user, String password){
String encoding = new String(Base64.encodeBase64((user+":"+password).getBytes()));
httppost.setHeader("Authorization", "Basic " + encoding);
}
private void addParts() throws UnsupportedEncodingException{
mpEntity.addPart("r", new StringBody("repository id"));
mpEntity.addPart("g", new StringBody("group id"));
mpEntity.addPart("a", new StringBody("artifact id"));
mpEntity.addPart("v", new StringBody("version"));
mpEntity.addPart("p", new StringBody("packaging"));
mpEntity.addPart("e", new StringBody("extension"));
mpEntity.addPart("file", new FileBody(this.filePath));
}
public String post() throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
addParts();
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println(httppost.getEntity().getContentLength());
HttpEntity resEntity = response.getEntity();
String statusLine = response.getStatusLine().toString();
System.out.println(statusLine);
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
return statusLine;
}
}
You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.
1) Give Alphas a Beta in the constructor. In class Alpha write:
public class Alpha {
private Beta beta;
public Alpha(Beta beta) {
this.beta = beta;
}
and call cAlpha = new Alpha(cBeta) from main()
2) give Alphas a mutator that gives them a beta. In class Alpha write:
public class Alpha {
private Beta beta;
public void setBeta (Beta newBeta) {
this.beta = beta;
}
and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or
3) have a beta as an argument to doSomethingAlpha. in class Alpha write:
public void DoSomethingAlpha(Beta cBeta) {
cbeta.DoSomethingBeta()
}
Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!
Since the post is active 2 Months ago. so I thought to give my input as well.
In my case i recieve date from a card reader which comes in dd/mm/yyyy format.
what i do. E.g.
var d="16/09/2019" // date received from card_x000D_
function filldate(){_x000D_
document.getElementById('cardexpirydate').value=d.split('/').reverse().join("-");_x000D_
}
_x000D_
<input type="date" id="cardexpirydate">_x000D_
<br /><br />_x000D_
<input type="button" value="fill the date" onclick="filldate();">
_x000D_
what the code do:
All this is done in a single line.
i thought this will help some one so i wrote this.
You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.
On the other hand, you have PAGE that seems active and works in python 2.7 and py3k
As you indicate on your comment, none of these use the grid
geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.
It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:
By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.
If you just want to check if the file uploaded is an image you can just try to load it into <img>
tag an check for any error callback.
Example:
var input = document.getElementsByTagName('input')[0];
var reader = new FileReader();
reader.onload = function (e) {
imageExists(e.target.result, function(exists){
if (exists) {
// Do something with the image file..
} else {
// different file format
}
});
};
reader.readAsDataURL(input.files[0]);
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
Just use MultipleActiveResultSets=True
in your connection string.
In a class you might call it like this:
public static string GetIPAddress(HttpRequestBase request)
{
string ip;
try
{
ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
if (ip.IndexOf(",") > 0)
{
string[] ipRange = ip.Split(',');
int le = ipRange.Length - 1;
ip = ipRange[le];
}
} else
{
ip = request.UserHostAddress;
}
} catch { ip = null; }
return ip;
}
I used this in a razor app with great results.
1) If file /var/spool/cron/crontabs/root
edit via SFTP client - need service cron restart
.
Reload service not work.
2) If edit file /var/spool/cron/crontabs/root
via console linux (nano, mc) - restart NOT need.
3) If edit cron via crontab -e
- restart NOT need.
Simplification from the above Andrew's answer leads to this key theme to generate the half border.
theme (panel.border = element_blank(),
axis.line = element_line(color='black'))
Try using firefox 46.0.1. It best matches with Selenium 2.53
https://ftp.mozilla.org/pub/firefox/releases/46.0.1/win64/en-US/
Manual + disable SOCKS didn't work for me (still tried to use SOCKS and my company proxy refused it),
Native + changed eclipse.ini worked for me
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyHost=myproxy
-Dhttp.proxyPort=8080
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1
These settings require IDE restart (sometimes with -clean -refresh
command line options).
https://bugs.eclipse.org/bugs/show_bug.cgi?id=281472
Java8, Eclipse Neon3, slow proxy server:
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4
-Dhttp.proxyHost=<proxy>
-Dhttp.proxyPort=8080
-Dhttps.proxyHost=<proxy>
-Dhttps.proxyPort=8080
-DsocksProxyHost=
-DsocksProxyPort=
-Dhttp.proxyUser=<user>
-Dhttp.proxyPassword=<pass>
-Dhttp.nonProxyHosts=localhost|127.0.0.1
-Dorg.eclipse.equinox.p2.transport.ecf.retry=5
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.connectTimeout=15000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.readTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.retryAttempts=20
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.closeTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.browse.connectTimeout=3000
-Dorg.eclipse.ecf.provider.filetransfer.browse.readTimeout=1000
I had the same problem in the Terraform:light container. It is based on Alpine.
There you have to install mariadb-dev with:
apk add mariadb-dev
But that one is not enough because also all the other dependencies are missed:
apk add python2 py2-pip gcc python2-dev musl-dev
How about this:
$(document).ready(function() {
$('#subscribeForm').submit(function() {
var $fields = $(this).find('input[name="list"]:checked');
if (!$fields.length) {
alert('You must check at least one box!');
return false; // The form will *not* submit
}
});
});
Here you will get all kinds of time related problems. I hope this will solve your problem.
public class MyClass {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// To get the current hour
int hour = cal.get(Calendar.HOUR_OF_DAY);
System.out.println("hour: " + hour);
// To get the current time in 12 hours format
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a",Locale.US);
String a = sdf.format(cal.getTime());
System.out.println("Time: " + a);
// To get the desired time in 12 hours format from 23 hours format
cal.set(Calendar.HOUR_OF_DAY, 24);
SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a",Locale.ENGLISH);
String a1 = sdf1.format(cal.getTime());
System.out.println("Time: " + a1);
/* H Hour in day (0-23)
k Hour in day (1-24)
*/
//To get the desired time in 24 hours format as 0-23 or 1-24
cal.set(Calendar.HOUR_OF_DAY, 24);
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm",Locale.ENGLISH);
SimpleDateFormat sdf3 = new SimpleDateFormat("kk:mm",Locale.ENGLISH);
String a2 = sdf2.format(cal.getTime());
String a3 = sdf3.format(cal.getTime());
System.out.println("Time: " + a2);
System.out.println("Time: " + a3);
//For example, time like 12:30 PM. How can i convert to 24 hours time in java?
SimpleDateFormat bigFormat = new SimpleDateFormat("kk:mm");
SimpleDateFormat smallFormat = new SimpleDateFormat("hh:mm a");
Date date = null;
try {
date = smallFormat.parse("12:30 AM");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(smallFormat.format(date) + " = " + bigFormat.format(date));
}
}
Note that the %
syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:
instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)
This also fixes the error that you happened to have.
You can use PropertyConfigurator
to load your log4j.properties wherever it is located in the disk.
Example:
Logger logger = Logger.getLogger(this.getClass());
String log4JPropertyFile = "C:/this/is/my/config/path/log4j.properties";
Properties p = new Properties();
try {
p.load(new FileInputStream(log4JPropertyFile));
PropertyConfigurator.configure(p);
logger.info("Wow! I'm configured!");
} catch (IOException e) {
//DAMN! I'm not....
}
If you have an XML Log4J configuration, use DOMConfigurator instead.
bind tells the running process to claim a port. i.e, it should bind itself to port 80 and listen for incomming requests. with bind, your process becomes a server. when you use connect, you tell your process to connect to a port that is ALREADY in use. your process becomes a client. the difference is important: bind wants a port that is not in use (so that it can claim it and become a server), and connect wants a port that is already in use (so it can connect to it and talk to the server)
Generally the practice would be to pass data as a DateTime with a "timezone" of UTC and then pass a TimeZoneInfo object and when you are ready to display the data, you use the TimeZoneInfo object to convert the UTC DateTime.
The other option is to set the DateTime with the current timezone, and then make sure the "timezone" is unknown for the DateTime object, then make sure the DateTime is again passed with a TimeZoneInfo that indicates the TimeZone of the DateTime passed.
As others have indicated here, it would be nice if Microsoft got on top of this and created one nice object to do it all, but for now you have to deal with two objects.
The Tumbler V2 API provides a pure JSON response but requires jumping through a few hoops:
Example URL: http://api.tumblr.com/v2/blog/puppygifs.tumblr.com/posts/photo?api_key=YOUR_KEY_HERE
Result showing tree structure in Fiddler:
Just setting the return value to the function name is still not exactly the same as the Java (or other) return
statement, because in java, return
exits the function, like this:
public int test(int x) {
if (x == 1) {
return 1; // exits immediately
}
// still here? return 0 as default.
return 0;
}
In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:
Public Function test(ByVal x As Integer) As Integer
If x = 1 Then
test = 1 ' does not exit immediately. You must manually terminate...
Exit Function ' to exit
End If
' Still here? return 0 as default.
test = 0
' no need for an Exit Function because we're about to exit anyway.
End Function
Since this is the case, it's also nice to know that you can use the return variable like any other variable in the method. Like this:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test <> 1 Then ' Test the currently set return value
test = 0 ' Reset the return value to a *new* value
End If
End Function
Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test > 0 Then
' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
' AND THE RESULT RESETTING THE RETURN VALUE.
test = test(test - 1)
End If
End Function
Test for ':' first, then take test string up to ':' or end, depending on if it was found
Dim strResult As String
' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
' : found, so take up to :
strResult = Left(strTest, intPos - 1)
Else
' : not found, so take whole string
strResult = strTest
End If
I know this has already been answered, but I stumbled across this question and went down the path of using format
, which works, but it returns them as strings when I wanted integers.
I just realized that moment comes with date
, month
and year
methods that return the actual integers for each method.
moment().date()
moment().month() // jan=0, dec=11
moment().year()
For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.
Example
<select id="mySelectOption">
<option value="" selected disabled>Please select</option>
</select>
Answer
$('#mySelectOption').val('Please Select');
Unfortunately there is only the function setColumnWidth(int columnIndex,
int width) from class Sheet
; in which width is a number of characters in the standard font (first font in the workbook) if your fonts are changing you cannot use it.
There is explained how to calculate the width in function of a font size. The formula is:
width = Truncate([{NumOfVisibleChar} * {MaxDigitWidth} + {5PixelPadding}] / {MaxDigitWidth}*256) / 256
You can always use autoSizeColumn(int column, boolean useMergedCells)
after inputting the data in your Sheet
.
UPDATE
This was an old answer. Nowadays you should just use click. For more advanced event firing, use dispatchEvent.
const body = document.body;_x000D_
_x000D_
body.addEventListener('click', e => {_x000D_
console.log('clicked body');_x000D_
});_x000D_
_x000D_
console.log('Using click()');_x000D_
body.click();_x000D_
_x000D_
console.log('Using dispatchEvent');_x000D_
body.dispatchEvent(new Event('click'));
_x000D_
Original Answer
Here is what I use: http://jsfiddle.net/mendesjuan/rHMCy/4/
Updated to work with IE9+
/**
* Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
* by testing for a 'synthetic=true' property on the event object
* @param {HTMLNode} node The node to fire the event handler on.
* @param {String} eventName The name of the event without the "on" (e.g., "focus")
*/
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style, you can drop this if you don't need to support IE8 and lower
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
Note that calling fireEvent(inputField, 'change');
does not mean it will actually change the input field. The typical use case for firing a change event is when you set a field programmatically and you want event handlers to be called since calling input.value="Something"
won't trigger a change event.
Go to python console by typing
$ python
in your terminal. Then, type the following 2 commands in your python shell to install the respective packages:
>> nltk.download('punkt') >> nltk.download('averaged_perceptron_tagger')
This solved the issue for me.
get_the_post_thumbnail function returns html not url of featured image. You should use get_post_thumbnail_id to get post id of featured image and then use wp_get_attachment_image_src to get url of featured image.
Try this:
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 80, 'product_cat' => 'profiler', 'orderby' => 'rand' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<div class="dvThumb col-xs-4 col-sm-3 col-md-3 profiler-select profiler<?php echo the_title(); ?>" data-profile="<?php echo $loop->post->ID; ?>">
<?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($loop->post->ID)); ?>
<?php if($featured_image) { ?>
<img src="<?php $featured_image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">
<?php } ?>
<p><?php the_title(); ?></p>
<span class="price"><?php echo $product->get_price_html(); ?></span>
</div>
<?php endwhile; ?>
Edit:
The problem i face is that HTML5 is all on one index page. So i need the timer to start on click of the blog link.
Try calling the setTimeout inside a click handler on the blog link,
$('#blogLink').click (function (e) {
e.preventDefault(); //will stop the link href to call the blog page
setTimeout(function () {
window.location.href = "blog.html"; //will redirect to your blog page (an ex: blog.html)
}, 2000); //will call the function after 2 secs.
});
Try using setTimeout
function like below,
setTimeout(function () {
window.location.href = "blog.html"; //will redirect to your blog page (an ex: blog.html)
}, 2000); //will call the function after 2 secs.
On express 3 you can use directly res.json({foo:bar})
res.json({ msgId: msg.fileName })
See the documentation
#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
You can do this with animation-keyframe rather than transition. Change your hover declaration and add the animation keyframe, you might also need to add browser prefixes for -moz- and -webkit-. See https://developer.mozilla.org/en/docs/Web/CSS/@keyframes for more detailed info.
nav.main ul ul {_x000D_
position: absolute;_x000D_
list-style: none;_x000D_
display: none;_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
padding: 10px;_x000D_
background-color: rgba(92, 91, 87, 0.9);_x000D_
-webkit-transition: opacity 600ms, visibility 600ms;_x000D_
transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
_x000D_
nav.main ul li:hover ul {_x000D_
display: block;_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
animation: fade 1s;_x000D_
}_x000D_
_x000D_
@keyframes fade {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<nav class="main">_x000D_
<ul>_x000D_
<li>_x000D_
<a href="">Lorem</a>_x000D_
<ul>_x000D_
<li><a href="">Ipsum</a></li>_x000D_
<li><a href="">Dolor</a></li>_x000D_
<li><a href="">Sit</a></li>_x000D_
<li><a href="">Amet</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
Here is an update on your fiddle. https://jsfiddle.net/orax9d9u/1/
Not an official name per se, but I've heard vertical ellipsis referred to as "snowman" in SAS community.
I spent a lot of time looking for a solution to this problem too. Here's what i've found thus far:
If you want your users to be able to click on a button and copy some text, you may have to use Flash.
If you want your users to press Ctrl+C anywhere on the page, but always copy xyz to the clipboard, I wrote an all-JS solution in YUI3 (although it could easily be ported to other frameworks, or raw JS if you're feeling particularly self-loathing).
It involves creating a textbox off the screen which gets highlighted as soon as the user hits Ctrl/CMD. When they hit 'C' shortly after, they copy the hidden text. If they hit 'V', they get redirected to a container (of your choice) before the paste event fires.
This method can work well, because while you listen for the Ctrl/CMD keydown anywhere in the body, the 'A', 'C' or 'V' keydown listeners only attach to the hidden text box (and not the whole body). It also doesn't have to break the users expectations - you only get redirected to the hidden box if you had nothing selected to copy anyway!
Here's what i've got working on my site, but check http://at.cg/js/clipboard.js for updates if there are any:
YUI.add('clipboard', function(Y) {
// Change this to the id of the text area you would like to always paste in to:
pasteBox = Y.one('#pasteDIV');
// Make a hidden textbox somewhere off the page.
Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');
// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:
// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
copyData();
// Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
// alert(e.keyCode);
// }, 'body', 'down:', Y);
}, 'body', 'down:91,224,17', Y);
// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
// Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
// Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
pasteBox.select();
}, '#copyBox', 'down:86', Y);
// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
pasteBox.select();
}, '#copyBox', 'down:65', Y);
// What to do when keybindings are fired:
// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
var txt = '';
// props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
if (window.getSelection) { txt = window.getSelection(); }
else if (document.getSelection) { txt = document.getSelection(); }
else if (document.selection) { txt = document.selection.createRange().text; }
else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');
// If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy.
if(txt=='') {
copyBox.select();
}
// They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
else if (txt == copyBox.get('value')) {
alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
copyBox.select();
} else {
// They also might have selected something completely different! If so, let them. It's only fair.
}
}
});
Hope someone else finds this useful :]
Try this instead:
echo "This is 02G05 a test string 20-Jul-2012" | sed 's/.* \([0-9]\+G[0-9]\+\) .*/\1/'
But note, if there is two pattern on one line, it will prints the 2nd.
I had to do this recently as well for both Mac and Linux OS's and after browsing through many posts and trying many things out, in my particular opinion I never got to where I wanted to which is: a simple enough to understand solution using well known and standard commands with simple patterns, one liner, portable, expandable to add in more constraints. Then I tried to looked at it with a different perspective, that's when I realized i could do without the "one liner" option if a "2-liner" met the rest of my criteria. At the end I came up with this solution I like that works in both Ubuntu and Mac which i wanted to share with everyone:
insertLine=$(( $(grep -n "foo" sample.txt | cut -f1 -d: | head -1) + 1 ))
sed -i -e "$insertLine"' i\'$'\n''bar'$'\n' sample.txt
In first command, grep looks for line numbers containing "foo", cut/head selects 1st occurrence, and the arithmetic op increments that first occurrence line number by 1 since I want to insert after the occurrence. In second command, it's an in-place file edit, "i" for inserting: an ansi-c quoting new line, "bar", then another new line. The result is adding a new line containing "bar" after the "foo" line. Each of these 2 commands can be expanded to more complex operations and matching.
You can use this library, makes it seamless to send push notifications using Firebase Service from a C# backend download here
For mac users,
It was working fine yesterday, now the hell broke. I was able to fix it.
My issue was with ANDROID_HOME
// This is wrong. No idea how it was working earlier.
ANDROID_HOME = Library/Android/sdk
If you did the same, change it to:
ANDROID_HOME = /Users/rana.singh/Library/Android/sdk
.bash_profile has
export ANDROID_HOME=/Users/rana.singh/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
I saw this warning on many websites. Also, I saw that YUI 3 library also gives the same warning. It's a warning generated from the library (whether is it jQuery or YUI).
Try this:
if (SELECT LEFT(CAST(SERVERPROPERTY('productversion') as varchar), 2)) = '10'
BEGIN
you use that code
ImageView[] ivCard = new ImageView[1];
@override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
It's an invisible folder. Just hit Command + Shift + G (takes you to the Go to Folder menu item) and type /etc/
.
Then it will take you to inside that folder.
Just use Request.QueryString.ToString()
to get full query string, like this:
string URL = "http://www.example.com/rendernews.php?"+Request.Querystring.ToString();
$(".advanced ul li").live('click',function(e){
if(e.target != this) return;
//code
// this code will execute only when you click to li and not to a child
})
I had a simllar problem. Main provider was antivirus "FortiClient" (antivirus + VPN CLient). When I disabled it - all update/checkout was made correctly
In information technology it means that:
f(n)=O(g(n)) If there is suitable constant C and N0 independent on N,
such that
for all N>N0 "C*g(n) > f(n) > 0" is true.
Ant it seems that this notation was mostly have taken from mathematics.
In this article there is a quote: D.E. Knuth, "BIG OMICRON AND BIG OMEGA AND BIG THETA", 1976:
On the basis of the issues discussed here, I propose that members of SIGACT, and editors of computer science and mathematics journals, adopt notations as defined above, unless a better alternative can be found reasonably soon.
Today is 2016, but we use it still today.
In mathematical analysis it means that:
lim (f(n)/g(n))=Constant; where n goes to +infinity
But even in mathematical analysis sometimes this symbol was used in meaning "C*g(n) > f(n) > 0".
As I know from university the symbol was intoduced by German mathematician Landau (1877-1938)
I decided for myself as follows.
Need to get the path to 'MyProject/drivers' from the main file.
MyProject/
+--- RootPackge/
¦ +-- __init__.py
¦ +-- main.py
¦ +-- definitions.py
¦
+--- drivers/
¦ +-- geckodriver.exe
¦
+-- requirements.txt
+-- setup.py
definitions.py
Put not in the root of the project, but in the root of the main package
from pathlib import Path
ROOT_DIR = Path(__file__).parent.parent
Use ROOT_DIR:
main.py
# imports must be relative,
# not from the root of the project,
# but from the root of the main package.
# Not this way:
# from RootPackge.definitions import ROOT_DIR
# But like this:
from definitions import ROOT_DIR
# Here we use ROOT_DIR
# get path to MyProject/drivers
drivers_dir = ROOT_DIR / 'drivers'
# Thus, you can get the path to any directory
# or file from the project root
driver = webdriver.Firefox(drivers_dir)
driver.get('http://www.google.com')
Then PYTHON_PATH will not be used to access the 'definitions.py' file.
Works in PyCharm:
run file 'main.py' (ctrl + shift + F10 in Windows)
Works in CLI from project root:
$ py RootPackge/main.py
Works in CLI from RootPackge:
$ cd RootPackge
$ py main.py
Works from directories above project:
$ cd ../../../../
$ py MyWork/PythoProjects/MyProject/RootPackge/main.py
Works from anywhere if you give an absolute path to the main file.
Doesn't depend on venv.
What container are you adding the UserControl to? Generally when you add controls to a Grid, they will stretch to fill the available space (unless their row/column is constrained to a certain width).
Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference
under the info tar
command.
x
means --extract
. v
means --verbose
. f
means --file
. z
means --gzip
. You can combine one-letter arguments together, and f
takes an argument, the filename. There is something you have to watch out for:
Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).
This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:tar cfz archive.tar.gz file tar -cfz archive.tar.gz file
are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.
You Can use just finish();
everywhere after Activity Start for clear that Activity from Stack.
If you are on Windows and facing the same problem, have a look at this answer of @Inazense https://stackoverflow.com/a/52869803/4567504.
In Visual studio code I was not able to find “Shell Command: Install 'code' command in PATH command.” so I had to do this manually.
"C:\Users\Your_Username\AppData\Local\Programs\Microsoft VS Code\bin"
Now you are done! restart command prompt and try again
Here is a class providing a cancel method for a delayed action
public class DelayedAction {
private Handler _handler;
private Runnable _runnable;
/**
* Constructor
* @param runnable The runnable
* @param delay The delay (in milli sec) to wait before running the runnable
*/
public DelayedAction(Runnable runnable, long delay) {
_handler = new Handler(Looper.getMainLooper());
_runnable = runnable;
_handler.postDelayed(_runnable, delay);
}
/**
* Cancel a runnable
*/
public void cancel() {
if ( _handler == null || _runnable == null ) {
return;
}
_handler.removeCallbacks(_runnable);
}}
Another way similar to the yglodt's
In application.properties:
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
And in your configuration class:
@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}
Then you can autowire the SessionFactory in your services as usual:
@Autowired
private SessionFactory sessionFactory;
When you use Angular, try not to use the jquery library. Try using the features and the libraries that are produced for angular framework. If you want to use the jquery functions like find(), html(), closest() and etc.., I suggest using the pure js. example: querySelector(), innerHTML, parentElement and etc...
I've discovered that if the filename has 300
in it, AdBlock blocks the page and throws a ERR_BLOCKED_BY_CLIENT
error.
The solution for me was very simple (after 10 hours of searching). Above where your folders are there is a combobox that says "android" click it and choose "Project".
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
You will need to define the repository outside of buildscript
. The buildscript
configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.
since you are using boto3.client()
, try:
import boto3
from io import StringIO #python3
s3 = boto3.client('s3', aws_access_key_id='key', aws_secret_access_key='secret_key')
def copy_to_s3(client, df, bucket, filepath):
csv_buf = StringIO()
df.to_csv(csv_buf, header=True, index=False)
csv_buf.seek(0)
client.put_object(Bucket=bucket, Body=csv_buf.getvalue(), Key=filepath)
print(f'Copy {df.shape[0]} rows to S3 Bucket {bucket} at {filepath}, Done!')
copy_to_s3(client=s3, df=df_to_upload, bucket='abc', filepath='def/test.csv')
AFAIK you must reformat your String in ISO format to be able to cast it as a Date:
cast(concat(substr(STR_DMY,7,4), '-',
substr(STR_DMY,1,2), '-',
substr(STR_DMY,4,2)
)
as date
) as DT
To display a Date as a String with specific format, then it's the other way around, unless you have Hive 1.2+ and can use date_format()
=> did you check the documentation by the way?
May be, it is not the very worst idea to merge (via difftool) from ... yes ... a branch!
> current_branch=$(git status | head -n1 | cut -d' ' -f3)
> stash_branch="$current_branch-stash-$(date +%yy%mm%dd-%Hh%M)"
> git stash branch $stash_branch
> git checkout $current_branch
> git difftool $stash_branch
When you use spring then you can use
boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);
where obj is any [map,collection,array,aything...]
otherwise: the code is:
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
// else
return false;
}
for String best is:
boolean isNullOrEmpty = (str==null || str.trim().isEmpty());
This is what I did to achieve image rendering in DEBUG = False mode in Python 3.6 with Django 1.11
from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]
Based on the answers and comments here, a naming convention which includes the FK table, FK field, and PK table (FK_FKTbl_FKCol_PKTbl) should avoid FK constraint name collisions.
So, for the given tables here:
fk_task_userid_user
fk_note_userid_user
So, if you add a column to track who last modified a task or a note...
fk_task_modifiedby_user
fk_note_modifiedby_user
http://jquerypriceformat.com/#examples
https://github.com/flaviosilveira/Jquery-Price-Format
html input runing for live chance.
<input type="text" name="v7" class="priceformat"/>
<input type="text" name="v8" class="priceformat"/>
$('.priceformat').each(function( index ) {
$(this).priceFormat({ prefix: '', thousandsSeparator: '' });
});
//5000.00
//5.000,00
//5,000.00
A tricky method: using small percent sign as below
<string name="zone_50">Fat Burning (50﹪ to 60﹪)</string>
mysql_query
function is used for executing mysql query in php. mysql_query
returns false if query execution fails.Alternatively you can try using mysql_error()
function
For e.g
$result=mysql_query($sql)
or
die(mysql_error());
In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.
I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.
Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))
with React-Router v4 on the horizon, there is now a new way of doing this.
import { MemoryRouter, BrowserRouter } from 'react-router';
const navigator = global && global.navigator && global.navigator.userAgent;
const hasWindow = typeof window !== 'undefined';
const isBrowser = typeof navigator !== 'undefined' && navigator.indexOf('Node.js') === -1;
const Router = isBrowser ? BrowserRouter : MemoryRouter;
<Router location="/page-to-go-to"/>
react-lego is an example app that shows how to use/update react-router and it includes example functional tests which navigate the app.
There's time.ParseDuration
which will happily accept negative durations, as per manual. Otherwise put, there's no need to negate a duration where you can get an exact duration in the first place.
E.g. when you need to substract an hour and a half, you can do that like so:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
duration, _ := time.ParseDuration("-1.5h")
then := now.Add(duration)
fmt.Println("then:", then)
}
This is very simple to do:
import matplotlib.pyplot as plt
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.legend(loc='best')
plt.show()
You can keep adding plt.plot
as many times as you like. As for line type
, you need to first specify the color. So for blue, it's b
. And for a normal line it's -
. An example would be:
plt.plot(total_lengths, sort_times_heap, 'b-', label="Heap")
Just use
If @searchType is null means 'return the whole table' then use
WHERE p.[Type] = @SearchType OR @SearchType is NULL
If @searchType is an empty string means 'return the whole table' then use
WHERE p.[Type] = @SearchType OR @SearchType = ''
If @searchType is null or an empty string means 'return the whole table' then use
WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''
One major feature of rsync
over scp
(beside the delta algorithm and encryption if used w/ ssh) is that it automatically verifies if the transferred file has been transferred correctly. Scp will not do that, which occasionally might result in corruption when transferring larger files. So in general rsync is a copy with guarantee.
Centos manpages mention this the end of the --checksum
option description:
Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option’s before-the-transfer “Does this file need to be updated?” check.
As you are not trying to move the files around in the tree, you should be able to just checkout the directory:
git checkout master -- dirname
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL
by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
Today (2020.06.16) I perform tests for chosen solutions on MacOs High Sierra on Chrome 83.0, Safari 13.1.1 and Firefox 77.0.
Get elements by name
getElementByName
(C) is fastest solution for all browsers for big and small arrays - however I is probably some kind of lazy-loading solution or It use some internal browser hash-cache with name-element pairsquerySelectorAll
(D) solutionGet rows by name and hide them (we exclude precalculated native solution (I) - theoretically fastest) from comparison - it is used as reference)
"default:none"
on hidden elements - but it looks that they find faster way of do it than element.style.display='none'
I perform two tests for read elements by name (A,B,C,D) and hide that elements (E,F,G,H,I)
Snippet below presents used codes
//https://stackoverflow.com/questions/1107220/how-can-i-select-an-element-by-name-with-jquery#
// https://jsbench.me/o6kbhyyvib/1
// https://jsbench.me/2fkbi9rirv/1
function A() {
return $('[name=tcol1]');
}
function B() {
return $(document.getElementsByName("tcol1"))
}
function C() {
return document.getElementsByName("tcol1")
}
function D() {
return document.querySelectorAll('[name=tcol1]')
}
function E() {
$('[name=tcol1]').hide();
}
function F() {
$(document.getElementsByName("tcol1")).hide();
}
function G() {
document.getElementsByName("tcol1").forEach(e=>e.style.display='none');
}
function H() {
document.querySelectorAll('[name=tcol1]').forEach(e=>e.style.display='none');
}
function I() {
let elArr = [...document.getElementsByName("tcol1")];
let length = elArr.length
for(let i=0; i<length; i++) elArr[i].style.display='none';
}
// -----------
// TEST
// -----------
function reset() { $('td[name=tcol1]').show(); }
[A,B,C,D].forEach(f=> console.log(`${f.name} rows: ${f().length}`)) ;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>This snippet only presents used codes</div>
<table>
<tr>
<td>data1</td>
<td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
<td>data1</td>
<td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
<td>data1</td>
<td name="tcol1" class="bold"> data2</td>
</tr>
</table>
<button onclick="E()">E: hide</button>
<button onclick="F()">F: hide</button>
<button onclick="G()">G: hide</button>
<button onclick="H()">H: hide</button>
<button onclick="I()">I: hide</button><br>
<button onclick="reset()">reset</button>
_x000D_
Example results on Chrome
Use git reset HEAD
to reset the index without removing files. (If you only want to reset a particular file in the index, you can use git reset HEAD -- /path/to/file
to do so.)
The pipe operator, in a shell, takes the stdout
of the process on the left and passes it as stdin
to the process on the right. It's essentially the equivalent of:
$ proc1 > proc1.out
$ proc2 < proc1.out
$ rm proc1.out
but instead it's $ proc1 | proc2
, the second process can start getting data before the first is done outputting it, and there's no actual file involved.
You can set a default style for the entire workbook (all worksheets):
$objPHPExcel->getDefaultStyle()
->getBorders()
->getTop()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getBottom()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getLeft()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getRight()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
or
$styleArray = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);
And this can be used for all style properties, not just borders.
But column autosizing is structural
rather than stylistic
, and has to be set for each column on each worksheet individually.
EDIT
Note that default workbook style only applies to Excel5 Writer
// Simple but unreliable function to create string hash by Sergey.Shuchkin [t] gmail.com
// alert( strhash('http://www.w3schools.com/js/default.asp') ); // 6mn6tf7st333r2q4o134o58888888888
function strhash( str ) {
if (str.length % 32 > 0) str += Array(33 - str.length % 32).join("z");
var hash = '', bytes = [], i = j = k = a = 0, dict = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','1','2','3','4','5','6','7','8','9'];
for (i = 0; i < str.length; i++ ) {
ch = str.charCodeAt(i);
bytes[j++] = (ch < 127) ? ch & 0xFF : 127;
}
var chunk_len = Math.ceil(bytes.length / 32);
for (i=0; i<bytes.length; i++) {
j += bytes[i];
k++;
if ((k == chunk_len) || (i == bytes.length-1)) {
a = Math.floor( j / k );
if (a < 32)
hash += '0';
else if (a > 126)
hash += 'z';
else
hash += dict[ Math.floor( (a-32) / 2.76) ];
j = k = 0;
}
}
return hash;
}
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
Short answer:
use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.
Long answer:
The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.
TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.
Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.
Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.
So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.
Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().
Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.
I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".
In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.
What you can do is:
For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.
I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:
The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)
Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.
To add one year to todays date use the following:
$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));
Here's what worked for me to copy and overwrite a file from B:\ to Z:\ drive in a batch script.
echo F| XCOPY B:\utils\MyFile.txt Z:\Backup\CopyFile.txt /Y
The "/Y" parameter at the end overwrites the destination file, if it exists.
svn log -r {2009-09-17}:HEAD
where 2009-09-17
is the date you went on holiday. To see the changed files as well as the summary, add a -v
option:
svn log -r {2009-09-17}:HEAD -v
I haven't used WebSVN but there will be a log viewer somewhere that does the equivalent of these commands under the hood.
FWIW, git rebase interactive now has a "reword" option, which makes this much less painful!
Use this way and check all parts :
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
version = tf.__version__
executing_eagerly = tf.executing_eagerly()
hub_version = hub.__version__
available = tf.config.experimental.list_physical_devices("GPU")
print("Version: ", version)
print("Eager mode: ", executing_eagerly)
print("Hub Version: ", h_version)
print("GPU is", "available" if avai else "NOT AVAILABLE")
result = map(str.strip, hello)
merge into t2 t2
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
t2.c1 = t1.c1
, t2.c2 = t1.c2
import torch.nn as nn
# a simple network
rand_net = nn.Sequential(nn.Linear(in_features, h_size),
nn.BatchNorm1d(h_size),
nn.ReLU(),
nn.Linear(h_size, h_size),
nn.BatchNorm1d(h_size),
nn.ReLU(),
nn.Linear(h_size, 1),
nn.ReLU())
# initialization function, first checks the module type,
# then applies the desired changes to the weights
def init_normal(m):
if type(m) == nn.Linear:
nn.init.uniform_(m.weight)
# use the modules apply function to recursively apply the initialization
rand_net.apply(init_normal)