I think the best solutions is the mix of requests and BeautifulSoup, I just wanted to update the question so it can be kept updated.
You can use getEventListeners in your Google Chrome developer console.
getEventListeners(object) returns the event listeners registered on the specified object.
getEventListeners(document.querySelector('option[value=Closed]'));
Sometimes it is the simple things. In my case, I had an invalid url. I had left out a colon before the at sign (@). I had "jdbc:oracle:thin@//localhost" instead of "jdbc:oracle:thin:@//localhost" Hope this helps someone else with this issue.
You can set background color to All Scaffolds in application at once.
just set scaffoldBackgroundColor: in ThemeData
MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(scaffoldBackgroundColor: const Color(0xFFEFEFEF)),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
the fancy answer. Use std::vector and search with std::find
the simple answer
use a for loop
The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:
http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.
Pass the arguments to the run
command from within gdb.
$ gdb ./a.out
(gdb) r < t
Starting program: /dir/a.out < t
SELECT
[User], Activity,
STUFF(
(SELECT DISTINCT ',' + PageURL
FROM TableName
WHERE [User] = a.[User] AND Activity = a.Activity
FOR XML PATH (''))
, 1, 1, '') AS URLList
FROM TableName AS a
GROUP BY [User], Activity
Perhaps you may want to consider doing a SELECT max(Id) - min(Id) + 1
. This will only work if your Ids are sequential and rows are not deleted. It is however very fast.
Your problem is simple:
names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
This code first declares a global variable called names
. Then, you start a for loop. The for loop declares a local variable that just happens to be called names
too; the fact that a variable had previously been defined with names
is entirely irrelevant. Any use of names
inside the for loop will refer to the local one, not the global one.
The for loop says that the inner part of the loop will be called with names = 1
, then names = 2
, and finally names = 3
. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.
What you actually wanted was something like this:
names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
print (names[nameCount])
end
The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).
Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.
However, this has a flaw. What happens if you remove one of the elements from the list?
names = {'John', 'Joe'}
for nameCount = 1, 3 do
print (names[nameCount])
end
Now, we get John Joe nil
, because attempting to access values from a table that don't exist results in nil
. To prevent this, we need to count from 1 to the length of the table:
names = {'John', 'Joe'}
for nameCount = 1, #names do
print (names[nameCount])
end
The #
is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names
gets, this will always work.
However, there is a more convenient way to iterate through an array of items:
names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
print (name)
end
ipairs
is a Lua standard function that iterates over a list. This style of for
loop, the iterator for loop, uses this kind of iterator function. The i
value is the index of the entry in the array. The name
value is the value at that index. So it basically does a lot of grunt work for you.
I think you would like to learn ajax
first, try this: Ajax Tutorial
If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest
:
var xhr = new XMLHttpReuqest();
xhr.open("GET", "http://some.com");
xhr.onreadystatechange = handler; // do something here...
xhr.send();
So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:
These options work great with me and I can start apache service without errors.
The other option is to change apache listen port from httpd.conf and set another port number.
Hope this solution helps anyone who face the same problem again.
try the following command:
which gcc-arm-linux-gnueabi
Its very likely the command is installed in /usr/bin
.
I suggest code bellow. You may work with exception, when convert error occured.
public static class Utils {
public static bool TryParse<Tin, Tout>(this Tin obj, Func<Tin, Tout> onConvert, Action<Tout> onFill, Action<Exception> onError) {
Tout value = default(Tout);
bool ret = true;
try {
value = onConvert(obj);
}
catch (Exception exc) {
onError(exc);
ret = false;
}
if (ret)
onFill(value);
return ret;
}
public static bool TryParse(this string str, Action<int?> onFill, Action<Exception> onError) {
return Utils.TryParse(str
, s => string.IsNullOrEmpty(s) ? null : (int?)int.Parse(s)
, onFill
, onError);
}
public static bool TryParse(this string str, Action<int> onFill, Action<Exception> onError) {
return Utils.TryParse(str
, s => int.Parse(s)
, onFill
, onError);
}
}
Use this extension method in code (fill int? Age property of a person class):
string ageStr = AgeTextBox.Text;
Utils.TryParse(ageStr, i => person.Age = i, exc => { MessageBox.Show(exc.Message); });
OR
AgeTextBox.Text.TryParse(i => person.Age = i, exc => { MessageBox.Show(exc.Message); });
I hacked this out for release Bootstrap 4.1.1 per my needs before I saw @florian_korner's post. Looks very similar.
If you use sass you can paste this snippet at the end of your bootstrap includes. It seems to fix the issue for chrome, IE, and edge. Does not seem to break anything in firefox.
@mixin make-td-col($size, $columns: $grid-columns) {
width: percentage($size / $columns);
}
@each $breakpoint in map-keys($grid-breakpoints) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
@for $i from 1 through $grid-columns {
td.col#{$infix}-#{$i}, th.col#{$infix}-#{$i} {
@include make-td-col($i, $grid-columns);
}
}
}
or if you just want the compiled css utility:
td.col-1, th.col-1 {
width: 8.33333%; }
td.col-2, th.col-2 {
width: 16.66667%; }
td.col-3, th.col-3 {
width: 25%; }
td.col-4, th.col-4 {
width: 33.33333%; }
td.col-5, th.col-5 {
width: 41.66667%; }
td.col-6, th.col-6 {
width: 50%; }
td.col-7, th.col-7 {
width: 58.33333%; }
td.col-8, th.col-8 {
width: 66.66667%; }
td.col-9, th.col-9 {
width: 75%; }
td.col-10, th.col-10 {
width: 83.33333%; }
td.col-11, th.col-11 {
width: 91.66667%; }
td.col-12, th.col-12 {
width: 100%; }
td.col-sm-1, th.col-sm-1 {
width: 8.33333%; }
td.col-sm-2, th.col-sm-2 {
width: 16.66667%; }
td.col-sm-3, th.col-sm-3 {
width: 25%; }
td.col-sm-4, th.col-sm-4 {
width: 33.33333%; }
td.col-sm-5, th.col-sm-5 {
width: 41.66667%; }
td.col-sm-6, th.col-sm-6 {
width: 50%; }
td.col-sm-7, th.col-sm-7 {
width: 58.33333%; }
td.col-sm-8, th.col-sm-8 {
width: 66.66667%; }
td.col-sm-9, th.col-sm-9 {
width: 75%; }
td.col-sm-10, th.col-sm-10 {
width: 83.33333%; }
td.col-sm-11, th.col-sm-11 {
width: 91.66667%; }
td.col-sm-12, th.col-sm-12 {
width: 100%; }
td.col-md-1, th.col-md-1 {
width: 8.33333%; }
td.col-md-2, th.col-md-2 {
width: 16.66667%; }
td.col-md-3, th.col-md-3 {
width: 25%; }
td.col-md-4, th.col-md-4 {
width: 33.33333%; }
td.col-md-5, th.col-md-5 {
width: 41.66667%; }
td.col-md-6, th.col-md-6 {
width: 50%; }
td.col-md-7, th.col-md-7 {
width: 58.33333%; }
td.col-md-8, th.col-md-8 {
width: 66.66667%; }
td.col-md-9, th.col-md-9 {
width: 75%; }
td.col-md-10, th.col-md-10 {
width: 83.33333%; }
td.col-md-11, th.col-md-11 {
width: 91.66667%; }
td.col-md-12, th.col-md-12 {
width: 100%; }
td.col-lg-1, th.col-lg-1 {
width: 8.33333%; }
td.col-lg-2, th.col-lg-2 {
width: 16.66667%; }
td.col-lg-3, th.col-lg-3 {
width: 25%; }
td.col-lg-4, th.col-lg-4 {
width: 33.33333%; }
td.col-lg-5, th.col-lg-5 {
width: 41.66667%; }
td.col-lg-6, th.col-lg-6 {
width: 50%; }
td.col-lg-7, th.col-lg-7 {
width: 58.33333%; }
td.col-lg-8, th.col-lg-8 {
width: 66.66667%; }
td.col-lg-9, th.col-lg-9 {
width: 75%; }
td.col-lg-10, th.col-lg-10 {
width: 83.33333%; }
td.col-lg-11, th.col-lg-11 {
width: 91.66667%; }
td.col-lg-12, th.col-lg-12 {
width: 100%; }
td.col-xl-1, th.col-xl-1 {
width: 8.33333%; }
td.col-xl-2, th.col-xl-2 {
width: 16.66667%; }
td.col-xl-3, th.col-xl-3 {
width: 25%; }
td.col-xl-4, th.col-xl-4 {
width: 33.33333%; }
td.col-xl-5, th.col-xl-5 {
width: 41.66667%; }
td.col-xl-6, th.col-xl-6 {
width: 50%; }
td.col-xl-7, th.col-xl-7 {
width: 58.33333%; }
td.col-xl-8, th.col-xl-8 {
width: 66.66667%; }
td.col-xl-9, th.col-xl-9 {
width: 75%; }
td.col-xl-10, th.col-xl-10 {
width: 83.33333%; }
td.col-xl-11, th.col-xl-11 {
width: 91.66667%; }
td.col-xl-12, th.col-xl-12 {
width: 100%; }
%date%
will give you the date.
%time%
will give you the time.
The date
and time /t
commands may give you more detail.
instead of getting Notepad++, You can simply Open the file with Wordpad and then Save As - Plain Text document
If you're writing modules for NodeJS, they are already encapsulated. Tell JSLint that you've got node by including at the top of your file:
/*jslint node: true */
Try setting its position
to absolute. That takes it out of the flow of the document.
If you don't want to change your pattern you can use the Group Index and Length properties of a matched group.
var text = "example-123-example";
var pattern = @"-(\d+)-";
var regex = new RegEx(pattern);
var match = regex.Match(text);
var firstPart = text.Substring(0,match.Groups[1].Index);
var secondPart = text.Substring(match.Groups[1].Index + match.Groups[1].Length);
var fullReplace = firstPart + "AA" + secondPart;
You can also use :=
construct to assign and decide on action in one step. Consider following example:
# Example of setting default server and reporting it's status
server=$1
if [[ ${server:=localhost} =~ [a-z] ]] # 'localhost' assigned here to $server
then echo "server is localhost" # echo is triggered since letters were found in $server
else
echo "server was set" # numbers were passed
fi
If $1
is not empty, localhost
will be assigned to server
in the if
condition field, trigger match and report match result. In this way you can assign on the fly and trigger appropriate action.
For collapse, you can try CTRL + M + O and expand using CTRL + M + P. This works in VS2008.
(Updated for completeness)
You can access session variables from any page or control using Session["loginId"]
and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].
But please read on for my original answer...
I always use a wrapper class around the ASP.NET session to simplify access to session variables:
public class MySession
{
// private constructor
private MySession()
{
Property1 = "default value";
}
// Gets the current session.
public static MySession Current
{
get
{
MySession session =
(MySession)HttpContext.Current.Session["__MySession__"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}
// **** add your session properties here, e.g like this:
public string Property1 { get; set; }
public DateTime MyDate { get; set; }
public int LoginId { get; set; }
}
This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:
int loginId = MySession.Current.LoginId;
string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;
DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;
This approach has several advantages:
You are trying to access the first element lstpp.get(0)
of an empty array. Just add an element to your array and check for !lstpp.isEmpty()
before accessing an element
Remove this file:
<YOUR FLUTTER FOLDER>/bin/cache/lockfile
This releases the occupied lock and makes you able to run other commands.
Another way to accomplish this would be using a linq statement. The recomended answer did not work for me in .NetCore2.0. I was able to figure it out however and below would also work if you are using newer technology.
[HttpPost]
public ActionResult Report(FormCollection collection)
{
var listofIDs = collection.ToList().Select(x => x.ToString());
List<Dinner> dinners = new List<Dinner>();
dinners = repository.GetDinners(listofIDs);
return View(dinners);
}
In order to get around the Enable Macro prompt I suggest
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Be sure to return it to default when you are done
Application.AutomationSecurity = msoAutomationSecurityLow
A reminder that the .SaveAs
function contains all optional arguments.I recommend removing CreatBackup:= False
as it is not necessary.
The most interesting way I think is to create an object of the workbook and access the .SaveAs
property that way. I have not tested it but you are never using Workbooks.Open
rendering Application.AutomationSecurity
inapplicable. Possibly saving resources and time as well.
That said I was able to execute the following without any notifications on Excel 2013 windows 10.
Option Explicit
Sub Convert()
OptimizeVBA (True)
'function to set all the things you want to set, but hate keying in
Application.AutomationSecurity = msoAutomationSecurityForceDisable
'this should stop those pesky enable prompts
ChDir "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to
xlsx stop popup"
Workbooks.Open ("Book1.xlsm")
ActiveWorkbook.SaveAs Filename:= _
"F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to xlsx_
stop popup\Book1.xlsx" _
, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
Application.AutomationSecurity = msoAutomationSecurityLow
'make sure you set this up when done
Kill ("F:\VBA Macros\Stack Overflow Questions\When changing type xlsm_
to xlsx stop popup\Book1.xlsx") 'clean up
OptimizeVBA (False)
End Sub
Function OptimizeVBA(ByRef Status As Boolean)
If Status = True Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Application.EnableEvents = False
Else
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
Application.EnableEvents = True
End If
End Function
Without favouring any particular naming choice, remember that a git repo can be cloned into any root directory of your choice:
git clone https://github.com/user/repo.git myDir
Here repo.git
would be cloned into the myDir
directory.
So even if your naming convention for a public repo ended up to be slightly incorrect, it would still be possible to fix it on the client side.
That is why, in a distributed environment where any client can do whatever he/she wants, there isn't really a naming convention for Git repo.
(except to reserve "xxx.git
" for bare form of the repo 'xxx
')
There might be naming convention for REST service (similar to "Are there any naming convention guidelines for REST APIs?"), but that is a separate issue.
To sort by cpu usage: top -o cpu
In JavaScript this
refers to the element containing the action. For example, if you have a function called hide()
:
function hide(element){
element.style.display = 'none';
}
Calling hide
with this
will hide the element. It returns only the element clicked, even if it is similar to other elements in the DOM.
For example, you may have this
clicking a number in the HTML below will only hide the bullet point clicked.
<ul>
<li class="bullet" onclick="hide(this);">1</li>
<li class="bullet" onclick="hide(this);">2</li>
<li class="bullet" onclick="hide(this);">3</li>
<li class="bullet" onclick="hide(this);">4</li>
</ul>
What finally worked for me is what I found here:
http://www.codeproject.com/Tips/395286/How-to-Access-WAMP-Server-in-LAN-or-WAN
To summarize:
set Listen in httpd.conf
:
Listen 192.168.1.154:8081
Add Allow from all to this section:
<Directory "cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
Set an inbound port rule. I think the was the crucial missing part for me:
Great! The next step is to open port (8081) of the server such that everyone can access your server. This depends on which OS you are using. Like if you are using Windows Vista, then follow the below steps.
Open Control Panel >> System and Security >> Windows Firewall then click on “Advance Setting” and then select “Inbound Rules” from the left panel and then click on “Add Rule…”. Select “PORT” as an option from the list and then in the next screen select “TCP” protocol and enter port number “8081” under “Specific local port” then click on the ”Next” button and select “Allow the Connection” and then give the general name and description to this port and click Done.
Now you are done with PORT opening as well.
Next is “Restart All Services” of WAMP and access your machine in LAN or WAN.
For those having a portable SDK edition on windows, simply add the 2 following path to your system.
F:\ADT_SDK\sdk\platforms
F:\ADT_SDK\sdk\platform-tools
This worked for me.
Try this!
List<String> x = new ArrayList<String>(Arrays.asList("xyz", "abc"));
It's a good practice to declare the ArrayList
with interface List
if you don't have to invoke the specific methods.
After Googling for few days, I found this is the only question similar to my situation.
However, I just solved the problem! So I am putting my answer here to help anyone else searching for this issue.
Open "Keychain Access.app" (You can find it in Spotlight or LaunchPad)
Select "All items" in Category
Search "git"
Delete every old & strange item
Try to Push again and it just WORKED
Another solution (without a wrapper) would be to set the form to display: table
, which would make it act like a table so it would have the width of its largest child, and then apply margin: 0 auto
to center it.
form {
display: table;
margin: 0 auto;
}
Credit goes to: https://stackoverflow.com/a/49378738/7841955
The first thing you need to do is read the HTTP spec which will explain what you can expect to receive over the wire. The data returned inside the content will be the "rendered" web page, not the source. The source could be a JSP, a servlet, a CGI script, in short, just about anything, and you have no access to that. You only get the HTML that the server sent you. In the case of a static HTML page, then yes, you will be seeing the "source". But for anything else you see the generated HTML, not the source.
When you say modify the page and return the modified page
what do you mean?
If you want Selected.Value being worked you have to do following things:
1. Set DisplayMember
2. Set ValueMember
3. Set DataSource (not use Items.Add, Items.AddRange, DataBinding etc.)
The key point is Set DataSource!
There is no straight forward way of doing this.
What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).
Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript
My favorite is(not applicable always):
<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");
Google's closure also provides similar functionality.
I am working on C# 9 and .NET 5, example
foo
is nullable int, I need get int value of foo
var foo = (context as AccountTransfer).TransferSide;
int value2 = 0;
if (foo != null)
{
value2 = foo.Value;
}
Here's an example using IterableDiffer with ngDoCheck. IterableDiffer is especially useful if you need to track changes over time as it lets you do things like iterate over only added/changed/removed values etc.
A simple example not using all advantages of IterableDiffer, but it works and shows the principle:
export class FeedbackMessagesComponent implements DoCheck {
@Input()
messages: UserFeedback[] = [];
// Example UserFeedback instance { message = 'Ooops', type = Notice }
@HostBinding('style.display')
display = 'none';
private _iterableDiffer: IterableDiffer<UserFeedback>;
constructor(private _iterableDiffers: IterableDiffers) {
this._iterableDiffer = this._iterableDiffers.find([]).create(null);
}
ngDoCheck(): void {
const changes = this._iterableDiffer.diff(this.messages);
if (changes) {
// Here you can do stuff like changes.forEachRemovedItem()
// We know contents of this.messages was changed so update visibility:
this.display = this.messages.length > 0 ? 'block' : 'none';
}
}
}
This will now automatically show/hide depending on myMessagesArray count:
<app-feedback-messages
[messages]="myMessagesArray"
></app-feedback-messages>
_x000D_
Say suppose, you have
File f = new File("SomeFile");
f.length();
You need not close the File
s, because its just the representation of a path.
You should always consider to close only reader/writers and in fact streams.
I had this error aswell.
I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.
I found the solution here
I had to create a action filter to override the default behaviour of MVC
Here is my exception class
class ValidationException : ApplicationException
{
public JsonResult exceptionDetails;
public ValidationException(JsonResult exceptionDetails)
{
this.exceptionDetails = exceptionDetails;
}
public ValidationException(string message) : base(message) { }
public ValidationException(string message, Exception inner) : base(message, inner) { }
protected ValidationException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
Note that I have constructor which initializes my JSON. Here is the action filter
public class HandleUIExceptionAttribute : FilterAttribute, IExceptionFilter
{
public virtual void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.Exception != null)
{
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
filterContext.Result = ((ValidationException)filterContext.Exception).myJsonError;
}
}
Now that I have the action filter, I will decorate my controller with the filter attribute
[HandleUIException]
public JsonResult UpdateName(string objectToUpdate)
{
var response = myClient.ValidateObject(objectToUpdate);
if (response.errors.Length > 0)
throw new ValidationException(Json(response));
}
When the error is thrown the action filter which implements IExceptionFilter get called and I get back the Json on the client on error callback.
To write inline styling use:
<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>
Inline styling serves a purpose however, it is not recommended in most situations.
The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.
if you have the file structure:
index.html
>>/css/
>>/css/styles.css
Then in your HTML document between <head>
and </head>
write:
<link href="css/styles.css" rel="stylesheet" />
Then, change your div structure to be:
<div id="someidname" class="someclassname">
asdfashdjkfhaskjdf
</div>
In css, you can reference your div from the ID or the CLASS.
To do so write:
.someclassname { height: 100px; }
OR
#someidname { height: 100px; }
Note that if you do both, the one that comes further down the file structure will be the one that actually works.
For example... If you have:
.someclassname { height: 100px; }
.someclassname { height: 150px; }
Then in this situation the height will be 150px.
EDIT:
To answer your secondary question from your edit, probably need overflow: hidden;
or overflow: visible;
. You could also do this:
<div class="span12">
<div style="height:100px;">
asdfashdjkfhaskjdf
</div>
</div>
If you found authentication error problem when you entered correct password and username it's git problem. To solves this problem when you are installing the git in your machine uncheck the enable git credential manager
You can see whether the output of the following code is 0 or not.
'import re
x=' beer '
len(re.findall('\s', x))
* { font-family: Algerian; }
The universal selector *
refers to any element.
Along with the other answers, I thought I'd note that if you get sortedDictionary.Keys
or sortedDictionary.Values
and then loop over them with foreach
, you also go through in sorted order. This is because those methods return System.Collections.Generic.SortedDictionary<TKey,TValue>.KeyCollection
or SortedDictionary<TKey,TValue>.ValueCollection
objects, which maintain the sort of the original dictionary.
Dan's idea doesn't quite work:
#!/usr/bin/env python
class flushfile(file):
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
import sys
sys.stdout = flushfile(sys.stdout)
print "foo"
The result:
Traceback (most recent call last):
File "./passpersist.py", line 12, in <module>
print "foo"
ValueError: I/O operation on closed file
I believe the problem is that it inherits from the file class, which actually isn't necessary. According to the docs for sys.stdout:
stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.
so changing
class flushfile(file):
to
class flushfile(object):
makes it work just fine.
It's a formal way of specifying a correlation name for an entity so that you can address it easily in another part of the query.
Walk of shame:
The connection string was pointing at the live database. The error message was completely accurate - the stored procedure was only present in the dev DB. Thanks to all who provided excellent answers, and my apologies for wasting your time.
I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.
If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.
If you are currently not on branch master, that's super easy:
git branch -f master 1258f0d0aae
This does exactly what you want: It points master
at the given commit, and does nothing else.
If you are currently on master, you need to get into detached head state first. I'd recommend the following two command sequence:
git checkout 1258f0d0aae #detach from master
git branch -f master HEAD #exactly as above
#optionally reattach to master
git checkout master
Be aware, though, that any explicit manipulation of where a branch points has the potential to leave behind commits that are no longer reachable by any branches, and thus become object to garbage collection. So, think before you type git branch -f
!
This method is better than the git reset --hard
approach, as it does not destroy anything in the index or working directory.
Differences between PUT and PATCH The main difference between PUT and PATCH requests is witnessed in the way the server processes the enclosed entity to update the resource identified by the Request-URI. When making a PUT request, the enclosed entity is viewed as the modified version of the resource saved on the original server, and the client is requesting to replace it. However, with PATCH, the enclosed entity boasts a set of instructions that describe how a resource stored on the original server should be partially modified to create a new version.
The second difference is when it comes to idempotency. HTTP PUT is said to be idempotent since it always yields the same results every after making several requests. On the other hand, HTTP PATCH is basically said to be non-idempotent. However, it can be made to be idempotent based on where it is implemented.
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
Some ideas:
Maybe you could simply not inherit from the parent in that case (and declare a dependency on base
with the exclusion). Not handy if you have lot of stuff in the parent pom.
Another thing to test would be to declare the mail
artifact with the version required by ALL-DEPS
under the dependencyManagement
in the parent pom to force the convergence (although I'm not sure this will solve the scoping problem).
<dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>???</version><!-- put the "right" version here -->
</dependency>
</dependencies>
</dependencyManagement>
mail
dependency from log4j if you're not using the features relying on it (and this is what I would do):<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
You probably specify the .php
extension and It don't found your class.
What I was doing :
php artisan db:seed --class=RolesPermissionsTableSeeder.php
What solved my problem : What I was doing :
php artisan db:seed --class=RolesPermissionsTableSeeder
Upon adding few bits and pieces from all the solutions on this page, I was able to get something like this(for someone who need to use it right away). parameters to the function are df(input dataframe) and key(column that has delimiter separated string). Just replace with your delimiter if that is different to semicolon ";".
def split_df_rows_for_semicolon_separated_key(key, df):
df=df.set_index(df.columns.drop(key,1).tolist())[key].str.split(';', expand=True).stack().reset_index().rename(columns={0:key}).loc[:, df.columns]
df=df[df[key] != '']
return df
You can find examples for writing OAuth clients here:
In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails
. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:
@EnableOAuth2Client
@Configuration
class MyConfig{
@Value("${oauth.resource:http://localhost:8082}")
private String baseUrl;
@Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
private String authorizeUrl;
@Value("${oauth.token:http://localhost:8082/oauth/token}")
private String tokenUrl;
@Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource;
resource = new ResourceOwnerPasswordResourceDetails();
List scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setAccessTokenUri(tokenUrl);
resource.setClientId("restapp");
resource.setClientSecret("restapp");
resource.setGrantType("password");
resource.setScope(scopes);
resource.setUsername("**USERNAME**");
resource.setPassword("**PASSWORD**");
return resource;
}
@Bean
public OAuth2RestOperations restTemplate() {
AccessTokenRequest atr = new DefaultAccessTokenRequest();
return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
}
}
@Service
@SuppressWarnings("unchecked")
class MyService {
@Autowired
private OAuth2RestOperations restTemplate;
public MyService() {
restTemplate.getAccessToken();
}
}
Do not forget about @EnableOAuth2Client
on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger
with debug
enabled set.
Good luck
I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .
FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :
strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"
I agree with Duncan ...I have tried it with mutable object but still get the same problem... I got a simple solution to this... use ListIterator instead Iterator and use set method of ListIterator
ListIterator<Integer> i = a.listIterator();
//changed the value of first element in List
Integer x =null;
if(i.hasNext()) {
x = i.next();
x = Integer.valueOf(9);
}
//set method sets the recent iterated element in ArrayList
i.set(x);
//initialized the iterator again and print all the elements
i = a.listIterator();
while(i.hasNext())
System.out.print(i.next());
But this constraints me to use this only for ArrayList only which can use ListIterator...i will have same problem with any other Collection
Using flexbox
#parent_div_1{
display:flex;
flex-wrap: wrap;
}
You could store this into a temporary table.
So instead of doing the CTE/sub query you would use a temp table.
Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
The symptoms indicate that the JSON string which was originally in UTF-8 encoding was written to the HTTP response using ISO-8859-1 encoding and the webbrowser was instructed to display it as UTF-8. If it was written using UTF-8 and displayed as ISO-8859-1, then you would have seen aériennes
. If it was written and displayed using ISO-8859-1, then you would have seen a�riennes
.
To fix the problem of the JSON string incorrectly been written as ISO-8859-1, you need to configure your webapp / Spring to use UTF-8 as HTTP response encoding. Basically, it should be doing the following under the covers:
response.setCharacterEncoding("UTF-8");
Don't change your content type header. It's perfectly fine for JSON and it is been displayed as UTF-8.
A more modern solution that utilises the URL
WebAPI:
(req, res) => {
const { pathname } = new URL(req.url || '', `https://${req.headers.host}`)
}
In this particular example I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable
the Optional stuff is really for return types not to be doing logic... but really neither here nor there.
I wanted to point out that java.util.Objects
has a nice method for this in a broad case, so you can do this:
cars.stream()
.filter(Objects::nonNull)
Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:
cars.stream()
.filter(car -> Objects.nonNull(car))
To partially answer the question at hand to return the list of car names that starts with "M"
:
cars.stream()
.filter(car -> Objects.nonNull(car))
.map(car -> car.getName())
.filter(carName -> Objects.nonNull(carName))
.filter(carName -> carName.startsWith("M"))
.collect(Collectors.toList());
Once you get used to the shorthand lambdas you could also do this:
cars.stream()
.filter(Objects::nonNull)
.map(Car::getName) // Assume the class name for car is Car
.filter(Objects::nonNull)
.filter(carName -> carName.startsWith("M"))
.collect(Collectors.toList());
Unfortunately once you .map(Car::getName)
you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:
cars.stream()
.filter(car -> Objects.nonNull(car))
.filter(car -> Objects.nonNull(car.getName()))
.filter(car -> car.getName().startsWith("M"))
.collect(Collectors.toList());
// Using super keyword access parent class variable
class test {
int is,xs;
test(int i,int x) {
is=i;
xs=x;
System.out.println("super class:");
}
}
class demo extends test {
int z;
demo(int i,int x,int y) {
super(i,x);
z=y;
System.out.println("re:"+is);
System.out.println("re:"+xs);
System.out.println("re:"+z);
}
}
class free{
public static void main(String ar[]){
demo d=new demo(4,5,6);
}
}
If you're removing a commit and don't want to keep its changes @ferit has a good solution.
If you want to add that commit to the current branch, but doesn't make sense to be part of the current pr, you can do the following instead:
git rebase -i HEAD~n
git reset HEAD^ --soft
to uncommit the changes and get them back in a staged state.git push --force
to update the remote branch without your removed commit.Now you'll have removed the commit from your remote, but will still have the changes locally.
Remove -Werror
from your Make or CMake files, as suggested in this post
I always found working with attributed strings to be an incredibly long winded and tedious process.
So I made a Mac App that creates all the code for you.
https://itunes.apple.com/us/app/attributed-string-creator/id730928349?mt=12
You can change easy marker label css without use any extra plugin.
var marker = new google.maps.Marker({
position: this.overlay_text,
draggable: true,
icon: '',
label: {
text: this.overlay_field_text,
color: '#fff',
fontSize: '20px',
fontWeight: 'bold',
fontFamily: 'custom-label'
},
map:map
});
marker.setMap(map);
$("[style*='custom-label']").css({'text-shadow': '2px 2px #000'})
You have to use Bootstrap version 4 with the custom-*
classes to get this style:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- example code of the bootstrap website -->_x000D_
<label class="custom-control custom-checkbox">_x000D_
<input type="checkbox" class="custom-control-input">_x000D_
<span class="custom-control-indicator"></span>_x000D_
<span class="custom-control-description">Check this custom checkbox</span>_x000D_
</label>_x000D_
_x000D_
<!-- your code with the custom classes of version 4 -->_x000D_
<div class="checkbox">_x000D_
<label class="custom-control custom-checkbox">_x000D_
<input type="checkbox" [(ngModel)]="rememberMe" name="rememberme" class="custom-control-input">_x000D_
<span class="custom-control-indicator"></span>_x000D_
<span class="custom-control-description">Remember me</span>_x000D_
</label>_x000D_
</div>
_x000D_
Documentation: https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios-1
Custom checkbox style on Bootstrap version 3?
Bootstrap version 3 doesn't have custom checkbox styles, but you can use your own. In this case: How to style a checkbox using CSS?
These custom styles are only available since version 4.
I have found a good reference: https://unix.stackexchange.com/questions/69111/
In my case I would like to paste content on the clipboard and also to see what is been pasted there, so I used also the tee
command with a file descriptor:
echo "just a test" | tee >(xclip -i -selection clipboard)
>()
is a form of process substitution. bash replaces each with the path to a file descriptor which is connected to the standard input of the program within the parentheses.
The tee
command forks your command allowing you to "pipe its content" and see the result on standard output "stdout"
you can also create aliases to get and write on the clipboard, allowing you to use "pbcopy" and "pbpaste" as if you where on MAC. In my case, as I use zsh I have this on my aliases file:
(( $+commands[xclip] )) && {
alias pbpaste='xclip -i -selection clipboard -o'
alias pbcopy='xclip -selection clipboard'
}
the (( $+command[name] ))
in zsh tests if the command "name" is installed on your system, then both aliases are grouped with {}
. the &&
is a binary AND, if a then b, hence if you have xclip then the aliases will be set.
echo "another test" | tee >(pbcopy)
To get your clipboard content just type:
pbpaste | "any-command-you-need-here"
If ComboBox1.SelectedIndex = -1 Then
ComboBox1.SelectedIndex = 0
End If
@Petr Mensik & kensen john
Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:
<%
String callback = request.getParameter("callback");
response.setCharacterEncoding("UTF-8");
if (callback != null) {
// Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
response.setContentType("text/javascript");
} else {
// Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
response.setContentType("application/json");
}
[...]
String output = "";
if (callback != null) {
output += callback + "(";
}
output += jsonObj.toString();
if (callback != null) {
output += ");";
}
%>
<%=output %>
When callback is supplied, returns:
callback({...JSON stuff...});
with content-type "text/javascript"
When callback is NOT supplied, returns:
{...JSON stuff...}
with content-type "application/json"
set termout off
doesn't work from the command line, so create a file e.g. termout_off.sql
containing the line:
set termout off
and call this from the SQL prompt:
SQL> @termout_off
I found out that you need to add the pointer eg:
div{
cursor: url('cursorurl.png'), pointer;
}
There is a program "OpenFiles", seems to be part of windows 7. Seems that it can do what you want. It can list files opened by remote users (through file share) and, after calling "openfiles /Local on" and a system restart, it should be able to show files opened locally. The latter is said to have performance penalties.
Instead of getting all the table columns using * in your sql statement, you use to specify the table columns you need.
You can use the SQL statement something like:
SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS FIRSTNAME FROM customer;
BTW, why couldn't you use FullName instead of FirstName? Like this:
SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'CUSTOMER NAME' FROM customer;
The Git GUI for Windows has a window-based application that allows you to paste in locations for ssh keys and repo url etc:
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
Edit: This is a more complete version that shows more differences between [
(aka test
) and [[
.
The following table shows that whether a variable is quoted or not, whether you use single or double brackets and whether the variable contains only a space are the things that affect whether using a test with or without -n/-z
is suitable for checking a variable.
| 1a 2a 3a 4a 5a 6a | 1b 2b 3b 4b 5b 6b
| [ [" [-n [-n" [-z [-z" | [[ [[" [[-n [[-n" [[-z [[-z"
-----+------------------------------------+------------------------------------
unset| false false true false true true | false false false false true true
null | false false true false true true | false false false false true true
space| false true true true true false| true true true true false false
zero | true true true true false false| true true true true false false
digit| true true true true false false| true true true true false false
char | true true true true false false| true true true true false false
hyphn| true true true true false false| true true true true false false
two | -err- true -err- true -err- false| true true true true false false
part | -err- true -err- true -err- false| true true true true false false
Tstr | true true -err- true -err- false| true true true true false false
Fsym | false true -err- true -err- false| true true true true false false
T= | true true -err- true -err- false| true true true true false false
F= | false true -err- true -err- false| true true true true false false
T!= | true true -err- true -err- false| true true true true false false
F!= | false true -err- true -err- false| true true true true false false
Teq | true true -err- true -err- false| true true true true false false
Feq | false true -err- true -err- false| true true true true false false
Tne | true true -err- true -err- false| true true true true false false
Fne | false true -err- true -err- false| true true true true false false
If you want to know if a variable is non-zero length, do any of the following:
-n
and quote the variable in single brackets (column 4a)-n
(columns 1b - 4b)Notice in column 1a starting at the row labeled "two" that the result indicates that [
is evaluating the contents of the variable as if they were part of the conditional expression (the result matches the assertion implied by the "T" or "F" in the description column). When [[
is used (column 1b), the variable content is seen as a string and not evaluated.
The errors in columns 3a and 5a are caused by the fact that the variable value includes a space and the variable is unquoted. Again, as shown in columns 3b and 5b, [[
evaluates the variable's contents as a string.
Correspondingly, for tests for zero-length strings, columns 6a, 5b and 6b show the correct ways to do that. Also note that any of these tests can be negated if negating shows a clearer intent than using the opposite operation. For example: if ! [[ -n $var ]]
.
If you're using [
, the key to making sure that you don't get unexpected results is quoting the variable. Using [[
, it doesn't matter.
The error messages, which are being suppressed, are "unary operator expected" or "binary operator expected".
This is the script that produced the table above.
#!/bin/bash
# by Dennis Williamson
# 2010-10-06, revised 2010-11-10
# for http://stackoverflow.com/q/3869072
# designed to fit an 80 character terminal
dw=5 # description column width
w=6 # table column width
t () { printf '%-*s' "$w" " true"; }
f () { [[ $? == 1 ]] && printf '%-*s' "$w" " false" || printf '%-*s' "$w" " -err-"; }
o=/dev/null
echo ' | 1a 2a 3a 4a 5a 6a | 1b 2b 3b 4b 5b 6b'
echo ' | [ [" [-n [-n" [-z [-z" | [[ [[" [[-n [[-n" [[-z [[-z"'
echo '-----+------------------------------------+------------------------------------'
while read -r d t
do
printf '%-*s|' "$dw" "$d"
case $d in
unset) unset t ;;
space) t=' ' ;;
esac
[ $t ] 2>$o && t || f
[ "$t" ] && t || f
[ -n $t ] 2>$o && t || f
[ -n "$t" ] && t || f
[ -z $t ] 2>$o && t || f
[ -z "$t" ] && t || f
echo -n "|"
[[ $t ]] && t || f
[[ "$t" ]] && t || f
[[ -n $t ]] && t || f
[[ -n "$t" ]] && t || f
[[ -z $t ]] && t || f
[[ -z "$t" ]] && t || f
echo
done <<'EOF'
unset
null
space
zero 0
digit 1
char c
hyphn -z
two a b
part a -a
Tstr -n a
Fsym -h .
T= 1 = 1
F= 1 = 2
T!= 1 != 2
F!= 1 != 1
Teq 1 -eq 1
Feq 1 -eq 2
Tne 1 -ne 2
Fne 1 -ne 1
EOF
To bypass "30days left must go online to sign-in", sign-in once to Microsoft account, you'll get %LocalAppData%\Microsoft\VSCommon\OnlineLicensing folder that you can copy to offline PCs.
To count everything just pipe ls to word count line:
ls | wc -l
To count with pattern, pipe to grep first:
ls | grep log | wc -l
Just an other java example:
long dayLength = 1000 * 60 * 60 * 24;
long dayMs = System.currentTimeMillis() % dayLength;
double percentOfDay = (double) dayMs / dayLength;
int hour = (int) (percentOfDay * 24);
int minute = (int) (percentOfDay * 24 * 60) % 60;
int second = (int) (percentOfDay * 24 * 60 * 60) % 60;
an advantage is that you can simulate shorter days, if you adjust dayLength
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
I always do:
git fetch origin && git checkout --track origin/branch_name
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]>
Try It :
DECLARE @String NVARCHAR(100)
SET @String = '12354851'
SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))
I will go with ParentNode.children:
As it provides namedItem
method that allows me directly to get one of the children elements without looping through all children or avoiding to use getElementById
etc.
e.g.
ParentNode.children.namedItem('ChildElement-ID'); // JS
ref.current.children.namedItem('ChildElement-ID'); // React
this.$refs.ref.children.namedItem('ChildElement-ID'); // Vue
I will go with Node.childNodes:
As it provides forEach
method when I work with window.IntersectionObserver
e.g.
nodeList.forEach((node) => { observer.observe(node) })
// IE11 does not support forEach on nodeList, but easy to be polyfilled.
On Chrome 83
Node.childNodes provides
entries
,forEach
,item
,keys
,length
andvalues
ParentNode.children provides
item
,length
andnamedItem
In Mgmt Studio, when you are editing the top 200, you can view the SQL pane - either by right clicking in the grid and choosing Pane->SQL or by the button in the upper left. This will allow you to write a custom query to drill down to the row(s) you want to edit.
But ultimately mgmt studio isn't a data entry/update tool which is why this is a little cumbersome.
apt-get update apt-get upgrade
by far the easiest way to upgrade on linux, works like a charm everytime.
rails 3:
MyModel.send("_#{symbol}_callbacks") # list
MyModel.reset_callbacks symbol # reset
We can use dplyr
to select only numeric columns and purr
to get sum
for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )
library("dplyr")
library("purrr")
people %>%
select_if(is.numeric) %>%
map_dbl(sum)
Or another easy way by only using dplyr
library("dplyr")
people %>%
summarize_if(is.numeric, sum, na.rm=TRUE)
I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.
The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).
And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)
You can use a for loop:
for (i in 1:nrow(df)) {
df$col3[i] <- df$col1[i] + df$col2[i]
}
Yes. Have a look at Wikipedia and Cloanto Implementation of INI File Format (see bottom of page).
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information
You can use "iPhone Configuration Utility" to manage provisioning profiles.
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
The solution for the error is to add this line at the top of the code:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
Check the domain's web server for http://www.<domain>.com
configuration for X-Frame-Options
It is a security feature designed to prevent clickJacking attacks,
Technically the evil has an iframe
with the source to the victim page.
<html>
<iframe src='victim_domain.com'/>
<input id="username" type="text" style="display: none;"/>
<input id="password" type="text" style="display: none;"/>
<script>
//some JS code that click jacking the user username and input from inside the iframe...
<script/>
<html>
If you want to prevent web server request to be rendered within an iframe
add the x-frame-options
X-Frame-Options DENY
The options are:
This is IIS config example:
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="SAMEORIGIN" />
</customHeaders>
</httpProtocol>
If the web server activated the security feature it may cause a client-side SecurityError as it should.
>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]
Or
>>> L[::-1]
[40, 20, 10, 0]
In your Terminal run ipython:
ipython
then locate your script and put there:
%run your_script.ipynb
Maybe the array_view/span in the GSL library is a good option.
Here is also a single file implementation: array_view.
Netcat sends one packet per newline. So you're fine. If you do anything more complex then you might need something else.
I was fooling around with Wireshark when I realized this. Don't know if it helps.
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
If you are running Rails (its the default db in Rails) check the {RAILS_ROOT}/config/database.yml file and you will see something like:
database: db/development.sqlite3
This means that it will be in the {RAILS_ROOT}/db directory.
My requirement was to keep the password in a config file in encrypted form and decrypt when the program runs. For this I used the jasypt
library (jasypt-1.9.3.jar
). This is a very good library and we can accomplish the task with just 4 lines of code.
First, after adding jar to my project I imported the below library.
import org.jasypt.util.text.AES256TextEncryptor;
Then I created the below method. I then called this method by passing the text which I need to encrypt in password
parameter. Using aesEncryptor.encrypt
method, I encrypted the password which is stored to the myEncryptedPassword
variable.
public void EncryptPassword(String password)
{
AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
aesEncryptor.setPassword("mypassword");
String myEncryptedPassword = aesEncryptor.encrypt(password);
System.out.println(myEncryptedPassword );
}
You might have noticed the method setPassword
method and the value mypassword
is used in the above code. This is to make sure that no one can decrypt the password even if they use the encrypted password using the same library.
Now I can see the value in the myEncryptedPassword
variable something like h9oJ4P5P8ToRy38wvK11PUQCBrT1oH/zbMWuMrbOlI0rfZrj+qSg6f/u0jctOs/ZUf9t3shiwnEt05/nq8bnag==
. This is the encrypted password. Keep this value in the config file.
I then created the below method to decrypt the password to be used in my program. The value of passwordFromConfigFile
is the encrypted text which I got from the EncryptPassword
method. Note that you have to use the same password in the aesEncryptor.setPassword
method that you used to encrypt the password.
public String DecryptPassword(String passwordFromConfigFile)
{
AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
aesEncryptor.setPassword("mypassword");
String decryptedPassword = aesEncryptor.decrypt(passwordFromConfigFile);
return decryptedPassword;
}
The variable decryptedPassword
will now have the decrypted password value.
a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
c = 2 · atan2( va, v(1-a) )
distance = R · c
where f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
note that angles need to be in radians to pass to trig functions!
fun distanceInMeter(firstLocation: Location, secondLocation: Location): Double {
val earthRadius = 6371000.0
val deltaLatitudeDegree = (firstLocation.latitude - secondLocation.latitude) * Math.PI / 180f
val deltaLongitudeDegree = (firstLocation.longitude - secondLocation.longitude) * Math.PI / 180f
val a = sin(deltaLatitudeDegree / 2).pow(2) +
cos(firstLocation.latitude * Math.PI / 180f) * cos(secondLocation.latitude * Math.PI / 180f) *
sin(deltaLongitudeDegree / 2).pow(2)
val c = 2f * atan2(sqrt(a), sqrt(1 - a))
return earthRadius * c
}
data class Location(val latitude: Double, val longitude: Double)
Codeproject has a complete solution for this:
http://www.codeproject.com/Articles/17241/Capturing-the-Enter-key-to-cause-a-button-click
and like the article says: "decide which solution best fits your needs"
=================== EDITED ANSWER ============================
The link mentioned above, talks about two ways of capturing the "Enter Key" event:
Javascript (bind the onKeyPress event to the object and create a javascript function to check which key was pressed and do your logic)
_Page_Load in code behind:_
//Add the javascript so we know where we want the enter key press to go
if (!IsPostBack)
{
txtboxFirstName.Attributes.Add("onKeyPress",
"doClick('" + btnSearch.ClientID + "',event)");
txtboxLastName.Attributes.Add("onKeyPress",
"doClick('" + btnSearch.ClientID + "',event)");
}
Javascript code:
<SCRIPT type=text/javascript>
function doClick(buttonName,e)
{
//the purpose of this function is to allow the enter key to
//point to the correct button to click.
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if (key == 13)
{
//Get the button the user wants to have clicked
var btn = document.getElementById(buttonName);
if (btn != null)
{ //If we find the button click it
btn.click();
event.keyCode = 0
}
}
}
</SCRIPT>
Panel Control
<asp:Panel ID="panSearch" runat="server" DefaultButton="btnSearch2" Width="100%" >
<asp:TextBox ID="txtboxFirstName2" runat="server" ></asp:TextBox>
</asp:Panel>
Quoting:
Notice that the Panel tag has a property called DefaultButton. You set this property to the button ID of the button you want to be clicked on an Enter key press event. So any text box inside of the Panel will direct its Enter key press to the button set in the DefaultButton property of the Panel
What about using MAX?
That way if no data is found the variable is set to NULL, otherwise the maximum value.
Since you expect either 0 or 1 value, MAX should be OK to use.
v_column my_table.column%TYPE;
select MAX(column) into v_column from my_table where ...;
Also, Make sure that you are doing command Cntrl+C in the same terminal (tab) which is used to start the server.
In my case, I had 2 tabs but i forgot to stop the server from correct tab and i was wondering why Cntrl+C is not working.
One of the best way is a single row of code like this:
In this example we search all PictureBox
by name in a form
PictureBox[] picSample =
(PictureBox)this.Controls.Find(PIC_SAMPLE_NAME, true);
Most important is the second paramenter of find
.
if you are certain that the control name exists you can directly use it:
PictureBox picSample =
(PictureBox)this.Controls.Find(PIC_SAMPLE_NAME, true)[0];
In MacOS Mojave, the location is:
/Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home/jre/lib/security/cacerts
If using sdkman to manage java versions, the cacerts is in
~/.sdkman/candidates/java/current/jre/lib/security
Sendmail wasn't working for me so I used msmtp 1.6.2 w32 and most just followed the instructions at DeveloperSide. Here is a quick rundown of the setup for posterity:
Enabled IMAP access under your Gmail account (the one msmtp is sending emails from)
Enable access for less secure apps. Log into your google account and go here
Edit php.ini
, find and change each setting below to reflect the following:
; These are commented out by prefixing a semicolon
;SMTP = localhost
;smtp_port = 25
; Set these paths to where you put your msmtp files.
; I used backslashes in php.ini and it works fine.
; The example in the devside guide uses forwardslashes.
sendmail_path = "C:\wamp64\msmtp\msmtp.exe -d -C C:\wamp64\msmtp\msmtprc.ini -t --read-envelope-from"
mail.log = "C:\wamp64\msmtp\maillog.txt"
Create and edit the file msmtprc.ini
in the same directory as your msmtp.exe
file as follows, replacing it with your own email and password:
# Default values for all accounts
defaults
tls_certcheck off
# I used forward slashes here and it works.
logfile C:/wamp64/msmtp/msmtplog.txt
account Gmail
host smtp.gmail.com
port 587
auth on
tls on
from [email protected]
user [email protected]
password ReplaceWithYourPassword
account default : gmail
No need to rename or delete the whole folder:
(%AppData%\..\Local\Microsoft\VisualStudio\11.0\ComponentModelCache)
Just rename or delete the Microsoft.VisualStudio.Default.cache
file inside the above location.
Excellent solutions Xuan, Theller.
For it to work with python 3 make the following changes
import sys, urllib.request
def reporthook(a, b, c):
print ("% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c))
sys.stdout.flush()
for url in sys.argv[1:]:
i = url.rfind("/")
file = url[i+1:]
print (url, "->", file)
urllib.request.urlretrieve(url, file, reporthook)
print
Also, the URL you enter should be preceded by a "http://", otherwise it returns a unknown url type error.
You can use the extension methods below as well and do like this
int? id = Request["id"].ToInt();
if(id.HasValue)
{
}
// Extension methods
public static int? ToInt(this string input)
{
int val;
if (int.TryParse(input, out val))
return val;
return null;
}
public static DateTime? ToDate(this string input)
{
DateTime val;
if (DateTime.TryParse(input, out val))
return val;
return null;
}
public static decimal? ToDecimal(this string input)
{
decimal val;
if (decimal.TryParse(input, out val))
return val;
return null;
}
It will be available using .NET 6: https://devblogs.microsoft.com/dotnet/announcing-net-6-preview-1/
But you can already create WinForms applications using netcore 3.1 and net 5 (at least in Visual Studio 2019 16.8.4+).
Are you possibly depending on development versions that obviously change a lot during development?
Instead of incrementing the version of development releases, you could just use a snapshot version that you overwrite when necessary, which means you wouldn't have to change the version tag on every minor change. Something like 1.0-SNAPSHOT...
But maybe you are trying to achieve something else ;)
For this scenario HTTP 404 is response code for the response from the REST API Like 400, 401, 404 , 422 unprocessable entity
use the Exception handling to check the full exception message.
try{
// call the rest api
} catch(RestClientException e) {
//process exception
if(e instanceof HttpStatusCodeException){
String responseText=((HttpStatusCodeException)e).getResponseBodyAsString();
//now you have the response, construct json from it, and extract the errors
System.out.println("Exception :" +responseText);
}
}
This exception block give you the proper message thrown by the REST API
One approach:
(
shopt -s nullglob
files=(/home/edward/bank1/fiche/Test*)
if [[ "${#files[@]}" -gt 0 ]] ; then
echo found one
else
echo found none
fi
)
Explanation:
shopt -s nullglob
will cause /home/edward/bank1/fiche/Test*
to expand to nothing if no file matches that pattern. (Without it, it will be left intact.)( ... )
sets up a subshell, preventing shopt -s nullglob
from "escaping".files=(/home/edward/bank1/fiche/Test*)
puts the file-list in an array named files
. (Note that this is within the subshell only; files
will not be accessible after the subshell exits.)"${#files[@]}"
is the number of elements in this array.Edited to address subsequent question ("What if i also need to check that these files have data in them and are not zero byte files"):
For this version, we need to use -s
(as you did in your question), which also tests for the file's existence, so there's no point using shopt -s nullglob
anymore: if no file matches the pattern, then -s
on the pattern will be false. So, we can write:
(
found_nonempty=''
for file in /home/edward/bank1/fiche/Test* ; do
if [[ -s "$file" ]] ; then
found_nonempty=1
fi
done
if [[ "$found_nonempty" ]] ; then
echo found one
else
echo found none
fi
)
(Here the ( ... )
is to prevent file
and found_file
from "escaping".)
I know this is an old questions but none of the solutions seemed like a good practice hence I am putting how I have solved this issue:
Tried solving this issue by using Homebrew but it was also installing node in /usr/local directory
which would again cause EACCES
error.
Had to use a version manager like nvm for more informations see the official npm guide.
For various operating system.
nvm installs node and it's modules in the user's HOME FOLDER thereby solving EACCES
issues.
Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.
write.csv(Data_output, "output.csv", row.names = F, quote = F)
The standard approach is to use sprintf(buffer, "%lu", value);
to write a string rep of value
to buffer
. However, overflow is a potential problem, as sprintf
will happily (and unknowingly) write over the end of your buffer.
This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.
This site discusses this and related problems at some length.
Some libraries offer snprintf
as an alternative which lets you specify a maximum buffer size.
Tell the correlation to ignore the NAs with use
argument, e.g.:
cor(data$price, data$exprice, use = "complete.obs")
For first Date
$_firstDate = date("m-d-Y", strtotime($_yourDateString));
For New Date
$_newDate = date("Y-m-d",strtotime($_yourDateString));
this part :
"Your new price is: $"(float(price)
asks python to call this string:
"Your new price is: $"
just like you would a function:
function( some_args)
which will ALWAYS trigger the error:
TypeError: 'str' object is not callable
Rather than thinking of the indices in the [a:]
-, [:b]
- and [a:b]
-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed 0
before the element indexed as 0
.
Looking at just the blue numbers, it's much easier to see what is going on: [0:3]
encloses everything, [3:3]
is empty and [1:2]
would yield {"B"}
. Then [a:]
is just the short version of [a:len(arrayOrSlice)]
, [:b]
the short version of [0:b]
and [:]
the short version of [0:len(arrayOrSlice)]
. The latter is commonly used to turn an array into a slice when needed.
I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.
Do not forget to open and close connection. follow this link for more under standing.
CSS Flexbox was designed to simplify creating these types of layouts.
html {
height: 100%;
}
body {
height: 100%;
display: flex;
}
.Content {
flex-grow: 1;
}
.Sidebar {
width: 290px;
flex-shrink: 0;
}
_x000D_
<div class="Content" style="background:#bed">Content</div>
<div class="Sidebar" style="background:#8cc">Sidebar</div>
_x000D_
You're on a 64-bit system, and don't have 32-bit library support installed.
(if you don't use sudo in your setup read note below)
Most desktop Linux systems in the Fedora/Red Hat family:
pkcon install glibc.i686
Possibly some desktop Debian/Ubuntu systems?:
pkcon install ia32-libs
Fedora or newer Red Hat, CentOS:
sudo dnf install glibc.i686
Older RHEL, CentOS:
sudo yum install glibc.i686
Even older RHEL, CentOS:
sudo yum install glibc.i386
Debian or Ubuntu:
sudo apt-get install ia32-libs
should grab you the (first, main) library you need.
Anyone needing to install glibc.i686
or glibc.i386
will probably run into other library dependencies, as well. To identify a package providing an arbitrary library, you can use
ldd /usr/bin/YOURAPPHERE
if you're not sure it's in /usr/bin
you can also fall back on
ldd $(which YOURAPPNAME)
The output will look like this:
linux-gate.so.1 => (0xf7760000)
libpthread.so.0 => /lib/libpthread.so.0 (0xf773e000)
libSM.so.6 => not found
Check for missing libraries (e.g. libSM.so.6
in the above output), and for each one you need to find the package that provides it.
Fedora/Red Hat Enterprise/CentOS:
dnf provides /usr/lib/libSM.so.6
or, on older RHEL/CentOS:
yum provides /usr/lib/libSM.so.6
or, on Debian/Ubuntu:
first, install and download the database for apt-file
sudo apt-get install apt-file && apt-file update
then search with
apt-file find libSM.so.6
Note the prefix path /usr/lib
in the (usual) case; rarely, some libraries still live under /lib
for historical reasons … On typical 64-bit systems, 32-bit libraries live in /usr/lib
and 64-bit libraries live in /usr/lib64
.
(Debian/Ubuntu organise multi-architecture libraries differently.)
The above should give you a package name, e.g.:
libSM-1.2.0-2.fc15.i686 : X.Org X11 SM runtime library
Repo : fedora
Matched from:
Filename : /usr/lib/libSM.so.6
In this example the name of the package is libSM
and the name of the 32bit version of the package is libSM.i686
.
You can then install the package to grab the requisite library using pkcon
in a GUI, or sudo dnf/yum/apt-get
as appropriate…. E.g pkcon install libSM.i686
. If necessary you can specify the version fully. E.g sudo dnf install ibSM-1.2.0-2.fc15.i686
.
Some libraries will have an “epoch” designator before their name; this can be omitted (the curious can read the notes below).
Incidentially, the issue you are facing either implies that your RPM (resp. DPkg/DSelect) database is corrupted, or that the application you're trying to run wasn't installed through the package manager. If you're new to Linux, you probably want to avoid using software from sources other than your package manager, whenever possible...
Type
su -c
every time you see sudo
, eg,
su -c dnf install glibc.i686
The “epoch” designator before the name is an artifact of the way that the underlying RPM libraries handle version numbers; e.g.
2:libpng-1.2.46-1.fc16.i686 : A library of functions for manipulating PNG image format files
Repo : fedora
Matched from:
Filename : /usr/lib/libpng.so.3
Here, the 2:
can be omitted; just pkcon install libpng.i686
or sudo dnf install libpng-1.2.46-1.fc16.i686
. (It vaguely implies something like: at some point, the version number of the libpng
package rolled backwards, and the “epoch” had to be incremented to make sure the newer version would be considered “newer” during updates. Or something similar happened. Twice.)
Updated to clarify and cover the various package manager options more fully (March, 2016)
Try
String regex = "[0-9]+";
or
String regex = "\\d+";
As per Java regular expressions, the +
means "one or more times" and \d
means "a digit".
Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d
in a java String gives you the actual result: \d
References:
Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.
Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:
String regex = "\\d+";
// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));
// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));
Isn't it necessary to add
^
and$
to the regex, so it won't match "aa123bb" ?
No. In java, the matches
method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$
(even though it is also correct). Please see the last negative test case.
Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find
method instead, described in detail here:
Difference between matches() and find() in Java Regex
Won't this regex also match the empty string,
""
?*
No. A regex \\d*
would match the empty string, but \\d+
does not. The star *
means zero or more, whereas the plus +
means one or more. Please see the first negative test case.
Isn't it faster to compile a regex Pattern?
Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches
, and so if performance implications are important then a Pattern
can be compiled and used like this:
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());
The other answers didn't work for me. I kept searching and found a blog post that covered how a team was running non-root inside of a docker container.
Here's the TL;DR version:
RUN apt-get update \
&& apt-get install -y sudo
RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
USER docker
# this is where I was running into problems with the other approaches
RUN sudo apt-get update
I was using FROM node:9.3
for this, but I suspect that other similar container bases would work as well.
I've found another reason for user's crontab not running: the hostname is not present on the hosts file:
user@ubuntu:~$ cat /etc/hostname
ubuntu
Now the hosts file:
user@ubuntu:~$ cat /etc/hosts
127.0.0.1 localhost
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
This is on a Ubuntu 14.04.3 LTS, the way to fix it is adding the hostname to the hosts file so it resembles something like this:
user@ubuntu:~$ cat /etc/hosts
127.0.0.1 ubuntu localhost
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
Instead of getting the frame from the document, try getting the frame from the window object.
in the above example change this:
if (typeof (document.all.resultFrame.Reset) == "function")
document.all.resultFrame.Reset();
else
alert("resultFrame.Reset NOT found");
to
if (typeof (window.frames[0].Reset) == "function")
window.frames[0].Reset();
else
alert("resultFrame.Reset NOT found");
the problem is that the scope of the javascript inside the iframe is not exposed through the DOM element for the iframe. only window objects contain the javascript scoping information for the frames.
Use LinkedHashMap and use this function.
private LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
Define like this and.
private Entry getEntry(int id){
Iterator iterator = map.entrySet().iterator();
int n = 0;
while(iterator.hasNext()){
Entry entry = (Entry) iterator.next();
if(n == id){
return entry;
}
n ++;
}
return null;
}
The function can return the selected entry.
This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.
This can happen if the other side crashes and then comes back up or if it calls close()
on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.
It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.
For local access, large numbers of directories/files doesn't seem to be an issue. However, if you're accessing it across a network, there's a noticeable performance hit after a few hundred (especially when accessed from Vista machines (XP to Windows Server w/NTFS seemed to run much faster in that regard)).
This has always worked for me.
Provided you set a fixed width for your DIV, and the proper DOCTYPE, try this
div {
margin-left:auto;
margin-right:auto;
}
Hope this helps.
To convert Blob to String in Java:
byte[] bytes = baos.toByteArray();//Convert into Byte array
String blobString = new String(bytes);//Convert Byte Array into String
Typical scenario,
scp -r -P port username@ip:/path-to-folder .
explained with an sample,
scp -r -P 27000 [email protected]:/tmp/hotel_dump .
where,
port = 27000
username = "abc" , remote server username
path-to-folder = tmp/hotel_dump
. = current local directory
Images can be placed in place of radio buttons by using label and span elements.
<div class="customize-radio">
<label>Favourite Smiley</label>
<br>
<label for="hahaha">
<input type="radio" name="smiley" id="hahaha">
<span class="haha-img"></span>
HAHAHA
</label>
<label for="kiss">
<input type="radio" name="smiley" id="kiss">
<span class="kiss-img"></span>
Kiss
</label>
<label for="tongueOut">
<input type="radio" name="smiley" id="tongueOut">
<span class="tongueout-img"></span>
TongueOut
</label>
</div>
Radio button should be hidden,
.customize-radio label > input[type = 'radio'] {
visibility: hidden;
position: absolute;
}
Image can be given in the span tag,
.customize-radio label > input[type = 'radio'] ~ span{
cursor: pointer;
width: 27px;
height: 24px;
display: inline-block;
background-size: 27px 24px;
background-repeat: no-repeat;
}
.haha-img {
background-image: url('hahabefore.png');
}
.kiss-img{
background-image: url('kissbefore.png');
}
.tongueout-img{
background-image: url('tongueoutbefore.png');
}
To change the image on click of radio button, add checked state to the input tag,
.customize-radio label > input[type = 'radio']:checked ~ span.haha-img{
background-image: url('haha.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.kiss-img{
background-image: url('kiss.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.tongueout-img{
background-image: url('tongueout.png');
}
If you have any queries, Refer to the following link, As I have taken solution from the below blog, http://frontendsupport.blogspot.com/2018/06/cool-radio-buttons-with-images.html
Actually, super()
is the first statement of a constructor because to make sure its superclass is fully-formed before the subclass being constructed. Even if you don't have super()
in your first statement, the compiler will add it for you!
Any mature enough SQL database should be able to execute that just as effectively as the equivalent JOIN
. Use whatever is more readable to you.
Somewhat like the other suggestions you could use the following code. However, if you do go the margin: 0 auto; route I'd recommend having the margin for the top and bottom of an H1 be set to something other than 0. So, perhaps margin: 6px auto; or something.
.centercol h1{
display: inline-block;
color: #006bb6;
font-weight: normal;
font-size: 18px;
padding:3px 3px 3px 6px;
border-left:3px solid #c6c1b8;
background:#f2efe9;
display:block;
}
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
This works for both float
and double
:
double NAN = 0.0/0.0;
double POS_INF = 1.0 /0.0;
double NEG_INF = -1.0/0.0;
Edit: As someone already said, the old IEEE standard said that such values should raise traps. But the new compilers almost always switch the traps off and return the given values because trapping interferes with error handling.
You will get it here (change "yourtwitch" by your twitch nickname")
http://www.twitch.tv/yourtwitch/dashboard/streamkey
The link simply moved. You can get this link on the main page of twitch.tv, click on your name then "Dashboard".
This really belongs with @Ramnath's answer but I can't comment as I don't have enough reputation yet. You can also use the arrange
function from the dplyr
package in the same way as the plyr
package.
library(dplyr)
arrange(DF, ID, desc(num))
You mean Selenium WebDriver? Huh....
Prerequisite: Install Python based on your OS
Install with following command
pip install -U selenium
And use this module in your code
from selenium import webdriver
You can also use many of the following as required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
I would recommend you to run script without IDE... Here is my approach
An example below shows login page automation
#ScriptName : Login.py
#---------------------
from selenium import webdriver
#Following are optional required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
baseurl = "http://www.mywebsite.com/login.php"
username = "admin"
password = "admin"
xpaths = { 'usernameTxtBox' : "//input[@name='username']",
'passwordTxtBox' : "//input[@name='password']",
'submitButton' : "//input[@name='login']"
}
mydriver = webdriver.Firefox()
mydriver.get(baseurl)
mydriver.maximize_window()
#Clear Username TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).clear()
#Write Username in Username TextBox
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)
#Clear Password TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).clear()
#Write Password in password TextBox
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)
#Click Login button
mydriver.find_element_by_xpath(xpaths['submitButton']).click()
There is an another way that you can find xpath of any object -
Run script -
python Login.py
You can also use a CSS selector instead of xpath. CSS selectors are slightly faster than xpath in most cases, and are usually preferred over xpath (if there isn't an ID attribute on the elements you're interacting with).
Firepath can also capture the object's locator as a CSS selector if you move your cursor to the object. You'll have to update your code to use the equivalent find by CSS selector method instead -
find_element_by_css_selector(css_selector)
This fixes it:
let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);
There were two problems with your code:
g
flag, for 'global', so that all instances will be replaced.How about just Dir.mkdir('dir') rescue nil
?
Use
s.replace(/\d/g, "X")
which will replace all occurrences. The g
means global match and thus will not stop matching after the first occurrence.
Or to stay with your RegExp
constructor:
s.replace(new RegExp("\\d", "g"), "X")
First case:
A normal product lookup would look like this
http://our.api.com/product/1
So Im thinking that best practice would be for you to do this
http://our.api.com/Product/101404,7267261
Second Case
Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using []
.
PS This can be subjective, so do what you feel comfortable with.
The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.
EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.
Yes, you can use this query (Instead of 'Specialist'
and 'Developer'
, type any strings you want separated by comma and change employees
table with your table)
SELECT * FROM employees em
WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt where em.job like ('%' || mt.column_value || '%'));
Why my query is better than the accepted answer: You don't need a CREATE TABLE
permission to run it. This can be executed with just SELECT
permissions.
I was stuck in this issue today and found this code is working fine for me
$('#content').on('mousewheel', function(event) {
//console.log(event.deltaX, event.deltaY, event.deltaFactor);
if(event.deltaY > 0) {
console.log('scroll up');
} else {
console.log('scroll down');
}
});
I've had the same problem with you.
cd to ../etc/ then use ls to make sure your "paths" file is in , vim paths, add "/usr/local/bin" at the end of the file.
Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:
#parent {
-webkit-box-align:center;
-webkit-box-pack:center;
display:-webkit-box;
}
If you are using an SQL script when you are creating your database and have any users created by your script, you need to drop them too. Lastly you need to flush the users; i.e., force MySQL to read the user's privileges again.
-- DELETE ALL RECIPE
drop schema <database_name>;
-- Same as `drop database <database_name>`
drop user <a_user_name>;
-- You may need to add a hostname e.g `drop user bob@localhost`
FLUSH PRIVILEGES;
Good luck!
First of all you should do such things only if it is really necessary - e.g. to use some old-style API with char*
arguments which are not modified. If an API function modifies the string which was const originally, then this is unspecified behaviour, very likely crash.
Use cast:
(char*)const_char_ptr
Create a new style
<!-- Theme.AppCompat.Light.Dialog -->
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/blue_500</item>
</style>
Java code:
The parent theme is the key here. Choose your colorAccent
DatePickerDialog = new DatePickerDialog(context,R.style.DialogTheme,this,now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH);
Result:
Syntactically MySQL LIMIT query is something like this:
SELECT * FROM table LIMIT OFFSET, ROW_COUNT
This can be translated into Microsoft SQL Server like
SELECT * FROM
(
SELECT TOP #{OFFSET+ROW_COUNT} *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rnum
FROM table
) a
WHERE rnum > OFFSET
Now your query select * from table1 LIMIT 10,20
will be like this:
SELECT * FROM
(
SELECT TOP 30 *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rnum
FROM table1
) a
WHERE rnum > 10
if you are using tomcat you may try this
<servlet-mapping>
<http-method>POST</http-method>
</servlet-mapping>
in addition to <servlet-name>
and <url-mapping>
If you have a Mac and not a English keyboard: Cmd-/ is still easy to produce.
Follow the below steps:
Whenever you want a Cmd-/, you have to change to the ABC keyboard (in your menu row at the top of your screen,if you have ticked it to be shown there in the System Settings - Keyboard tab
).
Cmd and the key to the left of the right "shift key
" gives you Cmd-/.
P.S: Don't forget to switch back to your normal keyboard.
df = data.frame(cond=c(rep("x",3),rep("y",3)),rating=c(x,y))
macro-less and portable way to declare one or more parameters as unused:
template <typename... Args> inline void unused(Args&&...) {}
int main(int argc, char* argv[])
{
unused(argc, argv);
return 0;
}
Html
$('#save').click(function(event) {
var jenis = $('#jenis').val();
var model = $('#model').val();
var harga = $('#harga').val();
var json = { "jenis" : jenis, "model" : model, "harga": harga};
$.ajax({
url: 'phone/save',
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data){
alert(data);
}
});
event.preventDefault();
});
Controller
@Controller
@RequestMapping(value="/phone")
public class phoneController {
phoneDao pd=new phoneDao();
@RequestMapping(value="/save",method=RequestMethod.POST)
public @ResponseBody
int save(@RequestBody Smartphones phone)
{
return pd.save(phone);
}
Dao
public Integer save(Smartphones i) {
int id = 0;
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction trans=session.beginTransaction();
try {
session.save(i);
id=i.getId();
trans.commit();
}
catch(HibernateException he){}
return id;
}
If you compile multiple files in the same line, ensure that you use javac only once and not for every class file.
You can put expressions inside braces. Notice in the compiled JavaScript why a for
loop would never be possible inside JSX syntax; JSX amounts to function calls and sugared function arguments. Only expressions are allowed.
(Also: Remember to add key
attributes to components rendered inside loops.)
JSX + ES2015:
render() {
return (
<table className="MyClassName">
<thead>
<tr>
{this.props.titles.map(title =>
<th key={title}>{title}</th>
)}
</tr>
</thead>
<tbody>
{this.props.rows.map((row, i) =>
<tr key={i}>
{row.map((col, j) =>
<td key={j}>{col}</td>
)}
</tr>
)}
</tbody>
</table>
);
}
JavaScript:
render: function() {
return (
React.DOM.table({className: "MyClassName"},
React.DOM.thead(null,
React.DOM.tr(null,
this.props.titles.map(function(title) {
return React.DOM.th({key: title}, title);
})
)
),
React.DOM.tbody(null,
this.props.rows.map(function(row, i) {
return (
React.DOM.tr({key: i},
row.map(function(col, j) {
return React.DOM.td({key: j}, col);
})
)
);
})
)
)
);
}
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
Right click on your database and select Tasks -> Generate Scripts
Select things you want to restore or just let the complete database be selected by default.
Now click Next -> Click Advanced and Choose 'Script for Server Version' to the 'ssms version' you want to restore like 2008 or 2008 R2 or other.
also, select 'type of data to script' to 'Schema and Data'
Finally execute this .sql file on destination ssms and Change Database Name in first Line Use Database
if database is not there then create one and if you get error with executing the script execute the script from alter keyword to complete bottom.
if (!System.IO.File.Exists(filePath))
return SomeHelper.EmptyImageResult(); // preventing JSON GET/POST exception
else
return new FilePathResult(filePath, contentType);
SomeHelper.EmptyImageResult()
should return FileResult
with existing image (1x1 transparent, for example).
This is easiest way if you have files stored on local drive.
If files are byte[]
or stream
- then use FileContentResult
or FileStreamResult
as Dylan suggested.
The break
statement breaks out of the loop (the next statement to be executed is the first one after the closing brace), while continue
starts the loop over at the next iteration.
benchmark result with memory allocation statistics. check benchmark code at github.
use strings.Builder to optimize performance.
go test -bench . -benchmem
goos: darwin
goarch: amd64
pkg: github.com/hechen0/goexp/exps
BenchmarkConcat-8 1000000 60213 ns/op 503992 B/op 1 allocs/op
BenchmarkBuffer-8 100000000 11.3 ns/op 2 B/op 0 allocs/op
BenchmarkCopy-8 300000000 4.76 ns/op 0 B/op 0 allocs/op
BenchmarkStringBuilder-8 1000000000 4.14 ns/op 6 B/op 0 allocs/op
PASS
ok github.com/hechen0/goexp/exps 70.071s
Actually in multiline mode a more correct answer is this:
/((\r\n|\n|\r)$)|(^(\r\n|\n|\r))|^\s*$/gm
The accepted answer: ^\s*$
does not match a scenario when the last line is blank (in multiline mode).
I could fix it using below steps.(GlassFish server3.1.2.2 and eclipse Luna 4.4.1)
Pretty easy to do this across multiple cells, without having to add '%' to each individually.
Select all the cells you want to change to percent, right Click, then format Cells, choose Custom. Type in 0.0\%
.
You could use the string formatting operator for that:
>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'
The result of the operator is a string, so you can store it in a variable, print etc.
Use this jQuery extension by James Padoley
Here more flexible variant: it uses external shell, but allows to check for arbitrary conditions:
ifeq ($(shell test ".$(GCC_MINOR)" = .4 -o \
".$(GCC_MINOR)" = .5 -o \
".$(TODAY)" = .Friday && printf "true"), true)
CFLAGS += -fno-strict-overflow
endif
The following will do.
string datestring = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
(Explanation in more details can be found in an archived Microsoft KB article.)
Three things to know:
%1
, %2
, ...Two percent signs with any characters in between them are interpreted as a variable:
echo %myvar%
%%f
Why's that?
For example, if we execute your (simplified) command line
FOR /f %f in ('dir /b .') DO somecommand %f
in a batch file, rule 2 would try to interpret
%f in ('dir /b .') DO somecommand %
as a variable. In order to prevent that, you have to apply rule 3 and escape the %
with an second %
:
FOR /f %%f in ('dir /b .') DO somecommand %%f
Another option is to create a file in the $_SERVER['DOCUMENT_ROOT']
directory with the definition of your absolute path.
For example, if your $_SERVER['DOCUMENT_ROOT']
directory is
C:\wamp\www\
create a file (i.e. my_paths.php
) containing this
<?php if(!defined('MY_ABS_PATH')) define('MY_ABS_PATH',$_SERVER['DOCUMENT_ROOT'].'MyProyect/')
Now you only need to include in every file inside your MyProyect folder this file (my_paths.php
), so you can user MY_ABS_PATH
as an absolute path for MyProject.
The best way is to use menu mnemonics, i.e. to have menu entries in your main form that get assigned the keyboard shortcut you want. Then everything else is handled internally and all you have to do is to implement the appropriate action that gets executed in the Click
event handler of that menu entry.
Arrays in PHP can have Key Value structure.
Summary:
I know this is a super old post, but I figured this may still be helpful.
If you're comfortable with reading json format you could replace your var_dump with:
return json_encode($myvar);
I've been using this to help troubleshoot a service I've been building that has some deeply nested arrays. This will return every level of your array without truncating anything or requiring you to change your php.ini file.
Also, because the json_encoded data is a string it means you can write it to the error log easily
error_log(json_encode($myvar));
It probably isn't the best choice for every situation, but it's a choice!
If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors();
in the configure
method. The method looks like that:
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests() // authorize
.anyRequest().authenticated() // all requests are authenticated
.and()
.httpBasic();
http.cors();
}
I have done some investigation and sharing my results here,this may be useful for others.
First, we can check whether MockSetting option is turned ON
public static boolean isMockSettingsON(Context context) {
// returns true if mock location enabled, false if not enabled.
if (Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
return false;
else
return true;
}
Second, we can check whether are there other apps in the device, which are using android.permission.ACCESS_MOCK_LOCATION
(Location Spoofing Apps)
public static boolean areThereMockPermissionApps(Context context) {
int count = 0;
PackageManager pm = context.getPackageManager();
List<ApplicationInfo> packages =
pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo applicationInfo : packages) {
try {
PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName,
PackageManager.GET_PERMISSIONS);
// Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;
if (requestedPermissions != null) {
for (int i = 0; i < requestedPermissions.length; i++) {
if (requestedPermissions[i]
.equals("android.permission.ACCESS_MOCK_LOCATION")
&& !applicationInfo.packageName.equals(context.getPackageName())) {
count++;
}
}
}
} catch (NameNotFoundException e) {
Log.e("Got exception " , e.getMessage());
}
}
if (count > 0)
return true;
return false;
}
If both above methods, first and second are true, then there are good chances that location may be spoofed or fake.
Now, spoofing can be avoided by using Location Manager's API.
We can remove the test provider before requesting the location updates from both the providers (Network and GPS)
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
Log.d(TAG ,"Removing Test providers")
lm.removeTestProvider(LocationManager.GPS_PROVIDER);
} catch (IllegalArgumentException error) {
Log.d(TAG,"Got exception in removing test provider");
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
I have seen that removeTestProvider(~) works very well over Jelly Bean and onwards version. This API appeared to be unreliable till Ice Cream Sandwich.
Flutter Update:
Use Geolocator and check Position
object's isMocked
property.
Scape slashes is simply use \
before /
and it will be escaped. (\/
=> /
).
Otherwise you're regex DD/MM/YYYY could be next:
/^[0-9]{2}[\/]{1}[0-9]{2}[\/]{1}[0-9]{4}$/g
[0-9]
: Just Numbers{2}
or {4}
: Length 2 or 4. You could do {2,4}
as well to length between two numbers (2 and 4 in this case)[\/]
: Character /
g
: Global -- Or m
: Multiline (Optional, see your requirements)$
: Anchor to end of string. (Optional, see your requirements)^
: Start of string. (Optional, see your requirements)An example of use:
var regex = /^[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}$/g;
var dates = ["2009-10-09", "2009.10.09", "2009/10/09", "200910-09", "1990/10/09",
"2016/0/09", "2017/10/09", "2016/09/09", "20/09/2016", "21/09/2016", "22/09/2016",
"23/09/2016", "19/09/2016", "18/09/2016", "25/09/2016", "21/09/2018"];
//Iterate array
dates.forEach(
function(date){
console.log(date + " matches with regex?");
console.log(regex.test(date));
});
_x000D_
Of course you can use as boolean:
if(regex.test(date)){
//do something
}
How about creating a new list and adding elements you want to that new list. You cannot remove elements while iterating through a list
You must use
filter:{color_name:by_colour}
instead of
filter:by_colour
If you want to match with a single property of an object, then write that property instead of object, otherwise some other property will get match.
Take a look at this:
http://developer.android.com/reference/android/util/DisplayMetrics.html
You can get the heigth of the screen and it's simple math to calculate 68 percent of the screen.
You may wonder how to interpret your probability in the context of looking for a correlation in a particular direction (negative or positive correlation.) Here is a function I wrote to help with that. It might even be right!
It's based on info I gleaned from http://www.vassarstats.net/rsig.html and http://en.wikipedia.org/wiki/Student%27s_t_distribution, thanks to other answers posted here.
# Given (possibly random) variables, X and Y, and a correlation direction,
# returns:
# (r, p),
# where r is the Pearson correlation coefficient, and p is the probability
# that there is no correlation in the given direction.
#
# direction:
# if positive, p is the probability that there is no positive correlation in
# the population sampled by X and Y
# if negative, p is the probability that there is no negative correlation
# if 0, p is the probability that there is no correlation in either direction
def probabilityNotCorrelated(X, Y, direction=0):
x = len(X)
if x != len(Y):
raise ValueError("variables not same len: " + str(x) + ", and " + \
str(len(Y)))
if x < 6:
raise ValueError("must have at least 6 samples, but have " + str(x))
(corr, prb_2_tail) = stats.pearsonr(X, Y)
if not direction:
return (corr, prb_2_tail)
prb_1_tail = prb_2_tail / 2
if corr * direction > 0:
return (corr, prb_1_tail)
return (corr, 1 - prb_1_tail)
As noted above by other contributors, using a .bowerrc
file with the JSON
{ "directory": "some/path" }
is necessary -- HOWEVER, you may run into an issue on Windows while creating that file. If Windows gives you a message imploring you to add a "file name", simply use a text editor / IDE such as Notepad++.
Add the JSON to an unnamed file, save it as .bowerrc -- you're good to go!
Probably an easy assumption, but I hope this save others the unnecessary headache :)