Even with something like an ArrayList or Vector, where "get" is a simple array lookup, the second loop still has additional overhead that the first one doesn't. I would expect it to be a tiny bit slower than the first.
Scripts are usually interpreted (by another executable).
A program is usually a standalone compiled executable in its own right (although it might have library dependencies), consisting of machine code or byte codes (for just-in-time compiled programs)
I think it is fine because I've seen many people doing this way.
If you are just defining the event handler within the directive, you do not have to define it on the scope, though. Following would be fine.
myApp.directive('clickme', function() {
return function(scope, element, attrs) {
var clickingCallback = function() {
alert('clicked!')
};
element.bind('click', clickingCallback);
}
});
In VS - project properties - in the Build tab - platform target =X86
In /etc/subversion/servers
you are setting http-proxy-host
, which has nothing to do with svn://
which connects to a different server usually running on port 3690 started by svnserve
command.
If you have access to the server, you can setup svn+ssh://
as explained here.
Update: You could also try using connect-tunnel
, which uses your HTTPS proxy server to tunnel connections:
connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690
Then you would use
svn checkout svn://localhost:10234/path/to/trunk
Use the oncontextmenu
event.
Here's an example:
<div oncontextmenu="javascript:alert('success!');return false;">
Lorem Ipsum
</div>
And using event listeners (credit to rampion from a comment in 2011):
el.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success!');
return false;
}, false);
Don't forget to return false, otherwise the standard context menu will still pop up.
If you are going to use a function you've written rather than javascript:alert("Success!")
, remember to return false in BOTH the function AND the oncontextmenu
attribute.
In Visual Studio Code, by pressing Ctrl+ and Ctrl- you can change the overall font size of the IDE. This helps faster than changing settings in every session. Hope it helps...
Adapted from Timmmm to PYQT5
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel
class Label(QLabel):
def __init__(self):
super(Label, self).__init__()
self.pixmap_width: int = 1
self.pixmapHeight: int = 1
def setPixmap(self, pm: QPixmap) -> None:
self.pixmap_width = pm.width()
self.pixmapHeight = pm.height()
self.updateMargins()
super(Label, self).setPixmap(pm)
def resizeEvent(self, a0: QResizeEvent) -> None:
self.updateMargins()
super(Label, self).resizeEvent(a0)
def updateMargins(self):
if self.pixmap() is None:
return
pixmapWidth = self.pixmap().width()
pixmapHeight = self.pixmap().height()
if pixmapWidth <= 0 or pixmapHeight <= 0:
return
w, h = self.width(), self.height()
if w <= 0 or h <= 0:
return
if w * pixmapHeight > h * pixmapWidth:
m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
self.setContentsMargins(m, 0, m, 0)
else:
m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
self.setContentsMargins(0, m, 0, m)
Limit is very simple, example limit first 50 rows
val df_subset = data.limit(50)
If you get the error "Unrecognized attribute 'enableSsl'" when following the advice to add that parameter to your web.config. I found that I was able to workaround the error by adding it to my code file instead in this format:
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
try
{
smtp.Send(mm);
}
catch (Exception ex)
{
MsgBox("Message not emailed: " + ex.ToString());
}
This is the system.net section of my web.config:
<system.net>
<mailSettings>
<smtp from="<from_email>">
<network host="smtp.gmail.com"
port="587"
userName="<your_email>"
password="<your_app_password>" />
</smtp>
</mailSettings>
</system.net>
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
If you don't have access to sysjobs table (someone elses server etc) you might be have or be allowed access to sysjobs_view
SELECT *
from msdb..sysjobs_view s
left join master.sys.syslogins l on s.owner_sid = l.sid
or
SELECT *, SUSER_SNAME(s.owner_sid) AS owner
from msdb..sysjobs_view s
If you know how far back, you can try something like:
# Current branch vs. parent
git diff HEAD^ HEAD
# Current branch, diff between commits 2 and 3 times back
git diff HEAD~3 HEAD~2
Prior commits work something like this:
# Parent of HEAD
git show HEAD^1
# Grandparent
git show HEAD^2
There are a lot of ways you can specify commits:
# Great grandparent
git show HEAD~3
From 6.11. Boolean operations:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.
The expression '/bla/bla/bla'
will be treated as true where a Boolean expression is expected (like in an if
statement), but the expressions '/bla/bla/bla' is True
and '/bla/bla/bla' == True
will evaluate to False for the reasons in Ignacio's answer.
The standard error is just the standard deviation divided by the square root of the sample size. So you can easily make your own function:
> std <- function(x) sd(x)/sqrt(length(x))
> std(c(1,2,3,4))
[1] 0.6454972
204 responses are sometimes used in AJAX to track clicks and page activity. In this case, the only information being passed to the server in the get request is a cookie and not specific information in request parameters, so this doesn't seem to be the case here.
It seems that clients1.google.com is the server behind google search suggestions. When you visit http://www.google.com, the cookie is passed to http://clients1.google.com/generate_204. Perhaps this is to start up some kind of session on the server? Whatever the use, I doubt it's a very standard use.
Try this code its working Firefox, Chrome, IE
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="" selected>---Select---</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
I'm surprised nobody pointed out JSON's []
method, which makes it very easy and transparent to decode and encode from/to JSON.
If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise generate a JSON text from the Ruby data structure object and return it.
Consider this:
require 'json'
hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"
str
now contains the JSON encoded hash
.
It's easy to reverse it using:
JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}
Custom objects need to_s
defined for the class, and inside it convert the object to a Hash then use to_json
on it.
Here's another method that's unorthodox, but works*.
I recently found myself in a situation where I'd checked in breaking code, knowing that I couldn't update our production code to it until all the integration work had taken place (in retrospect this was a bad decision, but we didn't expect to get stalled out, but other projects took precedence). That was several months ago, and the integration has been stalled for that entire time. Along comes a requirement to change the base code and get it into production last week without the breaking change.
Here's what we did:
After verifying that the new requirement doesn't break anything when using the revision before my check in, I made a copy of the working directory containing the new code. Then I deleted everything in the working directory and checked out the revision I wanted to it. Then I deleted all the files I'd just checked out, and copied in the files from the working copy. Then I committed that change, effectively wiping out the breaking change from the repository and getting the production code in place as the head revision. We still have the breaking change available, but it's no longer in the head revision so we can move forward to production.
*I don't recommend this method, but if you find yourself in a similar situation, it's a way out that's not too painful.
In one situation involving a multi-domain application, app.request.getHttpHost
helped me out. It returns something like example.com
or subdomain.example.com
(or example.com:8000
when the port is not standard). This was in Symfony 3.4.
You can do the same with .ix
, like this:
In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))
In [2]: df
Out[2]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 -0.905302 -0.435821 1.934512
3 0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
In [3]: df.ix[df.a>0, ['b','c']] = 0
In [4]: df
Out[4]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 0.000000 0.000000 1.934512
3 0.266113 0.000000 0.000000 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
EDIT
After the extra information, the following will return all columns - where some condition is met - with halved values:
>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)
I hope this helps!
This might be easier to explain with a sample dataset.
Create Sample Data
Let's assume we have a single column of Timestamps, date
and another column we would like to perform an aggregation on, a
.
df = pd.DataFrame({'date':pd.DatetimeIndex(['2012-1-1', '2012-6-1', '2015-1-1', '2015-2-1', '2015-3-1']),
'a':[9,5,1,2,3]}, columns=['date', 'a'])
df
date a
0 2012-01-01 9
1 2012-06-01 5
2 2015-01-01 1
3 2015-02-01 2
4 2015-03-01 3
There are several ways to group by year
year
propertydate
in index and use anonymous function to access yearresample
method.dt
accessor with year
propertyWhen you have a column (and not an index) of pandas Timestamps, you can access many more extra properties and methods with the dt
accessor. For instance:
df['date'].dt.year
0 2012
1 2012
2 2015
3 2015
4 2015
Name: date, dtype: int64
We can use this to form our groups and calculate some aggregations on a particular column:
df.groupby(df['date'].dt.year)['a'].agg(['sum', 'mean', 'max'])
sum mean max
date
2012 14 7 9
2015 6 2 3
If you set the date column as the index, it becomes a DateTimeIndex with the same properties and methods as the dt
accessor gives normal columns
df1 = df.set_index('date')
df1.index.year
Int64Index([2012, 2012, 2015, 2015, 2015], dtype='int64', name='date')
Interestingly, when using the groupby method, you can pass it a function. This function will be implicitly passed the DataFrame's index. So, we can get the same result from above with the following:
df1.groupby(lambda x: x.year)['a'].agg(['sum', 'mean', 'max'])
sum mean max
2012 14 7 9
2015 6 2 3
resample
methodIf your date column is not in the index, you must specify the column with the on
parameter. You also need to specify the offset alias as a string.
df.resample('AS', on='date')['a'].agg(['sum', 'mean', 'max'])
sum mean max
date
2012-01-01 14.0 7.0 9.0
2013-01-01 NaN NaN NaN
2014-01-01 NaN NaN NaN
2015-01-01 6.0 2.0 3.0
You can also convert the date column to a pandas Period object. We must pass in the offset alias as a string to determine the length of the Period.
df['date'].dt.to_period('A')
0 2012
1 2012
2 2015
3 2015
4 2015
Name: date, dtype: object
We can then use this as a group
df.groupby(df['date'].dt.to_period('Y'))['a'].agg(['sum', 'mean', 'max'])
sum mean max
2012 14 7 9
2015 6 2 3
You could use this query to get the no of indexes as well as the index names of each table in specified database.
SELECT TABLE_NAME,
COUNT(1) index_count,
GROUP_CONCAT(DISTINCT(index_name) SEPARATOR ',\n ') indexes
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = 'mydb'
AND INDEX_NAME != 'primary'
GROUP BY TABLE_NAME
ORDER BY COUNT(1) DESC;
In JavaScript, \w and \d are ASCII, while \s is Unicode. Don't ask me why. JavaScript does support \p with Unicode categories, which you can use to emulate a Unicode-aware \w and \d.
For \d use \p{N} (numbers)
For \w use [\p{L}\p{N}\p{Pc}\p{M}] (letters, numbers, underscores, marks)
Update: Unfortunately, I was wrong about this. JavaScript does does not officially support \p either, though some implementations may still support this. The only Unicode support in JavaScript regexes is matching specific code points with \uFFFF. You can use those in ranges in character classes.
You don't need to call json.getJSONArray()
at all, because the JSON you're working with already is an array. So, don't construct an instance of JSONObject
; use a JSONArray
. This should suffice:
// ...
JSONArray json = new JSONArray(result);
// ...
for(int i=0;i<json.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = json.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArray
at the root, not a JSONObject
.
To automate the answer of @Jordan S. Jones at WIN/DOS command-line,
Put this in a batch file named: getmns.bat (get mail name server):
@echo off
if @%1==@ goto USAGE
echo set type=MX>mnscmd.txt
echo %1>>mnscmd.txt
echo exit>>mnscmd.txt
nslookup<mnscmd.txt>mnsresult.txt
type mnsresult.txt
del mnsresult.txt
goto END
:USAGE
echo usage:
echo %0 domainname.ext
:END
echo.
For example:
getmns google.com
output:
google.com MX preference = 20, mail exchanger = alt1.aspmx.l.google.com
google.com MX preference = 10, mail exchanger = aspmx.l.google.com
google.com MX preference = 50, mail exchanger = alt4.aspmx.l.google.com
google.com MX preference = 40, mail exchanger = alt3.aspmx.l.google.com
google.com MX preference = 30, mail exchanger = alt2.aspmx.l.google.com
alt4.aspmx.l.google.com internet address = 74.125.25.27
alt3.aspmx.l.google.com internet address = 173.194.72.27
aspmx.l.google.com internet address = 173.194.65.27
alt1.aspmx.l.google.com internet address = 74.125.200.27
alt2.aspmx.l.google.com internet address = 64.233.187.27
For example to pipe the result again into a file do:
getmns google.com > google.mns.txt
:-D
In some cases you can just use the flex-box
property order
.
Very simple:
.flex-item {
order: 2;
}
I was facing the same issue; and the following worked well for me. Hope this helps someone landing here:
<div class="row">
<div class="col-md-6">
<div class="col-md-12">
Set room heater temperature
</div>
</div>
<div class="col-md-6">
<div class="col-md-12">
Set room heater temperature
</div>
</div>
</div>
This will automatically render some space between the 2 divs.
How about:
df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']).dt.days
This will return difference as int
if there are no missing values(NaT
) and float
if there is.
Sadly, no, you can't run 4.5 programs on XP.
And the relevant post from that Connect page:
Posted by Microsoft on 23/03/2012 at 10:39
Thanks for the report. This behavior is by design in .NET Framework 4.5 Beta. The minimum supported operating systems are Windows 7, Windows Server 2008 SP2 and Windows Server 2008 R2 SP1. Windows XP is not a supported operating system for the Beta release.
For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:
2nd Child:
td:first-child + td
3rd Child:
td:first-child + td + td
Then simply add another + td
for each additional child you wish to select.
If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):
$(function() {
$('td:first-child').addClass("firstChild");
$(".table-class tr").each(function() {
$(this).find('td:eq(1)').addClass("secondChild");
$(this).find('td:eq(2)').addClass("thirdChild");
});
});
Then in your css you simply use those class selectors to make whatever changes you like:
table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }
Check out the language reference:
http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx
expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
document.getElementById('something') can be 'undefined'. Usually (thought not always) it's sufficient to do tests like if (document.getElementById('something'))
.
I know this question is old. But this might be useful for someone who is having the problem with legend. In addition to the answer given by ZaneDarken, I modified the chart.js file to show the legend in my pie chart. I changed the legendTemplate(which is declared many times for every chart type) just above these lines :
Chart.Type.extend({_x000D_
//Passing in a name registers this chart in the Chart namespace_x000D_
name: "Doughnut",_x000D_
//Providing a defaults will also register the deafults in the chart namespace_x000D_
defaults: defaultConfig,_x000D_
.......
_x000D_
My legendTemplate is changed from
legendTemplate : "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
<% for (var i=0; i<datasets.length; i++){%>_x000D_
<li><span style=\ "background-color:<%=datasets[i].strokeColor%>\"></span>_x000D_
<%if(datasets[i].label){%>_x000D_
<%=datasets[i].label%>_x000D_
<%}%>_x000D_
</li>_x000D_
<%}%>_x000D_
</ul>"
_x000D_
To
legendTemplate: "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
<% for (var i=0; i<segments.length; i++){%>_x000D_
<li><span style=\ "-moz-border-radius:7px 7px 7px 7px; border-radius:7px 7px 7px 7px; margin-right:10px;width:15px;height:15px;display:inline-block;background-color:<%=segments[i].fillColor%>\"> </span>_x000D_
<%if(segments[i].label){%>_x000D_
<%=s egments[i].label%>_x000D_
<%}%>_x000D_
</li>_x000D_
<%}%>_x000D_
</ul>"
_x000D_
It really depends on what technology restrictions you have.
One way is to have a spatial database with the outline of the countries and cities you are interested in. By outline I mean that countries and cities are store as the spatial type polygon. Your set of coordinates can be converted to the spatial type point and queried against the polygons to get the country/city name where the point is located.
Here are some of the databases which support spatial type: SQL server 2008, MySQL, postGIS - an extension of postgreSQL and Oracle.
If you would like to use a service in stead of having your own database for this you can use Yahoo's GeoPlanet. For the service approach you might want to check out this answer on gis.stackexchange.com, which covers the availability of services for solving your problem.
char (with a lower-case c) is a numeric type. It already holds the ascii value of the char. Just cast it to an integer to display it as a numeric value rather than a textual value:
System.out.println("char " + ch + " has the following value : " + (int) ch);
You can use clone, and then since each div has a class of car_well you can use insertAfter to insert after the last div.
$("#car2").clone().insertAfter("div.car_well:last");
I would prefer the C++ size constraints over the C versions:
// Ignore to the end of file
cin.ignore(std::numeric_limits<std::streamsize>::max())
// Ignore to the end of line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
You are iterating over one string (word
), but then using the index into that to look up a character in so_far
. There is no guarantee that these two strings have the same length.
If the millis value is number of millis since Jan 1, 1970 GMT, as is standard for the JVM, then that is independent of time zone. If you want to format it with a specific time zone, you can simply convert it to a GregorianCalendar object and set the timezone. After that there are numerous ways to format it.
.list-comma::before {_x000D_
content: ',';_x000D_
}_x000D_
.list-comma:first-child::before {_x000D_
content: '';_x000D_
}
_x000D_
<span class="list-comma" ng-repeat="destination in destinations">_x000D_
{{destination.name}}_x000D_
</span>
_x000D_
IE11 does implement String.prototype.includes so why not using the official Polyfill?
Source: polyfill source
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
The 60 you're passing is just the initial capacity for internal storage. It's a hint on how big you think it might be, yet of course it's not limited by that. If you need to preset values you'll have to set them yourself, e.g.:
for (int i = 0; i < 60; i++) {
list.add(0);
}
Processing the ASP.NET web-form takes place in stages. At each state various events
are raised. If you are interested to plug your code into the processing flow
(on server side) then you have to handle appropriate page event.
Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp
or specify the main class. In your case it would contain lines like this:
Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar
Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar
.
Then execute it with
java -jar MyJar.jar
You can use urllib2 to make the HTTP requests, and then you'll have web content.
You can get it like this:
import urllib2
response = urllib2.urlopen('http://example.com')
html = response.read()
Beautiful Soup is a python HTML parser that is supposed to be good for screen scraping.
In particular, here is their tutorial on parsing an HTML document.
Good luck!
If anyone still looking for a quick solution and don't want dependencies like jquery etc I wrote a mini lib that add expiration to local / session / custom storage, you can find it with source here:
You didn't select post_id
in the subquery. You have to select it in the subquery like this:
SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM wp_woocommerce_order_items
LEFT JOIN
(
SELECT meta_value As Prenom, post_id -- <----- this
FROM wp_postmeta
WHERE meta_key = '_shipping_first_name'
) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE wp_woocommerce_order_items.order_id =2198
sorted(filter(os.path.isfile, os.listdir('.')),
key=lambda p: os.stat(p).st_mtime)
You could use os.walk('.').next()[-1]
instead of filtering with os.path.isfile
, but that leaves dead symlinks in the list, and os.stat
will fail on them.
Its quite old question, and I'm not sure if it was an option at that time, but this is the reason why I always prefer DependencyInjection by the constructor than by the value.
I can imagine that your class might look like this:
class ExampleClass{
@Autowired
private Dog dog;
@Value("${this.property.value}")
private String thisProperty;
...other stuff...
}
You can change it to:
class ExampleClass{
private Dog dog;
private String thisProperty;
//optionally @Autowire
public ExampleClass(final Dog dog, @Value("${this.property.value}") final String thisProperty){
this.dog = dog;
this.thisProperty = thisProperty;
}
...other stuff...
}
With this implementation, the spring will know what to inject automatically, but for unit testing, you can do whatever you need. For example Autowire every dependency wth spring, and inject them manually via constructor to create "ExampleClass" instance, or use only spring with test property file, or do not use spring at all and create all object yourself.
we are using below configuration to do something similar
var gulp = require('gulp'),
async = require("async"),
less = require('gulp-less'),
minifyCSS = require('gulp-minify-css'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
gulpDS = require("./gulpDS"),
del = require('del');
// CSS & Less
var jsarr = [gulpDS.jsbundle.mobile, gulpDS.jsbundle.desktop, gulpDS.jsbundle.common];
var cssarr = [gulpDS.cssbundle];
var generateJS = function() {
jsarr.forEach(function(gulpDSObject) {
async.map(Object.keys(gulpDSObject), function(key) {
var val = gulpDSObject[key]
execGulp(val, key);
});
})
}
var generateCSS = function() {
cssarr.forEach(function(gulpDSObject) {
async.map(Object.keys(gulpDSObject), function(key) {
var val = gulpDSObject[key];
execCSSGulp(val, key);
})
})
}
var execGulp = function(arrayOfItems, dest) {
var destSplit = dest.split("/");
var file = destSplit.pop();
del.sync([dest])
gulp.src(arrayOfItems)
.pipe(concat(file))
.pipe(uglify())
.pipe(gulp.dest(destSplit.join("/")));
}
var execCSSGulp = function(arrayOfItems, dest) {
var destSplit = dest.split("/");
var file = destSplit.pop();
del.sync([dest])
gulp.src(arrayOfItems)
.pipe(less())
.pipe(concat(file))
.pipe(minifyCSS())
.pipe(gulp.dest(destSplit.join("/")));
}
gulp.task('css', generateCSS);
gulp.task('js', generateJS);
gulp.task('default', ['css', 'js']);
sample GulpDS file is below:
{
jsbundle: {
"mobile": {
"public/javascripts/sample.min.js": ["public/javascripts/a.js", "public/javascripts/mobile/b.js"]
},
"desktop": {
'public/javascripts/sample1.js': ["public/javascripts/c.js", "public/javascripts/d.js"]},
"common": {
'public/javascripts/responsive/sample2.js': ['public/javascripts/n.js']
}
},
cssbundle: {
"public/stylesheets/a.css": "public/stylesheets/less/a.less",
}
}
You could always check manually if your EventListener exist using Chrome inspector for example. In Element tab you have the traditional "Styles" subtab and close to it another one : "Event Listeners". Which will give you the list of all EventListeners with their linked elements.
EDIT : my bad! With my answer, the icon won't behave as a toggler Actually, it will be shown even when not collapsed... Still searching...
This would work :
<button class="btn btn-primary" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span>
<i class="fas fa-bars"></i>
</span>
</button>
The trick proposed by my answer is to replace the navbar-toggler
with a classical button class btn
and then, as answered earlier, use an icon font.
Note, that if you keep <button class="navbar-toggler">
, the button will have a "strange" shape.
As stated in this post on github, bootstrap uses some "css trickery", so users don't have to rely on fonts.
So, just don't use the "navbar-toggler"
class on your button if you want to use an icon font.
Cheers.
To use cache-control in HTML, you use the meta tag, e.g.
<meta http-equiv="Cache-control" content="public">
The value in the content field is defined as one of the four values below.
Some information on the Cache-Control
header is as follows
HTTP 1.1. Allowed values = PUBLIC | PRIVATE | NO-CACHE | NO-STORE.
Public - may be cached in public shared caches.
Private - may only be cached in private cache.
No-Cache - may not be cached.
No-Store - may be cached but not archived.The directive CACHE-CONTROL:NO-CACHE indicates cached information should not be used and instead requests should be forwarded to the origin server. This directive has the same semantics as the PRAGMA:NO-CACHE.
Clients SHOULD include both PRAGMA: NO-CACHE and CACHE-CONTROL: NO-CACHE when a no-cache request is sent to a server not known to be HTTP/1.1 compliant. Also see EXPIRES.
Note: It may be better to specify cache commands in HTTP than in META statements, where they can influence more than the browser, but proxies and other intermediaries that may cache information.
CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.
Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.
Try something like this:
var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
method: 'JSONP',
url: url
}).
success(function(status) {
//your code when success
}).
error(function(status) {
//your code when fails
});
If you need a name on your pin, you can also use:
http://maps.google.com/?q=MY%20LOCATION@lat,long
DISCLAIMER: I'm the author of gitchangelog of which I'll be speaking in the following.
TL;DR: You might want to check gitchangelog's own changelog or the ascii output that generated the previous.
If you want to generate a changelog from your git history, you'll probably have to consider:
Optionaly you might want some categorization (new things, changes, bugfixes)...
With all this in mind, I created and use gitchangelog. It's meant to leverage a git commit message convention to achieve all of the previous goals.
Having a commit message convention is mandatory to create a nice changelog (with or without using gitchangelog
).
commit message convention
The following are suggestions to what might be useful to think about adding in your commit messages.
You might want to separate roughly your commits into big sections:
Additionally, you could want to tag some commits:
Try to write your commit message by targeting users (functionality) as often as you can.
example
This is standard git log --oneline
to show how these information could be stored::
* 5a39f73 fix: encoding issues with non-ascii chars.
* a60d77a new: pkg: added ``.travis.yml`` for automated tests.
* 57129ba new: much greater performance on big repository by issuing only one shell command for all the commits. (fixes #7)
* 6b4b267 chg: dev: refactored out the formatting characters from GIT.
* 197b069 new: dev: reverse ``natural`` order to get reverse chronological order by default. !refactor
* 6b891bc new: add utf-8 encoding declaration !minor
So if you've noticed, the format I chose is:
{new|chg|fix}: [{dev|pkg}:] COMMIT_MESSAGE [!{minor|refactor} ... ]
To see an actual output result, you could look at the end of the PyPI page of gitchangelog
To see a full documentation of my commit message convention you can see the reference file gitchangelog.rc.reference
How to generate exquisite changelog from this
Then, it's quite easy to make a complete changelog. You could make your own script quite quickly, or use gitchangelog
.
gitchangelog
will generate a full changelog (with sectioning support as New
, Fix
...), and is reasonably configurable to your own committing conventions. It supports any type of output thanks to templating through Mustache
, Mako templating
, and has a default legacy engine written in raw python ; all current 3 engines have examples of how to use them and can output changelog's as the one displayed on the PyPI page of gitchangelog.
I'm sure you know that there are plenty of other git log
to changelog
tools out there also.
and(re.search("bla_bla_pattern", str_item, re.IGNORECASE) == None)
is working.
If sounds like the type ACTInterface
is not public
, but is using the default accessibility of either internal
(if it is top-level) or private
(if it is nested in another type).
Giving the type the public
modifier would fix it.
Another approach is to make both the type and the method internal
, if that is your intent.
The issue is not the accessibility of the field (oActInterface
), but rather of the type ACTInterface
itself.
I'm using jQuery UI 1.8.13 and the following configuration works as I need:
var buttonsConfig = [
{
text: "Ok",
"class": "ok",
click: function() {
}
},
{
text: "Annulla",
"class": "cancel",
click: function() {
}
}
];
$("#foo").dialog({
buttons: buttonsConfig
// ...
ps: remember to wrap "class" with quotes because it's a reserved word in js!
It is technically approved that MD5 is faster than SHA256 so in just verifying file integrity it will be sufficient and better for performance.
You are able to checkout the following resources:
git log -S"string_to_search" # options like --source --reverse --all etc
Pay attention not to use spaces between S and "string_to_search". In some setups (git 1.7.1), you'll get an error like:
fatal: ambiguous argument 'string_to_search': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
You can iterate through the array or you can convert it to a String
and use indexOf
.
if (new String(charArray).indexOf('q') < 0) {
break;
}
Creating a new String
is a bit wasteful, but it's probably the tersest code. You can also write a method to imitate the effect without incurring the overhead.
Extend to Danny W. Adair Answer, to get month also
def calculate_age(b):
t = date.today()
c = ((t.month, t.day) < (b.month, b.day))
c2 = (t.day< b.day)
return t.year - b.year - c,c*12+t.month-b.month-c2
#
and ##
tables are actual tables represented in the temp database. These tables can have indexes and statistics, and can be accessed across sprocs in a session (in the case of a global temp table, it is available across sessions).
The @table is a table variable.
It depends where the string 'came from'. A .NET string is Unicode (UTF-16). The only way it could be different if you, say, read the data from a database into a byte array.
This CodeProject article might be of interest: Detect Encoding for in- and outgoing text
Jon Skeet's Strings in C# and .NET is an excellent explanation of .NET strings.
The important thing to note here is that the mime type is not the same as the file extension. Sometimes, however, they have the same value.
https://www.iana.org/assignments/media-types/media-types.xhtml includes a list of registered Mime types, though there is nothing stopping you from making up your own, as long as you are at both the sending and the receiving end. Here is where Microsoft comes in to the picture.
Where there is a lot of confusion is the fact that operating systems have their own way of identifying file types by using the tail end of the file name, referred to as the extension. In modern operating systems, the whole name is one long string, but in more primitive operating systems, it is treated as a separate attribute.
The OS which caused the confusion is MSDOS, which had limited the extension to 3 characters. This limitation is inherited to this day in devices, such as SD cards, which still store data in the same way.
One side effect of this limitation is that some file extensions, such as .gif
match their Mime Type, image/gif
, while others are compromised. This includes image/jpeg
whose extension is shortened to .jpg
. Even in modern Windows, where the limitation is lifted, Microsoft never let the past go, and so the file extension is still the shortened version.
Given that that:
The short answer is:
image/jpg
, so the answer is
that it is not the same as image/jpeg
While we’re at it …
Legacy versions of Internet Explorer took the liberty of uploading jpeg
files with the Mime Type of image/pjpeg
, which, of course, just means more work for everybody else. They also uploaded png
files as image/x-png
.
@duncan's solution above specifying new()
for the static type works also with interfaces:
interface MyType {
instanceMethod();
}
interface MyTypeStatic {
new():MyType;
staticMethod();
}
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
try following statement
Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
string pathQuery = myuri.PathAndQuery;
string hostName = myuri.ToString().Replace(pathQuery , "");
Example1
Input : http://localhost:4366/Default.aspx?id=notlogin
Ouput : http://localhost:4366
Example2
Input : http://support.domain.com/default.aspx?id=12345
Output: support.domain.com
I had the same issue.
I didn't need to download anything else to solve this. CV2 had everything I needed.
Instead of trying to figure out where the .xml
files are and hard coding the values, I used a property given by cv2.
From OP
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
Becomes
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
if condition is null then it is number
IF(rtrim(P_COD_LEGACY, '0123456789') IS NULL) THEN
return 1;
ELSE
return 0;
END IF;
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
Please checkout! https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
In my case adding statement
server.port=${port:8081}
override the default tomcat server port.
The answer is .IsPostBack
as suggested by @Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load
private void PopulateFields()
{
using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
TextBoxPassword.Text = (myReader["password"].ToString());
TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
DropDownListMonth.Text = (myReader["birth"].ToString());
DropDownListYear.Text = (myReader["birth"].ToString());
TextBoxAddress.Text = (myReader["address"].ToString());
TextBoxCity.Text = (myReader["city"].ToString());
DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
TextBoxPostcode.Text = (myReader["postcode"].ToString());
TextBoxEmail.Text = (myReader["email"].ToString());
TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
}//end using
}
Then call it in your Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PopulateFields();
}
}
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
If you have access to the server then you can use
select local_tcp_port from sys.dm_exec_connections where local_tcp_port is not null
For full details see port number of SQL Server
It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.
Map:
class Map<T> {
private items: { [key: string]: T };
constructor() {
this.items = {};
}
add(key: string, value: T): void {
this.items[key] = value;
}
has(key: string): boolean {
return key in this.items;
}
get(key: string): T {
return this.items[key];
}
}
List:
class List<T> {
private items: Array<T>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(value);
}
get(index: number): T {
return this.items[index];
}
}
I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...
As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:
class ListItem<T> {
private list: List<T>;
private index: number;
public value: T;
constructor(list: List<T>, value: T, index: number) {
this.list = list;
this.index = index;
this.value = value;
}
prev(): ListItem<T> {
return this.list.get(this.index - 1);
}
next(): ListItem<T> {
return this.list.get(this.index + 1);
}
}
class List<T> {
private items: Array<ListItem<T>>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(new ListItem<T>(this, value, this.size()));
}
get(index: number): ListItem<T> {
return this.items[index];
}
}
Here too you're looking at untested code..
Hope this helps.
Javascript has a native Map object so there's no need to create your own:
let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1
If you want to maintain a sorted list which you will frequently modify (i.e. a structure which, in addition to being sorted, allows duplicates and whose elements can be efficiently referenced by index), then use an ArrayList but when you need to insert an element, always use Collections.binarySearch() to determine the index at which you add a given element. The latter method tells you the index you need to insert at to keep your list in sorted order.
It's easy to get this error in a multi-module project. If, for example, you made changes to modules A, B, and C, but then you try to compile just module B, you are susceptible to this error. Say module B has a dependency on module A. Since only module B was compiled, the class files from module A are now out of date and possibly invalid.
Compiling all the modules (or modules in the proper hierarchical dependency order) resolves this error, if this is the nature of your problem.
Check out the COPY command of Postgres:
I was getting this error while posting a FormData object because I was not setting up the ajax call correctly. Setup below fixed my issue.
var myformData = new FormData();
myformData.append('leadid', $("#leadid").val());
myformData.append('date', $(this).val());
myformData.append('time', $(e.target).prev().val());
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
url: 'include/ajax.php',
success: function (response) {
$("#subform").html(response).delay(4000).hide(1);
}
});
There is a 3rd party debugger in the works, it's currently in preview, but you can install the debugger Android extension in VSCode right now and get more information on it here:
Get text from a dropdown multiple
var texts = [];
$('#list :selected').each(function(){
texts.push($(this).text());
});
texts now contains a list of selected text
If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf
must be in the same directory in which you execute the program.
You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd
to the directory where your input file is located and start the Python script there using the command
$ python script.py
In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd
to the directory containing your Python script file and run it.
In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.
uese following code.
NSString *searchText = @"Bhupi"
NSString *formatedSearchText = [NSString stringWithFormat:@"%%%@%%",searchText];
will output: %Bhupi%
It is XOR. Another name for the XOR function is addition without carry. I suppose that's how the symbol might make sense.
var now = new Date();_x000D_
now.setMinutes(now.getMinutes() + 30); // timestamp_x000D_
now = new Date(now); // Date object_x000D_
console.log(now);
_x000D_
Modal Window using ExtJS approach.
In Main Window
<html>
<link rel="stylesheet" href="ext.css" type="text/css">
<head>
<script type="text/javascript" src="ext-all.js"></script>
function openModalDialog() {
Ext.onReady(function() {
Ext.create('Ext.window.Window', {
title: 'Hello',
height: Ext.getBody().getViewSize().height*0.8,
width: Ext.getBody().getViewSize().width*0.8,
minWidth:'730',
minHeight:'450',
layout: 'fit',
itemId : 'popUpWin',
modal:true,
shadow:false,
resizable:true,
constrainHeader:true,
items: [{
xtype: 'box',
autoEl: {
tag: 'iframe',
src: '2.html',
frameBorder:'0'
}
}]
}).show();
});
}
function closeExtWin(isSubmit) {
Ext.ComponentQuery.query('#popUpWin')[0].close();
if (isSubmit) {
document.forms[0].userAction.value = "refresh";
document.forms[0].submit();
}
}
</head>
<body>
<form action="abc.jsp">
<a href="javascript:openModalDialog()"> Click to open dialog </a>
</form>
</body>
</html>
In popupWindow 2.html
<html>
<head>
<script type="text\javascript">
function doSubmit(action) {
if (action == 'save') {
window.parent.closeExtWin(true);
} else {
window.parent.closeExtWin(false);
}
}
</script>
</head>
<body>
<a href="javascript:doSubmit('save');" title="Save">Save</a>
<a href="javascript:doSubmit('cancel');" title="Cancel">Cancel</a>
</body>
</html>
Not in core, no. A search for "java array join string glue" will give you some code snippets on how to achieve this though.
e.g.
public static String join(Collection s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
Since JDK8 I love Streams and Lambdas a lot, so I would suggest:
public static String join( String delimiter, String[] array )
{
return Arrays.asList( array ).stream().collect( Collectors.joining( delimiter ) );
}
This is called the "shape" in NumPy, and can be requested via the .shape
attribute:
>>> a = zeros((2, 5))
>>> a.shape
(2, 5)
If you prefer a function, you could also use numpy.shape(a)
.
You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.
In case someone else hits this... Here's another difference:
If the id contains characters that are not supported by the HTML standard (see SO question here) then jQuery may not find it even if getElementById does.
This happened to me with an id containing "/" characters (ex: id="a/b/c"), using Chrome:
var contents = document.getElementById('a/b/c');
was able to find my element but:
var contents = $('#a/b/c');
did not.
Btw, the simple fix was to move that id to the name field. JQuery had no trouble finding the element using:
var contents = $('.myclass[name='a/b/c']);
If you have multiple projects in your solution and one of your projects fails to build because of this error then ensure you have installed the WebApi Core nuget package in that project. Simply adding a reference to the System.Web.Http does not help, you need to install the correct nuget package into that project.
I had multiple projects in my solution and WebApi Core was already installed in another project. I referenced the System.Web.Http assembly by right-clicking and ticking the assembly from the list and it did not work on Azure, though locally it would build okay. I had to remove the manual reference and add the WebApi Core nuget package to each project that needed the assembly reference.
You can use the following code snippet :
java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
-version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
In my pc I am getting following output :
uintx InitialHeapSize := 536870912 {product}
uintx MaxHeapSize := 1073741824 {product}
uintx PermSize := 67108864 {pd product}
uintx MaxPermSize := 134217728 {pd product}
intx ThreadStackSize := 512 {pd product}
In rails 4 you can now use a css and sass helper image-url:
div.logo {background-image: image-url("logo.png");}
If your background images aren't showing up consider looking at how you're referencing them in your stylesheets.
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
If you decide to add a .pch file manually and you want to use Objective-C just like before xCode 6 you will also have to import UIKit and Foundation frameworks in the .pch file. Otherwise you will have to import these frameworks manually in each header file. You can add the following code anyway as it tests for the language used:
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif
xcopy e:\source_folder f:\destination_folder /e /i /h
The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.
in 2021 to create .d.ts
file manually, you just need to do the following:
1- enter src folder
2- create global.d.ts
file
3-declare modules in it like:
declare module 'module-name';
i answred it here before and it was nice
Else this will helps you
The ADB is now located in the Android SDK platform-tools.
Check your [sdk directory]/platform-tools directory and if it does not exist, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), switch to SDK tools tab and and select/install the Android SDK Platform-tools.
Alternatively, you can try the standalone SDK Manager: Open the SDK manager and you should see a "Launch Standalone SDK manager" link somewhere at the bottom of the settings window. Click and open the standalone SDK manager, then install/update the
"Tools > Android SDK platform tools". If the above does not solve the problem, try reinstalling the tools: open the "Standalone SDK manager" and uninstall the Android SDK platform-tools, delete the [your sdk directory]/platform-tools directory completely and install it again using the SDK manager.
Hope this helps!
Javascript provides more than one method to check the viewport width. As you noticed, innerWidth doesn't include the toolbar width, and toolbar widths will differ across systems. There is also the outerWidth option, which will include the toolbar width. The Mozilla Javascript API states:
Window.outerWidth gets the width of the outside of the browser window. It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles.
The state of javascript is such that one cannot rely on a specific meaning for outerWidth in every browser on every platform.
outerWidth
is not well supported on older mobile browsers, though it enjoys support across major desktop browsers and most newer smart phone browsers.
As ausi pointed out, matchMedia
would be a great choice as CSS is better standardised (matchMedia uses JS to read the viewport values detected by CSS). But even with accepted standards, retarded browsers still exist that ignore them (IE < 10 in this case, which makes matchMedia not very useful at least until XP dies).
In summary, if you are only developing for desktop browsers and newer mobile browsers, outerWidth should give you what you are looking for, with some caveats.
step one wrap your app in Router
import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));
Now my entire App will have access to BrowserRouter. Step two I import Route and then pass down those props. Probably in one of your main files.
import { Route } from "react-router-dom";
//lots of code here
//somewhere in my render function
<Route
exact
path="/" //put what your file path is here
render={props => (
<div>
<NameOfComponent
{...props} //this will pass down your match, history, location objects
/>
</div>
)}
/>
Now if I run console.log(this.props) in my component js file that I should get something that looks like this
{match: {…}, location: {…}, history: {…}, //other stuff }
Step 2 I can access the history object to change my location
//lots of code here relating to my whatever request I just ran delete, put so on
this.props.history.push("/") // then put in whatever url you want to go to
Also I'm just a coding bootcamp student, so I'm no expert, but I know you can also you use
window.location = "/" //wherever you want to go
Correct me if I'm wrong, but when I tested that out it reloaded the entire page which I thought defeated the entire point of using React.
nasm -f bin -o 2_hello 2_hello.asm
I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:
Make a bash (shell) script version of your .bat file (like other
answers, with \
changed to /
in file paths). For example:
# File "example.command":
#!/bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar; ...etc.
Then rename it to have the Mac OS file extension .command
.
That should make the script run using the Terminal app.
If the app user is going to use a bash script version of the file on Linux
or run it from the command line, they need to add executable rights
(change mode bits) using this command, in the folder that has the file:
chmod +rx [filename].sh
#or:# chmod +rx [filename].command
The forum page question:
Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.
Info from some answers after the question:
Write a shell script, and give it the extension ".command". For example:
#!/bin/bash printf "Hello World\n"
- Mar 23, 2010, Tony T1.
The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.However, OS X adds the feature that if you give the file the suffix
.command
, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]#!/bin/sh echo Hello World
- Mar 23, 2010, J D McIninch.
Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:
On mac, there is a specific extension for executing shell
scripts by double clicking them: this is.command
.
If you use Iclick pluging, it is as simply as you see below.
$('#radio1').iCheck('uncheck');
A simple example in shell script
#!/bin/bash
current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;
With out punctuation format :- +%Y%m%d%H%M%S
With punctuation :- +%Y-%m-%d %H:%M:%S
What's a memory leak:
Typical example:
A cache of objects is a good starting point to mess things up.
private static final Map<String, Info> myCache = new HashMap<>();
public void getInfo(String key)
{
// uses cache
Info info = myCache.get(key);
if (info != null) return info;
// if it's not in cache, then fetch it from the database
info = Database.fetch(key);
if (info == null) return null;
// and store it in the cache
myCache.put(key, info);
return info;
}
Your cache grows and grows. And pretty soon the entire database gets sucked into memory. A better design uses an LRUMap (Only keeps recently used objects in cache).
Sure, you can make things a lot more complicated:
What often happens:
If this Info object has references to other objects, which again have references to other objects. In a way you could also consider this to be some kind of memory leak, (caused by bad design).
Disclaimer :- Only for ios 9 and above (Stack View).
If you are deploying your app on ios 9 devices use a stack view. Here are the steps :-
Just a quick note/summary for any who came here via Google looking for the answer to the general question asked in the title (as I was). Any of the following should work for getting access to shell variables inside quotes:
echo "$VARIABLE"
echo "${VARIABLE}"
Use of single quotes is the main issue. According to the Bash Reference Manual:
Enclosing characters in single quotes (
'
) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. [...] Enclosing characters in double quotes ("
) preserves the literal value of all characters within the quotes, with the exception of$
,`
,\
, and, when history expansion is enabled,!
. The characters$
and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters:$
,`
,"
,\
, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an!
appearing in double quotes is escaped using a backslash. The backslash preceding the!
is not removed. The special parameters*
and@
have special meaning when in double quotes (see Shell Parameter Expansion).
In the specific case asked in the question, $COLUMNS is a special variable which has nonstandard properties (see lhunath's answer above).
My version of this is an adaptation of Arvo's work, with a little more added on to ensure two other cases.
1) If we have all 0s, we should return the digit 0.
2) If we have a blank, we should still return a blank character.
CASE
WHEN PATINDEX('%[^0]%', str_col + '.') > LEN(str_col) THEN RIGHT(str_col, 1)
ELSE SUBSTRING(str_col, PATINDEX('%[^0]%', str_col + '.'), LEN(str_col))
END
SELECT * FROM SysColumns WHERE Name like 'a%'
Will get you a list of columns, you will want to filter more to restrict it to your target table
From there you can construct some ad-hoc sql
At line 5 there is a /
missing.
There is a good answer on the differences between ;
and /
here.
Basically, when running a CREATE
block via script, you need to use /
to let SQLPlus know when the block ends, since a PL/SQL block can contain many instances of ;
.
Remove the declaration from AppModule
, but update the AppModule
configuration to import your AddEventModule
.
.....
import { AddEventModule } from './add-event.module'; // <-- don't forget to import the AddEventModule class
@NgModule({
declarations: [
MyApp,
HomePage,
Login,
Register,
//AddEvent, <--- remove this
EventDetails
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule,
AngularFireModule.initializeApp(config),
AddEventModule, // <--- add this import here
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
Login,
Register,
AddEvent,
EventDetails
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}, Eventdata, AuthProvider
]
})
export class AppModule {}
Also,
Note that it's important that your AddEventModule
exports the AddEvent
component if you want to use it outside that module. Luckily, you already have that configured, but if it was omitted, you would've gotten an error if you tried to use the AddEvent
component in another component of your AppModule
I got the same issue.
I fixed it by removing line-height from my input. Check if there is some lineheight which is causing the problem
Setting adjustViewBounds to true and using a LinearLayout view group worked very well for me. No need to subclass or ask for device metrics:
//NOTE: "this" is a subclass of LinearLayout
ImageView splashImageView = new ImageView(context);
splashImageView.setImageResource(R.drawable.splash);
splashImageView.setAdjustViewBounds(true);
addView(splashImageView);
OK, but you don`t want to open the whole realtime database! You need something like this.
{
/* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
"rules": {
".read": "auth.uid !=null",
".write": "auth.uid !=null"
}
}
or
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid"
}
}
}
}
I had some problems with result transformers combined with HQL queries. When I tried
final ResultTransformer trans = new DistinctRootEntityResultTransformer();
qry.setResultTransformer(trans);
it didn't work. I had to transform manually like this:
final List found = trans.transformList(qry.list());
With Criteria API transformers worked just fine.
Make sure you have closed your MSAccess file before running the java program.
you can use list comprehensions to do this in a single line
n = 4
chunks = [df[i:i+n] for i in range(0,df.shape[0],n)]
If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:
substr( sha1( time() ), 0, 15 )
time()
gives you the current time in seconds since epoch, sha1()
encrypts it to a string of 0-9a-f, and substr()
lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.
TLDR; Here's why:
The reason this works is because
gulp
tries to run yourgulpfile.js
using your locally installed version ofgulp
, see here. Hence the reason for a global and local install of gulp.
Essentially, when you install gulp
locally the script isn't in your PATH
and so you can't just type gulp
and expect the shell to find the command. By installing it globally the gulp
script gets into your PATH
because the global node/bin/
directory is most likely on your path.
To respect your local dependencies though, gulp
will use your locally installed version of itself to run the gulpfile.js
.
Meaning of
@classmethod
and@staticmethod
?
self
) as the implicit first argument.cls
) as the implicit first argument.when should I use them, why should I use them, and how should I use them?
You don't need either decorator. But on the principle that you should minimize the number of arguments to functions (see Clean Coder), they are useful for doing just that.
class Example(object):
def regular_instance_method(self):
"""A function of an instance has access to every attribute of that
instance, including its class (and its attributes.)
Not accepting at least one argument is a TypeError.
Not understanding the semantics of that argument is a user error.
"""
return some_function_f(self)
@classmethod
def a_class_method(cls):
"""A function of a class has access to every attribute of the class.
Not accepting at least one argument is a TypeError.
Not understanding the semantics of that argument is a user error.
"""
return some_function_g(cls)
@staticmethod
def a_static_method():
"""A static method has no information about instances or classes
unless explicitly given. It just lives in the class (and thus its
instances') namespace.
"""
return some_function_h()
For both instance methods and class methods, not accepting at least one argument is a TypeError, but not understanding the semantics of that argument is a user error.
(Define some_function
's, e.g.:
some_function_h = some_function_g = some_function_f = lambda x=None: x
and this will work.)
A dotted lookup on an instance is performed in this order - we look for:
__dict__
Note, a dotted lookup on an instance is invoked like this:
instance = Example()
instance.regular_instance_method
and methods are callable attributes:
instance.regular_instance_method()
The argument, self
, is implicitly given via the dotted lookup.
You must access instance methods from instances of the class.
>>> instance = Example()
>>> instance.regular_instance_method()
<__main__.Example object at 0x00000000399524E0>
The argument, cls
, is implicitly given via dotted lookup.
You can access this method via an instance or the class (or subclasses).
>>> instance.a_class_method()
<class '__main__.Example'>
>>> Example.a_class_method()
<class '__main__.Example'>
No arguments are implicitly given. This method works like any function defined (for example) on a modules' namespace, except it can be looked up
>>> print(instance.a_static_method())
None
Again, when should I use them, why should I use them?
Each of these are progressively more restrictive in the information they pass the method versus instance methods.
Use them when you don't need the information.
This makes your functions and methods easier to reason about and to unittest.
Which is easier to reason about?
def function(x, y, z): ...
or
def function(y, z): ...
or
def function(z): ...
The functions with fewer arguments are easier to reason about. They are also easier to unittest.
These are akin to instance, class, and static methods. Keeping in mind that when we have an instance, we also have its class, again, ask yourself, which is easier to reason about?:
def an_instance_method(self, arg, kwarg=None):
cls = type(self) # Also has the class of instance!
...
@classmethod
def a_class_method(cls, arg, kwarg=None):
...
@staticmethod
def a_static_method(arg, kwarg=None):
...
Here are a couple of my favorite builtin examples:
The str.maketrans
static method was a function in the string
module, but it is much more convenient for it to be accessible from the str
namespace.
>>> 'abc'.translate(str.maketrans({'a': 'b'}))
'bbc'
The dict.fromkeys
class method returns a new dictionary instantiated from an iterable of keys:
>>> dict.fromkeys('abc')
{'a': None, 'c': None, 'b': None}
When subclassed, we see that it gets the class information as a class method, which is very useful:
>>> class MyDict(dict): pass
>>> type(MyDict.fromkeys('abc'))
<class '__main__.MyDict'>
Use static methods when you don't need the class or instance arguments, but the function is related to the use of the object, and it is convenient for the function to be in the object's namespace.
Use class methods when you don't need instance information, but need the class information perhaps for its other class or static methods, or perhaps itself as a constructor. (You wouldn't hardcode the class so that subclasses could be used here.)
First make sure you have SessionMiddleware
and AuthenticationMiddleware
middlewares added to your MIDDLEWARE_CLASSES
setting.
The current user
is in request
object, you can get it by:
def sample_view(request):
current_user = request.user
print current_user.id
request.user
will give you a User
object representing the currently logged-in user. If a user isn't currently logged in, request.user
will be set to an instance of AnonymousUser
. You can tell them apart with the field is_authenticated
, like so:
if request.user.is_authenticated:
# Do something for authenticated users.
else:
# Do something for anonymous users.
The Sortable JS library is compatible with touch screens and does not require jQuery.
The way it handles touch screens it that you need to touch the screen for about 1 second to start dragging an item.
Also, they present a video test showing that this library is running faster than JQuery UI Sortable.
First things first, the definition of "peak" is vague if without further specifications. For example, for the following series, would you call 5-4-5 one peak or two?
1-2-1-2-1-1-5-4-5-1-1-5-1
In this case, you'll need at least two thresholds: 1) a high threshold only above which can an extreme value register as a peak; and 2) a low threshold so that extreme values separated by small values below it will become two peaks.
Peak detection is a well-studied topic in Extreme Value Theory literature, also known as "declustering of extreme values". Its typical applications include identifying hazard events based on continuous readings of environmental variables e.g. analysing wind speed to detect storm events.
You can get the screenshot of a division and save it easily just using the below snippet. Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.
html2canvas(document.getElementsByClassName("image-div")[0], {
useCORS: true,
}).then(function (canvas) {
var imageURL = canvas.toDataURL("image/png");
let a = document.createElement("a");
a.href = imageURL;
a.download = imageURL;
a.click();
});
You can use the simple not flag to validate that. Example
if !@objectname
This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw
*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass
An ideal nil check would be like:
!@objectname || @objectname.nil? || @objectname.empty?
Swift 4
If you are trying to change your keyboard type when a condition is met, follow this. For example: If we want to change the keyboard type from Default to Number Pad when the count of the textfield is 4 or 5, then do this:
textField.addTarget(self, action: #selector(handleTextChange), for: .editingChanged)
@objc func handleTextChange(_ textChange: UITextField) {
if textField.text?.count == 4 || textField.text?.count == 5 {
textField.keyboardType = .numberPad
textField.reloadInputViews() // need to reload the input view for this to work
} else {
textField.keyboardType = .default
textField.reloadInputViews()
}
Given the context loader.getResourceAsStream("myPackage/myProp.properties")
should be used.
Leading '/'
doesn't work with ClassLoader.getResourceAsStream(String)
method.
Alternatively you could use Class.getResourceAsStream(String)
method, which uses '/'
to determine if the path is absolute or relative to the class location.
Examples:
myClass.class.getResourceAsStream("myProp.properties")
myClass.class.getResourceAsStream("/myPackage/myProp.properties")
I would actually create a template for it and use that template with an EditorFor().
Here is how I did it:
Create My template, which is basically a partial view I created in the EditorTemplates directory, under Shared, under Views name it as (for example): CheckboxTemplate
:
@using System.Globalization
@using System.Web.Mvc.Html
@model bool?
@{
bool? myModel = false;
if (Model.HasValue)
{
myModel = Model.Value;
}
}
<input type="checkbox" checked="@(myModel)" name="@ViewData.TemplateInfo.HtmlFieldPrefix" value="True" style="width:20px;" />
Use it like this (in any view):
@Html.EditorFor(x => x.MyNullableBooleanCheckboxToBe, "CheckboxTemplate")
Thats all.
Templates are so powerful in MVC, use them.. You can create an entire page as a template, which you would use with the @Html.EditorFor()
; provided that you pass its view model in the lambda expression..
In Jackson 2.4, you can convert as follows:
MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);
where jsonObjectMapper
is a Jackson ObjectMapper
.
In older versions of Jackson, it would be
MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);
First make sure that the input element is visible
As stated by Mark Collin in the discussion here:
Don't click on the browse button, it will trigger an OS level dialogue box and effectively stop your test dead.
Instead you can use:
driver.findElement(By.id("myUploadElement")).sendKeys("<absolutePathToMyFile>");
myUploadElement is the id of that element (button in this case) and in sendKeys you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.
Keep in mind that the upload will work only If the element you send a file should be in the form <input type="file">
As I recall, the only portable way to do it, is to cast the result to "unsigned long int" and use %lu
.
printf("sizeof(int) = %lu", (unsigned long) sizeof(int));
Using only nltk tools
from nltk.tokenize import word_tokenize
from nltk.util import ngrams
def get_ngrams(text, n ):
n_grams = ngrams(word_tokenize(text), n)
return [ ' '.join(grams) for grams in n_grams]
Example output
get_ngrams('This is the simplest text i could think of', 3 )
['This is the', 'is the simplest', 'the simplest text', 'simplest text i', 'text i could', 'i could think', 'could think of']
In order to keep the ngrams in array format just remove ' '.join
After upgrading react-native, you may have stale dependencies. The steps below should fix it.
cd ios
pod deintegrate && pod install
react-native run-ios
Hope this helps, I did this after upgrading to react-native 0.61
If you want see your buffer size in terminal, you can take a look at:
/proc/sys/net/ipv4/tcp_rmem
(for read) /proc/sys/net/ipv4/tcp_wmem
(for write)They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.
I liked Mike Lewis' answer but the code did not pass jslint and I could not understand the funky while loop. My use case is to put up a browser not supported message if less than or equal to IE8.
Here is a jslint free version based on Mike Lewis':
/*jslint browser: true */
/*global jQuery */
(function () {
"use strict";
var browserNotSupported = (function () {
var div = document.createElement('DIV');
// http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
div.innerHTML = '<!--[if lte IE 8]><I></I><![endif]-->';
return div.getElementsByTagName('I').length > 0;
}());
if (browserNotSupported) {
jQuery("html").addClass("browserNotSupported").data("browserNotSupported", browserNotSupported);
}
}());
I couldn't copy files using the answers above but I have putty and I found a workaround on Quora.
Note: it copies all the printed characters of that session to the log file, so it will get big eventually. In that case, delete the log file and cat the target file so you get that particular file's content copied on your machine.
You can change axis text and label size with arguments axis.text=
and axis.title=
in function theme()
. If you need, for example, change only x axis title size, then use axis.title.x=
.
g+theme(axis.text=element_text(size=12),
axis.title=element_text(size=14,face="bold"))
There is good examples about setting of different theme()
parameters in ggplot2 page.
Another option is to run ng serve
command with the --port
option e.g
ng serve --port 5050
(i.e for port 5050)
Alternatively, the command: ng serve --port 0
, will auto assign an available port for use.
Moved from the closed topic
del /s d:\test\archive*.txt
This should get you all of your text files
Alternatively,
I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.
Please test this on your system before using it though.
@echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION
REM ---------------------------
REM *** EDIT VARIABLES BELOW ***
REM ---------------------------
set targetFolder=
REM targetFolder is the location you want to delete from
REM ---------------------------
REM *** DO NOT EDIT BELOW ***
REM ---------------------------
IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
set "Subfolders[!Index!]=%%D"
set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!
:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in:
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start
:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end
:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end
:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit
REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)
If you change the
set targetFolder=
to the folder you want you won't get prompted for the folder. *Remember when putting the base path in, the format does not include a '\' on the end. e.g. d:\test c:\temp
Hope this helps
In Laravel 5.4 the following worked for me:
return back()->withErrors(['field_name' => ['Your custom message here.']]);
print "%02d"%a
is the python 2 variant
python 3 uses a somewhat more verbose formatting system:
"{0:0=2d}".format(a)
The relevant doc link for python2 is: http://docs.python.org/2/library/string.html#format-specification-mini-language
For python3, it's http://docs.python.org/3/library/string.html#string-formatting
The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.
Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.
Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.
Enough explanation, the solution (JS, CSS, HTML):
$(window).on("load",function() {_x000D_
$(window).scroll(function() {_x000D_
var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
}_x000D_
});_x000D_
}).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
if ($(this).css("opacity")==0) {...}
. This makes sure the object is only faded in when the opacity
is 0
. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object..animate()
to .fadeTo()
. It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate..position()
to .offset()
. This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.$(window).height()
to $(window).innerHeight()
. The latter is more reliable in my experience.$(window).scroll();
. Now you can give all desired objects on the page the .fade
class, and objects that should be invisible at page-load, will be faded out immediately.#container
from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px
because you used .position()
instead of .offset()
, otherwise I don't know. Feel free of course to leave it in your code.)If you want opacity values other than 0
and 1
, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
var min = 0.3;_x000D_
var max = 0.7;_x000D_
var threshold = 0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
threshold
and for min/max
at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.|| pageLoad
to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad
is a boolean that is send along as an argument when fade()
is invoked.function fade() {...}
, in order to be able to send along the pageLoad
boolean when the scroll-handler is invoked.Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3
, the actual value (in this case) is 0.300000011920929
. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}
.
I added a threshold, to take that difference into account: == 0.3
becomes <= 0.31
.
(I've set the threshold to 0.01
, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)
The operators are now changed from ==
to <=
and >=
.
If you want to fade the elements based on their visible percentage, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
var min=0.3, max=0.7, threshold=0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
_x000D_
/* Fade element in/out based on its visible percentage */_x000D_
if (objectTop < windowTop) {_x000D_
if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if (objectBottom > windowBottom) {_x000D_
if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
One "dimension" of this topic has been left out yet it's very important: there are times when the "best practices" have to come into terms with the plaform we are implementing or augmenting with REST capabilities.
Practical example:
Many web applications nowadays implement the MVC (Model, View, Controller) architecture. They assume a certain standard path is provided, even more so when those web applications come with an "Enable SEO URLs" option.
Just to mention a fairly famous web application: an OpenCart e-commerce shop. When the admin enables the "SEO URLs" it expects said URLs to come in a quite standard MVC format like:
http://www.domain.tld/special-offers/list-all?limit=25
Where
special-offers
is the MVC controller that shall process the URL (showing the special-offers page)
list-all
is the controller's action or function name to call. (*)
limit=25 is an option, stating that 25 items will be shown per page.
(*) list-all
is a fictious function name I used for clarity. In reality, OpenCart and most MVC frameworks have a default, implied (and usually omitted in the URL) index
function that gets called when the user wants a default action to be performed. So the real world URL would be:
http://www.domain.tld/special-offers?limit=25
With a now fairly standard application or frameworkd structure similar to the above, you'll often get a web server that is optimized for it, that rewrites URLs for it (the true "non SEOed URL" would be: http://www.domain.tld/index.php?route=special-offers/list-all&limit=25
).
Therefore you, as developer, are faced into dealing with the existing infrastructure and adapt your "best practices", unless you are the system admin, know exactly how to tweak an Apache / NGinx rewrite configuration (the latter can be nasty!) and so on.
So, your REST API would often be much better following the referring web application's standards, both for consistency with it and ease / speed (and thus budget saving).
To get back to the practical example above, a consistent REST API would be something with URLs like:
http://www.domain.tld/api/special-offers-list?from=15&limit=25
or (non SEO URLs)
http://www.domain.tld/index.php?route=api/special-offers-list?from=15&limit=25
with a mix of "paths formed" arguments and "query formed" arguments.
I had the same issue but finally it worked after storage clean on my mobile. May be happen because of insufficient storage
Inside a GitLab CI pipeline the CI_JOB_TOKEN
environment variable works for me:
git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/...
Source: Gitlab Docs
BTW, setting this variable in .gitlab-ci.yml
helps to debug errors.
variables:
CI_DEBUG_TRACE: "true"
This is a shortcut for $(document).ready()
, which is executed when the browser has finished loading the page (meaning here, "when the DOM is available"). See http://www.learningjquery.com/2006/09/introducing-document-ready. If you are trying to call example()
before the browser has finished loading the page, it may not work.
Thanks, Max S. conda-forge worked for me as well.
Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:
First, check available the packages with versions
conda list
It will show packages and their installed versions in the output:
scikit-learn 0.19.1 py36hedc7406_0
Upgrade to 0.19.2 July 2018 release.
conda config --append channels conda-forge
conda install scikit-learn=0.19.2
Now check the version installed correctly or not?
conda list
Output is:
scikit-learn 0.19.2 py36_blas_openblasha84fab4_201 [blas_openblas] conda-forge
I tried following commands:
!conda update conda
!pip install -U scikit-learn
It will install the required packages also will show in the conda list
but when try to import that package it will not work.
On the website http://scikit-learn.org/stable/install.html it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.
I haven't really found a good way to do that natively, so I just use a utility called hstart which does it for me. If there's a neater way to do it, that would be nice.
On Windows Platform the simplest way is to use the terminal.
Please Run the command RMDIR /Q/S foldername to delete the folder and all of its subfolders.
Example: RMDIR /Q/S node_modules
The Above Command deletes node_modules folder and its subfolders.
For information please visit this https://www.ghacks.net/2017/07/18/how-to-delete-large-folders-in-windows-super-fast/
Simplest solution: Use Unicode Characters
No expression
or other packages needed.
Not sure if this is a newer feature for ggplot, but it works.
It also makes it easy to mix Greek and regular text (like adding '*' to the ticks)
Just use unicode characters within the text string. seems to work well for all options I can think of. Edit: previously it did not work in facet labels. This has apparently been fixed at some point.
library(ggplot2)
ggplot(mtcars,
aes(mpg, disp, color=factor(gear))) +
geom_point() +
labs(title="Title (\u03b1 \u03a9)", # works fine
x= "\u03b1 \u03a9 x-axis title", # works fine
y= "\u03b1 \u03a9 y-axis title", # works fine
color="\u03b1 \u03a9 Groups:") + # works fine
scale_x_continuous(breaks = seq(10, 35, 5),
labels = paste0(seq(10, 35, 5), "\u03a9*")) + # works fine; to label the ticks
ggrepel::geom_text_repel(aes(label = paste(rownames(mtcars), "\u03a9*")), size =3) + # works fine
facet_grid(~paste0(gear, " Gears \u03a9"))
Created on 2019-08-28 by the reprex package (v0.3.0)
Try docker cp
.
Usage:
docker cp CONTAINER:PATH HOSTPATH
It copies files/folders from PATH
to the HOSTPATH
.
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.
simplified generic form,
int div_up(int n, int d) {
return n / d + (((n < 0) ^ (d > 0)) && (n % d));
} //i.e. +1 iff (not exact int && positive result)
For a more generic answer, C++ functions for integer division with well defined rounding strategy
One of most upleasing functional forEach
's limitations is lack of checked exceptions support.
One possible workaround is to replace terminal forEach
with plain old foreach loop:
Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
Iterable<String> iterable = stream::iterator;
for (String s : iterable) {
fileWriter.append(s);
}
Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:
Java 8 Lambda function that throws exception?
Java 8: Lambda-Streams, Filter by Method with Exception
How can I throw CHECKED exceptions from inside Java 8 streams?
Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?
Had a similar issue, it turned out the listening port printed was different from what it actually was. Typos in the request string or listening function might make the target server appear to not exist.
One bizarre thing is that in Chrome + Firefox, the MOUSE_LEAVE event isn't dispatched for OPAQUE
and TRANSPARENT
.
With WINDOW
it works fine. That one took some time to find out! grr...
(note: jediericb mentioned this bug - which is similar but doesn't mention MOUSE_LEAVE
)
The Statement
gives you the following option:
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')");
stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
stmt.addBatch("INSERT INTO emp_dept VALUES (1000, 260)");
// submit a batch of update commands for execution
int[] updateCounts = stmt.executeBatch();
Today this also happened to me. The function name maybe conflicts with keywords. My case is scrape()
. I change the function name, everything works fine.
if you add the rule to the print.css file you don't have to use @media.
I uncluded it in the smarty foreach i use to give some elements a background color.
<script type='text/javascript'>_x000D_
document.styleSheets[3].insertRule(" #caldiv_<?smarty $item.calendar_id ?> { border-color:<?smarty $item.color ?> }", 1);_x000D_
</script>
_x000D_
I get a similar error in iOS9 (working with Xcode 7 and Swift 2): Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first. I was following a tutorial but the tutor was using iOS8 and Swift 1.2. There are some changes in Xcode 7 and Swift 2, I found this code and it works fine for me (if somebody needs help):
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
// MARK: Properties
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
// MARK: - Location Delegate Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Errors: " + error.localizedDescription)
}
}
Finally, I put that in info.plist: Information Property List: NSLocationWhenInUseUsageDescription Value: App needs location servers for staff
There was an answer here: Secure distribution of NodeJS applications. Raynos said: V8 allows you to pre-compile JavaScript.
The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:
#!/usr/bin/python
import lxml.etree
import lxml.builder
E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2
the_doc = ROOT(
DOC(
FIELD1('some value1', name='blah'),
FIELD2('some value2', name='asdfasd'),
)
)
print lxml.etree.tostring(the_doc, pretty_print=True)
Output:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
It also supports adding to an already-made node, e.g. after the above you could say
the_doc.append(FIELD2('another value again', name='hithere'))
Quick and easy with no external tools, works well as long as the two sheets you are comparing are similar:
=if(Sheet1!A1 <> Sheet2!A1, "X", "")
in the top left cell (or equivalent: click on the actual cells to automatically have the references inserted into the formula)If the sheets are similar, this spreadsheet will be empty except for a few cells with X in them, highlighting the differences. Unzoom to 40% to quickly see what is different.
Bootstrap 5 has changed the ml,mr,pl,pr
classes, which no longer work if you're upgrading from a lower version.
The l
and r
have now been replaced with s
(...which is confusing) and e
(east?) respectively.
From bootstrap website:
Where property is one of:
Where sides is one of:
0 - for classes that eliminate the margin or padding by setting it to 0 1 - (by default) for classes that set the margin or padding to $spacer * .25 2 - (by default) for classes that set the margin or padding to $spacer * .5 3 - (by default) for classes that set the margin or padding to $spacer 4 - (by default) for classes that set the margin or padding to $spacer * 1.5 5 - (by default) for classes that set the margin or padding to $spacer * 3 auto - for classes that set the margin to auto (You can add more sizes by adding entries to the $spacers Sass map variable.)
In my case I forgot to enable
app.use(express.json());
in my NodeJs server.
Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu
Bootstrap 3
I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/
The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..
http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook
Using inputStream.available()
It is always acceptable for System.in.available() to return 0.
I've found the opposite - it always returns the best value for the number of bytes available. Javadoc for InputStream.available()
:
Returns an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next invocation of a method for
this input stream.
An estimate is unavoidable due to timing/staleness. The figure can be a one-off underestimate because new data are constantly arriving. However it always "catches up" on the next call - it should account for all arrived data, bar that arriving just at the moment of the new call. Permanently returning 0 when there are data fails the condition above.
First Caveat: Concrete subclasses of InputStream are responsible for available()
InputStream
is an abstract class. It has no data source. It's meaningless for it to have available data. Hence, javadoc for available()
also states:
The available method for class InputStream always returns 0.
This method should be overridden by subclasses.
And indeed, the concrete input stream classes do override available(), providing meaningful values, not constant 0s.
Second Caveat: Ensure you use carriage-return when typing input in Windows.
If using System.in
, your program only receives input when your command shell hands it over. If you're using file redirection/pipes (e.g. somefile > java myJavaApp or somecommand | java myJavaApp ), then input data are usually handed over immediately. However, if you manually type input, then data handover can be delayed. E.g. With windows cmd.exe shell, the data are buffered within cmd.exe shell. Data are only passed to the executing java program following carriage-return (control-m or <enter>
). That's a limitation of the execution environment. Of course, InputStream.available() will return 0 for as long as the shell buffers the data - that's correct behaviour; there are no available data at that point. As soon as the data are available from the shell, the method returns a value > 0. NB: Cygwin uses cmd.exe too.
Just use this:
byte[] inputData = new byte[1024];
int result = is.read(inputData, 0, is.available());
// result will indicate number of bytes read; -1 for EOF with no data read.
OR equivalently,
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")),1024);
// ...
// inside some iteration / processing logic:
if (br.ready()) {
int readCount = br.read(inputData, bufferOffset, inputData.length-bufferOffset);
}
Declare this:
public static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis)
throws IOException {
int bufferOffset = 0;
long maxTimeMillis = System.currentTimeMillis() + timeoutMillis;
while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) {
int readLength = java.lang.Math.min(is.available(),b.length-bufferOffset);
// can alternatively use bufferedReader, guarded by isReady():
int readResult = is.read(b, bufferOffset, readLength);
if (readResult == -1) break;
bufferOffset += readResult;
}
return bufferOffset;
}
Then use this:
byte[] inputData = new byte[1024];
int readCount = readInputStreamWithTimeout(System.in, inputData, 6000); // 6 second timeout
// readCount will indicate number of bytes read; -1 for EOF with no data read.
You must use CSS. Can't be done with PHP.
Requirement ::
- To wait execution of next thread until previous finished.
- Next thread must not start until previous thread stops, irrespective of time consumption.
- It must be simple and easy to use.
Answer ::
@See java.util.concurrent.Future.get() doc.
future.get() Waits if necessary for the computation to complete, and then retrieves its result.
Job Done!! See example below
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
public class ThreadTest {
public void print(String m) {
System.out.println(m);
}
public class One implements Callable<Integer> {
public Integer call() throws Exception {
print("One...");
Thread.sleep(6000);
print("One!!");
return 100;
}
}
public class Two implements Callable<String> {
public String call() throws Exception {
print("Two...");
Thread.sleep(1000);
print("Two!!");
return "Done";
}
}
public class Three implements Callable<Boolean> {
public Boolean call() throws Exception {
print("Three...");
Thread.sleep(2000);
print("Three!!");
return true;
}
}
/**
* @See java.util.concurrent.Future.get() doc
* <p>
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*/
@Test
public void poolRun() throws InterruptedException, ExecutionException {
int n = 3;
// Build a fixed number of thread pool
ExecutorService pool = Executors.newFixedThreadPool(n);
// Wait until One finishes it's task.
pool.submit(new One()).get();
// Wait until Two finishes it's task.
pool.submit(new Two()).get();
// Wait until Three finishes it's task.
pool.submit(new Three()).get();
pool.shutdown();
}
}
Output of this program ::
One...
One!!
Two...
Two!!
Three...
Three!!
You can see that takes 6sec before finishing its task which is greater than other thread. So Future.get() waits until the task is done.
If you don't use future.get() it doesn't wait to finish and executes based time consumption.
Good Luck with Java concurrency.
best solution:
echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
No need to include your http://domain.com in your if you're submitting a form to the same domain.
Give them a trivial pom with these jars listed as dependencies and instructions to run:
mvn dependency:go-offline
This will pull the dependencies to the local repo.
A more direct solution is dependency:get, but it's a lot of arguments to type:
mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version
If you are planning to use JdbcTemplate in multiple locations, it would be a good idea to create a Spring Bean for it.
Using Java Config it would be:
@Configuration
public class DBConfig {
@Bean
public DataSource dataSource() {
//create a data source
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
@Bean
public TransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
Then a repository that uses that JdbcTemplate could be:
@Repository
public class JdbcSomeRepository implements SomeRepository {
private final JdbcTemplate jdbcTemplate ;
@Autowired
public JdbcSomeRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
@Transactional
public int someUpdate(SomeType someValue, SomeOtherType someOtherValue) {
return jdbcTemplate.update("INSERT INTO SomeTable(column1, column2) VALUES(?,?)", someValue, someOtherValue)
}
}
The update method from JdbcTemplate that I have used can be found here.
code:
function insertValueAtPosition($arr, $insertedArray, $position) {
$i = 0;
$new_array=[];
foreach ($arr as $key => $value) {
if ($i == $position) {
foreach ($insertedArray as $ikey => $ivalue) {
$new_array[$ikey] = $ivalue;
}
}
$new_array[$key] = $value;
$i++;
}
return $new_array;
}
example:
$array = ["A"=8, "K"=>3];
$insert_array = ["D"= 9];
insertValueAtPosition($array, $insert_array, $position=2);
// result ====> ["A"=>8, "D"=>9, "K"=>3];
May not really look perfect, but it works.
For Back Button in jquery // http://code.jquery.com/jquery-latest.js
jQuery(window).bind("unload", function() { //
and in html5 there is an event The event is called 'popstate'
window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
and for refresh please check Check if page gets reloaded or refreshed in Javascript
In Mozilla Client-x and client-y is inside document area https://developer.mozilla.org/en-US/docs/Web/API/event.clientX
Check if scp
is installed or not on from where you want want to copy
check using which scp
If it's already installed, it will print you a path like /usr/bin/scp
Else, install scp using:
yum -y install openssh-clients
Then copy command
scp -r [email protected]:/var/www/html/database_backup/restore_fullbackup/backup_20140308-023002.sql /var/www/html/db_bkp/
Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize
and add following two methods:
public class SerilizeDeserialize
{
// Serialize collection of any type to a byte stream
public static byte[] Serialize<T>(T obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binSerializer = new BinaryFormatter();
binSerializer.Serialize(memStream, obj);
return memStream.ToArray();
}
}
// DSerialize collection of any type to a byte stream
public static T Deserialize<T>(byte[] serializedObj)
{
T obj = default(T);
using (MemoryStream memStream = new MemoryStream(serializedObj))
{
BinaryFormatter binSerializer = new BinaryFormatter();
obj = (T)binSerializer.Deserialize(memStream);
}
return obj;
}
}
How To use these method in your Class:
ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);
ArrayList arrayListMemDes = new ArrayList();
arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);
Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
Console.WriteLine(item);
}
You can try with
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
you can use css to set the body tag to these settings:
body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}
alter table company drop constraint Company_CountryID_FK
How about htis:
Private Sub ArrangeWindows(Order As Window())
For I As Integer = 1 To Order.Length -1
Order(I).Owner = Order(I - 1)
Next
End Sub
Try using Delete method:
DataRow[] drr = dt.Select("Student=' " + id + " ' ");
for (int i = 0; i < drr.Length; i++)
drr[i].Delete();
dt.AcceptChanges();
You can create a putty session, and auto load the script on the server, when starting the session:
putty -load "sessionName"
At remote command, point to the remote script.
I'd like to add this is a solution to search multiple attributes of an ActiveRecord. Since
.where(A: param[:A], B: param[:B])
will search for A and B.
Short and simple answer would be,
Constructor
: constructor
is a default method
runs (by default) when component is being constructed. When you create an instance
of a class that time also constructor(default method)
would be called. So in other words, when the component is being constructed or/and an instance is created constructor(default method)
is called and relevant code is written within is called. Basically and generally in Angular2
, it used to inject things like services
when the component is being constructed for further use.
OnInit
: ngOnInit is component's life cycle hook which runs first after constructor(default method)
when the component is being initialized.
So, Your constructor will be called first and Oninit will be called later after constructor method.
boot.ts
import {Cmomponent, OnInit} from 'angular2/core';
import {ExternalService} from '../externalService';
export class app implements OnInit{
constructor(myService:ExternalService)
{
this.myService=myService;
}
ngOnInit(){
// this.myService.someMethod()
}
}
Resources: LifeCycle hook
You can check this small demo which shows an implementation of both things.
Another related tip is to use "%~1" instead of "%1". Type "CALL /?" at the command line in Windows to get more details.
This was sort of tricky for me too, I did the following which worked pretty well.
chmod
the egg to be executable: chmod a+x [egg]
(ie, for Python 2.6, chmod a+x setuptools-0.6c9-py2.6.egg
)./[egg]
(ie, for Python 2.6, ./setuptools-0.6c9-py2.6.egg
)Not sure if you'll need to use sudo if you're just installing it for you current user. You'd definitely need it to install it for all users.
this works only if WebResponse is a HttpWebResponse.
try
{
...
}
catch (System.Net.WebException exc)
{
var webResponse = exc.Response as System.Net.HttpWebResponse;
if (webResponse != null &&
webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
MessageBox.Show("401");
}
else
throw;
}
If @Cybernate's solution doesn't work, try breaking the trigger off in to it's own function so you can reference it.
clickHandler = function(event){
if (click++ == 49)
canvas.removeEventListener('click',clickHandler);
}
canvas.addEventListener('click',clickHandler);
The simple solution is to install Python 3. I think why you have this problem is because you are using Python 2. I did this and it worked.
When installing Python 3, make sure to select PIP. It installs it with Python.
You have to user ../../projectName/Filename.jsp in your action attr. or href
../ = contains current folder simple(demo.project.filename.jsp)
Servlet can only be called with 1 slash forward to your project name..
You have a couple of basic misconceptions about Java:
I want it to return the array without having to explicitly tell the console to print.
1) Java does not work that way. Nothing ever gets printed implicitly. (Java does not support an interactive interpreter with a "repl" loop ... like Python, Ruby, etc.)
2) The "main" doesn't "return" anything. The method signature is:
public static void main(String[] args)
and the void
means "no value is returned". (And, sorry, no you can't replace the void
with something else. If you do then the java
command won't recognize the "main" method.)
3) If (hypothetically) you did want your "main" method to return something, and you altered the declaration to allow that, then you still would need to use a return
statement to tell it what value to return. Unlike some language, Java does not treat the value of the last statement of a method as the return value for the method. You have to use a return
statement ...