You can use the Calendar
class to convert Date
public long getDifference()
{
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");
Calendar c = Calendar.getInstance();
c.setTime(d);
long time = c.getTimeInMillis();
long curr = System.currentTimeMillis();
long diff = curr - time; //Time difference in milliseconds
return diff/1000;
}
The issue for you is that you are using mm
. You should use MM
. MM
is for month and mm
is for minutes. Try with yyyy-MM-dd HH:mm
Other approach:
It can be as simple as this (other option is to use joda-time)
static final long ONE_MINUTE_IN_MILLIS=60000;//millisecs
Calendar date = Calendar.getInstance();
long t= date.getTimeInMillis();
Date afterAddingTenMins=new Date(t + (10 * ONE_MINUTE_IN_MILLIS));
You could also set the timezone at the JVM level
Date date1 = new Date();
System.out.println(date1);
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// or pass in a command line arg: -Duser.timezone="UTC"
Date date2 = new Date();
System.out.println(date2);
output:
Thu Sep 05 10:11:12 EDT 2013
Thu Sep 05 14:11:12 UTC 2013
myPreparedStatement.setObject( // Directly exchange java.time objects with database without the troublesome old java.sql.* classes.
… ,
LocalDate.parse( // Parse string as a `LocalDate` date-only value.
"2018-01-23" // Input string that complies with standard ISO 8601 formatting.
)
)
The modern approach uses the java.time classes that supplant the troublesome old legacy classes such as java.util.Date
and java.sql.Date
.
For a date-only value, use LocalDate
. The LocalDate
class represents a date-only value without time-of-day and without time zone.
The java.time classes use standard formats when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( input ) ;
You can directly exchange java.time objects with your database using a JDBC driver compliant with JDBC 4.2 or later. You can forget about transforming in and out of java.sql.* classes.
myPreparedStatement.setObject( … , ld ) ;
Retrieval:
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
For a docker application like beehuang commented you should set your timezone.
Alternatively you can use withZoneSameLocal. For example:
2014-07-01T00:00+02:00[GMT+02:00] is converted by
Date.from(zonedDateTime.withZoneSameLocal(ZoneId.systemDefault()).toInstant())
to Tue Jul 01 00:00:00 CEST 2014 and by
Date.from(zonedDateTime.toInstant())
to Mon Jun 30 22:00:00 UTC 2014
If you have d1 and d2 as your dates, the best solution is probably the following:
int days1 = d1.getTime()/(60*60*24*1000);//find the number of days since the epoch.
int days2 = d2.getTime()/(60*60*24*1000);
then just say
days2-days1
or whatever
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
Let's try this
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
Date today = cal.getTime();
DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String str7 = df7.format(today);
System.out.println("String in yyyy-MM-dd format is: " + str7);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Or a utility function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return dateStr;
}
There's the shade maven plugin. It can be used to package and rename dependencies (to omit dependency problems on the classpath).
Simply, row_num = df.shape[0] # gives number of rows, here's the example:
import pandas as pd
import numpy as np
In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])
In [323]: df
Out[323]:
col_1 col_2
0 -0.894268 1.309041
1 -0.120667 -0.241292
2 0.076168 -1.071099
3 1.387217 0.622877
4 -0.488452 0.317882
In [324]: df.shape
Out[324]: (5, 2)
In [325]: df.shape[0] ## Gives no. of rows/records
Out[325]: 5
In [326]: df.shape[1] ## Gives no. of columns
Out[326]: 2
A combination of two answers, with a twist. The code will be detected as changed, when the file is created or the permission updated.
- name: Touch again the same file, but dont change times this makes the task idempotent
file:
path: /etc/foo.conf
state: touch
mode: 0644
modification_time: preserve
access_time: preserve
changed_when: >
p.diff.before.state == "absent" or
p.diff.before.mode|default("0644") != "0644"
and a version that also corrects the owner and group and detects it as changed when it does correct these:
- name: Touch again the same file, but dont change times this makes the task idempotent
file:
path: /etc/foo.conf
state: touch
state: touch
mode: 0644
owner: root
group: root
modification_time: preserve
access_time: preserve
register: p
changed_when: >
p.diff.before.state == "absent" or
p.diff.before.mode|default("0644") != "0644" or
p.diff.before.owner|default(0) != 0 or
p.diff.before.group|default(0) != 0
This solution works fine for all major browsers, except IE. So keep that in mind.
In this example, basicaly I use positioning, horizontal and vertical transform for the UI element to center it.
.container {_x000D_
/* set the the position to relative */_x000D_
position: relative;_x000D_
width: 30rem;_x000D_
height: 20rem;_x000D_
background-color: #2196F3;_x000D_
}_x000D_
_x000D_
_x000D_
.paragh {_x000D_
/* set the the position to absolute */_x000D_
position: absolute;_x000D_
/* set the the position of the helper container into the middle of its space */_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
font-size: 30px;_x000D_
/* make sure padding and margin do not disturb the calculation of the center point */_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
/* using centers for the transform */_x000D_
transform-origin: center center;_x000D_
/* calling calc() function for the calculation to move left and up the element from the center point */_x000D_
transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));_x000D_
}
_x000D_
<div class="container">_x000D_
<p class="paragh">Text</p>_x000D_
</div>
_x000D_
I hope this help.
First things first, you have to install Maven on your workstation. You need also to install M2E, what you obviously did. Not all distributions of Juno have it pre-installed.
Then configure your Eclipse so it can find your Maven install. In the menu Window -> Preferences, then open the Maven section. In your right panel, you have a list of the Maven installations Eclipse knows. Add your installation and select it instead of the embedded Maven provided with M2E. Don't forget to set the "Global settings from installation directory" field with the path to the settings.xml of your Maven installation.
Which leads us to the settings.xml. If the above doesn't solve your problem, you will have to configure your Maven. More infos here.
Another way to avoid using the print statement:
$ awk '{$1=$2=$3=""}sub("^"FS"*","")' file
In awk when a condition is true print is the default action.
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
About efficiency and concernig time spent on allocation, I made this simple test below, I created many instances through these two ways (one at a time):
for (int k = 0 ; k < 30000000; ++k)
{
// took more time than using new
std::shared_ptr<int> foo = std::make_shared<int> (10);
// was faster than using make_shared
std::shared_ptr<int> foo2 = std::shared_ptr<int>(new int(10));
}
The thing is, using make_shared took the double time compared with using new. So, using new there are two heap allocations instead of one using make_shared. Maybe this is a stupid test but doesn't it show that using make_shared takes more time than using new? Of course, I'm talking about time used only.
To extrapolate on Felix Kling's comment, you can use .filter()
like this:
var sources = images.map(function (img) {
if(img.src.split('.').pop() === "json") { // if extension is .json
return null; // skip
} else {
return img.src;
}
}).filter(Boolean);
That will remove falsey values from the array that is returned by .map()
You could simplify it further like this:
var sources = images.map(function (img) {
if(img.src.split('.').pop() !== "json") { // if extension is .json
return img.src;
}
}).filter(Boolean);
Or even as a one-liner using an arrow function, object destructuring and the &&
operator:
var sources = images.map(({ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);
I figured this wouldn't be UTF, but I just found a pretty simple solution that seems to work...
Get-Content path/to/file.ext | out-file -encoding ASCII targetFile.ext
For me this results in a utf-8 without bom file regardless of the source format.
Try to surround strings
(hoot
, story
, article
) with quotes '
:
<div ng-repeat = "data in comments">
<div ng-if="data.type == 'hoot' ">
//different template with hoot data
</div>
<div ng-if="data.type == 'story' ">
//different template with story data
</div>
<div ng-if="data.type == 'article' ">
//different template with article data
</div>
</div>
If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.
You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?
I'm quoting the steps here:
Step 1: Setup a new External Configuration Tool
In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.
Step 2: Click New Launch Configuration option in Create, manage and run configuration screen
Step 3: New Configuration screen for configuring the command prompt
Step 4: Provide configuration details of the Command Prompt in the Main tab
Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt
Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.
Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory
It's as simple as that:
function isMacintosh() {
return navigator.platform.indexOf('Mac') > -1
}
function isWindows() {
return navigator.platform.indexOf('Win') > -1
}
You can do funny things then like:
var isMac = isMacintosh();
var isPC = !isMacintosh();
Python
element.get_attribute("attribute name")
Java
element.getAttribute("attribute name")
Ruby
element.attribute("attribute name")
C#
element.GetAttribute("attribute name");
conda create -n py37 -c anaconda anaconda=5.3
seems to be working.
Here is a query, you can run it in SQL Developer (or SQL*Plus):
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
GROUP BY DS.TABLESPACE_NAME,
SEGMENT_NAME;
This is for Nikola.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
break;
}
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
}
If it's help bro,Do not forget to up for my reputation)))
In my opinion that is easiest and fastest way:
$ npm -v
4.2.0
$ npm install -g npm@latest-3
...
$ npm -v
3.10.10
You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.
There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use
&
infoo(&$a);
.
For example, instead of using:
// Wrong way!
myFunc(&$arg); # Deprecated pass-by-reference argument
function myFunc($arg) { }
Use:
// Right way!
myFunc($var); # pass-by-value argument
function myFunc(&$arg) { }
If its just about detecting whether or not you're dealing with an Object
, I could think of
Object.getPrototypeOf( obj ) === Object.prototype
However, this would probably fail for non-object primitive values. Actually there is nothing wrong with invoking .toString()
to retreive the [[cclass]] property. You can even create a nice syntax like
var type = Function.prototype.call.bind( Object.prototype.toString );
and then use it like
if( type( obj ) === '[object Object]' ) { }
It might not be the fastest operation but I don't think the performance leak there is too big.
While cloning you might be using SSH in the dropdown list. Change it to Https and then clone.
if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.
A simple DELETE
before the INSERT
would suffice:
DELETE FROM Table2 WHERE Id = (SELECT Id FROM Table1)
INSERT INTO Table2 (Id, name) SELECT Id, name FROM Table1
Switching Table1
for Table2
depending on which table's Id
and name
pairing you want to preserve.
You can use $locationChangeStart
event to store the previous value in $rootScope
or in a service. When you come back, just initialize all previously stored values. Here is a quick demo using $rootScope
.
var app = angular.module("myApp", ["ngRoute"]);_x000D_
app.controller("tab1Ctrl", function($scope, $rootScope) {_x000D_
if ($rootScope.savedScopes) {_x000D_
for (key in $rootScope.savedScopes) {_x000D_
$scope[key] = $rootScope.savedScopes[key];_x000D_
}_x000D_
}_x000D_
$scope.$on('$locationChangeStart', function(event, next, current) {_x000D_
$rootScope.savedScopes = {_x000D_
name: $scope.name,_x000D_
age: $scope.age_x000D_
};_x000D_
});_x000D_
});_x000D_
app.controller("tab2Ctrl", function($scope) {_x000D_
$scope.language = "English";_x000D_
});_x000D_
app.config(function($routeProvider) {_x000D_
$routeProvider_x000D_
.when("/", {_x000D_
template: "<h2>Tab1 content</h2>Name: <input ng-model='name'/><br/><br/>Age: <input type='number' ng-model='age' /><h4 style='color: red'>Fill the details and click on Tab2</h4>",_x000D_
controller: "tab1Ctrl"_x000D_
})_x000D_
.when("/tab2", {_x000D_
template: "<h2>Tab2 content</h2> My language: {{language}}<h4 style='color: red'>Now go back to Tab1</h4>",_x000D_
controller: "tab2Ctrl"_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>_x000D_
<body ng-app="myApp">_x000D_
<a href="#/!">Tab1</a>_x000D_
<a href="#!tab2">Tab2</a>_x000D_
<div ng-view></div>_x000D_
</body>_x000D_
</html>
_x000D_
var abox = document.getElementsByClassName("box")[0];_x000D_
function allmove(){_x000D_
abox.classList.remove("move-ltr");_x000D_
abox.classList.remove("move-ttb");_x000D_
abox.classList.toggle("move");_x000D_
}_x000D_
function ltr(){_x000D_
abox.classList.remove("move");_x000D_
abox.classList.remove("move-ttb");_x000D_
abox.classList.toggle("move-ltr");_x000D_
}_x000D_
function ttb(){_x000D_
abox.classList.remove("move-ltr");_x000D_
abox.classList.remove("move");_x000D_
abox.classList.toggle("move-ttb");_x000D_
}
_x000D_
.box {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: red;_x000D_
position: relative;_x000D_
}_x000D_
.move{_x000D_
-webkit-animation: moveall 5s;_x000D_
animation: moveall 5s;_x000D_
}_x000D_
.move-ltr{_x000D_
-webkit-animation: moveltr 5s;_x000D_
animation: moveltr 5s;_x000D_
}_x000D_
.move-ttb{_x000D_
-webkit-animation: movettb 5s;_x000D_
animation: movettb 5s;_x000D_
}_x000D_
@keyframes moveall {_x000D_
0% {left: 0px; top: 0px;}_x000D_
25% {left: 200px; top: 0px;}_x000D_
50% {left: 200px; top: 200px;}_x000D_
75% {left: 0px; top: 200px;}_x000D_
100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes moveltr {_x000D_
0% { left: 0px; top: 0px;}_x000D_
50% {left: 200px; top: 0px;}_x000D_
100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes movettb {_x000D_
0% {left: 0px; top: 0px;}_x000D_
50% {top: 200px;left: 0px;}_x000D_
100% {left: 0px; top: 0px;}_x000D_
}
_x000D_
<div class="box"></div>_x000D_
<button onclick="allmove()">click</button>_x000D_
<button onclick="ltr()">click</button>_x000D_
<button onclick="ttb()">click</button>
_x000D_
The answer to use the 'traditional' option is correct. I'm just providing some more background info for this who wish to learn more.
From the jQuery documentation:
As of jQuery 1.8, the $.param() method no longer uses jQuery.ajaxSettings.traditional as its default setting and will default to false.
You can also read more here: http://michaelsync.net/2012/04/05/tips-asp-net-mvc-javascriptserializer-3-questions-and-3-answers and http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
HTH
It will already work, as David pointed out!
>>> def machineEpsilon(func=float):
... machine_epsilon = func(1)
... while func(1)+func(machine_epsilon) != func(1):
... machine_epsilon_last = machine_epsilon
... machine_epsilon = func(machine_epsilon) / func(2)
... return machine_epsilon_last
...
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07
The +
operation adds the array elements to the original array. The array.append
operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion).
The difference here is that the + operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element. The append-method however does literally what you ask: append the object on the right-hand side that you give it (the array or any other object), instead of taking its elements.
Use extend()
if you want to use a function that acts similar to the + operator (as others have shown here as well). It's not wise to do the opposite: to try to mimic append with the + operator for lists (see my earlier link on why).
For fun, a little history: the birth of the array module in Python in February 1993. it might surprise you, but arrays were added way after sequences and lists came into existence.
With TortoiseSVN I just move the file on disk.
When I come to commit my changes I select the missing file and the new one and select "Repair move" from the right click menu:
This means I can let my IDE move round files and use it refactoring tools without losing history.
All you need to do is run
pip install /opt/mypackage
and pip will search /opt/mypackage
for a setup.py
, build a wheel, then install it.
The problem with using the -e
flag for pip install
as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.
Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.
Please try the following code below:
//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.
using (reader = cmd.ExecuteReader())
{
// Load the Data table object
dataTable.Load(reader);
if (dataTable.Rows.Count > 0)
{
DataColumn col = dataTable.Columns["YourColumnName"];
foreach (DataRow row in dataTable.Rows)
{
strJsonData = row[col].ToString();
}
}
}
Clearly:
Server side generating a token example
private string GenerateToken(string userName)
{
var someClaims = new Claim[]{
new Claim(JwtRegisteredClaimNames.UniqueName, userName),
new Claim(JwtRegisteredClaimNames.Email, GetEmail(userName)),
new Claim(JwtRegisteredClaimNames.NameId,Guid.NewGuid().ToString())
};
SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Tokenizer.Key));
var token = new JwtSecurityToken(
issuer: _settings.Tokenizer.Issuer,
audience: _settings.Tokenizer.Audience,
claims: someClaims,
expires: DateTime.Now.AddHours(_settings.Tokenizer.ExpiryHours),
signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
(note: Tokenizer is my helper class that contains Issuer Audience etc..)
Definitely:
Client side getting a token for authentication
public async Task<string> GetToken()
{
string token = "";
var siteSettings = DependencyResolver.Current.GetService<SiteSettings>();
var client = new HttpClient();
client.BaseAddress = new Uri(siteSettings.PopularSearchRequest.StaticApiUrl);
client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StatisticUserModel user = new StatisticUserModel()
{
Password = siteSettings.PopularSearchRequest.Password,
Username = siteSettings.PopularSearchRequest.Username
};
string jsonUser = JsonConvert.SerializeObject(user, Formatting.Indented);
var stringContent = new StringContent(jsonUser, Encoding.UTF8, "application/json");
var response = await client.PostAsync(siteSettings.PopularSearchRequest.StaticApiUrl + "/api/token/new", stringContent);
token = await response.Content.ReadAsStringAsync();
return token;
}
You can use this token for the authorization (that is in the subsequent requests)
To help other bug-hunters. I had this error because the function didn't exist.
I had a spelling error.
Simple solution for the LEFT OUTER JOIN:
var setA = context.SetA;
var setB = context.SetB.Select(st=>st.Id).Distinct().ToList();
var leftOuter = setA.Where(stA=> !setB.Contains(stA.Id));
notes:
You need to set a border-right
on the td's then target the last tds in a row to set the border to none
. Ways to target:
td
of each row and use thattd + td + td
td:last-child
Straight out of the documentation for collections.OrderedDict
:
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
Adapted to the example in the original post:
>>> l=[2,3,1,4,5]
>>> OrderedDict(sorted(enumerate(l), key=lambda x: x[1])).keys()
[2, 0, 1, 3, 4]
See http://docs.python.org/library/collections.html#collections.OrderedDict for details.
BufferedReader#read
reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.
String s= inp.readLine();
int[] m= new int[2];
String[] s1 = inp.readLine().split(" ");
m[0]=Integer.parseInt(s1[0]);
m[1]=Integer.parseInt(s1[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
You can check also Scanner vs. BufferedReader.
$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=".$new." ".implode(" ", $files);
shell_exec($cmd);
A simplified version of Chauhan's answer
take a look at Trim()
which returns a new string with whitespace removed from the beginning and end of the string it is called on.
Like this?
In LINQ:
var sortedList = originalList.OrderBy(foo => !foo.AVC)
.ToList();
Or in-place:
originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));
As Jon Skeet says, the trick here is knowing that false
is considered to be 'smaller' than true.
If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo
to implement the IComparable<Foo>
and IComparable
interfaces.
The syntax for index hints is documented here:
http://dev.mysql.com/doc/refman/5.6/en/index-hints.html
FORCE INDEX
goes right after the table reference:
SELECT * FROM (
SELECT owner_id,
product_id,
start_time,
price,
currency,
name,
closed,
active,
approved,
deleted,
creation_in_progress
FROM db_products FORCE INDEX (products_start_time)
ORDER BY start_time DESC
) as resultstable
WHERE resultstable.closed = 0
AND resultstable.active = 1
AND resultstable.approved = 1
AND resultstable.deleted = 0
AND resultstable.creation_in_progress = 0
GROUP BY resultstable.owner_id
ORDER BY start_time DESC
WARNING:
If you're using ORDER BY
before GROUP BY
to get the latest entry per owner_id
, you're using a nonstandard and undocumented behavior of MySQL to do that.
There's no guarantee that it'll continue to work in future versions of MySQL, and the query is likely to be an error in any other RDBMS.
Search the greatest-n-per-group tag for many explanations of better solutions for this type of query.
There is no generic type which will tell the compiler that a method returns nothing.
I believe the convention is to use Object when inheriting as a type parameter
OR
Propagate the type parameter up and then let users of your class instantiate using Object and assigning the object to a variable typed using a type-wildcard ?
:
interface B<E>{ E method(); }
class A<T> implements B<T>{
public T method(){
// do something
return null;
}
}
A<?> a = new A<Object>();
Since .NET Framework version 3.0, it is possible to use the Keyboard.IsKeyDown
method from the new System.Windows.Input
namespace. For instance:
if (((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && Keyboard.IsKeyDown(Key.F))
{
// CTRL + F is currently pressed
}
Even though it's part of WPF, that method works fine for WinForm applications (provided that you add references to PresentationCore.dll and WindowsBase.dll). Unfortunately, however, the 3.0 and 3.5 versions of the Keyboard.IsKeyDown
method did not work for WinForm applications. Therefore, if you do want to use it in a WinForm application, you'll need to be targeting .NET Framework 4.0 or later in order for it to work.
It's treating the string application
as your URL.
This means your shell isn't parsing the command correctly.
My guess is that you copied the string from somewhere, and that when you pasted it, you got some characters that looked like regular quotes, but weren't.
Try retyping the command; you'll only get valid characters from your keyboard. I bet you'll get a much different result from what looks like the same query.
As this is probably a shell problem and not a 'curl' problem (you didn't build cURL yourself from source, did you?), it might be good to mention whether you're on Linux/Windows/etc.
you might use default parameters in your function and then just pass the entire dataset itself, since the dataset is already a DOMStringMap Object
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">
<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) {
//
}
</script>
that way, you can deal with any data-values that got set in the html tag, or use defaults if they weren't set - that kind of thing
maybe not in this situation, but in others, it might be advantageous to put all your preferences in a single data-attribute
<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">
there are probably more terse ways of doing that, if you already know certain things about the order of the data
<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">
If I don't know the size up front, I use an arraylist instead of an array.
$al = New-Object System.Collections.ArrayList
for($i=0; $i -lt 5; $i++)
{
$al.Add($i)
}
If you want to clean up the whole form, you can use such approach. This is your model into controller:
$scope.registrationForm = {
'firstName' : '',
'lastName' : ''
};
Your HTML:
<form class="form-horizontal" name="registrForm" role="form">
<input type="text" class="form-control"
name="firstName"
id="firstName"
ng-model="registrationForm.firstName"
placeholder="First name"
required> First name
<input type="text" class="form-control"
name="lastName"
id="lastName"
ng-model="registrationForm.lastName"
placeholder="Last name"
required> Last name
</form>
Then, you should clone/save your clear state by:
$scope.originForm = angular.copy($scope.registrationForm);
Your reset function will be:
$scope.resetForm = function(){
$scope.registrationForm = angular.copy($scope.originForm); // Assign clear state to modified form
$scope.registrForm.$setPristine(); // this line will update status of your form, but will not clean your data, where `registrForm` - name of form.
};
In such way you are able to clean up the whole your form
Just to suggest another way without using if statements, you can use the get()
method for DataFrame
s. For performing the sum based on the question:
df['sum'] = df.get('A', df['B']) + df['C']
The DataFrame
get method has similar behavior as python dictionaries.
Some linux distributions have a php_mysql and php_mysqli package to install.
Given
std::vector<Rule>& topPriorityRules;
The correct way to remove the first element of the referenced vector is
topPriorityRules.erase(topPriorityRules.begin());
which is exactly what you suggested.
Looks like i need to do iterator overloading.
There is no need to overload an iterator in order to erase first element of std::vector
.
P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.
Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data.
Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:
num_list[-9:]
When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")
The full notation is
sequence[start:stop:step]
But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists in Python 2 is
list_copy = sequence[:]
And clearing them is with:
del my_list[:]
(Lists get list.copy
and list.clear
in Python 3.)
You may find it useful to separate forming the slice from passing it to the list.__getitem__
method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.
However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:
last_nine_slice = slice(-9, None)
The second argument, None
, is required, so that the first argument is interpreted as the start
argument otherwise it would be the stop
argument.
You can then pass the slice object to your sequence:
>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]
islice
islice
from the itertools module is another possibly performant way to get this. islice
doesn't take negative arguments, so ideally your iterable has a __reversed__
special method - which list does have - so you must first pass your list (or iterable with __reversed__
) to reversed
.
>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>
islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list
):
>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]
I am trying to do that in jQuery 2.1, and with the "$().click() -> $(element).data("events").click;
" method it doesn't work.
I realized that only the $._data() functions works in my case :
$(document).ready(function(){_x000D_
_x000D_
var node = $('body');_x000D_
_x000D_
// Bind 3 events to body click_x000D_
node.click(function(e) { alert('hello'); })_x000D_
.click(function(e) { alert('bye'); })_x000D_
.click(fun_1);_x000D_
_x000D_
// Inspect the events of body_x000D_
var events = $._data(node[0], "events").click;_x000D_
var ev1 = events[0].handler // -> function(e) { alert('hello')_x000D_
var ev2 = events[1].handler // -> function(e) { alert('bye')_x000D_
var ev3 = events[2].handler // -> function fun_1()_x000D_
_x000D_
$('body')_x000D_
.append('<p> Event1 = ' + eval(ev1).toString() + '</p>')_x000D_
.append('<p> Event2 = ' + eval(ev2).toString() + '</p>')_x000D_
.append('<p> Event3 = ' + eval(ev3).toString() + '</p>'); _x000D_
_x000D_
});_x000D_
_x000D_
function fun_1() {_x000D_
var txt = 'text del missatge'; _x000D_
alert(txt);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
</body>
_x000D_
You can create an array dynamically in this way:
static void Main()
{
// Create a string array 2 elements in length:
int arrayLength = 2;
Array dynamicArray = Array.CreateInstance(typeof(int), arrayLength);
dynamicArray.SetValue(234, 0); // ? a[0] = 234;
dynamicArray.SetValue(444, 1); // ? a[1] = 444;
int number = (int)dynamicArray.GetValue(0); // ? number = a[0];
int[] cSharpArray = (int[])dynamicArray;
int s2 = cSharpArray[0];
}
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
You may face this issue if you are running your app on Android's Marshmallow or later version (API level 23 or greater), because of the new Real-time Permissions model introduced in this.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.
For getting permissions at runtime, you will have to request the user. You can do that in following way.
First request for permissions.
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, WRITE_REQUEST_CODE);
And then you can check the results in
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case WRITE_REQUEST_CODE:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Permission granted.
//Continue with writing files...
}
else{
//Permission denied.
}
break;
}
}
Here is good learning source requesting-runtime-permissions-in-android-marshmallow/
Here is another example using the lapply
and table
functions in base R.
freqList = lapply(select_if(tips, is.factor),
function(x) {
df = data.frame(table(x))
df = data.frame(fct = df[, 1],
n = sapply(df[, 2], function(y) {
round(y / nrow(dat), 2)
}
)
)
return(df)
}
)
Use print(freqList)
to see the proportion tables (percent of frequencies) for each column/feature/variable (depending on your tradecraft) that is labeled as a factor.
You can try this
$('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});
The $('div.easy_editor')
refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.
Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/
Html:
<div id="content">
<iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>
Relevant parts of CSS:
div#content {
position: fixed;
top: 80px;
left: 40px;
bottom: 25px;
min-width: 200px;
width: 40%;
background: black;
}
div#content iframe {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
}
You can always change a date on your computer, make a commit, then change the date back and push.
double myDb = 12.3;
int myInt = (int) myDb;
Result is: myInt = 12
Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:
-vm
path/javaw.exe
for example:
-vm
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe
If using Angular Material Design, you can use the datepicker component there and this will work in Firefox, IE etc.
https://material.angularjs.org/latest/demo/datepicker
Fair warning though - personal experience is that there are problems with this, and seemingly it is being re-worked at present. See here:
If you want to grab the query parameter value in the URL, follow below code pieces
//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid
If you want to grab the URL parameter using Express param function
Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.
This can be used for validations or grabbing important information about item.
An example for this would be:
// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {
// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';
// save name to the request
req.tagid= modified;
next();
});
// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});
iOS 10 update
The ban on autoplay has been lifted as of iOS 10 - but with some restrictions (e.g. A can be autoplayed if there is no audio track).
To see a full list of these restrictions, see the official docs: https://webkit.org/blog/6784/new-video-policies-for-ios/
iOS 9 and before
As of iOS 6.1, it is no longer possible to auto-play videos on the iPad.
My assumption as to why they've disabled the auto-play feature?
Well, as many device owners have data usage/bandwidth limits on their devices, I think Apple felt that the user themselves should decide when they initiate bandwidth usage.
After a bit of research I found the following extract in the Apple documentation in regard to auto-play on iOS devices to confirm my assumption:
"Apple has made the decision to disable the automatic playing of video on iOS devices, through both script and attribute implementations.
In Safari, on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and auto-play are disabled. No data is loaded until the user initiates it." - Apple documentation.
Here is a separate warning featured on the Safari HTML5 Reference page about why embedded media cannot be played in Safari on iOS:
Warning: To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.
What this means (in terms of code) is that Javascript's play()
and load()
methods are inactive until the user initiates playback, unless the play()
or load()
method is triggered by user action (e.g. a click event).
Basically, a user-initiated play button works, but
an onLoad="play()"
event does not.
For example, this would play the movie:
<input type="button" value="Play" onclick="document.myMovie.play()">
Whereas the following would do nothing on iOS:
<body onload="document.myMovie.play()">
From MSDN Documentation
nvarchar [ ( n | max ) ]
Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is two times the actual length of data entered + 2 bytes
If fptr
is NULL
, then you don't have an open file. Therefore, you can't freopen
it, you should just fopen
it.
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("scores.dat", "wb");
}
note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.
int main()
{
FILE *fptr;
char there_was_error = 0;
char opened_in_read = 1;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("scores.dat", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
}
Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:
IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);
Disclaimer: I own SpreadsheetGear LLC
I know this is an old question but no one ever answered the first part, to set width in percent. That can easily be done with FillWeight (MSDN). In case anyone else searching comes across this answer.
You can set DataGridAutoSizeColumnMode to Fill in the designer. By default that gives each column FillWeight of 100. Then in code behind, on FormLoad event or after binding data to grid, you can simply:
gridName.Columns[0].FillWeight = 200;
gridName.Columns[1].FillWeight = 50;
And so on, for whatever proportional weight you want. If you want to do every single column with numbers that add up to 100, for a literal percent width, you can do that too.
It gives a nice full DataGrid where the headers use the whole space, even if the user resizes the window. Looks good on widescreen, 4:3, whatever.
Have you checked these official docs?
HostListener - Declares a host listener. Angular will invoke the decorated method when the host element emits the specified event.
@HostListener
- will listen to the event emitted by the host element that's declared with @HostListener
.
HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive.
@HostBinding
- will bind the property to the host element, If a binding changes, HostBinding
will update the host element.
NOTE: Both links have been removed recently. The "HostBinding-HostListening" portion of the style guide may be a useful alternative until the links return.
Here's a simple code example to help picture what this means:
DEMO : Here's the demo live in plunker - "A simple example about @HostListener & @HostBinding"
role
property -- declared with @HostBinding
-- to the host's element
role
is an attribute, since we're using attr.role
.<p myDir>
becomes <p mydir="" role="admin">
when you view it in developer tools.onClick
event declared with @HostListener
, attached to the component's host element, changing role
with each click.
<p myDir>
is clicked is that its opening tag changes from <p mydir="" role="admin">
to <p mydir="" role="guest">
and back.directives.ts
import {Component,HostListener,Directive,HostBinding,Input} from '@angular/core';
@Directive({selector: '[myDir]'})
export class HostDirective {
@HostBinding('attr.role') role = 'admin';
@HostListener('click') onClick() {
this.role= this.role === 'admin' ? 'guest' : 'admin';
}
}
AppComponent.ts
import { Component,ElementRef,ViewChild } from '@angular/core';
import {HostDirective} from './directives';
@Component({
selector: 'my-app',
template:
`
<p myDir>Host Element
<br><br>
We have a (HostListener) listening to this host's <b>click event</b> declared with @HostListener
<br><br>
And we have a (HostBinding) binding <b>the role property</b> to host element declared with @HostBinding
and checking host's property binding updates.
If any property change is found I will update it.
</p>
<div>View this change in the DOM of the host element by opening developer tools,
clicking the host element in the UI.
The role attribute's changes will be visible in the DOM.</div>
`,
directives: [HostDirective]
})
export class AppComponent {}
By the way, you can use serialization technology to send strings, numbers or any objects which are support serialization (most of .NET data-storing classes & structs are [Serializable]). There, you should at first send Int32-length in four bytes to the stream and then send binary-serialized (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter) data into it.
On the other side or the connection (on both sides actually) you definetly should have a byte[] buffer which u will append and trim-left at runtime when data is coming.
Something like that I am using:
namespace System.Net.Sockets
{
public class TcpConnection : IDisposable
{
public event EvHandler<TcpConnection, DataArrivedEventArgs> DataArrive = delegate { };
public event EvHandler<TcpConnection> Drop = delegate { };
private const int IntSize = 4;
private const int BufferSize = 8 * 1024;
private static readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
private readonly TcpClient _tcpClient;
private readonly object _droppedRoot = new object();
private bool _dropped;
private byte[] _incomingData = new byte[0];
private Nullable<int> _objectDataLength;
public TcpClient TcpClient { get { return _tcpClient; } }
public bool Dropped { get { return _dropped; } }
private void DropConnection()
{
lock (_droppedRoot)
{
if (Dropped)
return;
_dropped = true;
}
_tcpClient.Close();
_syncContext.Post(delegate { Drop(this); }, null);
}
public void SendData(PCmds pCmd) { SendDataInternal(new object[] { pCmd }); }
public void SendData(PCmds pCmd, object[] datas)
{
datas.ThrowIfNull();
SendDataInternal(new object[] { pCmd }.Append(datas));
}
private void SendDataInternal(object data)
{
if (Dropped)
return;
byte[] bytedata;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
try { bf.Serialize(ms, data); }
catch { return; }
bytedata = ms.ToArray();
}
try
{
lock (_tcpClient)
{
TcpClient.Client.BeginSend(BitConverter.GetBytes(bytedata.Length), 0, IntSize, SocketFlags.None, EndSend, null);
TcpClient.Client.BeginSend(bytedata, 0, bytedata.Length, SocketFlags.None, EndSend, null);
}
}
catch { DropConnection(); }
}
private void EndSend(IAsyncResult ar)
{
try { TcpClient.Client.EndSend(ar); }
catch { }
}
public TcpConnection(TcpClient tcpClient)
{
_tcpClient = tcpClient;
StartReceive();
}
private void StartReceive()
{
byte[] buffer = new byte[BufferSize];
try
{
_tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, DataReceived, buffer);
}
catch { DropConnection(); }
}
private void DataReceived(IAsyncResult ar)
{
if (Dropped)
return;
int dataRead;
try { dataRead = TcpClient.Client.EndReceive(ar); }
catch
{
DropConnection();
return;
}
if (dataRead == 0)
{
DropConnection();
return;
}
byte[] byteData = ar.AsyncState as byte[];
_incomingData = _incomingData.Append(byteData.Take(dataRead).ToArray());
bool exitWhile = false;
while (exitWhile)
{
exitWhile = true;
if (_objectDataLength.HasValue)
{
if (_incomingData.Length >= _objectDataLength.Value)
{
object data;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(_incomingData, 0, _objectDataLength.Value))
try { data = bf.Deserialize(ms); }
catch
{
SendData(PCmds.Disconnect);
DropConnection();
return;
}
_syncContext.Post(delegate(object T)
{
try { DataArrive(this, new DataArrivedEventArgs(T)); }
catch { DropConnection(); }
}, data);
_incomingData = _incomingData.TrimLeft(_objectDataLength.Value);
_objectDataLength = null;
exitWhile = false;
}
}
else
if (_incomingData.Length >= IntSize)
{
_objectDataLength = BitConverter.ToInt32(_incomingData.TakeLeft(IntSize), 0);
_incomingData = _incomingData.TrimLeft(IntSize);
exitWhile = false;
}
}
StartReceive();
}
public void Dispose() { DropConnection(); }
}
}
That is just an example, you should edit it for your use.
If you want to be able to perform a lookup on each type to get its frequency then you will need to transform the enumeration into a dictionary.
var types = new[] {typeof(string), typeof(string), typeof(int)};
var x = types
.GroupBy(type => type)
.ToDictionary(g => g.Key, g => g.Count());
foreach (var kvp in x) {
Console.WriteLine("Type {0}, Count {1}", kvp.Key, kvp.Value);
}
Console.WriteLine("string has a count of {0}", x[typeof(string)]);
if i want to check if any speicfic position of command line arguement is passed or not then how to check? like for example in some scenarios 2 command line args will be passed and in some only one will be passed then how do it check wheather the specfic commnad line is passed or not?
public class check {
public static void main(String[] args) {
if(args[0].length()!=0)
{
System.out.println("entered first if");
}
if(args[0].length()!=0 && args[1].length()!=0)
{
System.out.println("entered second if");
}
}
}
So in the above code if args[1] is not passed then i get java.lang.ArrayIndexOutOfBoundsException:
so how do i tackle this where i can check if second arguement is passed or not and if passed then enter it. need assistance asap.
Try this...
function nationList($limit=null, $start=null) {
if ($this->session->userdata('language') == "it") {
$this->db->select('nation.id, nation.name_it as name');
}
if ($this->session->userdata('language') == "en") {
$this->db->select('nation.id, nation.name_en as name');
}
$this->db->from('nation');
$this->db->order_by("name", "asc");
if ($limit != '' && $start != '') {
$this->db->limit($limit, $start);
}
$query = $this->db->get();
$nation = array();
foreach ($query->result() as $row) {
array_push($nation, $row);
}
return $nation;
}
Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:
pd.DataFrame({'email':sf.index, 'list':sf.values})
There are lots of ways to construct a df, see the docs
It means that the value type in question is a nullable type
Nullable types are instances of the System.Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a
Nullable<Int32>
, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. ANullable<bool>
can be assigned the values true, false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.class NullableExample { static void Main() { int? num = null; // Is the HasValue property true? if (num.HasValue) { System.Console.WriteLine("num = " + num.Value); } else { System.Console.WriteLine("num = Null"); } // y is set to zero int y = num.GetValueOrDefault(); // num.Value throws an InvalidOperationException if num.HasValue is false try { y = num.Value; } catch (System.InvalidOperationException e) { System.Console.WriteLine(e.Message); } } }
Use formula =row(b2)-x, where x will adjust the entries so that the first S/No is marked as 1 and will increment with the rows.
Check outdated packages
npm outdated
Check and pick packages to update
npx npm-check -u
In the course of developing an in-house address verification service at a German company I used to work for I've come across a number of ways to tackle this issue. I'll do my best to sum up my findings below:
Free, Open Source Software
Clearly, the first approach anyone would take is an open-source one (like openstreetmap.org), which is never a bad idea. But whether or not you can really put this to good and reliable use depends very much on how much you need to rely on the results.
Addresses are an incredibly variable thing. Verifying U.S. addresses is not an easy task, but bearable, but once you're going for Europe, especially the U.K. with their extensive Postal Code system, the open-source approach will simply lack data.
Web Services / APIs
Enterprise-Class Software
Money gets it done, obviously. But not every business or developer can spend ~$0.15 per address lookup (that's $150 for 1,000 API requests) - a very expensive business model the vast majority of address validation APIs have implemented.
What I ended up integrating: streetlayer API
Since I was not willing to take on the programmatic approach of verifying address data manually I finally came to the conclusion that I was in need of an API with a price tag that would not make my boss want to fire me and still deliver solid and reliable international verification results.
Long story short, I ended up integrating an API built by apilayer, called "streetlayer API". I was easily convinced by a simple JSON integration, surprisingly accurate validation results and their developer-friendly pricing. Also, 100 requests/month are entirely free.
Hope this helps!
I tried all of the suggestions above and none of them worked for me, they changed the clientWidth and clientHeight not the actual width and height.
The jQuery docs for $().width and height methods says: "Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property."
The css approach did the same thing so I had to use the $().attr() methods instead.
_canvas.attr('width', 100);
_canvas.attr('height', 200);
I don't know is this affect me because I was trying to resize a element and it is some how different or not.
Two ways:
char *c = new char[length];
std::fill(c, c + length, INITIAL_VALUE);
// just this once, since it's char, you could use memset
Or:
std::vector<char> c(length, INITIAL_VALUE);
In my second way, the default second parameter is 0 already, so in your case it's unnecessary:
std::vector<char> c(length);
[Edit: go vote for Fred's answer, char* c = new char[length]();
]
The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}
Demo:
input {_x000D_
font: small-caption;_x000D_
font-size: 16px;_x000D_
}
_x000D_
<input type="password">
_x000D_
a.update(b)
Will add keys and values from b to a, overwriting if there's already a value for a key.
DISTINCT
: will gives you unique values.
SELECT GROUP_CONCAT(DISTINCT(categories )) AS categories FROM table
I know that the topic is way too old. But I am pretty sure that there are some developpers who still need this, so I made this simple script for you. I hope you enjoy it!
Hello back, It's 2020 and I've added some modification hope it will help a lot better now!
function strtotime(date, addTime){
let generatedTime=date.getTime();
if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds
if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes
if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours
return new Date(generatedTime);
}
Date.prototype.strtotime = function(addTime){
return strtotime(new Date(), addTime);
}
let futureDate = new Date().strtotime({
hours: 16, //Adding one hour
minutes: 45, //Adding fourty five minutes
seconds: 0 //Adding 0 seconds return to not adding any second so we can remove it.
});
_x000D_
<button onclick="console.log(futureDate)">Travel to the future</button>
_x000D_
You can use either date or strftime. In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?)
For example:
<?php echo date("Y"); ?>
On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the php manual on date:
To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().
From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that's not an issue, pick the one you like best.
The jQuery-rss project is pretty lightweight and doesn't impose any particular styling.
The syntax can be as simple as
$("#rss-feeds").rss("http://www.recruiter.com/feed/career.xml")
See a working example at http://jsfiddle.net/jhfrench/AFHfn/
You can do this with the apksigner
tool that is part of the Android SDK:
apksigner verify --print-certs my_app.apk
You can find apksigner inside the build-tools directory. For example:
~/Library/Android/sdk/build-tools/29.0.1/apksigner
For some reason Andrew method of creating the checkbox by hand didn't work for me using Mvc 5. Instead I used this
@Html.CheckBox("checkResp")
to create a checkbox that would play nice with the controller.
I had the similar issue showing the error
For more information about this error navigate to the report server on the local server machine, or enable remote errors Query execution failed for dataset 'PrintInvoice'.
Solution: 1) The error may be with the dataset in some cases, you can always check if the dataset is populating the exact data you are expecting by going to the dataset properties and choosing 'Query Designer' and try 'Run', If you can successfully able to pull the fields you are expecting, then you can be sure that there isn't any problem with the dataset, which takes us to next solution.
2) Even though the error message says "Query Failed Execution for the dataset", another probable chances are with the datasource connection, make sure you have connected to the correct datasource that has the tables you need and you have permissions to access that datasource.
If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.
If your string looks like below
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines
In my case i had to install google repository from the SDK manager.
A much simpler solution would be to download the file using Chrome. In this manner you don't have to manually click on the save button.
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace MyProcessSample
{
class MyProcess
{
public static void Main()
{
Process myProcess = new Process();
myProcess.Start("chrome.exe","http://www.com/newfile.zip");
}
}
}
You can use the ID
field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.
<select
ng-model="Choice.SelectedOption.ID"
ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// Submit Button
String Fname = jTextField1.getText();
String Lname = jTextField2.getText();
String Desig = jTextField3.getText();
String Nic = jTextField4.getText();
String Phone = jTextField5.getText();
String Add = jTextArea1.getText();
String Dob = jTextField6.getText();
// String Gender;
// Image
if (Fname.hashCode() == 0 || Lname.hashCode() == 0 || Desig.hashCode() == 0 || Nic.hashCode() == 0 || Phone.hashCode() == 0 || Add.hashCode() == 0)
{
JOptionPane.showMessageDialog(null, "Some fields are empty!");
}
else
{
JOptionPane.showMessageDialog(null, "OK");
}
}
If you'd checked the results of stream.Read
, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;
.) However, it's easier to just call ToArray
:
settingsString = LocalEncoding.GetString(stream.ToArray());
(You'll need to change the type of stream
from Stream
to MemoryStream
, but that's okay as it's in the same method where you create it.)
Alternatively - and even more simply - just use StringWriter
instead of StreamWriter
. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.
I'm concerned by the way you're just catching Exception
and assuming that it means something harmless, by the way - without even logging anything. Note that using
statements are generally cleaner than writing explicit finally
blocks.
In addition, it's convenient to define variables referring to objects. For instance,
Sub CreateTable()
Dim lo as ListObject
Set lo = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes)
lo.Name = "Table1"
lo.TableStyle = "TableStyleLight2"
...
End Sub
You will probably find it advantageous at once.
A previous answer only mentioned SSL in the context of data transfer and didn't actually cover authentication.
You're really asking about securely authenticating REST API clients. Unless you're using TLS client authentication, SSL alone is NOT a viable authentication mechanism for a REST API. SSL without client authc only authenticates the server, which is irrelevant for most REST APIs because you really want to authenticate the client.
If you don't use TLS client authentication, you'll need to use something like a digest-based authentication scheme (like Amazon Web Service's custom scheme) or OAuth 1.0a or even HTTP Basic authentication (but over SSL only).
These schemes authenticate that the request was sent by someone expected. TLS (SSL) (without client authentication) ensures that the data sent over the wire remains untampered. They are separate - but complementary - concerns.
For those interested, I've expanded on an SO question about HTTP Authentication Schemes and how they work.
set global sql_mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Nothing above worked, this is what worked for me:
ftype Python.File=C:\Path\to\python.exe "%1" %*
This command should be run in Command prompt launched as administrator
Warning: even if the path in this command is set to python35, if you have python36 installed it's going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36
to xxPython36
, run the command and then remove the change to the Python 36 folder.
One who has tried all other answers and had no luck the please check this check box, hope it'll help (did the trick for me xcode 6.0.1)
If this is something you are only going to need to do once, have you considered downloading a demo version of Crystal? There's a 30-day trial version available here: http://www.developers.net/businessobjectsshowcase/view/3154
Of course, if you need to edit these files after the 30 day period is over, you would be better off buying Crystal.
Alternatively, if all you need to do is replace a few static literal words, have you tried doing a search and replace in a text editor? (Don't forget to save the original files somewhere safe first!)
Latest news:
Google announce that with Android N and Android Studio 2.1+, platform will support Java 8. Also stable version of studio 2.1 was released.
At last we can use lambda expressions. No more list filter in for loop. Horeeey.
declare your date column as NOT NULL, but without a default. Then add this trigger:
USE `ddb`;
DELIMITER $$
CREATE TRIGGER `default_date` BEFORE INSERT ON `dtable` FOR EACH ROW
if ( isnull(new.query_date) ) then
set new.query_date=curdate();
end if;
$$
delimiter ;
.env
>= 5.0 (tested on 5.5)In .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=secret
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret
In config/database.php
'mysql' => [
'driver' => env('DB_CONNECTION'),
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
'mysql2' => [
'driver' => env('DB_CONNECTION_SECOND'),
'host' => env('DB_HOST_SECOND'),
'port' => env('DB_PORT_SECOND'),
'database' => env('DB_DATABASE_SECOND'),
'username' => env('DB_USERNAME_SECOND'),
'password' => env('DB_PASSWORD_SECOND'),
],
Note: In
mysql2
if DB_username and DB_password is same, then you can useenv('DB_USERNAME')
which is metioned in.env
first few lines.
.env
<5.0Define Connections
app/config/database.php
return array(
'default' => 'mysql',
'connections' => array(
# Primary/Default database connection
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'database1',
'username' => 'root',
'password' => 'secret'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Secondary database connection
'mysql2' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'database2',
'username' => 'root',
'password' => 'secret'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
Schema
To specify which connection to use, simply run the connection()
method
Schema::connection('mysql2')->create('some_table', function($table)
{
$table->increments('id'):
});
Query Builder
$users = DB::connection('mysql2')->select(...);
Eloquent
Set the $connection
variable in your model
class SomeModel extends Eloquent {
protected $connection = 'mysql2';
}
You can also define the connection at runtime via the setConnection
method or the on
static method:
class SomeController extends BaseController {
public function someMethod()
{
$someModel = new SomeModel;
$someModel->setConnection('mysql2'); // non-static method
$something = $someModel->find(1);
$something = SomeModel::on('mysql2')->find(1); // static method
return $something;
}
}
Note Be careful about attempting to build relationships with tables across databases! It is possible to do, but it can come with some caveats and depends on what database and/or database settings you have.
Using Multiple Database Connections
When using multiple connections, you may access each connection
via the connection method on the DB
facade. The name
passed to the connection
method should correspond to one of the connections listed in your config/database.php
configuration file:
$users = DB::connection('foo')->select(...);
You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:
$pdo = DB::connection()->getPdo();
Useful Links
I had this error aswell.
I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.
In Objective-C, if you wanted to use a class in another file you had to import it:
#import "SomeClass.h"
However, in Swift, you don't have to import at all. Simply use it as if it was already imported.
// This is a file named SomeClass.swift
class SomeClass : NSObject {
}
// This is a different file, named OtherClass.swift
class OtherClass : NSObject {
let object = SomeClass()
}
As you can see, no import was needed. Hope this helps.
You can use:
getActiveNetworkInfo();
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to mobile data
}
} else {
// not connected to the internet
}
Or in a switch case
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
switch (activeNetwork.getType()) {
case ConnectivityManager.TYPE_WIFI:
// connected to wifi
break;
case ConnectivityManager.TYPE_MOBILE:
// connected to mobile data
break;
default:
break;
}
} else {
// not connected to the internet
}
Maybe your mobile view port is not set.
Add following meta tag inside <head></head>
to allow menu to work on mobiles.
<meta name=viewport content="width=device-width, initial-scale=1">
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
The answer depends upon the degree of confidence you place in the data and how your data is being used. For example, if you're using it for mailing or shipping, you'll want to be be confident that the data is correct. If you're just using it as another fraud-prevention mechanism then you could potentially allow a degree of error to creep into the data.
If you want any degree of real accuracy, you're need to go with a service that does real address verification and you're going to have to pay for it. As has been mentioned by Adam, address verification and validation at first seems simple and easy, but it's a black hole fraught with challenges and, unless you've some underlying data to work with, virtually impossible to do by yourself. Trust me, you're actually saving money by using a service. You're welcome to go down this road yourself to experience what I mean, but I can guarantee you'll see the light, so to speak, after even a few hours (or days) of spinning your wheels.
I should mention that I'm the founder of SmartyStreets. We do address validation and verification addresses and we offer this for the USA and international as well. I'm more than happy to personally answer any questions you have on the topic of address cleansing, standardization, and validation.
@Valkyrie awesome answer. Thought I put in here a case when performing the same with a subquery insides a stored procedure, as I wondered if your answer works in this case, and it did awesome.
...WHERE fieldname COLLATE DATABASE_DEFAULT in (
SELECT DISTINCT otherfieldname COLLATE DATABASE_DEFAULT
FROM ...
WHERE ...
)
Noticed this is a 2-years old question, but still want to share my workaround for this particular question:
Firstly, run docker container ls -a
to list all the containers you have and pinpoint the want you want to delete.
Secondly, delete the one with command docker container rm <CONTAINER ID>
(If the container is currently running, you should stop it first, run docker container stop <CONTAINER ID>
to gracefully stop the specified container, if it does not stop it for whatever the reason is, alternatively you can run docker container kill <CONTAINER ID> to force shutdown of the specified container
).
Thirdly, remove the container by running docker container rm <CONTAINER ID>
.
Lastly you can run docker image ls -a
to view all the images and delete the one you want to by running docker image rm <hash>
.
As from March 2013 IANA.ORG recommends for .otf:
application/font-sfnt
Other fonts:
.eot -> application/vnd.ms-fontobject (as from December 2005)
.otf -> application/font-sfnt (as from March 2013)
.svg -> image/svg+xml (as from August 2011)
.ttf -> application/font-sfnt (as from March 2013)
.woff -> application/font-woff (as from January 2013)
See more...
by the way, the zoo package, if it is loaded, overrides the base as.Date() with its own which, by default, provides origin="1970-01-01".
(i mention this in case you find that sometimes you need to add the origin, and sometimes you don't.)
As complement to Mark's answer, the compile function does not have access to scope, but the link function does.
I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).
Try the Parse method.
I had a similar issue. I needed to keep the legacy encrypted passwords (Base64/SHA-1/Random salt Encoded) as users will not want to change their passwords or re-register. However I wanted to use the BCrypt encoder moving forward too.
My solution was to write a bespoke decoder that checks to see which encryption method was used first before matching (BCrypted ones start with $
).
To get around the salt issue, I pass into the decoder a concatenated String of salt + encrypted password via my modified user object.
Decoder
@Component
public class LegacyEncoder implements PasswordEncoder {
private static final String BCRYP_TYPE = "$";
private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();
@Override
public String encode(CharSequence rawPassword) {
return BCRYPT.encode(rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (encodedPassword.startsWith(BCRYP_TYPE)) {
return BCRYPT.matches(rawPassword, encodedPassword);
}
return sha1SaltMatch(rawPassword, encodedPassword);
}
@SneakyThrows
private boolean sha1SaltMatch(CharSequence rawPassword, String encodedPassword) {
String[] saltHash = encodedPassword.split(User.SPLIT_CHAR);
// Legacy code from old system
byte[] b64salt = Base64.getDecoder().decode(saltHash[0].getBytes());
byte[] validHash = Base64.getDecoder().decode(saltHash[1]);
byte[] checkHash = Utility.getHash(5, rawPassword.toString(), b64salt);
return Arrays.equals(checkHash, validHash);
}
}
User Object
public class User implements UserDetails {
public static final String SPLIT_CHAR = ":";
@Id
@Column(name = "user_id", nullable = false)
private Integer userId;
@Column(nullable = false, length = 60)
private String password;
@Column(nullable = true, length = 32)
private String salt;
.
.
@PostLoad
private void init() {
username = emailAddress; //To comply with UserDetails
password = salt == null ? password : salt + SPLIT_CHAR + password;
}
You can also add a hook to re-encode the password in the new BCrypt format and replace it. Thus phasing out the old method.
Note that 1>&2
cannot be used interchangeably with 2>&1
.
Imagine your command depends on piping, for example:
docker logs 1b3e97c49e39 2>&1 | grep "some log"
grepping will happen across both stderr
and stdout
since stderr
is basically merged into stdout
.
However, if you try:
docker logs 1b3e97c49e39 1>&2 | grep "some log"
,
grepping will not really search anywhere at all because Unix pipe is connecting processes via connecting stdout | stdin
, and stdout
in the second case was redirected to stderr
in which Unix pipe has no interest.
Use clearRect method by passing x,y co-ordinates and height and width of canvas. ClearRect will clear whole canvas as :
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
Just a quick note. Be wary of using for..in
if you use a library (jQuery, Prototype, etc.), as most of them add methods to created Objects (including dictionaries).
This will mean that when you loop over them, method names will appear as keys. If you are using a library, look at the documentation and look for an enumerable section, where you will find the right methods for iteration of your objects.
The git submodule update
command actually tells Git that you want your submodules to each check out the commit already specified in the index of the superproject. If you want to update your submodules to the latest commit available from their remote, you will need to do this directly in the submodules.
So in summary:
# Get the submodule initially
git submodule add ssh://bla submodule_dir
git submodule init
# Time passes, submodule upstream is updated
# and you now want to update
# Change to the submodule directory
cd submodule_dir
# Checkout desired branch
git checkout master
# Update
git pull
# Get back to your project root
cd ..
# Now the submodules are in the state you want, so
git commit -am "Pulled down update to submodule_dir"
Or, if you're a busy person:
git submodule foreach git pull origin master
maybe its better using the case
instead of if
dunno if this eliminates the error, but its cleaner i think.. switch (operation){case +: System.out.println("your answer is" + (num1 + num2));break;case -: System.out.println("your answer is" - (num1 - num2));break; ...
As proposed nanoTime () is very precise on short time scales. When this precision is required you need to take care about what you really measure. Especially not to measure the nanotime call itself
long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization
long start2 = System.nanoTime();
myCall();
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;
System.out.println(diff + " ns");
By the way, you will measure different values for the same call due to
Reinstalling the software fixes the issue, just make sure not to delete the htdocs folder in the process.
I prefer the JOIN to join full tables/Views and then use the WHERE To introduce the predicate of the resulting set.
It feels syntactically cleaner.
In my case I just needed to remove Homebrew's executable using:
sudo rm -f `which brew`
Then reinstall Homebrew:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
You can include the Jython library in your Java Project. You can download the source code from the Jython project itself.
Jython does offers support for JSR-223 which basically lets you run a Python script from Java.
You can use a ScriptContext
to configure where you want to send your output of the execution.
For instance, let's suppose you have the following Python script in a file named numbers.py
:
for i in range(1,10):
print(i)
So, you can run it from Java as follows:
public static void main(String[] args) throws ScriptException, IOException {
StringWriter writer = new StringWriter(); //ouput will be stored here
ScriptEngineManager manager = new ScriptEngineManager();
ScriptContext context = new SimpleScriptContext();
context.setWriter(writer); //configures output redirection
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader("numbers.py"), context);
System.out.println(writer.toString());
}
And the output will be:
1
2
3
4
5
6
7
8
9
As long as your Python script is compatible with Python 2.5 you will not have any problems running this with Jython.
I solved in this way:
git archive --remote=ssh://[email protected]/user/mi-repo.git BranchName /path-to-file/file_name | tar -xO /path-to-file/file_name > /path-to-save-the-file/file_name
If you want, you could replace "BranchName" for "HEAD"
As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()
) in combination with svg's <foreignObject>
element.
You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup)
)
But note that it is mostly a hack and that there are a lot of limitations :
document.styleSheets
. for this part, DOMParser
and XMLSerializer
may help.<img>
tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).Now, a small demo of some html markup in a pseudo element :
/* _x000D_
** original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
* xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
* I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
Here comes the structure of template I used:
select
/*this is a row number counter*/
( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 )
as rownumber,
d3.*
from
( select d1.* from table_name d1 ) d3
And here is my working code:
select
( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 )
as rownumber,
d3.*
from
( select year( d1.date ), month( d1.date ), count( d1.id )
from maindatabase d1
where ( ( d1.date >= '2013-01-01' ) and ( d1.date <= '2014-12-31' ) )
group by YEAR( d1.date ), MONTH( d1.date ) ) d3
At least in case of EclipseLink 10g and 11g differ. Since 11g it is not recommended to use first_rows hint for pagination queries.
See "Is it possible to disable jpa hints per particular query". Such a query should not be used in 11g.
SELECT * FROM (
SELECT /*+ FIRST_ROWS */ a.*, ROWNUM rnum FROM (
SELECT * FROM TABLES INCLUDING JOINS, ORDERING, etc.) a
WHERE ROWNUM <= 10 )
WHERE rnum > 0;
But there can be other nuances.
If the relation must not be bidirectional then an @ElementCollection might be easier than using a lazy One2Many collection.
Replace the * with a /
So instead of
COPY * <destination>
use
COPY / <destination>
This worked for me:
git branch
Copy the current branch name to clipboard
git pull origin <paste-branch-name>
git push
Using combination of grep
and sed
for pp in $(grep -Rl looking_for_string)
do
sed -i 's/looking_for_string/something_other/g' "${pp}"
done
The method suggested by @roe and @MohitNanda work, but if the right div is set as float:right;
, then it must come first in the HTML source. This breaks the left-to-right read order, which could be confusing if the page is displayed with styles turned off. If that's the case, it might be better to use a wrapper div and absolute positioning:
<div id="wrap" style="position:relative;">
<div id="left" style="margin-right:201px;border:1px solid red;">left</div>
<div id="right" style="position:absolute;width:200px;right:0;top:0;border:1px solid blue;">right</div>
</div>
Demonstrated:
left rightEdit: Hmm, interesting. The preview window shows the correctly formatted divs, but the rendered post item does not. Sorry then, you'll have to try it for yourself.
int i = 65;
char c = Convert.ToChar(i);
You may run:
git log <SHA1>..HEAD --ancestry-path --merges
From comment of last commit in the output you may find original branch name
Example:
c---e---g--- feature
/ \
-a---b---d---f---h---j--- master
git log e..master --ancestry-path --merges
commit h
Merge: g f
Author: Eugen Konkov <>
Date: Sat Oct 1 00:54:18 2016 +0300
Merge branch 'feature' into master
Try this
rename .html .txt *.html
usage:
rename [find] [replace_with] [criteria]
What you are asking, Sir, is as the answer of RedFilter. This answer as well helps in understanding why group by is somehow a simpler version or partition over: SQL Server: Difference between PARTITION BY and GROUP BY since it changes the way the returned value is calculated and therefore you could (somehow) return columns group by can not return.
Updated version of @martin's answer for Swift 5+ using Combine. This one also includes unavailibity reason check for iOS 14.
import Combine
import Network
enum NetworkType {
case wifi
case cellular
case loopBack
case wired
case other
}
final class ReachabilityService: ObservableObject {
@Published var reachabilityInfos: NWPath?
@Published var isNetworkAvailable: Bool?
@Published var typeOfCurrentConnection: NetworkType?
private let monitor = NWPathMonitor()
private let backgroundQueue = DispatchQueue.global(qos: .background)
init() {
setUp()
}
init(with interFaceType: NWInterface.InterfaceType) {
setUp()
}
deinit {
monitor.cancel()
}
}
private extension ReachabilityService {
func setUp() {
monitor.pathUpdateHandler = { [weak self] path in
self?.reachabilityInfos = path
switch path.status {
case .satisfied:
print("ReachabilityService: satisfied")
self?.isNetworkAvailable = true
break
case .unsatisfied:
print("ReachabilityService: unsatisfied")
if #available(iOS 14.2, *) {
switch path.unsatisfiedReason {
case .notAvailable:
print("ReachabilityService: unsatisfiedReason: notAvailable")
break
case .cellularDenied:
print("ReachabilityService: unsatisfiedReason: cellularDenied")
break
case .wifiDenied:
print("ReachabilityService: unsatisfiedReason: wifiDenied")
break
case .localNetworkDenied:
print("ReachabilityService: unsatisfiedReason: localNetworkDenied")
break
@unknown default:
print("ReachabilityService: unsatisfiedReason: default")
}
} else {
// Fallback on earlier versions
}
self?.isNetworkAvailable = false
break
case .requiresConnection:
print("ReachabilityService: requiresConnection")
self?.isNetworkAvailable = false
break
@unknown default:
print("ReachabilityService: default")
self?.isNetworkAvailable = false
}
if path.usesInterfaceType(.wifi) {
self?.typeOfCurrentConnection = .wifi
} else if path.usesInterfaceType(.cellular) {
self?.typeOfCurrentConnection = .cellular
} else if path.usesInterfaceType(.loopback) {
self?.typeOfCurrentConnection = .loopBack
} else if path.usesInterfaceType(.wiredEthernet) {
self?.typeOfCurrentConnection = .wired
} else if path.usesInterfaceType(.other) {
self?.typeOfCurrentConnection = .other
}
}
monitor.start(queue: backgroundQueue)
}
}
Usage:
In your view model:
private let reachability = ReachabilityService()
init() {
reachability.$isNetworkAvailable.sink { [weak self] isConnected in
self?.isConnected = isConnected ?? false
}.store(in: &cancelBag)
}
In your controller:
viewModel.$isConnected.sink { [weak self] isConnected in
print("isConnected: \(isConnected)")
DispatchQueue.main.async {
//Update your UI in here
}
}.store(in: &bindings)
Please keep in mind that only a few elements can be self-closing, most others have to be closed through adding an explicit end tag. In the above case, the first script tag was not closed properly, the end script tag of the second script then closed the script section, causing only the first script to be loaded as external script source and ignoring the second script.
More info about which tags can be self-closed, have a look at the W3C drafts for HTML5 (although the definition was no different in earlier HTML-versions):
http://www.w3.org/TR/html5/syntax.html#end-tags (8.1.2.1, Point 6)
Since the previous answers don't appear to work in with Visual Styles. You'll probably need to create your own class or extend the progress bar:
public class NewProgressBar : ProgressBar
{
public NewProgressBar()
{
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rec = e.ClipRectangle;
rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - 4;
if(ProgressBarRenderer.IsSupported)
ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle);
rec.Height = rec.Height - 4;
e.Graphics.FillRectangle(Brushes.Red, 2, 2, rec.Width, rec.Height);
}
}
EDIT: Updated code to make the progress bar use the visual style for the background
Use the following functions to show/hide the keyboard:
/**
* Hides the soft keyboard
*/
public void hideSoftKeyboard() {
if(getCurrentFocus()!=null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
/**
* Shows the soft keyboard
*/
public void showSoftKeyboard(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
view.requestFocus();
inputMethodManager.showSoftInput(view, 0);
}
One option is to use the delete method as follows:
StringBuffer sb = new StringBuffer();
for (int n = 0; n < 10; n++) {
sb.append("a");
// This will clear the buffer
sb.delete(0, sb.length());
}
Another option (bit cleaner) uses setLength(int len):
sb.setLength(0);
See Javadoc for more info:
router.navigate
is just a convenience method that wraps router.navigateByUrl
, it boils down to:
navigate(commands: any[], extras) {
return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}
As mentioned in other answers router.navigateByUrl
will only accept absolute URLs:
// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})
All the relative calculations are done by router.createUrlTree
and router.navigate
. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".."
- go up, "path"
- go down, {expand: true}
- add query param, etc.. You can use it like this:
// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);
// assuming the current url is `/team/33/user/11` and the route points to `user/11`
// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});
// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});
// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});
That {relativeTo: route}
parameter is important as that's what router will use as the root for relative operations.
Get it through your component's constructor:
// In my-awesome.component.ts:
constructor(private route: ActivatedRoute, private router: Router) {}
// Example call
onNavigateClick() {
// Navigates to a parent component
this.router.navigate([..], { relativeTo: this.route })
}
Nicest thing about this directive is that it will retrieve the ActivatedRoute
for you. Under the hood it's using already familiar:
router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });
Following variants will produce identical result:
[routerLink]="['../..']"
// if the string parameter is passed it will be wrapped into an array
routerLink="../.."
For me this works fine and is also clean (Python 3)
def divisors(number):
n = 1
while(n<number):
if(number%n==0):
print(n)
else:
pass
n += 1
print(number)
Not very fast but returns divisors line by line as you wanted, also you can do list.append(n) and list.append(number) if you really want to
echo $PATH
and copy it's valueexport PATH=""
export PATH="/path/you/want/to/keep"
You need to rename your main class to Main
, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main
.
That's all.
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
Resolution fix: For me, the problem was related to active chrome sessions. I closed all of my chrome browser sessions and then tried building to chrome again. I am using Visual Studio Professional 2017 version 15.3.2. The VS application I was running into build errors with was a WebAPI project. When trying to click the green play button, I was getting dialog error stating "Unable to start the program 'http://localhost:18980/'. An operation is not legal in the current state. Hopefully this post helps someone.
Try changing your security mode to "transport".
You have a mismatch between the security tag and the transport tag.
To use the hex
encoding in Python 3, use
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
In legacy Python, there are several other ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
Yes there is a problem with Click event handler (klik) - First argument must be an object type and second must be EventArgs.
public void klik(object sender, EventArgs e) {
//
}
If you want to paint on a form or control then use CreateGraphics
method.
public void klik(object sender, EventArgs e) {
Bitmap c = this.DrawMandel();
Graphics gr = CreateGraphics(); // Graphics gr=(sender as Button).CreateGraphics();
gr.DrawImage(b, 150, 200);
}
A/code.cpp
#include <B/file.hpp>
A/a/code2.cpp
#include <B/file.hpp>
Compile using:
g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp
Edit:
You can use environment variables to change the path g++ looks for header files. From man page:
Some additional environments variables affect the behavior of the preprocessor.
CPATH C_INCLUDE_PATH CPLUS_INCLUDE_PATH OBJC_INCLUDE_PATH
Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon.
CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.
The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.
In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include.
There are many ways you can change an environment variable. On bash prompt you can do this:
$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp
You can of course add this in your Makefile etc.
This is the simple version, obviously you'll want to add some error checking:
var obj = {};
var pairs = queryString.split('&');
for(i in pairs){
var split = pairs[i].split('=');
obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
}
This should work:
start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2
The start
command interprets the first argument as a window title if it contains spaces. In this case, that means start
considers your whole argument a title and sees no command. Passing ""
(an empty title) as the first argument to start
fixes the problem.
HTML
<div class="selector">Text mates</div>
SCRIPT
alert(jQuery('.selector').text().length);
RESULT
10
For deleting use http://www.php.net/manual/en/function.unlink.php Hope you'll can to write logic?
input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);
open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.
So gaiour is right, but if you're looking for a full height item that doesn't scroll with the content, but is actually the height of the container, here's the fix. Have a parent with a height that causes overflow, a content container that has a 100% height and overflow: scroll
, and a sibling then can be positioned according to the parent size, not the scroll element size. Here is the fiddle: http://jsfiddle.net/M5cTN/196/
and the relevant code:
html:
<div class="container">
<div class="inner">
Lorem ipsum ...
</div>
<div class="full-height"></div>
</div>
css:
.container{
height: 256px;
position: relative;
}
.inner{
height: 100%;
overflow: scroll;
}
.full-height{
position: absolute;
left: 0;
width: 20%;
top: 0;
height: 100%;
}
Probably not the case of everybody but I had the same problem. I was using the last, in my case, the error was because I was using jfrog manage from the company where I am working.
npm config list
The result was
; cli configs
metrics-registry = "https://COMPANYNAME.jfrog.io/COMPANYNAM/api/npm/npm/"
scope = ""
user-agent = "npm/6.3.0 node/v8.11.2 win32 x64"
; userconfig C:\Users\USER\.npmrc
always-auth = true
email = "XXXXXXXXX"
registry = "https://COMPANYNAME.jfrog.io/COMPANYNAME/api/npm/npm/"
; builtin config undefined
prefix = "C:\\Users\\XXXXX\\AppData\\Roaming\\npm"
; node bin location = C:\Program Files\nodejs\node.exe
; cwd = C:\WINDOWS\system32
; HOME = C:\Users\XXXXXX
; "npm config ls -l" to show all defaults.
I solve the problem by using the global metrics.
Change setTimeout("changeImage()", 30000);
to setInterval("changeImage()", 30000);
and remove var timerid = setInterval(changeImage, 30000);
.
You can use actions for short event handlers:
btnSubmit.Click += (sender, e) => MessageBox.Show("You clicked save!");
<View style={{...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center'}}>
<Text>CENTERD TEXT</Text>
</View>
And add this
import {StyleSheet} from 'react-native';
You have some options
More work, best performance.
Less work, usually acceptable in web enviroments.
Less work, useful when OEMIV is not at option, for example in a Swing application, but may be useful too on repository implementations to initialize any entity in one shot.
For the last option, I wrote a utility class, JpaUtils to initilize entities at some deph.
For example:
@Transactional
public class RepositoryHelper {
@PersistenceContext
private EntityManager em;
public void intialize(Object entity, int depth) {
JpaUtils.initialize(em, entity, depth);
}
}
Regex for Facebook-like validation:
public static final String REGEX_EMAIL_VALIDATION = "^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-zA-Z]{2,})$";
Dto for Unit tests(with Lombok):
@Data
@Accessors(chain = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserCreateDto {
@NotNull
@Pattern(regexp = REGEX_EMAIL_VALIDATION)
@Size(min = 1, max = 254)
String email;
}
Valid/invalid emails below with Unit tests:
public class UserCreateValidationDtoTest {
private static final String[] VALID_EMAILS = new String[]{"[email protected]", "[email protected]",
"[email protected]", "[email protected]", "[email protected]",
"[email protected]", "[email protected]", "[email protected]",
"[email protected]", "[email protected]", "[email protected]"};
private static final String[] INVALID_EMAILS = new String[]{"[email protected]", "email@111",
"email", "[email protected]", "email123@gmail.", "[email protected]", "[email protected]",
"[email protected]", "email()*@gmAil.com", "eEmail()*@gmail.com", "email@%*.com", "[email protected]",
"[email protected]", "email@[email protected]", "[email protected]."};
private Validator validator;
@Before
public void setUp() throws Exception {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void emailValidationShouldBeValid() throws Exception {
Arrays.stream(VALID_EMAILS)
.forEach(email -> {
Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(
new UserCreateDto().setEmail(email));
System.out.println("Email: " + email + ", violations: " + violations);
Assert.assertTrue(violations.isEmpty());
}
);
}
@Test
public void emailValidationShouldBeNotValid() throws Exception {
Arrays.stream(INVALID_EMAILS)
.forEach(email -> {
Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(
new UserCreateDto().setEmail(email));
System.out.println("Email: " + email + ", violations: " + violations);
Assert.assertTrue(!violations.isEmpty());
}
);
}
private Set<ConstraintViolation<UserCreateDto>> validateEmail(UserCreateDto user) {
String emailFieldName = "email";
return validator.validateProperty(user, emailFieldName);
}
}
GitHub has a nice section called "Dealing with “non-fast-forward” errors"
This error can be a bit overwhelming at first, do not fear.
Simply put, git cannot make the change on the remote without losing commits, so it refuses the push.
Usually this is caused by another user pushing to the same branch. You can remedy this by fetching and merging the remote branch, or using pull to perform both at once.In other cases this error is a result of destructive changes made locally by using commands like
git commit --amend
orgit rebase
.
While you can override the remote by adding--force
to thepush
command, you should only do so if you are absolutely certain this is what you want to do.
Force-pushes can cause issues for other users that have fetched the remote branch, and is considered bad practice. When in doubt, don’t force-push.
Git cannot make changes on the remote like a fast-forward merge, which a Visual Git Reference illustrates like:
This is not exactly your case, but helps to see what "fast-forward" is (where the HEAD
of a branch is simply moved to a new more recent commit).
The "branch master->master (non-fast-forward) Already-up-to-date
" is usually for local branches which don't track their remote counter-part.
See for instance this SO question "git pull says up-to-date but git push rejects non-fast forward".
Or the two branches are connected, but in disagreement with their respective history:
See "Never-ending GIT story - what am I doing wrong here?"
This means that your subversion branch and your remote git master branch do not agree on something.
Some change was pushed/committed to one that is not in the other.
Fire upgitk --all
, and it should give you a clue as to what went wrong - look for "forks" in the history.
Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
actually it's not that simple, see the peer-review in the comments, especially:
=
(@AndrewF)+
(added by me)For further details, see MDN article and RFC 3986.
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
This function can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
I faced exactly the same issue. Calling '(!isFinishing())'
prevented the crash, but it could not display the 'alert' message.
Then I tried making calling function 'static', where alert is displayed. After that, no crash happened and message is also getting displayed.
For ex:
public static void connect_failure() {
Log.i(FW_UPD_APP, "Connect failed");
new AlertDialog.Builder(MyActivity)
.setTitle("Title")
.setMessage("Message")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//do nothing
}
})
.setIcon(R.drawable.the_image).show();
}
I was having same issue in IE9. I followed the above answer and I added the line:
<meta http-equiv="X-UA-Compatible" content="IE=8;FF=3;OtherUA=4" />
in my <head>
and it worked.
The best approach is using a lambda within "array_walk" native function to make the required changes:
array_walk($data, function (&$value, $key) {
if($key == 'transaction_date'){
$value = date('d/m/Y', $value);
}
});
The value is updated in the array as it's passed with as a reference "&".
I was able unable to locate the svn.simple
file, but was able to change credentials using the following three steps:
Checkout project from SVN
Select the repository you need to change the credentials on (note: you will not perform an checkout, but this will bring you to the screen to enter a username/password combination).
Finally, enter the new username and password credentials:
It's a bit confusing, because you begin the process of initializing a new project, but you're only resetting the repository credentials.
For Mac/Linux debug keystore, the Android docs have:
keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore
But there is something that may not be obvious: If you put the backslash, make sure to do a shift + return
in terminal after the backslash so that the second that starts with -alias
is on a new line. Simply pasting as-is will not work.
Your terminal (if successful) will look something like this:
$ keytool -exportcert -list -v \
? -alias androiddebugkey -keystore ~/.android/debug.keystore
Enter keystore password:
The default debug password is: android
Side note: In Android Studio you can manage signing in:
File > Project Structure > Modules - (Your App) > Signing
In httpd.conf file you need to remove #
#LoadModule rewrite_module modules/mod_rewrite.so
after removing # line will look like this:
LoadModule rewrite_module modules/mod_rewrite.so
And Apache restart
In my case I have some depencies in my library and when I create an aar
from it I failed, because of missed depencies, so my solution is to add all depencies from my lib with an arr
file.
So my project level build.gradle
looks so:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
}
}
allprojects {
repositories {
mavenCentral()
//add it to be able to add depency to aar-files from libs folder in build.gradle(yoursAppModule)
flatDir {
dirs 'libs'
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle(modile app)
so:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.example.sampleapp"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
//your project depencies
...
//add lib via aar-depency
compile(name: 'aarLibFileNameHere', ext: 'aar')
//add all its internal depencies, as arr don't have it
...
}
and library build.gradle
:
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
//here goes library projects dependencies, which you must include
//in yours build.gradle(modile app) too
...
}
If your RESTFul call sends XML Messages back and forth embedded in the Html Body of the HTTP request, you should be able to have all the benefits of WS-Security such as XML encryption, Cerificates, etc in your XML messages while using whatever security features are available from http such as SSL/TLS encryption.
Concatenation:
The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §2.2.1. Otherwise, the "concat" metamethod is called (see §2.8).
Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.
A simple get started:
Create test.cpp: (This will be built and run to verify you got things set up right.)
#include <X11/Xlib.h>
#include <unistd.h>
main()
{
// Open a display.
Display *d = XOpenDisplay(0);
if ( d )
{
// Create the window
Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
100, 0, CopyFromParent, CopyFromParent,
CopyFromParent, 0, 0);
// Show the window
XMapWindow(d, w);
XFlush(d);
// Sleep long enough to see the window.
sleep(10);
}
return 0;
}
Try: g++ test.cpp -lX11
If it builds to a.out
, try running it.
If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.
If your response is:
test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
compilation terminated.
you need to install X11 development libraries.
sudo apt-get install libx11-dev
Retry g++ test.cpp -lX11
If it works, you're golden.
Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb
Just put
echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";
inside the php code, then your style is incuded. Worked for me, I tried.
XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"
//production[not(contains(category,'Business'))]
I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.
There is another way to check - check the referrer. The first page usually will have an empty referrer...
if (document.referrer == "") {
window.close()
} else {
history.back()
}
Choose one class you want to view its documentation and press Ctrl+click over it, the Javadoc page will inform you that there is no Javadoc file attached and bellow will see a button named "Attach File". Press that button and browse to the directory where JDK is installed, normally for Win is C:\Program files\Java\jdk_xxx and inside this folder there is a src.zip file - sleect it and press OK and all is done - you already have Javadoc attached.
In my case I was using the prototype name as the object name. For e.g.
function proto1()
{}
var proto1 = new proto1();
It was a silly mistake but might be of help to someone like me ;)
Most likely that your key alias does not exist for your keystore file.
This answer should fix your signing issue ;)
This answer uses
git-filter-branch
, for which the docs now give this warning:git filter-branch has a plethora of pitfalls that can produce non-obvious manglings of the intended history rewrite (and can leave you with little time to investigate such problems since it has such abysmal performance). These safety and performance issues cannot be backward compatibly fixed and as such, its use is not recommended. Please use an alternative history filtering tool such as git filter-repo. If you still need to use git filter-branch, please carefully read SAFETY (and PERFORMANCE) to learn about the land mines of filter-branch, and then vigilantly avoid as many of the hazards listed there as reasonably possible.
Changing the author (or committer) would require re-writing all of the history. If you're okay with that and think it's worth it then you should check out git filter-branch. The man page includes several examples to get you started. Also note that you can use environment variables to change the name of the author, committer, dates, etc. -- see the "Environment Variables" section of the git man page.
Specifically, you can fix all the wrong author names and emails for all branches and tags with this command (source: GitHub help):
#!/bin/sh
git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
This is because findViewById()
searches in the activity_main
layout, while the button is located in the fragment's layout fragment_main
.
Move that piece of code in the onCreateView()
method of the fragment:
//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
Notice that now you access it through rootView
view:
Button buttonClick = (Button)rootView.findViewById(R.id.button);
otherwise you would get again NullPointerException.
To @R.. I think it's not enough to check errno
for error detection in strtol
call.
long strtol (const char *String, char **EndPointer, int Base)
You'll also need to check EndPointer
for errors.
wait until this call is finish its executing
You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground
execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.
To get result back in UI Thread start AsyncTask
as :
String str_result= new RunInBackGround().execute().get();
Here is a simple class that handles some basic validations on TextField
, using TextFormatter
introduced in JavaFX 8u40
EDIT:
(Code added regarding Floern's comment)
import java.text.DecimalFormatSymbols;
import java.util.regex.Pattern;
import javafx.beans.NamedArg;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
public class TextFieldValidator {
private static final String CURRENCY_SYMBOL = DecimalFormatSymbols.getInstance().getCurrencySymbol();
private static final char DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();
private final Pattern INPUT_PATTERN;
public TextFieldValidator(@NamedArg("modus") ValidationModus modus, @NamedArg("countOf") int countOf) {
this(modus.createPattern(countOf));
}
public TextFieldValidator(@NamedArg("regex") String regex) {
this(Pattern.compile(regex));
}
public TextFieldValidator(Pattern inputPattern) {
INPUT_PATTERN = inputPattern;
}
public static TextFieldValidator maxFractionDigits(int countOf) {
return new TextFieldValidator(maxFractionPattern(countOf));
}
public static TextFieldValidator maxIntegers(int countOf) {
return new TextFieldValidator(maxIntegerPattern(countOf));
}
public static TextFieldValidator integersOnly() {
return new TextFieldValidator(integersOnlyPattern());
}
public TextFormatter<Object> getFormatter() {
return new TextFormatter<>(this::validateChange);
}
private Change validateChange(Change c) {
if (validate(c.getControlNewText())) {
return c;
}
return null;
}
public boolean validate(String input) {
return INPUT_PATTERN.matcher(input).matches();
}
private static Pattern maxFractionPattern(int countOf) {
return Pattern.compile("\\d*(\\" + DECIMAL_SEPARATOR + "\\d{0," + countOf + "})?");
}
private static Pattern maxCurrencyFractionPattern(int countOf) {
return Pattern.compile("^\\" + CURRENCY_SYMBOL + "?\\s?\\d*(\\" + DECIMAL_SEPARATOR + "\\d{0," + countOf + "})?\\s?\\" +
CURRENCY_SYMBOL + "?");
}
private static Pattern maxIntegerPattern(int countOf) {
return Pattern.compile("\\d{0," + countOf + "}");
}
private static Pattern integersOnlyPattern() {
return Pattern.compile("\\d*");
}
public enum ValidationModus {
MAX_CURRENCY_FRACTION_DIGITS {
@Override
public Pattern createPattern(int countOf) {
return maxCurrencyFractionPattern(countOf);
}
},
MAX_FRACTION_DIGITS {
@Override
public Pattern createPattern(int countOf) {
return maxFractionPattern(countOf);
}
},
MAX_INTEGERS {
@Override
public Pattern createPattern(int countOf) {
return maxIntegerPattern(countOf);
}
},
INTEGERS_ONLY {
@Override
public Pattern createPattern(int countOf) {
return integersOnlyPattern();
}
};
public abstract Pattern createPattern(int countOf);
}
}
You can use it like this:
textField.setTextFormatter(new TextFieldValidator(ValidationModus.INTEGERS_ONLY).getFormatter());
or you can instantiate it in a fxml file, and apply it to a customTextField with the according properties.
app.fxml:
<fx:define>
<TextFieldValidator fx:id="validator" modus="INTEGERS_ONLY"/>
</fx:define>
CustomTextField.class:
public class CustomTextField {
private TextField textField;
public CustomTextField(@NamedArg("validator") TextFieldValidator validator) {
this();
textField.setTextFormatter(validator.getFormatter());
}
}
Use the variables "$1"
, "$2"
, "$3"
and so on to access arguments. To access all of them you can use "$@"
, or to get the count of arguments $#
(might be useful to check for too few or too many arguments).
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
There are several ways to do plots in R; lattice
is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:
Reasonstats <- read.table(text="Category Reason Species
Decline Genuine 24
Improved Genuine 16
Improved Misclassified 85
Decline Misclassified 41
Decline Taxonomic 2
Improved Taxonomic 7
Decline Unclear 41
Improved Unclear 117", header=T)
ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3 <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason
windows()
barplot(t(Reasonstats3), beside=TRUE, ylab="number of species",
cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
box(bty="l")
Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline
and for Improved
. Then I made those categories the column names. I also made the Reason
s the row names. The barplot()
function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot()
function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot()
wants for your intended output.
final File open = new File("PicDic.exe");
if (open.exists() == true) {
if (Desktop.isDesktopSupported()) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Desktop.getDesktop().open(open);
} catch (IOException ex) {
return;
}
}
});
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
//DocumentEditorView.this.getFrame().dispose();
System.exit(0);
}
});
} else {
JOptionPane.showMessageDialog(this.getFrame(), "Desktop is not support to open editor\n You should try manualy");
}
} else {
JOptionPane.showMessageDialog(this.getFrame(), "PicDic.exe is not found");
}
//you can start another apps by using it and can slit your whole project in many apps. it will work lot
Its more than just setting the connection to null. That may be what the documentation says, but that is not the truth for mysql. The connection will stay around for a bit longer (Ive heard 60s, but never tested it)
If you want to here the full explanation see this comment on the connections https://www.php.net/manual/en/pdo.connections.php#114822
To force the close the connection you have to do something like
$this->connection = new PDO();
$this->connection->query('KILL CONNECTION_ID()');
$this->connection = null;
you can update your war from the command line using java commands as mentioned here:
jar -uvf test.war yourclassesdir
Other useful commands:
Command to unzip/explode the war file
jar -xvf test.war
Command to create the war file
jar -cvf test.war yourclassesdir
Eg:
jar -cvf test.war *
jar -cvf test.war WEB-INF META-INF