Assuming that the order is the same in both objects, just stringify
them both and compare!
JSON.stringify(obj1) == JSON.stringify(obj2);
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
I found that that when I have two Get methods, one parameterless and one with a complex type as a parameter that I got the same error. I solved this by adding a dummy parameter of type int, named Id, as my first parameter, followed by my complex type parameter. I then added the complex type parameter to the route template. The following worked for me.
First get:
public IEnumerable<SearchItem> Get()
{
...
}
Second get:
public IEnumerable<SearchItem> Get(int id, [FromUri] List<string> layers)
{
...
}
WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{layers}",
defaults: new { id = RouteParameter.Optional, layers RouteParameter.Optional }
);
I feel like none of these messages quite answer the question still. See - https://api.slack.com/docs/message-attachments.
It requires you to put the link in an attachment. Hyperlinking is still not allowed in the body of the message.
{ "attachments": [ { ..., "text": " <https://honeybadger.io/path/to/event/|ReferenceError> - UI is not defined", ... ] }
ReferenceError
will be a hyperlink.
The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.
When page has no meta viewport tag:
When page has either of these two meta tags:
<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">
<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">
With <meta name="viewport" content="width=device-width">
:
With <meta name="viewport" content="height=device-height">
:
With <meta name="viewport" content="height=device-height,width=device-width">
:
With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">
With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">
Sleep meaning that thread is do nothing. Time is too large beacuse anthor thread query,but not disconnect server, default wait_timeout=28800;so you can set values smaller,eg 10. also you can kill the thread.
As of 2020, the most reliable password hashing algorithm in use, most likely to optimise its strength given any hardware, is Argon2id or Argon2i but not its Spring implementation.
The PBKDF2 standard includes the the CPU-greedy/computationally-expensive feature of the block cipher BCRYPT algo, and add its stream cipher capability. PBKDF2 was overwhelmed by the memory exponentially-greedy SCRYPT then by the side-channel-attack-resistant Argon2
Argon2 provides the necessary calibration tool to find optimized strength parameters given a target hashing time and the hardware used.
Memory greedy hashing would help against GPU use for cracking.
Spring security/Bouncy Castle implementation is not optimized and relatively week given what attacker could use. cf: Spring doc Argon2 and Scrypt
The currently implementation uses Bouncy castle which does not exploit parallelism/optimizations that password crackers will, so there is an unnecessary asymmetry between attacker and defender.
The most credible implementation in use for java is mkammerer's one,
a wrapper jar/library of the official native implementation written in C.
It is well written and simple to use.
The embedded version provides native builds for Linux, windows and OSX.
As an example, it is used by jpmorganchase in its tessera security project used to secure Quorum, its Ethereum cryptocurency implementation.
Here is an example:
final char[] password = "a4e9y2tr0ngAnd7on6P১M°RD".toCharArray();
byte[] salt = new byte[128];
new SecureRandom().nextBytes(salt);
final Argon2Advanced argon2 = Argon2Factory.createAdvanced(Argon2Factory.Argon2Types.ARGON2id);
byte[] hash = argon2.rawHash(10, 1048576, 4, password, salt);
(see tessera)
Declare the lib in your POM:
<dependency>
<groupId>de.mkammerer</groupId>
<artifactId>argon2-jvm</artifactId>
<version>2.7</version>
</dependency>
or with gradle:
compile 'de.mkammerer:argon2-jvm:2.7'
Calibration may be performed using de.mkammerer.argon2.Argon2Helper#findIterations
SCRYPT and Pbkdf2 algorithm might also be calibrated by writing some simple benchmark, but current minimal safe iterations values, will require higher hashing times.
simply execute -
git stash
it will remove all your local changes. and you can also use it later by executing -
git stash apply
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);_x000D_
_x000D_
app.controller("con",function($scope){_x000D_
$scope.class = "red";_x000D_
$scope.changeClass = function(){_x000D_
if ($scope.class === "red")_x000D_
$scope.class = "blue";_x000D_
else_x000D_
$scope.class = "red";_x000D_
};_x000D_
});
_x000D_
.red{_x000D_
color:red;_x000D_
}_x000D_
_x000D_
.blue{_x000D_
color:blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="ap" ng-controller="con">_x000D_
<div ng-class="class">{{class}}</div>_x000D_
<button ng-click="changeClass()">Change Class</button> _x000D_
</body>
_x000D_
Here is the example working on jsFiddle
One can also use requests if we would like to access a web page using proxies. Python 3 code:
>>> import requests
>>> url = 'http://www.google.com'
>>> proxy = '169.50.87.252:80'
>>> requests.get(url, proxies={"http":proxy})
<Response [200]>
More than one proxies can also be added.
>>> proxy1 = '169.50.87.252:80'
>>> proxy2 = '89.34.97.132:8080'
>>> requests.get(url, proxies={"http":proxy1,"http":proxy2})
<Response [200]>
Typically, a Json object would contain your values (including arrays) as named fields within. So, something like:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName",ja);
Which in JSON will be {"arrayName":[...]}.
If you're positive that you will never use this code in a compiler that doesn't support it (Windows/VS, GCC, and Clang are examples of compilers that do support it), then you can certainly use #pragma once without worries.
You can also just use both (see example below), so that you get portability and compilation speedup on compatible systems
#pragma once
#ifndef _HEADER_H_
#define _HEADER_H_
...
#endif
I've ran into the same problem recently. After finding the correct path to the pyuic4 file using the file finder I've ran:
C:\Users\ricckli.qgis2\python\plugins\qgis2leaf>C:\OSGeo4W64\bin\pyuic4 -o ui_q gis2leaf.py ui_qgis2leaf.ui
As you can see my ui file was placed in this folder...
QT Creator was installed separately and the pyuic4 file was placed there with the OSGEO4W installer
You can check if jQuery is loaded or not by many ways such as:
if (typeof jQuery == 'undefined') {
// jQuery IS NOT loaded, do stuff here.
}
if (typeof jQuery == 'function')
//or
if (typeof $== 'function')
if (jQuery) {
// This will throw an error in STRICT MODE if jQuery is not loaded, so don't use if using strict mode
alert("jquery is loaded");
} else {
alert("Not loaded");
}
if( 'jQuery' in window ) {
// Do Stuff
}
Now after checking if jQuery is not loaded, you can load jQuery like this:
Although this part has been answered by many in this post but still answering for the sake of completeness of the code
// This part should be inside your IF condition when you do not find jQuery loaded
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-3.3.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
All 3 of them represent the end of a line. But...
\r
(Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line\n
(Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n
moves to the beginning of the line.\r\n
(End Of Line) → a combination of \r
and \n
This happens because document.write
would overwrite your existing code therefore place your div
before your javascript code. e.g.:
CSS:
#mydiv {
visibility:hidden;
}
Inside your html file
<div id="mydiv">
<p>Hello world</p>
</div>
<script type="text/javascript">
document.getElementById('mydiv').style.visibility='visible';
</script>
Hope this was helpful
Public Sub PDFTxtToPdf(ByVal sTxtfile As String, ByVal sPDFSourcefile As String)
Dim sr As StreamReader = New StreamReader(sTxtfile)
Dim doc As New Document()
PdfWriter.GetInstance(doc, New FileStream(sPDFSourcefile, FileMode.Create))
doc.Open()
doc.Add(New Paragraph(sr.ReadToEnd()))
doc.Close()
End Sub
Based on Daniel Krom's solution. This is version in swift 3.0. Works great with AutoLayout, and moves whole view when keyboard appears.
extension UIView {
func bindToKeyboard(){
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
func unbindFromKeyboard(){
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
@objc
func keyboardWillChange(notification: NSNotification) {
guard let userInfo = notification.userInfo else { return }
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
let curFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let targetFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = targetFrame.origin.y - curFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
})
}
}
How to use it:
Add bindToKeyboard
function in viewDidLoad
like:
override func viewDidLoad() {
super.viewDidLoad()
view.bindToKeyboard()
}
And add unbindFromKeyboard
function in deinit:
deinit {
view.unbindFromKeyboard()
}
You can import modules but not text files. If you want to print the content do the following:
Open a text file for reading:
f = open('words.txt', 'r')
Store content in a variable:
content = f.read()
Print content of this file:
print(content)
After you're done close a file:
f.close()
$("input[placeholder]").each(function () {
$(this).attr("data-placeholder", this.placeholder);
$(this).bind("focus", function () {
this.placeholder = '';
});
$(this).bind("blur", function () {
this.placeholder = $(this).attr("data-placeholder");
});
});
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
The server first tries to authenticate you by public key. That doesn't work (I guess you haven't set one up), so it then falls back to 'keyboard-interactive'. It should then ask you for a password, which presumably you're not getting right. Did you see a password prompt?
{
"number" : ["1","2","3"],
"alphabet" : ["a", "b", "c"]
}
Using Maria-DB and DB-Navigator tool inside IntelliJ, MODIFY Column worked for me instead of Alter Column
I was trying to solve the same with a list of objects and was having issues because I was trying to repack the list of groups into the original list. So I came up with looping through the groups to repack the original List with items that have duplicates.
public List<MediaFileInfo> GetDuplicatePictures()
{
List<MediaFileInfo> dupes = new List<MediaFileInfo>();
var grpDupes = from f in _fileRepo
group f by f.Length into grps
where grps.Count() >1
select grps;
foreach (var item in grpDupes)
{
foreach (var thing in item)
{
dupes.Add(thing);
}
}
return dupes;
}
I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.
Basically the solution is to use CSS to hide the <input>
element and style a <label>
around it to look like a button. Click the 'Run code snippet' button to see the results.
I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.
label.cameraButton {_x000D_
display: inline-block;_x000D_
margin: 1em 0;_x000D_
_x000D_
/* Styles to make it look like a button */_x000D_
padding: 0.5em;_x000D_
border: 2px solid #666;_x000D_
border-color: #EEE #CCC #CCC #EEE;_x000D_
background-color: #DDD;_x000D_
}_x000D_
_x000D_
/* Look like a clicked/depressed button */_x000D_
label.cameraButton:active {_x000D_
border-color: #CCC #EEE #EEE #CCC;_x000D_
}_x000D_
_x000D_
/* This is the part that actually hides the 'Choose file' text box for camera inputs */_x000D_
label.cameraButton input[accept*="camera"] {_x000D_
display: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Nice image capture button</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<label class="cameraButton">Take a picture_x000D_
<input type="file" accept="image/*;capture=camera">_x000D_
</label>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
You can check the String.match
() or the String.indexOf()
methods.
_MSC_VER
and possibly _MSC_FULL_VER
is what you need. You can also examine visualc.hpp in any recent boost install for some usage examples.
Some values for the more recent versions of the compiler are:
MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)
MSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 version 16.3)
MSVC++ 14.22 _MSC_VER == 1922 (Visual Studio 2019 version 16.2)
MSVC++ 14.21 _MSC_VER == 1921 (Visual Studio 2019 version 16.1)
MSVC++ 14.2 _MSC_VER == 1920 (Visual Studio 2019 version 16.0)
MSVC++ 14.16 _MSC_VER == 1916 (Visual Studio 2017 version 15.9)
MSVC++ 14.15 _MSC_VER == 1915 (Visual Studio 2017 version 15.8)
MSVC++ 14.14 _MSC_VER == 1914 (Visual Studio 2017 version 15.7)
MSVC++ 14.13 _MSC_VER == 1913 (Visual Studio 2017 version 15.6)
MSVC++ 14.12 _MSC_VER == 1912 (Visual Studio 2017 version 15.5)
MSVC++ 14.11 _MSC_VER == 1911 (Visual Studio 2017 version 15.3)
MSVC++ 14.1 _MSC_VER == 1910 (Visual Studio 2017 version 15.0)
MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015 version 14.0)
MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013 version 12.0)
MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012 version 11.0)
MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010 version 10.0)
MSVC++ 9.0 _MSC_FULL_VER == 150030729 (Visual Studio 2008, SP1)
MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008 version 9.0)
MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005 version 8.0)
MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003 version 7.1)
MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002 version 7.0)
MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0 version 6.0)
MSVC++ 5.0 _MSC_VER == 1100 (Visual Studio 97 version 5.0)
The version number above of course refers to the major version of your Visual studio you see in the about box, not to the year in the name. A thorough list can be found here. Starting recently, Visual Studio will start updating its ranges monotonically, meaning you should check ranges, rather than exact compiler values.
cl.exe /?
will give a hint of the used version, e.g.:
c:\program files (x86)\microsoft visual studio 11.0\vc\bin>cl /?
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86
.....
In IIS7 with integrated mode, Current
is not available in Application_Start
. There is a similar thread here.
I would use the "count" for having always an integer as a result
SqlCommand check_User_Name = new SqlCommand("SELECT count([user]) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') " , conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist == 1) //anything different from 1 should be wrong
{
//Username Exist
}
If you want to identify slow queries, than the method is to use log_min_duration_statement setting (in postgresql.conf or set per-database with ALTER DATABASE SET).
When you logged the data, you can then use grep or some specialized tools - like pgFouine or my own analyzer - which lacks proper docs, but despite this - runs quite well.
AND (&&
):
.registration_form_right input:not([type="radio"]):not([type="checkbox"])
OR (||
):
.registration_form_right input:not([type="radio"]),
.registration_form_right input:not([type="checkbox"])
Can do the following
PRINT dbo.[FunctionName] ( [Parameter/Argument] )
E.g.:
PRINT dbo.StringSplit('77,54')
string minusvalue = TextBox1.Text.ToString();
if (Convert.ToDouble(minusvalue) < 0)
{
// set color of text in TextBox1 to red color and bold.
TextBox1.ForeColor = Color.Red;
}
<script type="text/JavaScript">
function validate()
{
if( document.form1.quali.value == "-1" )
{
alert( "Please select qualification!" );
return false;
}
}
</script>
<form name="form1" method="post" action="" onsubmit="return validate(this);">
<select name="quali" id="quali" ">
<option value="-1" selected="selected">select</option>
<option value="1">Graduate</option>
<option value="2">Post Graduate</option>
</select>
</form>
// this code works 110% tested by me after many complex jquery method validation but it is simple javascript method plz try this if u fail in drop down required validation//
Frankly, this looks like a semantic distinction, not a technical distinction. The phrase Data Access Object doesn't refer to a "database" at all. And, although you could design it to be database-centric, I think most people would consider doing so a design flaw.
The purpose of the DAO is to hide the implementation details of the data access mechanism. How is the Repository pattern different? As far as I can tell, it isn't. Saying a Repository is different to a DAO because you're dealing with/return a collection of objects can't be right; DAOs can also return collections of objects.
Everything I've read about the repository pattern seems rely on this distinction: bad DAO design vs good DAO design (aka repository design pattern).
SELECT SUBSTR(thatColumn, 1, 1) As NewColumn from student
You can also use blank single quotes for the auto_increment column. something like this. It worked for me.
$query = "INSERT INTO myTable VALUES ('','Fname', 'Lname', 'Website')";
I don't think it's good to generally turn off CSRF protection as long as you don't exclusively implement an API.
When looking at the Rails 4 API documentation for ActionController I found that you can turn off forgery protection on a per controller or per method base.
For example to turn off CSRF protection for methods you can use
class FooController < ApplicationController
protect_from_forgery except: :index
In main.xml file
You can put the following attrubute to validate only alphabatics character can accept in edittext.
Do this :
android:entries="abcdefghijklmnopqrstuvwxyz"
For adding zeros I really don't see the need to have a full other function where you can simply use for example
var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);
Its why we have conditional statements in the first place.
(condition?if true:if false) so if example seconds is more than 9 than just show seconds else add a string 0 before it.
Use time.sleep
or Event().wait
like this:
from threading import Event
from time import sleep
delay_in_sec = 2
# Use time.sleep like this
sleep(delay_in_sec) # Returns None
print(f'slept for {delay_in_sec} seconds')
# Or use Event().wait like this
Event().wait(delay_in_sec) # Returns False
print(f'waited for {delay_in_sec} seconds')
Use threading.Timer
like this:
from threading import Timer
delay_in_sec = 2
def hello(delay_in_sec):
print(f'function called after {delay_in_sec} seconds')
t = Timer(delay_in_sec, hello, [delay_in_sec]) # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start() # Returns None
print("Started")
Outputs:
Started
function called after 2 seconds
timer_obj.cancel()
.This will not work correctly, e.g. abcÑxyz
will pass thru this as it has a,b,c... you need to work with Collate or check each byte.
Since you asked for a way to complete this within an HTML
page I am answering this. I feel there is no need to mention the severe warnings and implications that would go along with this .. I trust you know the security of your .py
script better than I do :-)
I would use the .ajax()
function in the jQuery
library. This will allow you to call your Python
script as long as the script is in the publicly accessible html directory ... That said this is the part where I tell you to heed security precautions ...
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
function goPython(){
$.ajax({
url: "MYSCRIPT.py",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</body>
</html>
In addition .. It's worth noting that your script is going to have to have proper permissions for, say, the www-data
user to be able to run it ... A chmod
, and/or a chown
may be necessary.
Given a quadratic equation: x2 − 4.0000000 x + 3.9999999 = 0, the exact roots to 10 significant digits are, r1 = 2.000316228 and r2 = 1.999683772.
Using float
and double
, we can write a test program:
#include <stdio.h>
#include <math.h>
void dbl_solve(double a, double b, double c)
{
double d = b*b - 4.0*a*c;
double sd = sqrt(d);
double r1 = (-b + sd) / (2.0*a);
double r2 = (-b - sd) / (2.0*a);
printf("%.5f\t%.5f\n", r1, r2);
}
void flt_solve(float a, float b, float c)
{
float d = b*b - 4.0f*a*c;
float sd = sqrtf(d);
float r1 = (-b + sd) / (2.0f*a);
float r2 = (-b - sd) / (2.0f*a);
printf("%.5f\t%.5f\n", r1, r2);
}
int main(void)
{
float fa = 1.0f;
float fb = -4.0000000f;
float fc = 3.9999999f;
double da = 1.0;
double db = -4.0000000;
double dc = 3.9999999;
flt_solve(fa, fb, fc);
dbl_solve(da, db, dc);
return 0;
}
Running the program gives me:
2.00000 2.00000
2.00032 1.99968
Note that the numbers aren't large, but still you get cancellation effects using float
.
(In fact, the above is not the best way of solving quadratic equations using either single- or double-precision floating-point numbers, but the answer remains unchanged even if one uses a more stable method.)
Probably easiest way is to PInvoke LogonUser Win32 API.e.g.
MSDN Reference here...
Definitely want to use logon type
LOGON32_LOGON_NETWORK (3)
This creates a lightweight token only - perfect for AuthN checks. (other types can be used to build interactive sessions etc.)
If you need to find database objects (e.g. tables, columns, and triggers) by name - have a look at the free Redgate Software tool called SQL Search which does this - it searches your entire database for any kind of string(s).
It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely free to use for any kind of use??
just remove this because constructor don't have a return type like void it will be like this :
private Flow()
{
X = x;
Y = y;
}
I corrected my path variable but command prompt need to Restart otherwise, it won't be able to verify the change to the path variable. May be helpful for someone like me. so "restart command prompt"
I had a similar issue where I wanted a banner across the top of the screen that had one image on the left and a repeating image on the right to the edge of the screen. I ended up resolving it like so:
CSS:
.banner_left {
position: absolute;
top: 0px;
left: 0px;
width: 131px;
height: 150px;
background-image: url("left_image.jpg");
background-repeat: no-repeat;
}
.banner_right {
position: absolute;
top: 0px;
left: 131px;
right: 0px;
height: 150px;
background-image: url("right_repeating_image.jpg");
background-repeat: repeat-x;
background-position: top left;
}
The key was the right tag. I'm basically specifying that I want it to repeat from 131px in from the left to 0px from the right.
You can also create a project repository. It's useful if more developers are working on the same project, and the library must be included in the project.
First, create a repository structure in your project's lib directory, and then copy the library into it. The library must have following name-format: <artifactId>-<version>.jar
<your_project_dir>/lib/com/microsoft/sqlserver/<artifactId>/<version>/
Create pom file next to the library file, and put following information into it:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.2.0</modelVersion>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.2</version>
</project>
At this point, you should have this directory structure:
<your_project_dir>/lib/com/microsoft/sqlserver/sqljdbc4/4.2/sqljdbc4-4.2.jar
<your_project_dir>/lib/com/microsoft/sqlserver/sqljdbc4/4.2/sqljdbc4-4.2.pom
Go to your project's pom file and add new repository:
<repositories>
<repository>
<id>Project repository</id>
<url>file://${basedir}/lib</url>
</repository>
</repositories>
Finally, add a dependency on the library:
<dependencies>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.2</version>
</dependency>
</dependencies>
Update 2017-03-04
It seems like the library can be obtained from publicly available repository. @see nirmal's and Jacek Grzelaczyk's answers for more details.
Update 2020-11-04
Currently Maven has a convenient target install
which allow you to deploy an existing package into a project / file repository without the need of creating POM files manually. It will generate those files for you.
mvn install:install-file \
-Dfile=sqljdbc4.jar \
-DgroupId=com.microsoft.sqlserver \
-DartifactId=sqljdbc4 \
-Dversion=4.2 \
-Dpackaging=jar \
-DlocalRepositoryPath=${your_project_dir}/lib
I tried all above steps to resolve the problem but nothing worked. I had installed both JDK and JRE.
In my case, one jar file was being opened by double click while other was not being opened. I examined those files and the probable reason was that which was being opened, was created using JAVA SE 6 and the one not being opened was created using JAVA SE 7. Although, the problematic jar file was being run via command prompt (java -jar myfile.jar).
I tried Right Click -> Properties -> Change to javaw.exe with both in JDK\bin directory and JRE\bin directory.
I was finally able to fix the problem by changing javaw.exe path (from JDK\bin to JRE\bin) in registry editor.
Go to HKEY_CLASSES_ROOT\jarfile\shell\open\command, the value was,
"C:\Program Files\Java\jdk-11.0.1\bin\javaw.exe" -jar "%1" %*
I changed it to,
"C:\Program Files\Java\jre1.8.0_191\bin\javaw.exe" -jar "%1" %*
and it worked. Now the jar file can be opened by double click.
I had the exact same problem while trying to setup a Gitlab pipeline executed by a Docker runner installed on a Raspberry Pi 4
Using nload
to follow bandwidth usage within Docker runner container while pipeline was cloning the repo i saw the network usage dropped down to a few bytes per seconds..
After a some deeper investigations i figured out that the Raspberry temperature was too high and the network card start to dysfunction above 50° Celsius.
Adding a fan to my Raspberry solved the issue.
You could use this strategy described here as best practice (2006) or an updated strategy described here (2015):
This approach provides defense-in-depth. If someone manages to leak the database table, it does not give an attacker an open door for impersonating users.
The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector<const int>
is not allowed.
Your problem is that the indices returned by match.start()
correspond to the position of the character as it appeared in the original string when you matched it; however, as you rewrite the string c
every time, these indices become incorrect.
The best approach to solve this is to use replaceAll
, for example:
System.out.println(c.replaceAll("[^a-zA-Z0-9]", ""));
Hey I followed some sequence above, and found some solution.
SHOW CREATE TABLE footable;
You will get FK Constrain Name like
ProjectsInfo_ibfk_1
Now you need to remove this constraints. by alter table commantd
alter table ProjectsInfo drop foreign key ProjectsInfo_ibfk_1;
Then drop the table column,
alter table ProjectsInfo drop column clientId;
Disclaimer: This answer works, but is intended for educational purposes only. :) James Jones' solution is probably the best here and certainly the one I'd go with.
C# 4.0's dynamic
keyword makes this even easier, if less safe:
public static dynamic GetNullableValue(this IDataRecord record, string columnName)
{
var val = reader[columnName];
return (val == DBNull.Value ? null : val);
}
Now you don't need the explicit type hinting on the RHS:
int? value = myDataReader.GetNullableValue("MyColumnName");
In fact, you don't need it anywhere!
var value = myDataReader.GetNullableValue("MyColumnName");
value
will now be an int, or a string, or whatever type was returned from the DB.
The only problem is that this does not prevent you from using non-nullable types on the LHS, in which case you'll get a rather nasty runtime exception like:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot convert null to 'int' because it is a non-nullable value type
As with all code that uses dynamic
: caveat coder.
You can better achieve it by using the DrawableCompat like this:
Drawable backgroundDrawable = view.getBackground();
DrawableCompat.setTint(backgroundDrawable, newColor);
I don't know TeamCity so I hope this can work for you.
The best way I've found to do this is with MSDeploy.exe. This is part of the WebDeploy project run by Microsoft. You can download the bits here.
With WebDeploy, you run the command line
msdeploy.exe -verb:sync -source:contentPath=c:\webApp -dest:contentPath=c:\DeployedWebApp
This does the same thing as the VS Publish command, copying only the necessary bits to the deployment folder.
You can solve any equation including adding with this code:
@echo off
title Richie's Calculator 3.0
:main
echo Welcome to Richie's Calculator 3.0
echo Press any key to begin calculating...
pause>nul
echo Enter An Equation
echo Example: 1+1
set /p
set /a sum=%equation%
echo.
echo The Answer Is:
echo %sum%
echo.
echo Press any key to return to the main menu
pause>nul
cls
goto main
BaileyP's answer is already pretty good, but I would use this condition instead:
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() === 1){
$_POST = array_map( 'stripslashes', $_POST );
$_GET = array_map( 'stripslashes', $_GET );
$_COOKIE = array_map( 'stripslashes', $_COOKIE );
}
It is more defensive.
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value)
no add(value)
.
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
:w
- Write a file.
!sudo
- Call shell sudo command.
tee
- The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):
See .offset()
here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset()
and .position()
confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop()
and .scrollLeft()
values to account for the scrolled position.
Here's an excerpt from the doc:
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.
To combine these:
var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft();
You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/
The ENABLEDELAYEDEXPANSION part is REQUIRED in certain programs that use delayed expansion, that is, that takes the value of variables that were modified inside IF or FOR commands by enclosing their names in exclamation-marks.
If you enable this expansion in a script that does not require it, the script behaves different only if it contains names enclosed in exclamation-marks !LIKE! !THESE!. Usually the name is just erased, but if a variable with the same name exist by chance, then the result is unpredictable and depends on the value of such variable and the place where it appears.
The SETLOCAL part is REQUIRED in just a few specialized (recursive) programs, but is commonly used when you want to be sure to not modify any existent variable with the same name by chance or if you want to automatically delete all the variables used in your program. However, because there is not a separate command to enable the delayed expansion, programs that require this must also include the SETLOCAL part.
The libraries mentioned in other answers would be fine solutions, but if you already happen to be digging through real-world html in your project, the Jsoup
project has a lot more to offer than just managing "ampersand pound FFFF semicolon" things.
// textValue: <p>This is a sample. \"Granny\" Smith –.<\/p>\r\n
// becomes this: This is a sample. "Granny" Smith –.
// with one line of code:
// Jsoup.parse(textValue).getText(); // for older versions of Jsoup
Jsoup.parse(textValue).text();
// Another possibility may be the static unescapeEntities method:
boolean strictMode = true;
String unescapedString = org.jsoup.parser.Parser.unescapeEntities(textValue, strictMode);
And you also get the convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods. It's open source and MIT licence.
I implemented this in java and ran a unit test (source below). None of the above solutions work. This code passes the unit test. If anyone finds a unit test that does not pass, please let me know.
Code: NOTE: nearlyEqual(double,double)
returns true if the two numbers are very close.
/*
* @return integer code for which side of the line ab c is on. 1 means
* left turn, -1 means right turn. Returns
* 0 if all three are on a line
*/
public static int findSide(
double ax, double ay,
double bx, double by,
double cx, double cy) {
if (nearlyEqual(bx-ax,0)) { // vertical line
if (cx < bx) {
return by > ay ? 1 : -1;
}
if (cx > bx) {
return by > ay ? -1 : 1;
}
return 0;
}
if (nearlyEqual(by-ay,0)) { // horizontal line
if (cy < by) {
return bx > ax ? -1 : 1;
}
if (cy > by) {
return bx > ax ? 1 : -1;
}
return 0;
}
double slope = (by - ay) / (bx - ax);
double yIntercept = ay - ax * slope;
double cSolution = (slope*cx) + yIntercept;
if (slope != 0) {
if (cy > cSolution) {
return bx > ax ? 1 : -1;
}
if (cy < cSolution) {
return bx > ax ? -1 : 1;
}
return 0;
}
return 0;
}
Here's the unit test:
@Test public void testFindSide() {
assertTrue("1", 1 == Utility.findSide(1, 0, 0, 0, -1, -1));
assertTrue("1.1", 1 == Utility.findSide(25, 0, 0, 0, -1, -14));
assertTrue("1.2", 1 == Utility.findSide(25, 20, 0, 20, -1, 6));
assertTrue("1.3", 1 == Utility.findSide(24, 20, -1, 20, -2, 6));
assertTrue("-1", -1 == Utility.findSide(1, 0, 0, 0, 1, 1));
assertTrue("-1.1", -1 == Utility.findSide(12, 0, 0, 0, 2, 1));
assertTrue("-1.2", -1 == Utility.findSide(-25, 0, 0, 0, -1, -14));
assertTrue("-1.3", -1 == Utility.findSide(1, 0.5, 0, 0, 1, 1));
assertTrue("2.1", -1 == Utility.findSide(0,5, 1,10, 10,20));
assertTrue("2.2", 1 == Utility.findSide(0,9.1, 1,10, 10,20));
assertTrue("2.3", -1 == Utility.findSide(0,5, 1,10, 20,10));
assertTrue("2.4", -1 == Utility.findSide(0,9.1, 1,10, 20,10));
assertTrue("vertical 1", 1 == Utility.findSide(1,1, 1,10, 0,0));
assertTrue("vertical 2", -1 == Utility.findSide(1,10, 1,1, 0,0));
assertTrue("vertical 3", -1 == Utility.findSide(1,1, 1,10, 5,0));
assertTrue("vertical 3", 1 == Utility.findSide(1,10, 1,1, 5,0));
assertTrue("horizontal 1", 1 == Utility.findSide(1,-1, 10,-1, 0,0));
assertTrue("horizontal 2", -1 == Utility.findSide(10,-1, 1,-1, 0,0));
assertTrue("horizontal 3", -1 == Utility.findSide(1,-1, 10,-1, 0,-9));
assertTrue("horizontal 4", 1 == Utility.findSide(10,-1, 1,-1, 0,-9));
assertTrue("positive slope 1", 1 == Utility.findSide(0,0, 10,10, 1,2));
assertTrue("positive slope 2", -1 == Utility.findSide(10,10, 0,0, 1,2));
assertTrue("positive slope 3", -1 == Utility.findSide(0,0, 10,10, 1,0));
assertTrue("positive slope 4", 1 == Utility.findSide(10,10, 0,0, 1,0));
assertTrue("negative slope 1", -1 == Utility.findSide(0,0, -10,10, 1,2));
assertTrue("negative slope 2", -1 == Utility.findSide(0,0, -10,10, 1,2));
assertTrue("negative slope 3", 1 == Utility.findSide(0,0, -10,10, -1,-2));
assertTrue("negative slope 4", -1 == Utility.findSide(-10,10, 0,0, -1,-2));
assertTrue("0", 0 == Utility.findSide(1, 0, 0, 0, -1, 0));
assertTrue("1", 0 == Utility.findSide(0,0, 0, 0, 0, 0));
assertTrue("2", 0 == Utility.findSide(0,0, 0,1, 0,2));
assertTrue("3", 0 == Utility.findSide(0,0, 2,0, 1,0));
assertTrue("4", 0 == Utility.findSide(1, -2, 0, 0, -1, 2));
}
The reason of such behaviour is that the string that is printed is the exact value - probably not what you expected, but that's the real value stored in memory - it's just a limitation of floating point representation.
According to javadoc, BigDecimal(double val) constructor behaviour can be unexpected if you don't take into consideration this limitation:
The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
So in your case, instead of using
double val = 77.48;
new BigDecimal(val);
use
BigDecimal.valueOf(val);
Value that is returned by BigDecimal.valueOf is equal to that resulting from invocation of Double.toString(double)
.
For those running JPA in Spring, from version 3.1 onwards, you can set packagesToScan
property under LocalContainerEntityManagerFactoryBean
and get rid of persistence.xml altogether.
I'm late, but:
BufferReader.java:
public BufferedReader(Reader in) {
this(in, defaultCharBufferSize);
}
(...)
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
try {
in.close();
} finally {
in = null;
cb = null;
}
}
}
def get_rounded_datetime(self, dt, freq, nearest_type='inf'):
if freq.lower() == '1h':
round_to = 3600
elif freq.lower() == '3h':
round_to = 3 * 3600
elif freq.lower() == '6h':
round_to = 6 * 3600
else:
raise NotImplementedError("Freq %s is not handled yet" % freq)
# // is a floor division, not a comment on following line:
seconds_from_midnight = dt.hour * 3600 + dt.minute * 60 + dt.second
if nearest_type == 'inf':
rounded_sec = int(seconds_from_midnight / round_to) * round_to
elif nearest_type == 'sup':
rounded_sec = (int(seconds_from_midnight / round_to) + 1) * round_to
else:
raise IllegalArgumentException("nearest_type should be 'inf' or 'sup'")
dt_midnight = datetime.datetime(dt.year, dt.month, dt.day)
return dt_midnight + datetime.timedelta(0, rounded_sec)
In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.
If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.
#include <stdio.h>
#include <stdlib.h>
void handle_line(char *line) {
printf("%s", line);
}
int main(int argc, char *argv[]) {
int size = 1024, pos;
int c;
char *buffer = (char *)malloc(size);
FILE *f = fopen("myfile.txt", "r");
if(f) {
do { // read all lines in file
pos = 0;
do{ // read one line
c = fgetc(f);
if(c != EOF) buffer[pos++] = (char)c;
if(pos >= size - 1) { // increase buffer length - leave room for 0
size *=2;
buffer = (char*)realloc(buffer, size);
}
}while(c != EOF && c != '\n');
buffer[pos] = 0;
// line is now in buffer
handle_line(buffer);
} while(c != EOF);
fclose(f);
}
free(buffer);
return 0;
}
overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.
overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.
overflow: hidden;
would remove both scrollbars
It's a pretty old post, but I want to add something about appending one array to another:
If
you can use array functions like this:
array_merge(array_values($array), array_values($appendArray));
array_merge doesn't merge numeric keys so it appends all values of $appendArray. While using native php functions instead of a foreach-loop, it should be faster on arrays with a lot of elements.
Addition 2019-12-13: Since PHP 7.4, there is the possibility to append or prepend arrays the Array Spread Operator way:
$a = [3, 4];
$b = [1, 2, ...$a];
As before, keys can be an issue with this new feature:
$a = ['a' => 3, 'b' => 4];
$b = ['c' => 1, 'a' => 2, ...$a];
"Fatal error: Uncaught Error: Cannot unpack array with string keys"
$a = [3 => 3, 4 => 4];
$b = [1 => 1, 4 => 2, ...$a];
array(4) { [1]=> int(1) [4]=> int(2) [5]=> int(3) [6]=> int(4) }
$a = [1 => 1, 2 => 2];
$b = [...$a, 3 => 3, 1 => 4];
array(3) { [0]=> int(1) [1]=> int(4) [3]=> int(3) }
This came from a time before Java 1.5 exists and bring enums to us. Prior to that, there was no good way to define a set of constants or constrained values.
This is still used, most of the time either for backward compatibility or due to the amount of refactoring needed to get rid off, in a lot of project.
It is because creator of the SSIS packages is someone else and other person is executing the packages.
If suppose A person has created SSIS packages and B person is trying to execute than the above error comes.
You can solve the error by changing creator name from package properties from A to B.
Thanks, Kiran Sagar
Here is how POST HTTP request works for iOS 8+ using NSURLSession:
- (void)call_PostNetworkingAPI:(NSURL *)url withCompletionBlock:(void(^)(id object,NSError *error,NSURLResponse *response))completion
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
config.URLCache = nil;
config.timeoutIntervalForRequest = 5.0f;
config.timeoutIntervalForResource =10.0f;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
NSMutableURLRequest *Req=[NSMutableURLRequest requestWithURL:url];
[Req setHTTPMethod:@"POST"];
NSURLSessionDataTask *task = [session dataTaskWithRequest:Req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if (dict != nil) {
completion(dict,error,response);
}
}else
{
completion(nil,error,response);
}
}];
[task resume];
}
Hope this will satisfy your following requirement.
Laravel provides a Query Builder with lists() function
In your case, you can replace your code
$items = Items::all(['id', 'name']);
with
$items = Items::lists('name', 'id');
Also, you can chain it with other Query Builder as well.
$items = Items::where('active', true)->orderBy('name')->lists('name', 'id');
source: http://laravel.com/docs/5.0/queries#selects
Update for Laravel 5.2
Thank you very much @jarry. As you mentioned, the function for Laravel 5.2 should be
$items = Items::pluck('name', 'id');
or
$items = Items::where('active', true)->orderBy('name')->pluck('name', 'id');
ref: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0 -- look at Deprecations lists
This can be easily done using the tags
The example of tags is defined below:
---
hosts: localhost
tasks:
- name: Creating s3Bucket
s3_bucket:
name: ansiblebucket1234567890
tags:
- createbucket
- name: Simple PUT operation
aws_s3:
bucket: ansiblebucket1234567890
object: /my/desired/key.txt
src: /etc/ansible/myfile.txt
mode: put
tags:
- putfile
- name: Create an empty bucket
aws_s3:
bucket: ansiblebucket12345678901234
mode: create
permission: private
tags:
- emptybucket
to execute the tags we use the command
ansible-playbook creates3bucket.yml --tags "createbucket,putfile"
I had the same problem with Spring Boot, Spring Cloud (microservices) and a self-signed SSL certificate. Keystore worked out of the box from application properties, and Truststore didn't.
I ended up keeping both keystore and trustore configuration in application.properties, and adding a separate configuration bean for configuring truststore properties with the System.
@Configuration
public class SSLConfig {
@Autowired
private Environment env;
@PostConstruct
private void configureSSL() {
//set to TLSv1.1 or TLSv1.2
System.setProperty("https.protocols", "TLSv1.1");
//load the 'javax.net.ssl.trustStore' and
//'javax.net.ssl.trustStorePassword' from application.properties
System.setProperty("javax.net.ssl.trustStore", env.getProperty("server.ssl.trust-store"));
System.setProperty("javax.net.ssl.trustStorePassword",env.getProperty("server.ssl.trust-store-password"));
}
}
To avoid security issues in Gmail, you should generate an app password first from your Gmail settings and you can use this password instead of a real password to send an email even if you use two steps verification.
select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;
As of macOS Catalina 10.15.6, I run:
brew install git
brew install git-gui
and it worked for me.
EmEditor should handle this. As their site claims:
EmEditor is now able to open even larger than 248 GB (or 2.1 billion lines) by opening a portion of the file with the new custom bar - Large File Controller. The Large File Controller allows you to specify the beginning point, end point, and range of the file to be opened. It also allows you to stop the opening of the file and monitor the real size of the file and the size of the temporary disk available.
Not free though..
Using the SQL CASE statement with the dplyr and sqldf packages:
Data
df <-structure(list(idnat = structure(c(2L, 2L, 2L, 1L), .Label = c("foreign",
"french"), class = "factor"), idbp = structure(c(3L, 1L, 4L,
2L), .Label = c("colony", "foreign", "mainland", "overseas"), class = "factor")), .Names = c("idnat",
"idbp"), class = "data.frame", row.names = c(NA, -4L))
sqldf
library(sqldf)
sqldf("SELECT idnat, idbp,
CASE
WHEN idbp IN ('colony', 'overseas') THEN 'overseas'
ELSE idbp
END AS idnat2
FROM df")
dplyr
library(dplyr)
df %>%
mutate(idnat2 = case_when(.$idbp == 'mainland' ~ "mainland",
.$idbp %in% c("colony", "overseas") ~ "overseas",
TRUE ~ "foreign"))
Output
idnat idbp idnat2
1 french mainland mainland
2 french colony overseas
3 french overseas overseas
4 foreign foreign foreign
I was trying to integrate the public IP Address into my workflow and these answers didn't help (I like to use the IDE as the IDE). But the above lead me to the solution (after about 2 hours of beating my head against a wall to get this to integrate with Visual Studio 2012 / Windows 8) here's what ended up working for me.
applicationhost.config generated by VisualStudio under C:\Users\usr\Documents\IISExpress\config
<site name="MySite" id="1">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\Users\usr\Documents\Visual Studio 2012\Projects\MySite" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:8081:localhost" />
<binding protocol="http" bindingInformation="*:8082:localhost" />
<binding protocol="http" bindingInformation="*:8083:192.168.2.102" />
</bindings>
</site>
Administrator
so that it can bind to outside addresses (not local host)Administrator
so that it can start the process as an administrator allowing the binding to take place.The net result is you can browse to 192.168.2.102
in my case and test (for instance in an Android emulator. I really hope this helps someone else as this was definitely an irritating process for me.
Apparently it is a security feature which I'd love to see disabled.
You can just unpack both sets into one like this:
>>> set_1 = {1, 2, 3, 4}
>>> set_2 = {3, 4, 5, 6}
>>> union = {*set_1, *set_2}
>>> union
{1, 2, 3, 4, 5, 6}
The *
unpacks the set. Unpacking is where an iterable (e.g. a set or list) is represented as every item it yields. This means the above example simplifies to {1, 2, 3, 4, 3, 4, 5, 6}
which then simplifies to {1, 2, 3, 4, 5, 6}
because the set can only contain unique items.
The question is trickier than it appears, because in many cases there isn't "an IP address for the local computer" so much as a number of different IP addresses. For example, the Mac I'm typing on right now (which is a pretty basic, standard Mac setup) has the following IP addresses associated with it:
fe80::1%lo0
127.0.0.1
::1
fe80::21f:5bff:fe3f:1b36%en1
10.0.0.138
172.16.175.1
192.168.27.1
... and it's not just a matter of figuring out which of the above is "the real IP address", either... they are all "real" and useful; some more useful than others depending on what you are going to use the addresses for.
In my experience often the best way to get "an IP address" for your local computer is not to query the local computer at all, but rather to ask the computer your program is talking to what it sees your computer's IP address as. e.g. if you are writing a client program, send a message to the server asking the server to send back as data the IP address that your request came from. That way you will know what the relevant IP address is, given the context of the computer you are communicating with.
That said, that trick may not be appropriate for some purposes (e.g. when you're not communicating with a particular computer) so sometimes you just need to gather the list of all the IP addresses associated with your machine. The best way to do that under Unix/Mac (AFAIK) is by calling getifaddrs() and iterating over the results. Under Windows, try GetAdaptersAddresses() to get similar functionality. For example usages of both, see the GetNetworkInterfaceInfos() function in this file.
View rootLayout = view.getRootView().findViewById(android.R.id.content);
int[] viewLocation = new int[2];
view.getLocationInWindow(viewLocation);
int[] rootLocation = new int[2];
rootLayout.getLocationInWindow(rootLocation);
int relativeLeft = viewLocation[0] - rootLocation[0];
int relativeTop = viewLocation[1] - rootLocation[1];
First I get the root layout then calculate the coordinates difference with the view.
You can also use the getLocationOnScreen()
instead of getLocationInWindow()
.
There is doing XML reading right, or doing the dodgy just to get by. Doing it right would be using proper document parsing.
Or... dodgy would be using custom text parsing with either wisuzu's response or using regular expressions with matchers.
$(this).attr("name")
means the name of the select tag not option name.
To get option name
$("#band_type_choices option:selected").attr('name');
We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:
https://gitlab.example.com/<group>/<project>/commit/<commit hash>
We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.
You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:
$ /path/to/the/script.py > output.txt
This will overwrite the file. You can use >>
to append to it.
If you want errors to be logged in the file as well, use &>>
or &>
.
Here's a version that matches the output of ls -lh.
def human_size(num: int) -> str:
base = 1
for unit in ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']:
n = num / base
if n < 9.95 and unit != 'B':
# Less than 10 then keep 1 decimal place
value = "{:.1f}{}".format(n, unit)
return value
if round(n) < 1000:
# Less than 4 digits so use this
value = "{}{}".format(round(n), unit)
return value
base *= 1024
value = "{}{}".format(round(n), unit)
return value
NewScores is an alias to Scores table - it looks like you can combine the queries as follows:
SELECT
ROW_NUMBER() OVER( ORDER BY NETT) AS Rank,
Name,
FlagImg,
Nett,
Rounds
FROM (
SELECT
Members.FirstName + ' ' + Members.LastName AS Name,
CASE
WHEN MenuCountry.ImgURL IS NULL THEN
'~/images/flags/ismygolf.png'
ELSE
MenuCountry.ImgURL
END AS FlagImg,
AVG(CAST(NewScores.NetScore AS DECIMAL(18, 4))) AS Nett,
COUNT(Score.ScoreID) AS Rounds
FROM
Members
INNER JOIN
Score NewScores
ON Members.MemberID = NewScores.MemberID
LEFT OUTER JOIN MenuCountry
ON Members.Country = MenuCountry.ID
WHERE
Members.Status = 1
AND NewScores.InsertedDate >= DATEADD(mm, -3, GETDATE())
GROUP BY
Members.FirstName + ' ' + Members.LastName,
MenuCountry.ImgURL
) AS Dertbl
ORDER BY;
Instead of calling /usr/bin/gcc
, use /usr/bin/c99
. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc
after having added the -std=c99
flag, which is precisely what you want.
install intel's distribution of python https://software.intel.com/en-us/intel-distribution-for-python
better of for distribution of python should contain them initially
tldr; jsFiddle Demo
This functionality is not possible with an alert. However, you could use a div
function tempAlert(msg,duration)
{
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
el.innerHTML = msg;
setTimeout(function(){
el.parentNode.removeChild(el);
},duration);
document.body.appendChild(el);
}
Use this like this:
tempAlert("close",5000);
Time flies, the way I do without enabling less secured app
is making a password for specific app
Step one: enable 2FA
Step two: create an app-specific password
After this, put the sixteen digits password to the settings and reload the app, enjoy!
config.action_mailer.smtp_settings = {
...
password: 'HERE', # <---
authentication: 'plain',
enable_starttls_auto: true
}
Quick tip: !obj.blank? == obj.present?
Can be handy/easier on the eyes in some expressions
You can use the following for an awk solution -
awk '/^#/ {sub(/#.*/,"");getline;}1' inputfile
Your Last Edittext .setOnEditorActionListener call this method automatic hit api
I was Call in LoginActivity in et_password
et_Pass.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
Log.i(TAG,"Enter pressed");
Log.i(Check Internet," and Connect To Server");
}
return false;
}
});
Working Fine
this is because str is pointing to a string literal means a constant string ...but you are trying to modify it by copying . Note : if it would have been an error due to memory allocation it would have been given segmentation fault at the run time .But this error is coming due to constant string modification or you can go through the below for more details abt bus error :
Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:
Segmentation faults occur when accessing memory which does not belong to your process, they are very common and are typically the result of:
To be more precise this is not manipulating the pointer itself that will cause issues, it's accessing the memory it points to (dereferencing).
JavaScript doesn't have a built-in init()
function, that is, it's not a part of the language. But it's not uncommon (in a lot of languages) for individual programmers to create their own init()
function for initialisation stuff.
A particular init()
function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object, or...well, you name it.
What any given init()
does specifically is really up to whatever the person who wrote it needed it to do. Some types of code don't need any initialisation.
function init() {
// initialisation stuff here
}
// elsewhere in code
init();
The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.
As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:
/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml
The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.
BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is
@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
public void bussinesMethod(){
}
}
No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.
Now in your client code you need to lookup "MyComponentName".
set scrolling="no"
attribute in your iframe.
The code snippet in the linked proposed duplicate reads user input.
ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?:
The user can type as many letters as they want, and it will go into the delBuild variable.
To not mess with the prototype or other code, you could build and extend your own object:
function Hash(){
var length=0;
this.add = function(key, val){
if(this[key] == undefined)
{
length++;
}
this[key]=val;
};
this.length = function(){
return length;
};
}
myArray = new Hash();
myArray.add("lastname", "Simpson");
myArray.add("age", 21);
alert(myArray.length()); // will alert 2
If you always use the add method, the length property will be correct. If you're worried that you or others forget about using it, you could add the property counter which the others have posted to the length method, too.
Of course, you could always overwrite the methods. But even if you do, your code would probably fail noticeably, making it easy to debug. ;)
A slightly simpler syntax (in Robomongo at least) worked for me:
db.database.save({ Year : NumberInt(2015) });
You can use a For Each to iterate through all the cells in a defined range.
Public Sub IterateThroughRange()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Set wb = Application.Workbooks(1)
Set ws = wb.Sheets(1)
Set rng = ws.Range("A1", "C3")
For Each cell In rng.Cells
cell.Value = cell.Address
Next cell
End Sub
pattern="foo"
for _dir in *"${pattern}"*; do
[ -d "${_dir}" ] && dir="${_dir}" && break
done
echo "${dir}"
This is better than the other shell solution provided because
${dir}
will be empty)=~
operator (if you need this depends on your pattern)find
)Here's an example using @ars accepted answer and the BeautifulSoup4
, requests
, and wget
modules to handle the downloads.
import requests
import wget
import os
from bs4 import BeautifulSoup, SoupStrainer
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/eeg-mld/eeg_full/'
file_type = '.tar.gz'
response = requests.get(url)
for link in BeautifulSoup(response.content, 'html.parser', parse_only=SoupStrainer('a')):
if link.has_attr('href'):
if file_type in link['href']:
full_path = url + link['href']
wget.download(full_path)
Have a look at various solutions.
join()
API has been introduced in early versions of Java. Some good alternatives are available with this concurrent package since the JDK 1.5 release.
Executes the given tasks, returning a list of Futures holding their status and results when everything is completed.
Refer to this related SE question for code example:
How to use invokeAll() to let all thread pool do their task?
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the
countDown()
method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.
Refer to this question for usage of CountDownLatch
Iterate through all Future objects created after submitting to ExecutorService
I recommend you to use JSON.NET
. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...
Serialization Example:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Performance Comparison To Other JSON serializiation Techniques
As Foo
is a class can you not create virtual overloaded Initialise()
methods? Then they would be available to sub-classes and still extensible?
public class Foo
{
...
public Foo() {...}
public virtual void Initialise(int i) {...}
public virtual void Initialise(int i, int i) {...}
public virtual void Initialise(int i, int i, int i) {...}
...
public virtual void Initialise(int i, int i, ..., int i) {...}
...
public virtual void SomethingElse() {...}
...
}
This shouldn't have a higher performance cost unless you have lots of default property values and you hit it a lot.
Wait a few minutes. The application will start automatically
I know that this question has been asked for a long time but as of today one simple answer is:
<img src="image.png" style="width: 55vw; min-width: 330px;" />
The use of vw in here tells that the width is relative to 55% of the width of the viewport.
All the major browsers nowadays support this.
Check this link.
This answer has two main sections:
If you're only interested in the solutions, skip the first section.
To fully understand how centering works in a grid container, it's important to first understand the structure and scope of grid layout.
The HTML structure of a grid container has three levels:
Each of these levels is independent from the others, in terms of applying grid properties.
The scope of a grid container is limited to a parent-child relationship.
This means that a grid container is always the parent and a grid item is always the child. Grid properties work only within this relationship.
Descendants of a grid container beyond the children are not part of grid layout and will not accept grid properties. (At least not until the subgrid
feature has been implemented, which will allow descendants of grid items to respect the lines of the primary container.)
Here's an example of the structure and scope concepts described above.
Imagine a tic-tac-toe-like grid.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
}
You want the X's and O's centered in each cell.
So you apply the centering at the container level:
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
justify-items: center;
}
But because of the structure and scope of grid layout, justify-items
on the container centers the grid items, not the content (at least not directly).
article {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
justify-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
border: 2px solid black;_x000D_
font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
</article>
_x000D_
Same problem with align-items
: The content may be centered as a by-product, but you've lost the layout design.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
justify-items: center;
align-items: center;
}
article {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
justify-items: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
border: 2px solid black;_x000D_
font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
</article>
_x000D_
To center the content you need to take a different approach. Referring again to the structure and scope of grid layout, you need to treat the grid item as the parent and the content as the child.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
}
section {
display: flex;
justify-content: center;
align-items: center;
border: 2px solid black;
font-size: 3em;
}
article {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
}_x000D_
_x000D_
section {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
border: 2px solid black;_x000D_
font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
</article>
_x000D_
There are multiple methods for centering grid items and their content.
Here's a basic 2x2 grid:
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
For a simple and easy way to center the content of grid items use flexbox.
More specifically, make the grid item into a flex container.
There is no conflict, spec violation or other problem with this method. It's clean and valid.
grid-item {
display: flex;
align-items: center;
justify-content: center;
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
display: flex; /* new */_x000D_
align-items: center; /* new */_x000D_
justify-content: center; /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
See this post for a complete explanation:
In the same way that a flex item can also be a flex container, a grid item can also be a grid container. This solution is similar to the flexbox solution above, except centering is done with grid, not flex, properties.
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
display: grid; /* new */_x000D_
align-items: center; /* new */_x000D_
justify-items: center; /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
auto
marginsUse margin: auto
to vertically and horizontally center grid items.
grid-item {
margin: auto;
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
To center the content of grid items you need to make the item into a grid (or flex) container, wrap anonymous items in their own elements (since they cannot be directly targeted by CSS), and apply the margins to the new elements.
grid-item {
display: flex;
}
span, img {
margin: auto;
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
When considering using the following properties to align grid items, read the section on auto
margins above.
align-items
justify-items
align-self
justify-self
https://www.w3.org/TR/css-align-3/#property-index
text-align: center
To center content horizontally in a grid item, you can use the text-align
property.
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
text-align: center; /* new */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
Note that for vertical centering, vertical-align: middle
will not work.
This is because the vertical-align
property applies only to inline and table-cell containers.
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
text-align: center; /* <--- works */_x000D_
vertical-align: middle; /* <--- fails */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
One might say that display: inline-grid
establishes an inline-level container, and that would be true. So why doesn't vertical-align
work in grid items?
The reason is that in a grid formatting context, items are treated as block-level elements.
The
display
value of a grid item is blockified: if the specifieddisplay
of an in-flow child of an element generating a grid container is an inline-level value, it computes to its block-level equivalent.
In a block formatting context, something the vertical-align
property was originally designed for, the browser doesn't expect to find a block-level element in an inline-level container. That's invalid HTML.
Lastly, there's a general CSS centering solution that also works in Grid: absolute positioning
This is a good method for centering objects that need to be removed from the document flow. For example, if you want to:
Simply set position: absolute
on the element to be centered, and position: relative
on the ancestor that will serve as the containing block (it's usually the parent). Something like this:
grid-item {
position: relative;
text-align: center;
}
span {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
position: relative;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
position: absolute;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
Here's a complete explanation for how this method works:
Here's the section on absolute positioning in the Grid spec:
If you're after a promise-based solution, this is @Dmitri's code adapted for that:
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
data => console.log(data)
);
This is not possible, it will give you a compile time error,
You can use array for this type of requirement .
For your Reference :
http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx
What basically happens is,According to default updatePolicy of maven.Maven will fetch the jars from repo on daily basis.So if during 1st attempt your internet was not working then it would not try to fetch this jar again untill 24hours spent.
Resolution :
Either use
mvn -U clean install
where -U will force update the repo
or use
<profiles>
<profile>
...
<repositories>
<repository>
<id>myRepo</id>
<name>My Repository</name>
<releases>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</releases>
</repository>
</repositories>
...
</profile>
</profiles>
in your settings.xml
word
is on the stack and goes out of scope as soon as getStr()
returns. You are invoking undefined behavior.
Blanket.js works perfect too.
npm install --save-dev blanket
in front of your test/tests.js
require('blanket')({
pattern: function (filename) {
return !/node_modules/.test(filename);
}
});
run mocha -R html-cov > coverage.html
Try this one
textBox1.Text = "Line1" + Environment.NewLine + "Line2";
Working fine for me...
Well, Josh Bloch said himself in Effective Java 2d:
Some main points:
Existing classes can be easily retrofitted to implement a new interface. All you have to do is add the required methods if they don’t yet exist and add an implements clause to the class declaration.
Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type that a class can implement in addition to its “primary type” to declare that it provides some optional behavior. For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.
Interfaces allow the construction of nonhierarchical type frameworks. Type hierarchies are great for organizing some things, but other things don’t fall neatly into a rigid hierarchy.
Interfaces enable safe, powerful functionality enhancements via the wrap- per class idiom. If you use abstract classes to define types, you leave the programmer who wants to add functionality with no alternative but to use inheritance.
Moreover, you can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export.
On the other hand, interfaces are very hard to evolve. If you add a method to an interface it'll break all of it's implementations.
PS.: Buy the book. It's a lot more detailed.
Given that ECMA is a 'class-free' language, implementing classical composition doesn't - in my eyes - make a lot of sense. The danger is that, in so doing, you are effectively attempting to re-engineer the language (and, if one feels strongly about that, there are excellent holistic solutions such as the aforementioned TypeScript that mitigate reinventing the wheel)
Now that isn't to say that composition is out of the question however in Plain Old JS. I researched this at length some time ago. The strongest candidate I have seen for handling composition within the object prototypal paradigm is stampit, which I now use across a wide range of projects. And, importantly, it adheres to a well articulated specification.
more information on stamps here
An alternative, I think for your purpose, is to use the round() function:
select round((10 * 1.5),2) // prints 15.00
You can try it here:
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
EDIT (removed wrong solution). EDIT (to add this other option):
Another way to use it would be subclass QThread since it has protected *sleep methods.
QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);
Here's the code to create your own *sleep method.
#include <QThread>
class Sleeper : public QThread
{
public:
static void usleep(unsigned long usecs){QThread::usleep(usecs);}
static void msleep(unsigned long msecs){QThread::msleep(msecs);}
static void sleep(unsigned long secs){QThread::sleep(secs);}
};
and you call it by doing this:
Sleeper::usleep(10);
Sleeper::msleep(10);
Sleeper::sleep(10);
This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.
I used something that resembles singleton pattern:
function myclass() = {
var instance = this;
this.Days = function() {
var days = ["Piatek", "Sobota", "Niedziela"];
return days;
}
this.EventTime = function(day, hours, minutes) {
this.Day = instance.Days()[day];
this.Hours = hours;
this.minutes = minutes;
this.TotalMinutes = day*24*60 + 60*hours + minutes;
}
}
Jon Skeet has written a library called morelinq which has a DistinctBy()
operator. See here for the implementation. Your code would look like
IEnumerable<Note> distinctNotes = Notes.DistinctBy(note => note.Author);
Update: After re-reading your question, Kirk has the correct answer if you're just looking for a distinct set of Authors.
Added sample, several fields in DistinctBy:
res = res.DistinctBy(i => i.Name).DistinctBy(i => i.ProductId).ToList();
I used this answer with my local directory ( for example E://
) it is worked fine for the first directory and for the seconde directory the output made a java null pointer exception, after searching for the reason i discover that the problem was created by the hidden directory, and this directory was created by windows
to avoid this problem just use this
public void recursiveSearch(File file ) {
File[] filesList = file.listFiles();
for (File f : filesList) {
if (f.isDirectory() && !f.isHidden()) {
System.out.println("Directoy name is -------------->" + f.getName());
recursiveSearch(f);
}
if( f.isFile() ){
System.out.println("File name is -------------->" + f.getName());
}
}
}
For Bootstrap 4
In the same line as image
add height: 300px;
<img src="..." style="height: 300px;" class="d-block w-100" alt="image">
If you pass jQuery a function, it will not run until the page has loaded:
<script type="text/javascript">
$(function() {
//your header rotation code goes here
});
</script>
Here's a flowchart based on this answer. See also, using script
to emulate a terminal.
I'm rusty with structs, so I'm probably missing a few keywords here. But why not start with a global structure with the defaults initialized, copy it to your local variable, then modify it?
An initializer like:
void init_struct( structType * s )
{
memcopy(s,&defaultValues,sizeof(structType));
}
Then when you want to use it:
structType foo;
init_struct( &foo ); // get defaults
foo.fieldICareAbout = 1; // modify fields
update( &foo ); // pass to function
if you are using kotlin the use below code. it'll work
// for using image path
val image = Drawable.createFromPath(path)
val bitmap = (image as BitmapDrawable).bitmap
For me, the same issue happened when I both:
--force
) a .map filesvn:ignore
via svn propedit svn:ignore .
My solution was to:
I think it may be worth mentioning that [ConditionalAttribute]
is in the System.Diagnostics;
namespace. I stumbled a bit when I got:
Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
after using it for the first time (I thought it would have been in System
).
I'd suggest to use http://docopt.org/. There's a scala-port but the Java implementation https://github.com/docopt/docopt.java works just fine and seems to be better maintained. Here's an example:
import org.docopt.Docopt
import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
val doc =
"""
Usage: my_program [options] <input>
Options:
--sorted fancy sorting
""".stripMargin.trim
//def args = "--sorted test.dat".split(" ").toList
var results = new Docopt(doc).
parse(args()).
map {case(key, value)=>key ->value.toString}
val inputFile = new File(results("<input>"))
val sorted = results("--sorted").toBoolean
I was facing the issue of namenode not starting. I found a solution using following:
rm -Rf <tmp dir>
(my was /usr/local/hadoop/tmp)bin/hadoop namenode -format
bin/start-all.sh
You may consider rolling back as well using checkpoint (if you had it enabled).
calling getImageData every time will slow the process ... to speed up things i recommend store image data and then you can get pix value easily and quickly, so do something like this for better performance
// keep it global
let imgData = false; // initially no image data we have
// create some function block
if(imgData === false){
// fetch once canvas data
var ctx = canvas.getContext("2d");
imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
}
// Prepare your X Y coordinates which you will be fetching from your mouse loc
let x = 100; //
let y = 100;
// locate index of current pixel
let index = (y * imgData.width + x) * 4;
let red = imgData.data[index];
let green = imgData.data[index+1];
let blue = imgData.data[index+2];
let alpha = imgData.data[index+3];
// Output
console.log('pix x ' + x +' y '+y+ ' index '+index +' COLOR '+red+','+green+','+blue+','+alpha);
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.
Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.
As far as I know there is no such tool. Yet.
The main reason is, I suspect, that unlike with XML (which has XML Schema, and then tools like 'xjc' to do what you ask, between XML and POJO definitions), there is no fully features schema language. There is JSON Schema, but it has very little support for actual type definitions (focuses on JSON structures), so it would be tricky to generate Java classes. But probably still possible, esp. if some naming conventions were defined and used to support generation.
However: this is something that has been fairly frequently requested (on mailing lists of JSON tool projects I follow), so I think that someone will write such a tool in near future.
So I don't think it is a bad idea per se (also: it is not a good idea for all use cases, depends on what you want to do ).
This technet link has some good info for copying large files. I used an exchange server utility mentioned in the article which shows progress and uses non buffered copy functions internally for faster transfer.
In another scenario, I used robocopy. Robocopy GUI makes it easier to get your command line options right.
Complementary info:
On a running process you may use (at least with some recent Sun JDK5/6 versions):
$ /opt/java1.5/bin/jinfo -sysprops 14680 | grep sun.arch.data.model
Attaching to process ID 14680, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 1.5.0_16-b02
sun.arch.data.model = 32
where 14680 is PID of jvm running the application. "os.arch" works too.
Also other scenarios are supported:
jinfo [ option ] pid
jinfo [ option ] executable core
jinfo [ option ] [server-id@]remote-hostname-or-IP
However consider also this note:
"NOTE - This utility is unsupported and may or may not be available in future versions of the JDK. In Windows Systems where dbgent.dll is not present, 'Debugging Tools for Windows' needs to be installed to have these tools working. Also the PATH environment variable should contain the location of jvm.dll used by the target process or the location from which the Crash Dump file was produced."
Use this one
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Test
public void testInsertObject() throws Exception {
String url = BASE_URL + "/object";
ObjectBean anObject = new ObjectBean();
anObject.setObjectId("33");
anObject.setUserId("4268321");
//... more
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestJson=ow.writeValueAsString(anObject );
mockMvc.perform(post(url).contentType(APPLICATION_JSON_UTF8)
.content(requestJson))
.andExpect(status().isOk());
}
As described in the comments, this works because the object is converted to json and passed as the request body. Additionally, the contentType is defined as Json (APPLICATION_JSON_UTF8).
For OLEDB you can use this query:
select IIF(MAX(faculty_id) IS NULL,0,MAX(faculty_id)) AS max_faculty_id from faculties;
As IFNULL is not working there
So far, all solutions (Linux) require sudo
or root rights to install .
Here is a solution if you do not have root rights and without sudo
. (no sudo apt install ...
):
dpkg -x libmysqlclient-dev_<version tag>.deb .
This will extract a folder called usr
. Symlink ./usr/bin/mysql_config
to somewhere that is found on your $PATH
:
ln -s
`pwd`
/usr/bin/mysql_config FOLDER_IN_YOUR_PATH
It should now be able to find mysql_config
Tested on Ubuntu 18.04.
Try this:
String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
trimmedArray[i] = array[i].trim();
Now trimmedArray
contains the same strings as array
, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:
for (int i = 0; i < array.length; i++)
array[i] = array[i].trim();
Building on @Valentyn's answer a bit, here's one way to always automatically clear the cache whenever the ng-view content changes:
myApp.run(function($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function() {
$templateCache.removeAll();
});
});
If you have 2 installations of the JVM. Place the version upfront. Linux : export PATH=/usr/lib/jvm/java-8-oracle/bin:$PATH
This eliminates the ambiguity.
We can use the below code also to get the HTML Response in java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
public static void main(String[] args) throws Exception {
HttpClient client = new DefaultHttpClient();
// args[0] :- http://hostname:8080/abc/xyz/CheckResponse
HttpGet request1 = new HttpGet(args[0]);
HttpResponse response1 = client.execute(request1);
int code = response1.getStatusLine().getStatusCode();
try (BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));) {
// Read in all of the post results into a String.
String output = "";
Boolean keepGoing = true;
while (keepGoing) {
String currentLine = br.readLine();
if (currentLine == null) {
keepGoing = false;
} else {
output += currentLine;
}
}
System.out.println("Response-->" + output);
} catch (Exception e) {
System.out.println("Exception" + e);
}
}
There are a lot of questions already about this, so I will refer you to those.
One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.
Some references:
Although I have read a lot documentation about this one, I'm still confusing on how, when, and where to use it.
Make it very simple to understand:
When you have a similar situation like this:
String strA = null;
String strB = null;
if (2 > 1){
strA = "Hello World";
}
strB = strA.toLowerCase();
You might receive warning (displaying yellow line on strB = strA.toLowerCase(); ) that strA might produce a NULL value to strB. Although you know that strB is absolutely won't be null in the end, just in case, you use assert to
1. Disable the warning.
2. Throw Exception error IF worst thing happens (when you run your application).
Sometime, when you compile your code, you don't get your result and it's a bug. But the application won't crash, and you spend a very hard time to find where is causing this bug.
So, if you put assert, like this:
assert strA != null; //Adding here
strB = strA .toLowerCase();
you tell the compiler that strA is absolutely not a null value, it can 'peacefully' turn off the warning. IF it is NULL (worst case happens), it will stop the application and throw a bug to you to locate it.
Using the "Replace all" functionality, you can delete a line directly by ending your pattern with:
$\n?
$(\r\n)?
For instance, in your case :
.*#RedirectMatch Permanent.*$\n?
foreach (glob("classes/*.php") as $filename)
{
include $filename;
}
The url
template tag will pass the parameter as a string and not as a function reference to reverse()
. The simplest way to get this working is adding a name
to the view:
url(r'^/logout/' , logout_view, name='logout_view')
This solved my issue. I have added these lines in _layout.cshtml
@*@Scripts.Render("~/bundles/plugins")*@
<script src="/Content/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Kendo JS -->
<script src="/Content/kendo/js/kendo.all.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.web.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.aspnetmvc.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="/Content/bootstrap/js/bootstrap.min.js"></script>
<!-- Morris.js charts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="/Content/plugins/morris/morris.min.js"></script>
<!-- Sparkline -->
<script src="/Content/plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="/Content/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="/Content/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="/Content/plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script src="/Content/plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="/Content/plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="/Content/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="/Content/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="/Content/plugins/fastclick/fastclick.min.js"></script>
<!-- AdminLTE App -->
<script src="/Content/dist/js/app.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="/Content/dist/js/demo.js"></script>
<!-- Common -->
<script src="/Scripts/common/common.js"></script>
<!-- Render Sections -->
I think this is the best way:
this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);
Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?
As noted in another comment, SA() isn't returning anything explicitly.
http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html http://www.thinkage.ca/english/gcos/expl/c/lib/rand.html
Edit:
From Generating random number between [-1, 1] in C?
((float)rand())/RAND_MAX
returns a floating-point number in [0,1]
There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().
Try this:
Custom formula is
=countif(A:A,A1)>1
(or change A
to your chosen column)A1:A100
).Anything written in the A1:A100 cells will be checked, and if there is a duplicate (occurs more than once) then it'll be coloured.
For locales using comma (,
) as a decimal separator, the argument separator is most likely a semi-colon (;
). That is, try: =countif(A:A;A1)>1
, instead.
For multiple columns, use countifs
.
Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'
Select ProductName,
IsNull([1],0) as 'Week 1',
IsNull([2],0) as 'Week 2',
IsNull([3],0) as 'Week 3',
IsNull([4],0) as 'Week 4',
IsNull([5], 0) as 'Week 5'
From
(
Select ProductName,
DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2011-05-30'), 0), '2011-05-30') +1 as [Weeks],
Sale as 'Sale'
From dbo.WeekReport
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, '2011-05-30')= DatePart(Month, @DatePeriod)
)p
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv
OUTPUT LOOK LIKE THIS
a 0 0 0 0 20
b 0 0 0 0 4
c 0 0 0 0 3
I wanted to have a div appear like a 3D sphere and transition through colors. I discovered that gradient background colors don't transition (yet). I placed a radial gradient background in front of the element (using z-index) with a transitioning solid background.
/* overlay */
z-index : 1;
background : radial-gradient( ellipse at 25% 25%, rgba( 255, 255, 255, 0 ) 0%, rgba( 0, 0, 0, 1 ) 100% );
then the div.ball
underneath:
transition : all 1s cubic-bezier(0.25, 0.46, 0.45, 0.94);
then changed the background color of the div.ball
and voila!
Same problem. This code doesn't work anymore.
I've corrected it, change clearMarkers method this way:
set_map(null) ---> setMap(null)
google.maps.Map.prototype.clearMarkers = function() {
for(var i=0; i < this.markers.length; i++){
this.markers[i].setMap(null);
}
this.markers = new Array();
};
Documentation has been updated to include details on the topic: https://developers.google.com/maps/documentation/javascript/markers#remove
Here's a quick Perl script to get what you need. It needs some whitespace chomping.
#!/bin/perl
$sample = <<END;
Subject:
Security ID: S-1-5-21-3368353891-1012177287-890106238-22451
Account Name: ChamaraKer
Account Domain: JIC
Logon ID: 0x1fffb
Object:
Object Server: Security
Object Type: File
Object Name: D:\\ApacheTomcat\\apache-tomcat-6.0.36\\logs\\localhost.2013- 07-01.log
Handle ID: 0x11dc
END
my @sample_lines = split /\n/, $sample;
my $path;
foreach my $line (@sample_lines) {
($path) = $line =~ m/Object Name:([^s]+)/g;
if($path) {
print $path . "\n";
}
}
I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share
Syntax:
git diff <commit-ish>:./ -- <path>
Examples:
git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md
(Thanks Eric Boehs for a way to not have to type the filename twice)
Yes l1
and l2
will point to the same reference, same object.
If you want to create a new ArrayList based on the other ArrayList you do this:
List<String> l1 = new ArrayList<String>();
l1.add("Hello");
l1.add("World");
List<String> l2 = new ArrayList<String>(l1); //A new arrayList.
l2.add("Everybody");
The result will be l1
will still have 2 elements and l2
will have 3 elements.
You can use File.Exists to check if the file exists and create it using File.Create if required. Make sure you check if you have access to create files at that location.
Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.
When the game starts:
long tStart = System.currentTimeMillis();
When the game ends:
long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
If you use ggplot2
the preferred way of saving is to use ggsave
. First you have to plot, after creating the plot you call ggsave
:
ggplot(...)
ggsave("plot.png")
The format of the image is determined by the extension you choose for the filename. Additional parameters can be passed to ggsave
, notably width
, height
, and dpi
.
BR
generates a line-break and it is only a line-break. As this element has no content, there are only few styles that make sense to apply on it, like clear
or position
. You can set BR
's border but you won't see it as it has no visual dimension.
If you like to visually separate two sentences, then you probably want to use the horizontal ruler which is intended for this goal. Since you cannot change the markup, I'm afraid using only CSS you cannot achieve this.
It seems, it has been already discussed on other forums. Extract from Re: Setting the height of a BR element using CSS:
[T]his leads to a somewhat odd status for BR in that on the one hand it is not being treated as a normal element, but instead as an instance of \A in generated content, but on the other hand it is being treated as a normal element in that (a limited subset of) CSS properties are being allowed on it.
I also found a clarification in the CSS 1 specification (no higher level spec mentions it):
The current CSS1 properties and values cannot describe the behavior of the ‘BR’ element. In HTML, the ‘BR’ element specifies a line break between words. In effect, the element is replaced by a line break. Future versions of CSS may handle added and replaced content, but CSS1-based formatters must treat ‘BR’ specially.
Grant Wagner's tests show that there is no way to style BR
as you can do with other elements. There is also a site online where you can test the results in your browser.
Update
pelms made some further investigations, and pointed out that IE8 (on Win7) and Chrome 2/Safari 4b allows you to style BR
somewhat. And indeed, I checked the IE demo page with IE Net Renderer's IE8 engine, and it worked.
Update 2
c69 made some further investigations, and it turns out you can style the marker for br
quite heavily (though, not cross-browser), yet this will not affect the line-break itself, because it seem to belong to parent container.
I ran into the same issue and the above answers didn't help. I need to debug and find it.
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.6.0-cdh5.13.1</version>
<exclusions>
<exclusion>
<artifactId>jsp-api</artifactId>
<groupId>javax.servlet.jsp</groupId>
</exclusion>
</exclusions>
</dependency>
After excluding the jsp-api, it worked for me.
When you pass a lambda
to sort
, you need to return an integer, not a boolean. So your code should instead read as follows:
xs.sort(lambda x,y: cmp(len(x), len(y)))
Note that cmp is a builtin function such that cmp(x, y)
returns -1 if x
is less than y
, 0 if x
is equal to y
, and 1 if x
is greater than y
.
Of course, you can instead use the key
parameter:
xs.sort(key=lambda s: len(s))
This tells the sort
method to order based on whatever the key function returns.
EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len
directly as the key parameter to the function, thus eliminating the need for a lambda
:
xs.sort(key=len)
And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort
method, which creates a new list rather than sorting the existing one in-place:
print(sorted(xs, key=len))
Try this:
apt-get install lib32stdc++6
del is the equivalent of "unset" in many languages and as a cross reference point moving from another language to python.. people tend to look for commands that do the same thing that they used to do in their first language... also setting a var to "" or none doesn't really remove the var from scope..it just empties its value the name of the var itself would still be stored in memory...why?!? in a memory intensive script..keeping trash behind its just a no no and anyways...every language out there has some form of an "unset/delete" var function..why not python?
You can also find useful information about getView at the Adapter interface in Adapter.java file. It says;
/**
* Get a View that displays the data at the specified position in the data set. You can either
* create a View manually or inflate it from an XML layout file. When the View is inflated, the
* parent View (GridView, ListView...) will apply default layout parameters unless you use
* {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
*
* @param position The position of the item within the adapter's data set of the item whose view
* we want.
* @param convertView The old view to reuse, if possible. Note: You should check that this view
* is non-null and of an appropriate type before using. If it is not possible to convert
* this view to display the correct data, this method can create a new view.
* Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}).
* @param parent The parent that this view will eventually be attached to
* @return A View corresponding to the data at the specified position.
*/
View getView(int position, View convertView, ViewGroup parent);
Let's measure the performance by using the following piece of code.
import numpy as np
import time
exec_time0 = []
exec_time1 = []
exec_time2 = []
sizeOfArray = 5000
numOfIterations = 200
for i in xrange(numOfIterations):
A = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
B = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
a = time.clock()
res = (A==B).all()
b = time.clock()
exec_time0.append( b - a )
a = time.clock()
res = np.array_equal(A,B)
b = time.clock()
exec_time1.append( b - a )
a = time.clock()
res = np.array_equiv(A,B)
b = time.clock()
exec_time2.append( b - a )
print 'Method: (A==B).all(), ', np.mean(exec_time0)
print 'Method: np.array_equal(A,B),', np.mean(exec_time1)
print 'Method: np.array_equiv(A,B),', np.mean(exec_time2)
Output
Method: (A==B).all(), 0.03031857
Method: np.array_equal(A,B), 0.030025185
Method: np.array_equiv(A,B), 0.030141515
According to the results above, the numpy methods seem to be faster than the combination of the == operator and the all() method and by comparing the numpy methods the fastest one seems to be the numpy.array_equal method.
Yes, struct
is exactly like class
except the default accessibility is public
for struct
(while it's private
for class
).
From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):
Android and iOS devices respect the following
<meta>
tag:<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this
<meta>
tag be included within the page's<head>
element.
In order to display the results with the line numbers, you might try this
grep -nr "word to search for" /path/to/file/file
The result should be something like this:
linenumber: other data "word to search for" other data
I consider delegates to be Anonymous Interfaces. In many cases you can use them whenever you need an interface with a single method, but you don't want the overhead of defining that interface.
//Delete all records of table
db.execSQL("DELETE FROM " + TABLE_NAME);
//Reset the auto_increment primary key if you needed
db.execSQL("UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME=" + TABLE_NAME);
//For go back free space by shrinking sqlite file
db.execSQL("VACUUM");
The answer for Ashwini is great, in pointing out that scipy.math.factorial
, numpy.math.factorial
, math.factorial
are the same functions. However, I'd recommend use the one that Janne mentioned, that scipy.special.factorial
is different. The one from scipy can take np.ndarray
as an input, while the others can't.
In [12]: import scipy.special
In [13]: temp = np.arange(10) # temp is an np.ndarray
In [14]: math.factorial(temp) # This won't work
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-039ec0734458> in <module>()
----> 1 math.factorial(temp)
TypeError: only length-1 arrays can be converted to Python scalars
In [15]: scipy.special.factorial(temp) # This works!
Out[15]:
array([ 1.00000000e+00, 1.00000000e+00, 2.00000000e+00,
6.00000000e+00, 2.40000000e+01, 1.20000000e+02,
7.20000000e+02, 5.04000000e+03, 4.03200000e+04,
3.62880000e+05])
So, if you are doing factorial to a np.ndarray, the one from scipy will be easier to code and faster than doing the for-loops.
keytool -import -v -alias cacerts -keystore cacerts.jks -storepass changeit -file C:\cacerts.cer
Loop like
foreach (GridViewRow row in grid.Rows)
{
if (((CheckBox)row.FindControl("chkboxid")).Checked)
{
//read the label
}
}
This is untested, but fairly obviously correct:
private int findHeight(Treenode<T> aNode) {
if (aNode.left == null && aNode.right == null) {
return 0; // was 1; apparently a node with no children has a height of 0.
} else if (aNode.left == null) {
return 1 + findHeight(aNode.right);
} else if (aNode.right == null) {
return 1 + findHeight(aNode.left);
} else {
return 1 + max(findHeight(aNode.left), findHeight(aNode.right));
}
}
Often simplifying your code is easier than figuring out why it's off by one. This code is easy to understand: the four possible cases are clearly handled in an obviously correct manner:
I do prefer building from command line for better build times. If your app code base is large and you have multiple modules then you can try Local AAR approach as described here, it will give you a big boost in Android Studio performance & gradle build times. Its compatible with command line builds as well
Demo project with integration instructions can be found here: https://github.com/akhgupta/AndroidLocalMavenRepoAARDemo
Another way would be adding __getitem__, __setitem__ function
def __getitem__(self, key):
return getattr(self, key)
You can use self[key] to access now.
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
Drezus - you solved it for me. Thanks so much.
In your AccountController, login should look like this:
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
In the old language, to delete the entry with key k
from the map represented by m
, one wrote the statement,
m[k] = value, false
This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.
In Go 1, that syntax has gone; instead there is a new built-in function, delete
. The call
delete(m, k)
will delete the map entry retrieved by the expression m[k]
. There is no return value. Deleting a non-existent entry is a no-op.
Updating: Running go fix
will convert expressions of the form m[k] = value, false
into delete(m, k)
when it is clear that the ignored value can be safely discarded from the program and false
refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.
You can use jQuery to get text in textbox (work well for me), check in image detail
Code:
$(document.evaluate( "xpath" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()
Example:
$(document.evaluate( "//*[@id='mail']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()
Inject this above query to your code. Image detail: